@kemu-io/edge-runtime 1.8.0 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/package.json +1 -1
  2. package/runner.d.ts +10 -0
  3. package/runner.js +4 -4
package/runner.js CHANGED
@@ -1,12 +1,12 @@
1
- import{config as e}from"dotenv";import{readFile as t,access as n}from"node:fs/promises";import{nanoid as r}from"nanoid";import i from"util";import o from"crypto-js";import{z as s}from"zod";import a from"emittery";import{Parser as c}from"expr-eval";import l,{scryptSync as u,createDecipheriv as d,createHash as h}from"crypto";import{satisfies as f}from"compare-versions";import p from"debug";import g,{mkdir as m,access as y,constants as v,readdir as b,rm as w,readFile as S}from"fs/promises";import _ from"minimist";import I,{join as x,dirname as k,resolve as E}from"path";import"node-ipc";import*as C from"fs";import $ from"fs";import O from"tty";import N,{homedir as T,platform as A}from"os";import M from"stream";import P from"buffer";import D from"events";import j from"zlib";import R from"string_decoder";import L from"http";import F from"https";import U from"net";import B from"tls";import W from"dgram";import G,{fileURLToPath as V}from"url";import Y from"node:os";import{spawn as H}from"child_process";import{join as z,resolve as q,dirname as K}from"node:path";import{ImageData as J,loadImage as Z,createCanvas as X}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={}));const ee="undefined"!=typeof window&&void 0!==window.document&&void 0!==window.document.createElement,te="object"==typeof self&&self.constructor&&"DedicatedWorkerGlobalScope"===self.constructor.name,ne="undefined"!=typeof process&&null!=process.versions&&null!=process.versions.node,re={};let ie=0,oe="";const se=e=>re[e]?re[e]:null,ae=(e,t)=>{const n=se(e);if(!n)return n;return n.blocks[t]||null},ce=e=>{const{recipeId:t,widgetId:n}=e,r=se(t);if(!r)return null;for(const e in r.blocks){const t=r.blocks[e].gates[n];if(t)return t}return null},le=(e,t,n)=>{const r=ae(e,t);if(!r)return r;return r.gates[n]},ue=(e,t)=>{let n=r(4);for(;re[n];)n=r(4);const i=(o=e,JSON.parse(JSON.stringify(o)));var o;return i.logs="",i.addLog=e=>{i.logs+=`${(()=>{const e=Date.now();if(e!==ie){const t=new Date;ie=e,oe=t.toJSON()}return oe})()}:: ${e}\n`},i.dbInfo={...t},re[n]=i,n},de=e=>{const t=se(e);if(!t)throw new Error("Recipe not found. Cannot get recipe info.");return{poolId:e,uuid:t.uuid,name:t.name,type:t.dbInfo.recipeType,dbId:t.dbInfo.id,version:t.dbInfo.version,authorId:t.dbInfo.authorId}},he="interrupt_port",fe="UI:",pe="default";var ge,me,ye,ve,be,we,Se,_e;let Ie;!function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(ge||(ge={})),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"}(me||(me={})),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"}(ye||(ye={})),function(e){e.Javascript="js",e.Python="py",e.Executable="exe"}(ve||(ve={})),function(e){e.IpcAcknowledge="iack:",e.SocketAcknowledge="sack:",e.AcknowledgeResponse="ackr:",e.ServicesListChanged="update-services",e.SendManifest="send-manifest",e.BroadcastStart="broadcast-start",e.BroadcastEnd="broadcast-end",e.AssumeSession="assume:"}(be||(be={})),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.AddServiceSecret="addServiceSecret",e.OnParentEvent="onParentEvent",e.GetDefaultState="getDefaultState",e.BroadcastEvent="broadcastEvent",e.HubBroadcastEvent="hubBroadcastEvent",e.ServiceManifest="serviceManifest",e.SendToRecipe="sendToRecipe",e.KemuComposerDisconnected="kemu-composer-disconnected",e.GetState="getState",e.SetState="setState",e.SetOutputs="setOutputs",e.UIEvent="uiEvent",e.GetSystemInfo="getSystemInfo",e.InitializeInstance="initializeInstance",e.TerminateInstance="terminateInstance",e.UninstallService="uninstallService",e.ChooseDirectoryDialog="chooseDirectoryDialog",e.ChooseFileDialog="chooseFileDialog",e.SaveRecipeToFile="saveRecipeToFile",e.GetUniqueId="getUniqueId",e.RebootToInstallUpdate="rebootToInstallUpdate",e.GetFileContentFromCacheId="getFileContentFromCacheId",e.GetDecryptedEdgeApiKey="getDecryptedEdgeApiKey",e.GetHubConfig="getHubConfig",e.GetRecipeDecryptedSecretsValues="getRecipeDecryptedSecretsValues",e.GetRecipeSecretMappings="getRecipeSecretMappings",e.AddRecipeSecretMapping="addRecipeSecretMapping",e.DeleteRecipeSecretMapping="deleteRecipeSecretMapping",e.GetHubSecrets="getHubSecrets",e.AddHubSecrets="addHubSecrets",e.DeleteHubSecret="deleteHubSecret"}(we||(we={})),function(e){e.SetDependencyPath="setDependencyPath",e.GetDependencyPath="getDependencyPath",e.ParseStringExpression="parseStringExpression",e.GetGlobalVariableNames="getGlobalVariableNames",e.GetGlobalVariableValues="getGlobalVariableValues",e.SetGlobalVariableValues="setGlobalVariableValues"}(Se||(Se={})),function(e){e.IPC="ipc",e.WS="ws"}(_e||(_e={}));const xe=()=>{if(!Ie)throw new Error("CanvasManager not set");return Ie},ke=e=>{Ie=e},Ee=(e,t)=>xe().createCanvas(e,t),Ce=e=>ee?e.getContext("2d",{willReadFrequently:!0}):e.getContext("2d"),$e=e=>xe().loadImage(e),Oe="-",Ne=`inner${Oe}`,Te=`outer${Oe}`,Ae=`${Te}input${Oe}`,Me=`${Te}output${Oe}`,Pe=`${Ne}input${Oe}`,De=`${Ne}output${Oe}`,je=e=>e===he,Re=e=>e&&void 0!==e.width&&void 0!==e.height&&void 0!==e.data&&e.data.constructor&&"Uint8ClampedArray"===e.data.constructor.name,Le=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,Fe=e=>e&&"number"==typeof e.x&&"number"==typeof e.y,Ue=e=>e&&"string"==typeof e.format&&e.data&&e.data instanceof ArrayBuffer,Be=e=>"number"==typeof e?me.Number:"string"==typeof e?me.String:"boolean"==typeof e?me.Boolean:Array.isArray(e)?me.Array:Re(e)?me.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?me.AudioBuffer:e&&void 0!==e.byteLength?me.ArrayBuffer:Le(e)?me.Rect:e&&void 0!==e.x&&void 0!==e.y&&"number"==typeof e.x&&"number"==typeof e.y?me.Point:Ue(e)?me.BinaryFile:me.JsonObj,We=e=>{const t={};let n;n=Array.isArray(e)?e[0]:e;for(const e in n){const r=Be(n[e]);t[e]=r}return t},Ge=(e,t,n)=>"inner"===e?"input"===t?`${Pe}${n}`:`${De}${n}`:"input"===t?`${Ae}${n}`:`${Me}${n}`,Ve=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]}},Ye=async e=>{try{return new ImageData(e.data,e.width,e.height,{colorSpace:e.colorSpace})}catch(t){console.warn("Failed to create ImageData from info, assuming raw image data",t);return await $e(e.data)}},He=e=>{const t=(e=>{const t=Ee(e.width,e.height),n=Ce(t);if(!n)throw new Error("Failed to get canvas context");n.putImageData(e,0,0);const r=t.toDataURL("image/png");if(!r)throw new Error("Failed to convert canvas to data URL");return r})(e);return t.split(",")[1]},ze=async e=>{const{memoryCanvas:t,finalW:n,finalH:r}=e;let i=e.base64Str;i.startsWith("data:image/")||(i=`data:image/png;base64,${i}`);let o=await $e(i);return o=(e=>{const{image:t,newWidth:n,newHeight:r}=e;let i=e.resizeCanvas;if(n===t.width&&r===t.height&&t instanceof ImageData)return t;i||(i=Ee(n,r));const o=i.getContext("2d");if(!o)throw new Error("Failed to get canvas context");i.width=n,i.height=r;try{let e;if(t instanceof ImageData){e=Ee(t.width,t.height);const n=e.getContext("2d");if(!n)throw new Error("Failed to get canvas context");n.putImageData(t,0,0)}o.drawImage(e||t,0,0,t.width,t.height,0,0,n,r)}catch(e){throw console.warn("Failed to resize image",e),e}return o.getImageData(0,0,n,r)})({image:o,newWidth:n??o.width,newHeight:r??o.height,resizeCanvas:t}),o};var qe,Ke;!function(e){e.Action="action",e.CustomInput="customInput"}(qe||(qe={})),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.delay="delay",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.sequence="sequence",e.variable="variable",e.hubService="hubService",e.imageFilter="imageFilter",e.recipeLoad="recipeLoad",e.note="note",e.stringify="stringify",e.templateString="templateString",e.expressionEval="expressionEval",e.rescue="rescue",e.objectCombine="objectCombine",e.loop="loop",e.status="status",e.secret="secret",e.output="output",e.globalVariable="globalVariable",e.switch="switch",e.edgeFunction="edgeFunction",e.fieldValue="fieldValue"}(Ke||(Ke={}));const Je={};let Ze,Xe=()=>0;const Qe=async e=>{const t=Je[e],n={name:he,type:me.Boolean};if(t){const r={name:t.portName},i=t.data||{type:me.Boolean,value:!0};if(!Xe)throw new Error("consumeEventCounter is not set");const o=Xe();Ze?(await Ze({interruptDriven:!0,childGateId:t.targetWidgetId,sourceWidgetId:t.sourceWidgetId,block:t.thingId,recipeId:t.recipePoolId,sourcePortName:n.name,targetPort:r,data:{...i,timestamp:Date.now()},sourceOutputNames:[n],currentPath:[],eventId:o}),"timeout"===t.type&&et(e)):console.warn("Interrupt service has not been initialized")}},et=e=>{const t=Je[e];return!!t&&(t.timerRef&&("interval"===t.type?clearInterval(t.timerRef):"timeout"===t.type&&clearTimeout(t.timerRef)),delete Je[e],!0)};var tt={interruptHandler:Qe,createInterrupt:e=>{const{type:t,recipePoolId:n,thingId:i,targetWidgetId:o,sourceWidgetId:s,portName:a,config:c,data:l,customId:u}=e;if(u&&Je[u])throw new Error("The given interrupt id already exists");const d=u||r().replace(/_/g,"-");if("interval"===t&&!c.interval)throw new Error(`Invalid interval. Expected a number greater than 0, but got '${c.interval}'`);if("timeout"===t&&!c.timeout)throw new Error(`Invalid timeout. Expected a number greater than 0, but got '${c.timeout}'`);if(Je[d]={data:l,portName:a,recipePoolId:n,targetWidgetId:o,sourceWidgetId:s,thingId:i,type:t},"interval"===t)Je[d].timerRef=setInterval((async()=>await Qe(d)),c.interval);else{if("timeout"!==t)throw new Error(`Invalid interrupt type '${t}'`);Je[d].timerRef=setTimeout((async()=>await Qe(d)),c.timeout)}return d},destroyInterrupt:et,destroyAllInterrupts:()=>{Object.keys(Je).forEach(et)},setInvokeChildGateCb:e=>{Ze=e},setConsumeEventCounterCb:e=>{Xe=e}};const nt=[10001,"Invalid `sourcePort` parameter"],rt=[10002,"The gate [%s] does not exist. Have you called `loadWidgets` yet?"],it=(e,...t)=>JSON.stringify({code:e[0],message:t[0]?i.format(e[1],...t):e[1].replace(/ \[%s\]/g,"")});let ot=0,st={};var at=(e,t)=>{const n=`${e}-${++ot}`,r={event:t,eventKey:n,widgetId:e,resolve:()=>{},reject:()=>{}},i=new Promise(((e,t)=>{r.resolve=e,r.reject=t}));return r.promise=i,st[n]=r,r},ct=(e,t)=>{const n=st[e];n&&(delete st[e],n.resolve(t))};const lt=()=>({inputName:"",dataType:me.Anything}),ut="output",dt={processEvent:async(e,t)=>{const n=t.getState(),r={...lt(),...n};if(e.type!==r.dataType&&r.dataType!==me.Anything)return void console.error(`Invalid data type: ${e.type} for input: ${r.inputName}. Expected: ${r.dataType}`);const i=t.waitForOutputChild,o=i?at(t.id,e):void 0,s=i?{eventKey:o?.eventKey}:void 0;if(await t.nextWidget(ut,{type:e.type,value:e.value},s).catch((e=>{console.log("[INPUT] error resolving event: ",e),o?.reject(e)})),o){return await o.promise}},getOutputNames:e=>{const t={...lt(),...e};return[{name:ut,type:t.dataType}]},getInputNames:()=>[]},ht=Object.freeze({in:"in",reset:"reset",increment:"increment"}),ft="output";var pt={onParentEvent:async(e,t,n,r)=>{if(!e)throw new Error(it(nt));const i={currentValue:0,increment:1,...r.getState()};let o=i.increment,s=i.currentValue;const a=await r.getParentAtPort(ht.increment);if(t.name===ht.increment)return void(n.data.type===me.Number&&r.setState({...i,increment:Number(n.data.value)}));if(a){const e=a.getValue();null!==e&&(o=e)}if(t.name===ht.reset)return r.setState({...i,currentValue:0});s+=o,r.setState({currentValue:s,increment:o});const c={type:me.Number,value:s};return r.nextGate(ft,c)},getInputNames:()=>[{name:ht.in,type:me.Anything},{name:ht.reset,type:me.Anything},{name:ht.increment,type:me.Number}],getOutputNames:()=>[{name:ft,type:me.Number}]};const gt=Object.freeze({in:"in",reset:"reset"}),mt="output";var yt={onParentEvent:async(e,t,n,r)=>{const i={updatedAt:0,elapsed:0,...r.getState()},o=Date.now(),s=o-(i.updatedAt||o);return t.name===gt.reset?r.setState({...i,updatedAt:o,elapsed:0}):(r.setState({updatedAt:o,elapsed:s}),r.nextGate(mt,{type:me.Number,value:s}))},getInputNames:()=>[{name:gt.in,type:me.Anything},{name:gt.reset,type:me.Anything}],getOutputNames:()=>[{name:mt,type:me.Number}]};const vt=Object.freeze({data:"data",evaluation:"evaluation"}),bt="then",wt="else";var St={onParentEvent:async(e,t,n,r)=>{const i={value:5,condition:"Equal",useDataPort:!1,...r.getState()},o=n.data.value,s=!isNaN(Number(o)),a="string"==typeof o;if(!i.useDataPort&&(n.data.type===me.Number||n.data.type===me.String||n.data.type===me.Boolean||n.data.type===me.Anything&&s||n.data.type===me.Anything&&a)){let e=!1;return("Equal"===i.condition&&(n.data.value==i.value||n.data.type===me.Boolean&&n.data.value.toString()===i.value.toString())||"Not Equal"===i.condition&&(n.data.value!==i.value||n.data.type===me.Boolean&&n.data.value!==i.value.toString())||"Greater"===i.condition&&n.data.type===me.Number&&n.data.value>Number(i.value)||"Less"===i.condition&&n.data.type===me.Number&&n.data.value<Number(i.value)||"Starts With"===i.condition&&String(n.data.value).startsWith(String(i.value))||"Ends With"===i.condition&&String(n.data.value).endsWith(String(i.value))||"Includes"===i.condition&&String(n.data.value).includes(String(i.value))||"Matches"===i.condition&&String(n.data.value).match(String(i.value)))&&(e=!0),e?r.nextGate(bt,n.data):r.nextGate(wt,n.data)}if(t.name===vt.evaluation&&(n.data.type===me.Number||n.data.type===me.String||n.data.type===me.Boolean||n.data.type===me.Anything&&(s||a))&&(i.$lastValue=n.data.value,i.$lastInputDataType=n.data.type,r.setState({...i})),t.name===vt.data){let e=!1;return("Equal"===i.condition&&(i.$lastValue==i.value||i.$lastInputDataType===me.Boolean&&i.$lastValue?.toString()===i.value.toString())||"Not Equal"===i.condition&&(i.$lastValue!==i.value||i.$lastInputDataType===me.Boolean&&i.$lastValue!==i.value.toString())||"Greater"===i.condition&&i.$lastInputDataType===me.Number&&Number(i.$lastValue)>Number(i.value)||"Less"===i.condition&&i.$lastInputDataType===me.Number&&Number(i.$lastValue)<Number(i.value)||"Starts With"===i.condition&&String(i.$lastValue).startsWith(String(i.value))||"Ends With"===i.condition&&String(i.$lastValue).endsWith(String(i.value))||"Includes"===i.condition&&String(i.$lastValue).includes(String(i.value))||"Matches"===i.condition&&String(i.$lastValue).match(String(i.value)))&&(e=!0),r.setState({...i,$lastValue:void 0,$lastInputDataType:void 0}),e?r.nextGate(bt,n.data):r.nextGate(wt,n.data)}},getInputNames:e=>e.useDataPort?[{name:vt.data,type:me.Anything,triggerPort:!0},{name:vt.evaluation,type:[me.Number,me.String,me.Boolean]}]:[{name:"in",type:[me.Number,me.String,me.Boolean]}],getOutputNames:e=>e.$lastOutputDataType?[{name:bt,type:e.$lastOutputDataType},{name:wt,type:e.$lastOutputDataType}]:[{name:bt,type:[me.Number,me.String]},{name:wt,type:[me.Number,me.String]}]};const _t=Object.freeze({in:"in",reset:"reset"}),It="out",xt="skipped";var kt={onParentEvent:async(e,t,n,r)=>{const i={totalCalls:0,callsLimit:1,...r.getState()};return t.name===_t.reset?r.setState({...i,totalCalls:0}):(i.totalCalls=i.totalCalls+1,i.totalCalls>i.callsLimit?(i.totalCalls=0,r.setState(i),r.nextWidget(It,n.data)):(n.data.type!==i.$$lastDetectedType&&(i.$$lastDetectedType=n.data.type),r.setState(i),r.nextWidget(xt,n.data)))},getInputNames:()=>[{name:_t.in,type:me.Anything},{name:_t.reset,type:me.Anything}],getOutputNames:e=>[{name:It,type:e.$$lastDetectedType??me.Anything},{name:xt,type:e.$$lastDetectedType??me.Anything}]};const Et=Object.freeze({in:"in"}),Ct="then",$t="else";var Ot={onParentEvent:async(e,t,n,r)=>{const i={min:1,max:10,...r.getState()};if(n.data.type===me.Number)return n.data.value>=i.min&&n.data.value<=i.max?r.nextGate(Ct,n.data):r.nextGate($t,n.data)},getInputNames:()=>[{name:Et.in,type:me.Number}],getOutputNames:()=>[{name:Ct,type:me.Number},{name:$t,type:me.Number}]};const Nt=Object.freeze({in:"in"}),Tt="out";var At={onParentEvent:async(e,t,n,r)=>{const i={clamp:!0,...r.getState()},o=Number(n.data.value);if(void 0!==i.fromMax&&void 0!==i.fromMin&&void 0!==i.toMax&&void 0!==i.toMin&&""!==i.fromMax&&""!==i.fromMin&&""!==i.toMax&&""!==i.toMin&&(n.data.type===me.Number||n.data.type===me.Anything&&!isNaN(Number(o)))){let e=((e,t,n,r,i)=>(e-t)*(i-r)/(n-t)+r)(o,Number(i.fromMin),Number(i.fromMax),Number(i.toMin),Number(i.toMax));if(isNaN(e))return;return i.clamp&&(e<Number(i.toMin)&&(e=Number(i.toMin)),e>Number(i.toMax)&&(e=Number(i.toMax))),r.nextGate(Tt,{type:me.Number,value:Number(e)})}},getInputNames:()=>[{name:Nt.in,type:me.Number}],getOutputNames:()=>[{name:Tt,type:me.Number}]};const Mt=Object.freeze({in:"in"}),Pt="out",Dt=["image/png","image/jpeg","image/jpg","image/gif","image/webp","image/bmp","image/svg+xml"];var jt={onParentEvent:async(e,t,n,r)=>{const i={convertTo:"Integer",floatPlaces:2,...r.getState()};let o=n.data.value;if("ImageData"===i.convertTo){if(!Ue(n.data.value))throw new Error("Invalid data type, expected a BinaryFile type");const e=n.data.value;if(!Dt.includes(e.format))throw new Error(`Unsupported image format: ${e.format}. Supported formats are: ${Dt.join(", ")}.`);const t=await $e(e);return r.nextGate(Pt,{type:me.ImageData,value:t})}if(n.data.type===me.Number||n.data.type===me.Anything||n.data.type===me.String){if((!isNaN(Number(o))||"string"==typeof o)&&!Array.isArray(o))return"Integer"===i.convertTo?o=parseInt(o):"Decimal"===i.convertTo?o=parseFloat(Number(o).toFixed(i.floatPlaces)):"String"===i.convertTo?o=String(o):"Abs"===i.convertTo?o=Math.abs(Number(o)):"Round"===i.convertTo&&(o=Math.round(Number(o))),r.nextGate(Pt,{type:"String"===i.convertTo?me.String:me.Number,value:o})}},getInputNames:()=>[{name:Mt.in,type:me.Number}],getOutputNames:e=>{const t="String"===e?.convertTo?me.String:"ImageData"===e?.convertTo?me.ImageData:me.Number;return[{name:Pt,type:t}]}};const Rt=Object.freeze({in:"in"}),Lt="out";var Ft={onParentEvent:async(e,t,n,r)=>{const i={currentValue:50,min:0,max:100,...r.getState()};let o=!1;return i.currentValue<i.min&&(i.currentValue=i.min,o=!0),i.currentValue>i.max&&(i.currentValue=i.max,o=!0),o&&r.setState(i),r.nextWidget(Lt,{type:me.Number,value:i.currentValue})},getInputNames:()=>[{name:Rt.in,type:me.Anything}],getOutputNames:()=>[{name:Lt,type:me.Number}]};const Ut=Object.freeze({in:"in",reset:"reset"}),Bt="out",Wt="skipped";var Gt={onParentEvent:async(e,t,n,r)=>{const i={lastCalledAt:0,delayMs:500},o={lastCalledAt:0,delayMs:500,...r.getState()};if(t.name===Ut.reset)return r.setState({...o,lastCalledAt:0});const s=Date.now(),a=s-o.lastCalledAt;return o.lastCalledAt===i.lastCalledAt||a>=o.delayMs&&o.delayMs>0?(o.lastCalledAt=s,r.setState(o),r.nextWidget(Bt,n.data)):(n.data.type!==o.$$lastDetectedType&&(o.$$lastDetectedType=n.data.type),r.setState(o),r.nextWidget(Wt,n.data))},getInputNames:()=>[{name:Ut.in,type:me.Anything},{name:Ut.reset,type:me.Anything}],getOutputNames:e=>[{name:Bt,type:e.$$lastDetectedType??me.Anything},{name:Wt,type:e.$$lastDetectedType??me.Anything}]};const Vt="in";var Yt={onParentEvent:async()=>{},getInputNames:()=>[{name:Vt,type:[me.ImageData,me.Number]}],getOutputNames:()=>[]};const Ht=()=>({properties:[{label:"property1",name:"property1"}],detectedProperties:{}}),zt=(e,t)=>t.split(".").reduce(((e,t)=>null!=e?e[t]:e),e);var qt={onParentEvent:async(e,t,n,r)=>{const i={properties:[{label:"property1",name:"property1"}],detectedProperties:{},...r.getState()},o=n?.data?.value,s=Array.isArray(o);if(n.data.type===me.JsonObj||n.data.type===me.Rect||n.data.type===me.Point||n.data.type===me.BinaryFile||n.data.type===me.Anything||s){let e=!1;for(const t in o){const n=Be(o[t]),r=!!i.detectedProperties[t],s=i.detectedProperties[t]?.type!==n;if(!r||s){const r=n===me.JsonObj||n===me.Rect||n===me.Point||n===me.Array;i.detectedProperties[t]={type:n,...r?{shape:We(o[t])}:void 0},e=!0}}if(s&&void 0===i.detectedProperties.length&&(i.detectedProperties.length={type:me.Number}),e&&r.setState(i),o){const e=[];for(const t of i.properties||[]){const n=zt(o,t.label),s=t.label.includes(".");if(void 0!==n){const o=s?Be(n):void 0!==i.detectedProperties[t.label]?.type?i.detectedProperties[t.label].type:me.Anything;e.push(r.nextGate(t.name,{type:o,value:n}))}}await Promise.allSettled(e)}}},getInputNames:()=>[{name:"in",type:me.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:me.Anything,r=t.detectedProperties[e.label]?.shape||void 0,i="string"==typeof e;return{name:i?e:e.name,label:i?e:e.label,type:n,jsonShape:r}}))},getDefaultState:Ht};const Kt="output",Jt="noItem";var Zt={onParentEvent:async(e,t,n,r)=>{const i={index:0,...r.getState()};let o=i.index;const s=n.data.value,a="string"==typeof n.data.value,c=Array.isArray(n.data.value);if(n.data.type===me.Anything&&(c||a)||n.data.type===me.String&&a||n.data.type===me.Array&&c){o<0&&(o=s.length+o);const e=a?me.String:Be(s[o]);return e!==i.$$lastDetectedType&&r.setState({...i,$$lastDetectedType:e}),void 0!==s[o]?r.nextGate(Kt,{value:s[o],type:e}):r.nextGate(Jt,{value:!0,type:me.Boolean})}},getInputNames:()=>[{name:"in",type:[me.Array,me.String]}],getOutputNames:e=>[{name:Kt,type:e.$$lastDetectedType??me.Anything},{name:Jt,type:me.Boolean}]};const Xt={},Qt=e=>(Xt[e]||(Xt[e]={canvasFrom:Ee(320,240),canvasTo:Ee(320,240)}),Xt[e]),en=Object.freeze({image:"image",rect:"rect"}),tn="image";var nn={onParentEvent:async(e,t,n,r)=>{const i=Qt(r.id),o={offset:{height:0,left:0,top:0,width:0},...r.getState()},s=[me.Anything,me.Rect,me.JsonObj];if(t.name===en.rect&&Le(n.data.value)&&s.includes(n.data.type)&&(o.rect=n.data.value,r.setState({...o})),t.name===en.image){if(!((n.data.type===me.ImageData||n.data.type===me.Anything)&&Re(n.data.value)))throw new Error("Invalid image data. Expected a valid ImageData type");i.lastImage=n.data.value}if(i.lastImage&&o.rect){const e=((e,t,n,r,i)=>{if(r&&r.getContext){const o=r.getContext("2d"),s=n.getContext("2d");if(o&&s){n.width=e.width,n.height=e.height,s.putImageData(e,0,0);const a={...i};i&&(a.height=Number(i.height),a.width=Number(i.width),a.left=Number(i.left),a.top=Number(i.top));const c={top:0,width:0,left:0,height:0,...a};return i&&(Number.isInteger(c.width)||(c.width=t.width*c.width),Number.isInteger(c.height)||(c.height=t.height*c.height),Number.isInteger(c.left)||(c.left=t.left+t.width*c.left),Number.isInteger(c.top)||(c.top=t.top+t.height*c.top)),r.width=t.width+c.width,r.height=t.height+c.height,o.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),o.getImageData(0,0,r.width||1,r.height||1)}}return e})(i.lastImage,o.rect,i.canvasFrom,i.canvasTo,o.offset);r.setState({...o,rect:null}),i.lastImage=void 0,await r.nextWidget(tn,{type:me.ImageData,value:e})}},getInputNames:()=>[{name:en.image,type:me.ImageData},{name:en.rect,type:[me.Rect,me.JsonObj]}],getOutputNames:()=>[{name:tn,type:me.ImageData}],initialize:async e=>{Qt(e.widgetId)},terminate:async e=>{delete Xt[e.widgetId]}};const rn=(e,t)=>{const n=Math.round(Math.sqrt(t.length)),r=Math.floor(n/2),i=e.data,o=e.width,s=e.height,a=o,c=s,l=((e,t,n)=>{if(ee)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,h=4*(e*a+c);let f=0,p=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<s&&u>=0&&u<o){const r=4*(c*o+u),s=t[e*n+a];f+=i[r]*s,p+=i[r+1]*s,g+=i[r+2]*s,m+=i[r+3]*s}}u[h]=f,u[h+1]=p,u[h+2]=g,u[h+3]=m+1*(255-m)}return l},on=[-1,0,1,-2,0,2,1,0,1],sn=Object.freeze({image:"image"}),an="image";var cn={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),o={matrix:[...on],...i};if(n.data.type===me.ImageData||n.data.type===me.Anything&&Re(n.data.value)){const e=rn(n.data.value,o.matrix);return r.nextGate(an,{type:me.ImageData,value:e})}},getInputNames:()=>[{name:sn.image,type:me.ImageData}],getOutputNames:()=>[{name:an,type:me.ImageData}]};const ln=Object.freeze({output:"output",aborted:"aborted"}),un=()=>({inputs:2,matchingOutputs:!0,lastInputIndex:-1,delayMs:500,triggeredAt:0}),dn=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:me.Anything})));return n.push({name:"reset",type:me.Anything}),n};var hn={onParentEvent:async(e,t,n,r)=>{const i={inputs:2,matchingOutputs:!0,lastInputIndex:-1,delayMs:500,triggeredAt:0,...r.getState()};if("reset"===t.name)return r.setState({...i,triggeredAt:0});const o=Date.now(),s=o-i.triggeredAt;if(i.triggeredAt&&!(s>=i.delayMs&&i.delayMs>0)&&i.delayMs)return r.nextGate(ln.aborted,n.data);{i.triggeredAt=o;const e=dn(i,(r.recipePoolId,r.recipeType,r.thingRecipeId,r.id)).findIndex((e=>e.name===t.name));-1!==e&&(i.lastInputIndex=e),i.matchingOutputs?-1!==e&&await r.nextGate(`output${e+1}`,n.data):await r.nextGate(ln.output,n.data),r.setState(i)}},getInputNames:dn,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:me.Anything})));return e.push({name:ln.aborted,type:me.Anything}),e}return[{name:ln.output,type:me.Anything},{name:ln.aborted,type:me.Anything}]},getDefaultState:un};const fn=(e,t,n,r,i,o)=>{if(i){const s=e.measureText(i),a=s.fontBoundingBoxAscent+s.fontBoundingBoxDescent;e.fillStyle=r,e.fillRect(t,n-o,1.1*s.width,a),e.font=`${o}px Arial`,e.fillStyle="black",e.fillText(i,t,n)}},pn=(e,t,n,r,i,o,s)=>{e.fillStyle=i,e.fillRect(t,n,r,r),fn(e,t,n,i,o,s)},gn=(e,t,n,r,i,o)=>{e.beginPath(),e.strokeStyle=r,e.lineWidth=n,e.rect(t.left,t.top,t.width,t.height),e.stroke();const s=n/2;fn(e,t.left-s,t.top-s,r,i,o)},mn={},yn=e=>(mn[e]||(mn[e]={memCanvas:Ee(320,240),lastFrame:void 0,pixels:void 0}),mn[e]),vn=Object.freeze({image:"image",pixels:"pixels"}),bn="image";var wn={onParentEvent:async(e,t,n,r)=>{const i=yn(r.id),o={fontSize:12,color:"#00ff00",size:2,...r.getState()},s=(n.data.type===me.ImageData||n.data.type===me.Anything)&&Re(n.data.value);if(t.name===vn.pixels){const e=(e=>Fe(e)||Le(e)||Array.isArray(e)&&e[0]&&(Fe(e[0])||Le(e[0])))(n.data.value);if(!e)return;i.pixels=n.data.value}if(t.name===vn.image&&s){const e=n.data.value;i.lastFrame=e}if(i.lastFrame&&i.pixels&&i.memCanvas){const e=(e=>{const{sourceImage:t,pixels:n,memCanvas:r,size:i,color:o,labelProp:s,fontSize:a}=e;if(r){const e=Ce(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=s?n[s]:"";Le(n)?gn(e,n,i,o,r,a):Fe(n)&&pn(e,n.x,n.y,i,o,r,a)}return e.getImageData(0,0,r.width,r.height)}}return t})({sourceImage:i.lastFrame,pixels:i.pixels||[],memCanvas:i.memCanvas,size:o.size,color:o.color,labelProp:o.labelProp,fontSize:o.fontSize});return i.lastFrame=void 0,i.pixels=void 0,r.setState({...o}),r.nextWidget(bn,{type:me.ImageData,value:e})}r.setState(o)},getInputNames:()=>[{name:vn.image,type:me.ImageData},{name:vn.pixels,type:[me.Rect,me.Point,me.Array,me.JsonObj]}],getOutputNames:()=>[{name:bn,type:me.ImageData}],initialize:async e=>{yn(e.widgetId)},terminate:async e=>{delete mn[e.widgetId]}};const Sn=Object.freeze({in:"in"}),_n="output",In=e=>{const t=String(e).split(".");return t.length<2?0:t[1].length};var xn={onParentEvent:async(e,t,n,r)=>{const i={min:1,max:100,...r.getState()},o=!Number.isInteger(i.min),s=!Number.isInteger(i.max),a=o||s;let c=(l=i.min,u=i.max,Math.random()*(u-l)+l);var l,u;if(a){let e=0;if(o&&(e=In(i.min)),s){const t=In(i.max);t>e&&(e=t)}c=Number(c.toFixed(e))}else c=Math.floor(c);return r.nextGate(_n,{type:me.Number,value:c})},getInputNames:()=>[{name:Sn.in,type:me.Anything}],getOutputNames:()=>[{name:_n,type:me.Number}]};const kn=Object.freeze({output:"output",totalItems:"totalItems"}),En=Object.freeze({trigger:"trigger",clear:"clear"}),Cn=()=>({$$$time:0,totalSentItems:-1,totalSentAt:0,$$list:[],$$outputShape:{},totalInputs:1}),$n=async(e,t)=>t.nextGate(kn.totalItems,{type:me.Number,value:e});var On={onParentEvent:async(e,t,n,r)=>{const i={$$$time:0,totalSentItems:-1,totalSentAt:0,$$list:[],$$outputShape:{},totalInputs:1,...r.getState()};if(t.name===En.clear)return i.$$list=[],i.properties?.autoFilled&&delete i.properties,r.setState(i),$n(i.$$list.length,r);const o=t.name===En.trigger;if(!o)if(Array.isArray(n.data.value))n.data.type!==me.Array&&n.data.type!==me.Anything||(i.$$outputShape={...i.$$outputShape,...e?.jsonShape},i.$$list=i.$$list.concat(n.data.value),r.setState({...i}),await $n(i.$$list.length,r));else{const t=`$$primitive_${Object.keys(i.$$outputShape).length}`;n.data.type===me.JsonObj?i.$$outputShape={...i.$$outputShape,...e?.jsonShape?e.jsonShape:void 0}:i.$$outputShape={...i.$$outputShape,[t]:n.data.type},i.$$list.push(n.data.value),r.setState({...i}),await $n(i.$$list.length,r)}if(o){Object.keys(i.$$outputShape).length&&(i.properties={autoFilled:!0,jsonShape:{...i.$$outputShape}});const e=i.$$list.length,t=[...i.$$list];return i.$$list=[],r.setState({...i}),await $n(e,r),r.nextGate(kn.output,{type:me.Array,value:t})}},getInputNames:e=>{const t={$$$time:0,totalSentItems:-1,totalSentAt:0,$$list:[],$$outputShape:{},totalInputs:1,...e},n=Array(t.totalInputs||1).fill(0).map(((e,t)=>({name:`input${t+1}`,type:me.Anything})));return n.push({name:En.clear,type:me.Anything},{name:En.trigger,type:me.Anything}),n},getOutputNames:e=>[{name:kn.output,type:me.Array,...e.properties?{jsonShape:e.properties?.jsonShape}:void 0},{name:kn.totalItems,label:"Total Items",type:me.Number}],getDefaultState:Cn};const Nn=Object.freeze({start:"start",stop:"stop"}),Tn="output",An="clock_interrupt";var Mn={onParentEvent:async(e,t,n,r)=>{const i={enabled:!1,interval:1e3,intervalMode:"ms",...r.getState()};if(je(e?.name||"")&&t.name===An)return r.nextGate(Tn,{type:me.Boolean,value:!0});if(t.name===Nn.stop&&i.enabled&&i.$$interruptId){r.cancelInterrupt(i.$$interruptId)?(i.enabled=!1,i.$$interruptId=void 0,r.setState(i)):console.warn(`Failed to cancel interrupt [${i.$$interruptId}]`)}else t.name!==Nn.start||i.enabled||i.$$interruptId||(i.$$interruptId=r.registerInterrupt({type:"interval",sourceWidgetId:r.id,customTargetPortName:An,config:{interval:i.interval}}),i.enabled=!0,r.setState(i))},getInputNames:()=>[{name:Nn.start,type:me.Anything},{name:Nn.stop,type:me.Anything}],getOutputNames:()=>[{name:Tn,type:me.Boolean}],initialize:async e=>{const t=e.getState();if(t.enabled&&!t.$$interruptId){const n=e.registerInterrupt({type:"interval",sourceWidgetId:e.widgetId,customTargetPortName:An,config:{interval:t.interval}});e.setState({...t,$$interruptId:n})}}};const Pn=864e5;var Dn;!function(e){e.ABORTED="DELAY_ABORTED",e.CONTINUED="DELAY_CONTINUED",e.TERMINATED="WIDGET_TERMINATED"}(Dn||(Dn={}));const jn={},Rn=Object.freeze({in:"in",abort:"abort",continue:"continue"}),Ln="out",Fn=(e,t)=>{const n=e.getState();e.setState({...n,pendingDelaysCount:Math.max(0,n.pendingDelaysCount+t)})};var Un={onParentEvent:async(e,t,n,i)=>{const o={enabled:!1,interval:1e3,intervalMode:"ms",pendingDelaysCount:0,...i.getState()},s=i.id;jn[s]||(jn[s]=new Map);const a=jn[s];if(t.name!==Rn.abort)if(t.name!==Rn.continue){if(t.name===Rn.in){const e=o.interval;if(!((c=e)>=1&&c<=Pn))throw new Error(`Invalid interval: ${e}ms. Must be between 1ms and 86400000ms`);const t={...n.data},s=r();Fn(i,1);const l=new Promise(((n,r)=>{const o=setTimeout((()=>{n(t),a.delete(s),Fn(i,-1)}),e);a.set(s,{id:s,eventData:t,timeoutId:o,resolve:n,reject:r})}));try{const e=await l;return i.invokeNextWidget({port:Ln,data:e})}catch{Fn(i,-1)}}var c}else{const e=Array.from(a.entries());for(const[t,n]of e)clearTimeout(n.timeoutId),n.reject(new Error(Dn.CONTINUED)),a.delete(t);for(const[,t]of e)await i.invokeNextWidget({port:Ln,data:t.eventData});Fn(i,-i.getState().pendingDelaysCount)}else{for(const[e,t]of a)clearTimeout(t.timeoutId),t.reject(new Error(Dn.ABORTED)),a.delete(e);Fn(i,-i.getState().pendingDelaysCount)}},getInputNames:()=>[{name:Rn.in,type:me.Anything},{name:Rn.abort,type:me.Anything},{name:Rn.continue,type:me.Anything}],getOutputNames:()=>[{name:Ln,type:me.Anything}],initialize:async e=>{const t=e.getState();0!==t.pendingDelaysCount&&e.setState({...t,pendingDelaysCount:0})},terminate:async e=>{const t=e.widgetId;if(jn[t]){for(const[,e]of jn[t])clearTimeout(e.timeoutId),e.reject(new Error(Dn.TERMINATED));delete jn[t]}}};const Bn=Object.freeze({in:"in"}),Wn="output",Gn=(e,t,n)=>"number"==typeof e?Number((e*t).toFixed(n)):e;var Vn={onParentEvent:async(e,t,n,r)=>{const i={userProperties:[],factor:2,decimalPoints:2,...r.getState()},o=n.data.type;let s=n.data.value,a=!1;return e?.jsonShape&&(i.detectedInputJson={...i.detectedInputJson,...e?.jsonShape},a=!0),i.detectedInputType||(i.detectedInputType=o,a=!0),n.data.type===me.Array&&("number"==typeof n.data.value?.[0]?s=((e,t,n)=>{const r=(e||[]).map((e=>Gn(e,t,n)));return r})(n.data.value,i.factor,i.decimalPoints):"object"==typeof n.data.value?.[0]&&(s=((e,t,n,r)=>{const i=(e||[]).map((e=>{const i={...e};return Object.keys(i).forEach((e=>{r?.length&&!r?.includes(e)||(i[e]=Gn(i[e],t,n))})),i}));return i})(n.data.value,i.factor,i.decimalPoints,i.userProperties))),n.data.type===me.Number&&(s=Gn(n.data.value,i.factor,i.decimalPoints)),a&&r.setState(i),r.nextGate(Wn,{type:o,value:s})},getInputNames:()=>[{name:Bn.in,type:[me.Array,me.Number]}],getOutputNames:e=>[{name:Wn,type:e.detectedInputType||me.Number,jsonShape:e.detectedInputJson}]};const Yn={},Hn=Object.freeze({output:"output"}),zn=Object.freeze({trigger:"trigger"}),qn=()=>({useTriggerPort:!0,properties:[{name:"x",label:"x"},{name:"y",label:"y"}]}),Kn=(e,t)=>{const n={};Yn[t]=Yn[t]||{};for(let r=0;r<e.properties.length;r++){const i=Yn[t][e.properties[r].name];n[e.properties[r].label]=i}return n};var Jn={onParentEvent:async(e,t,n,r)=>{const i={useTriggerPort:!0,properties:[{name:"x",label:"x"},{name:"y",label:"y"}],...r.getState()};if(t.name===zn.trigger){const e=Kn(i,r.id);return r.nextWidget(Hn.output,{type:me.JsonObj,value:e})}const o=i.properties.findIndex((e=>e.name===t.name));if(-1!==o){const e=i.properties[o];if(Yn[r.id]=Yn[r.id]||{},Yn[r.id][e.name]=n.data.value,!i.useTriggerPort){const e=Kn(i,r.id);return r.nextWidget(Hn.output,{type:me.JsonObj,value:e})}}},getInputNames:e=>{const t={useTriggerPort:!0,properties:[{name:"x",label:"x"},{name:"y",label:"y"}],...e},n=t.properties.map((e=>({name:e.name,label:e.label,type:me.Anything})));return t.useTriggerPort&&n.push({name:zn.trigger,label:zn.trigger,type:me.Anything,triggerPort:!0}),n},getOutputNames:()=>[{name:Hn.output,label:Hn.output,type:me.JsonObj}],getDefaultState:qn,initialize:async e=>{Yn[e.widgetId]={}},terminate:async e=>{delete Yn[e.widgetId]}};const Zn=async e=>{const t=(e,t)=>e.split(t)[1];if(e.startsWith(Ae)){const n=t(e,Ae);return Ge("inner","input",n)}if(e.startsWith(De)){const n=t(e,De);return Ge("outer","output",n)}return null},Xn=()=>({canvasPosition:{x:0,y:0},canvasZoom:1,inputs:[{name:"input",type:[me.Anything],index:0}],outputs:[{name:"output",type:[me.Anything],index:0}],name:"Custom Widget 1",description:"",type:"custom"}),Qn=e=>{const t={...Xn(),...e},n=t.inputs.map(((e,t)=>({name:Ge("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:Ge("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 er={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),o={...Xn(),...i},s=Qn(o,(r.recipePoolId,r.recipeType,r.thingRecipeId,r.id));for(let e=0;e<s.length;e++){const i=s[e];if(t.name===i.name&&(i.type.includes(me.Anything)||i.type.includes(n.data.type))){const e=await Zn(t.name);e&&await r.nextWidget(e,{type:n.data.type,value:n.data.value})}}},getInputNames:Qn,getOutputNames:e=>{const t={...Xn(),...e},n=t.outputs.map(((e,t)=>({name:Ge("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:Ge("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:Xn};const tr=(e,t,n,r,i)=>{const o=4*(t*n.width+e),s=n.data[o],a=n.data[o+1],c=n.data[o+2];return Math.abs(s-r.r)<=i&&Math.abs(a-r.g)<=i&&Math.abs(c-r.b)<=i};var nr={image:{getPixelValueAtIndex:(e,t)=>{const n=e.data,r=n[t]||0,i=n[t+1]||0,o=n[t+2]||0;return{avr:(r+i+o)/3,r:r,g:i,b:o}},getBoundingBox:(e,t,n)=>{const r=e.width,i=e.height,o=new Set,s=Number(n.threshold||0),a=isNaN(s)?10:s,c=(n,s)=>{const c=[[n,s]];let l=n,u=n,d=s,h=s;for(;c.length>0;){const n=c.shift();if(!n)continue;const[s,f]=n;s<0||f<0||s>=r||f>=i||o.has(`${s},${f}`)||!tr(s,f,e,t,a||0)||(o.add(`${s},${f}`),l=Math.min(l,s),u=Math.max(u,s),d=Math.min(d,f),h=Math.max(h,f),c.push([s+1,f],[s-1,f],[s,f+1],[s,f-1]))}return{minX:l,maxX:u,minY:d,maxY:h}},l=[];for(let s=0;s<i;s+=4)for(let i=0;i<r;i+=4)if(!o.has(`${i},${s}`)&&tr(i,s,e,t,a)){const{minX:e,maxX:t,minY:r,maxY:o}=c(i,s),a=t-e,u=o-r;if(a>=(n.minWidth||1)&&u>=(n.minHeight||1)&&l.push({left:e,top:r,width:a,height:u}),n.maxBoxes&&l.length>=n.maxBoxes)return l}return l},copyImageData:e=>new ImageData(new Uint8ClampedArray(e.data),e.width,e.height),setPixelValueAtIndex:(e,t,n)=>{const r=e.data,i="object"==typeof n,o=i?n.r:n,s=i?n.g:n,a=i?n.b:n;r[t]=o,r[t+1]=s,r[t+2]=a,r[t+3]=255}}};const rr=e=>Be(e),ir=s.enum(["Read","Modify","Comment"]),or=s.object({email:s.email(),name:s.string(),accessMode:ir});var sr;!function(e){e.Seats="seats",e.RecipeInvocations="recipe_invocations",e.HubServices="hub_services",e.RecipeExports="recipe_exports",e.RecipeHistory="recipe_history",e.AssistedCodeGeneration="assisted_code_generation",e.CustomServices="custom_services",e.OnDeviceSecretManagement="on_device_secret_management",e.PrivateRecipes="private_recipes",e.InBrowserRecipeExecution="in_browser_recipe_execution",e.EventLoggerLogsRetention="event_logger_logs_retention",e.AgenticExecutions="agentic_executions",e.PrivateSnippets="private_snippets",e.SnippetHistory="snippet_history",e.LogHistoryRetentionDays="log_history_retention_days",e.LogHistoryMonthlyEvents="log_history_monthly_events",e.FileStorageRetentionHours="file_storage_retention_hours",e.FileStorageSizeMB="file_storage_size_mb",e.PrivateWidgets="private_widgets",e.WidgetHistory="widget_history"}(sr||(sr={}));const ar=s.enum(["active","inactive"]),cr=s.enum(["Owner","Admin","Member"]),lr=s.object({apiKey:s.string(),createdAt:s.string(),createdBy:s.string()}),ur=s.object({country:s.string(),city:s.string(),address1:s.string(),address2:s.string(),postCode:s.string()}),dr=s.object({id:s.string(),name:s.string(),groups:s.array(s.string()),logo:s.string().optional(),industry:s.string().optional(),accountOwner:s.string(),stripeCustomerId:s.string(),stripeSubscription:s.custom(),apiKeys:s.array(lr).optional(),domain:s.string().optional(),createdAt:s.string(),updatedAt:s.string(),accountState:s.custom(),location:ur.optional()}),hr=s.object({id:s.string(),firstName:s.string(),lastName:s.string(),email:s.email().optional(),loginId:s.string().optional(),role:cr,groups:s.array(s.string()).optional().default([]),status:ar,lastSeenAt:s.string().optional(),createdAt:s.string()});var fr,pr,gr,mr;dr.pick({id:!0,name:!0,stripeSubscription:!0,stripeCustomerId:!0}),s.object({member:s.object({firstName:s.string().optional(),lastName:s.string().optional(),email:s.string().optional(),role:cr.optional(),groups:s.array(s.string()).optional(),status:ar})}),hr.omit({id:!0,createdAt:!0,lastSeenAt:!0}),s.object({name:s.string(),location:ur.optional()}),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"}(fr||(fr={})),function(e){e.Hardware="hardware",e.Virtual="virtual"}(pr||(pr={})),function(e){e.Cloud="cloud",e.Web="web"}(gr||(gr={})),function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(mr||(mr={}));const yr=s.object({name:s.string(),category:s.string(),id:s.string(),type:s.enum(gr),version:s.string()}),vr=s.object({version:s.number(),contents:s.string(),contentsLength:s.number(),createdAt:s.string(),comments:s.string().optional()}),br=s.object({id:s.string(),name:s.string(),uuid:s.string().optional(),version:s.number(),dataSources:s.array(s.object({host:s.string().optional(),stream:s.string(),blocks:s.array(s.string())})).optional(),protocolVersion:s.string(),linkedTutorial:s.string().optional(),blocks:s.array(yr),widgets:s.array(s.object({type:s.string(),name:s.string(),thingId:s.string()})).optional(),contents:s.string(),storage:s.string().optional(),history:s.array(vr).optional(),cloud:s.object({environment:s.enum(fr),enabled:s.boolean()}).optional()}),wr=s.object({recipeId:s.string(),version:s.number()});br.extend({userId:s.string(),author:s.object({name:s.string(),id:s.string()}),copiedFrom:wr.optional(),updatedAt:s.string(),createdAt:s.string(),preview:s.string(),isPublic:s.boolean(),isDefault:s.boolean(),meta:s.object({contentsLength:s.number(),storageLength:s.number(),storageChecksum:s.string().optional()}),sharedWith:s.array(or),publicSharedId:s.string().optional(),marketplacePublication:s.string().optional()});const Sr=br.omit({id:!0,version:!0,contents:!0,storage:!0});var _r,Ir,xr,kr,Er,Cr,$r,Or;s.object({rawContents:s.string(),recipe:Sr.extend({contentLength:s.number(),copiedFrom:wr.optional()}),storageSize:s.number().optional(),storageChecksum:s.string().optional(),comments:s.string().optional(),currentVersion:s.number().optional()}),s.object({message:s.string(),recipeId:s.string(),version:s.number(),versionHistory:s.array(vr)}),function(e){e.Bundle="bundle",e.Group="group"}(_r||(_r={})),function(e){e.Gateway="gateway",e.Timer="timer"}(Ir||(Ir={})),function(e){e.InstallInProgress="installation-in-progress"}(xr||(xr={})),function(e){e.InstallDependencies="install-dependencies",e.GetInstalledDependencies="get-installed-dep"}(kr||(kr={})),function(e){e.Success="success",e.Error="error",e.Pending="pending"}(Er||(Er={})),function(e){e.NotFound="not-found",e.BadRequest="bad-request",e.Forbidden="forbidden",e.InternalError="internal-error"}(Cr||(Cr={})),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",e.IsCustomTier="is_custom_tier"}($r||($r={})),function(e){e.KeyCreated="key_created",e.ValidateKey="validate_key",e.ExecuteRecipe="execute_recipe",e.InstallHubService="install_hub_service",e.UninstallHubService="uninstall_hub_service",e.ExportRecipe="export_recipe"}(Or||(Or={}));const Nr=s.object({id:s.string(),name:s.string(),organizationId:s.string()}),Tr=s.object({version:s.number(),contents:s.string(),contentsLength:s.number(),createdAt:s.string(),title:s.string(),shortDescription:s.string(),comments:s.string().optional()}),Ar=s.object({id:s.string(),title:s.string(),author:Nr,shortDescription:s.string(),authorId:s.string(),category:s.string(),tags:s.array(s.string()),createdAt:s.string(),downloads:s.number().default(0),updatedAt:s.string(),iconSvg:s.string(),contents:s.string(),descriptionMarkdown:s.string(),githubUrl:s.string().optional(),visibility:s.enum(["public","private","organization"]),version:s.number(),history:s.array(Tr).default([]),deletedAt:s.string().optional()}),Mr=Ar.extend({rating:s.object({average:s.number(),total:s.number()}).optional()});s.object({id:s.string(),author:s.object({id:s.string(),name:s.string()}).optional(),description:s.string(),createdAt:s.string(),updatedAt:s.string(),snippetId:s.string(),deletedAt:s.string().optional(),isAbuseReport:s.boolean().optional(),reportReason:s.enum(["spam","inappropriate","not-working","security","other"]).optional()}),s.object({query:s.string().optional(),category:s.string().optional(),featured:s.boolean().optional(),recommended:s.boolean().optional(),sortBy:s.enum(["most_recent","most_liked","alphabetical"]).optional(),visibility:s.enum(["public","private","organization"]).optional(),page:s.number().optional(),limit:s.number().optional()}),s.object({snippets:s.array(Mr),total:s.number(),page:s.number(),limit:s.number(),hasMore:s.boolean()}),s.object({snippetId:s.string(),rating:s.number(),off:s.boolean().optional()}),s.object({average:s.number(),total:s.number()}),s.object({success:s.boolean(),error:s.string().optional()}),s.object({snippet:s.lazy((()=>s.object({title:s.string(),shortDescription:s.string(),category:s.string(),tags:s.array(s.string()),iconSvg:s.string(),contents:s.string(),descriptionMarkdown:s.string(),githubUrl:s.string().optional(),visibility:s.enum(["public","private","organization"]),deletedAt:s.string().optional()})))}),s.object({snippet:s.lazy((()=>s.object({title:s.string(),shortDescription:s.string(),category:s.string(),tags:s.array(s.string()),iconSvg:s.string(),contents:s.string(),descriptionMarkdown:s.string(),githubUrl:s.string().optional(),visibility:s.enum(["public","private","organization"])})))}),s.object({snippet:Ar}),s.object({snippet:Ar}),s.object({snippetId:s.string(),version:s.number()}),s.object({snippet:Ar});let Pr=null;var Dr=()=>{if(!Pr)throw new Error("Required function is not set");return Pr};class jr extends Error{targetWidgetId;targetPortName;sourcePortName;sourceWidgetId;targetWidgetType;sourceWidgetType;constructor(e,t){super(e),this.name="ChildWidgetError",t.stack&&(this.stack=t.stack),this.targetWidgetId=t.targetWidgetId,this.targetPortName=t.targetPortName,this.sourcePortName=t.sourcePortName,this.sourceWidgetId=t.sourceWidgetId,this.targetWidgetType=t.targetWidgetType,this.sourceWidgetType=t.sourceWidgetType}}class Rr extends Error{constructor(e,t){super(e),this.name="UserCodeError",t&&(this.stack=t)}}const Lr=(e,t)=>`\n\t\tfunction _user_code_(){\n\t\t\t${t===mr.Browser?"\n\t\t\tvar global = {\n\t\t\t\t__user_code: true\n\t\t\t};\n\t\t\tvar process = {};\n\t\t\tvar globalThis = global;\n\t\t\tvar require = this.___notSupportedMethod;\n\t\t\t":"\n\t\t\tvar require = this.require;\n\t\t\tvar process = this.kemuProcess;\n\t\t\t"}\n\t\t\t\n\t\t\tvar console = this.console;\n\t\t\tvar eval = () => {};\n\t\t\tvar document = {};\n\t\t\tvar navigator = {};\n\t\t\tvar window = this.window;\n\t\t\tvar alert = this.notify.info;\n\t\t\tvar DataType = this.dataTypesEnum;\n\t\t\tvar setInterval = this.setInterval;\n\t\t\tvar setTimeout = this.setTimeout;\n\t\t\tvar addEventListener = this.addEventListener;\n\t\t\tvar removeEventListener = this.removeEventListener;\n\t\t\tvar requestAnimationFrame = this.___notSupportedMethod;\n\t\t\tvar __delay = (ms) => new Promise((resolve, reject) => setTimeout(resolve, ms, reject));\n\t\t\tvar sendToPort;\n\t\t\t// Updated function to send data to the next widget using new object syntax\n\t\t\tvar setOutput;\n\n\t\t\tvar Kemu = {\n\t\t\t\timage: this.imageHelpers,\n\t\t\t\tvariable: this.variablesManager,\n\t\t\t\tstatus: this.statusManager,\n\t\t\t\tsecrets: this.secretsManager,\n\t\t\t\tglobalVars: this.globalVariablesManager,\n\t\t\t\thelpers: {\n\t\t\t\t\tdecodeDataType: this.decodeDataType,\n\t\t\t\t\tcryptoJS: this.CryptoJS,\n\t\t\t\t\thttp: this.http,\n\t\t\t\t\tdelay: __delay,\n\t\t\t\t}\n\t\t\t};\n\n\t\t\t\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\tlet userProcessEvent = typeof processEvent === 'undefined' ? undefined : processEvent;\n\t\t\t\tlet userOnParentEvent = typeof onParentEvent === 'undefined' ? undefined : onParentEvent;\n\t\t\t\t\n\n\t\t\t\tif(userProcessEvent || userOnParentEvent) {\n\t\t\t\t\ttry{\n\t\t\t\t\t\tif(userProcessEvent) {\n\t\t\t\t\t\t\treturn await userProcessEvent(targetPort, sourcePort, event);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\treturn await userOnParentEvent({ targetPort, sourcePort, event });\n\t\t\t\t\t\t}\n\t\t\t\t\t}catch(e){\n\t\t\t\t\t\tthis.__errorTracer(e);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/** invoked the very first time the recipe is initialized */\n\t\t\tconst asyncRecipeInit = async (context) => {\n\t\t\t\ttry {\n\t\t\t\t\tif(typeof recipeInit === 'function') {\n\t\t\t\t\t\treturn recipeInit(context);\n\t\t\t\t\t}\n\t\t\t\t}catch(e){\n\t\t\t\t\tthis.__errorTracer(e);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/** invoked every time the code is about to be replaced */\n\t\t\tconst asyncOnTerminate = async (context) => {\n\t\t\t\ttry {\n\t\t\t\t\tif(typeof onTerminate === 'function') {\n\t\t\t\t\t\treturn onTerminate(context);\n\t\t\t\t\t}\n\t\t\t\t}catch(e){\n\t\t\t\t\tthis.__errorTracer(e);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/** updates the function that allows widget contexts to send data to the next widget */\n\t\t\tconst setSendToPort = (sendNextFun) => {\n\t\t\t\tsendToPort = sendNextFun;\n\t\t\t}\n\n\t\t\t/** updates the function that allows widget contexts to send data to the next widget with the new object argument syntax */\n\t\t\tconst setSetOutputFn = (setOutputFn) => {\n\t\t\t\tsetOutput = setOutputFn;\n\t\t\t}\n\n\t\t\t/** invoked the every time the user code is compiled. */\n\t\t\tconst asyncMainEvent = async (sendNextFun) => {\n\t\t\t\ttry{\n\t\t\t\t\t// setSendToPort(sendNextFun);\n\t\t\t\t\tif(typeof main === 'function'){\n\t\t\t\t\t\treturn main();\n\t\t\t\t\t}\n\t\t\t\t}catch(e){\n\t\t\t\t\tthis.__errorTracer(e);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tasyncProcessEvent: asyncProcessEvent,\n\t\t\t\tmain: asyncMainEvent,\n\t\t\t\trecipeInit: asyncRecipeInit,\n\t\t\t\tsetSendToPortFun: setSendToPort,\n\t\t\t\tsetSetOutputFn: setSetOutputFn,\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`,Fr=(e,t,n,r)=>{const i=Lr(e,n),s={...t,document:{},__errorTracer:e=>{if(e instanceof jr)throw e;throw new Rr(e.message,e.stack)},__jest:void 0===globalThis.__jest?void 0:globalThis.__jest,___notSupportedMethod:()=>r?.error("This method is not supported."),console:{...t.logger},setInterval:()=>r?.error("'setInterval' is not supported. Please use a \"Timer\" widget instead."),setTimeout:t?.setTimeout,imageHelpers:nr.image,...n===mr.Cloud?{require:Dr(),kemuProcess:process.env.KEMU_PROCESS?process.env.KEMU_PROCESS:{}}:{},CryptoJS:o,decodeDataType:rr,window:{addEventListener:t?.addEventListener,removeEventListener:t?.removeEventListener}};try{const e="browser"===(()=>{if(ee)return"browser";if(ne)return"node";if(te)return"worker";throw new Error("Unsupported environment")})()?(e=>e.replace(/[//]{2}[ ]*@kemu-cloud[ \t]*\{[\s\S]*?[//]{2}[ ]*@kemu-cloud[ \t]*\}/gim,""))(i):(e=>e.replace(/[//]{2}[ ]*@kemu-browser[ \t]*\{[\s\S]*?[//]{2}[ ]*@kemu-browser[ \t]*\}/gim,""))(i),t=new Function(e);return{compiledModule:t()(s)}}catch(e){return{error:{name:"CompileError",message:e.message,stack:e.stack}}}},Ur="main",Br="My Script",Wr="This is a test script.",Gr=`\n/**\n * Name: ${Br}\n * Description: ${Wr}\n */\n\nconst getWidgetInputs = () => [\n\t{ name: 'Input 1', type: DataType.Number }\n];\n\nconst getWidgetOutputs = () => [\n\t{ name: 'Output 1', type: DataType.Number }\n]\n\nlet counter = 0;\n\nconst onParentEvent = async ({ targetPort, sourceWidget, event }) => {\n\tif(targetPort.name === 'Input 1'){\n\t\treturn setOutput({\n\t\t\tport: 'Output 1',\n\t\t\tdata: {\n\t\t\t\ttype: DataType.Number,\n\t\t\t\tvalue: counter++,\n\t\t\t}\n\t\t});\n\t}\n}\n`.trim(),Vr=()=>({pauseExecution:!1,autoPauseOnError:!0,$$eventListeners:{},version:2,metadata:{name:Br,description:Wr},pages:{[Ur]:{code:Gr,language:"javascript",name:"My First Script"}}}),Yr=(e,t)=>{const n={message:"Unknown Error"};if(e?.stack){const r=e?.stack?.split(":")[0].trim();n.type=r;const i=(e=>{const t=/,[ ]?<anonymous>:([0-9]+:[0-9]+)\)/gm;let n;for(;null!==(n=t.exec(e));){n.index===t.lastIndex&&t.lastIndex++;const e=n[1].split(":");if(2===e.length)return{line:Number(e[0])||0,column:Number(e[1])||0}}return null})(e.stack);i&&(n.line=i.line-(e=>{const t="___user_code_section___";return Lr(t,e).split(t)[0].split("\n").length+2})(t),n.column=i.column)}return e.message&&(n.message=e.message),n},Hr=(e,t)=>{const n={...{...Vr(),...t.getState()},$$error:e||void 0};e&&console.error(e.message),t.setState(n)},zr=new a;let qr,Kr,Jr={},Zr={};const Xr=e=>{const t=le(qr,Kr,e);if(!t)throw new Error(`Widget ${e} not found in thing ${Kr}`);return t},Qr=(e,t)=>`${e}:${t}`,ei=e=>`${Xr(e.createdByWidgetId).id}::${e.variableName}`,ti=e=>`${fe}${e}`;var ni=e=>{const t=Xr(e.createdByWidgetId),n=ei({variableName:e.variableName,createdByWidgetId:e.createdByWidgetId});Zr[n]={type:e.type,subscriberWidgetId:t.id,subscriberWidgetType:t.type}},ri=e=>{const t=ei({variableName:e.variableName,createdByWidgetId:e.createdByWidgetId});delete Zr[t]},ii=async e=>{const t=Xr(e.setByWidgetId);if(!t)throw new Error(`Widget ${e.setByWidgetId} not found in thing ${Kr} in recipe ${qr}`);const n=e.variableName.startsWith(fe)?ei({variableName:e.variableName,createdByWidgetId:e.setByWidgetId}):e.variableName;Jr[n]={value:e.value,type:e.type};const r={value:e.value,type:e.type,varName:e.variableName,isUIElement:e.variableName.startsWith(fe),setByWidgetType:t.type,setByWidgetId:e.setByWidgetId};await zr.emit(Qr(e.variableName,e.type),r),e.type!==me.Anything&&await zr.emit(Qr(e.variableName,me.Anything),r)},oi=e=>{const{readerWidgetId:t,variableName:n}=e;if(!Xr(t))throw new Error(`Widget ${t} not found in thing ${Kr} in recipe ${qr}`);const r=n.startsWith(fe)?ei({variableName:e.variableName,createdByWidgetId:e.readerWidgetId}):n,i=Jr[r];if(i)return{type:i.type,value:i.value}},si=e=>{const{widgetId:t,variableName:n,type:r}=e;if(!Xr(t))throw new Error(`Widget ${t} not found in thing ${Kr} in recipe ${qr}`);const i=Qr(n,r);let o;return o=zr.on(i,(async r=>{le(qr,Kr,t)?await e.onValueChange(r):(console.warn(`Zombie widget ${t} detected, unsubscribing from variable events "${n}"`),o?.())})),o},ai=e=>{Zr={},Jr={},qr=e.recipePoolId,Kr=e.thingId};const ci="setTimeout",li="variableChanged",ui="globalVariableChanged",di=e=>{const{recipePoolId:t,thingId:n,scriptWidgetId:r}=e,i=le(t,n,r);if(!i)throw new Error(`Widget "${r}" not found in recipe "${t}"`);const o=(e,t)=>{const n=oi({readerWidgetId:r,variableName:e});if(n||t)return void 0===n?{value:t?.value??t,type:t?.type??Be(t)}:{value:n.value,type:n.type}},s=(t,n,o)=>{if(!e.setState)return void console.warn("Cannot subscribe to variable changes without a setState function");const s={...Vr(),...e.getState()},a=si({variableName:t,type:me.Anything,widgetId:r,onValueChange:async e=>{n?e.setByWidgetType===Ke.widgetGroup&&e.setByWidgetId===i.groupId&&await o(e):o(e)}});delete s.$$eventListeners[t],s.$$eventListeners[t]={handler:o,abort:async()=>{a()},name:li},e.setState(s)};return{get:o,set:async(e,t,n)=>{await ii({variableName:e,type:n||Be(t),setByWidgetId:r,value:t})},onValueChange:(e,t)=>{s(e,!1,t)},onUIValueChange:(e,t)=>{const n=ti(e);s(n,!0,t)},getUIValue:e=>{const r=ti(e),s=o(r);if(s)return{value:s.value,type:s.type};const a=i.groupId;if(!a)throw new Error("You can only read UI variables from inside a widgetGroup");const c=le(t,n,a);if(!c)throw new Error(`Widget "${a}" not found in recipe "${t}"`);const l=c.state,u=(l.settings||[]).find((t=>t.variableName===e));if(!u)throw new Error(`Field "${e}" not found in widgetGroup "${l.name}"`);const d=u.config,h=d.customValue??d.defaultValue;if(void 0===h)throw new Error(`Field "${e}" in widgetGroup "${l.name}" has no default value`);return{value:h,type:Be(h)}}}};let hi;var fi=e=>{hi=e},pi=()=>{if(!hi)throw new Error("Hub Connector not set");return hi};const gi=new a,mi="invoked";let yi={},vi={},bi={},wi={};const Si=(e,t,n)=>`${e}-${t}${n?`-${n}`:""}`;var _i=e=>{const{data:t,thingId:n,widgetId:r,sourcePortName:i,recipeId:o,target:s,sourceOutputNames:a,currentPath:c,eventId:l}=e,u=Si(n,r,i),d=Si(n,r),h=Si(n,r,"produced"),f=bi[d],p=Date.now();wi[d]=p,yi[u]={data:t,recipeId:o,currentPath:c,eventId:l,source:{widgetId:r,portName:i},sourceOutputNames:a,...s?{target:{widgetId:s.widgetId,portName:s.portName}}:{}},gi.emit(h,{currentTime:p,prevTime:f,...s?{targetPort:s?.portName}:{}})},Ii=e=>{const{thingId:t,widgetId:n,targetPortName:r,data:i,source:o,originalEvent:s,recipeId:a,sourceOutputNames:c,currentPath:l,eventId:u}=e,d=Si(t,n,r),h=Si(t,n),f=Si(t,n,mi),p=bi[h],g=Date.now();bi[h]=g,vi[d]={data:i,recipeId:a,originalEvent:s,sourceOutputNames:c,currentPath:l,eventId:u,target:{widgetId:n,portName:r},...o?{source:{widgetId:o.widgetId,portName:o.portName}}:{}},gi.emit(f,{prevTime:p,currentTime:g,targetPort:r,sourceInfo:o})},xi=()=>{yi={},vi={},bi={},wi={},gi.clearListeners()};const ki=e=>{const{recipePoolId:t,widgetId:n,secrets:r,clearExistingSecrets:i}=e,o=ce({recipeId:t,widgetId:n});if(!o)throw new Error(`Widget [${n}] not found in recipe [${t}]`);i&&(o.secrets={});for(const e of r)o.secrets={...o.secrets,[e.name]:e}},Ei=e=>{const{recipePoolId:t,widgetId:n}=e,r=ce({recipeId:t,widgetId:n});if(!r)throw new Error(`Widget [${n}] not found in recipe [${t}]`);delete r.secrets},Ci={},$i="value",Oi=async e=>{const{recipeUuid:t,secretNames:n,serviceName:r}=e,i=pi(),o=[{recipeUuid:t,secretNames:n,serviceName:r}];let s={};try{const e=await i.executeHubFunction(we.GetRecipeDecryptedSecretsValues,o);e&&(s=e[0].secrets)}catch(e){if("FNC_NOT_FOUND"===e.errCode)throw new Error("Your Hub does not support dynamic secrets. Please update your Hub to the latest version.");throw new Error(`Failed to read secret "${n.join(", ")}" from Hub: ${e.message}`)}return s},Ni=e=>{const t=se(e);if(!t)throw new Error(`Recipe [${e}] does not exist]`);return{uuid:t.uuid,recipeType:t.dbInfo?.recipeType}};var Ti={onParentEvent:async(e,t,n,r)=>{const i={name:"",...r.getState()};if(!i.name||!e)return;const{uuid:o}=Ni(r.recipePoolId);if(!o)throw new Error(`Recipe [${o}] does not have a valid id]`);const s=r.recipeType===ge.Desktop,a=Ci[r.id]?.[i.name];let c=a;if(!a||a&&!s){const e=await Oi({recipeUuid:o,secretNames:[i.name]});c=e?.[i.name],null!=c&&s&&(Ci[r.id]||(Ci[r.id]={}),Ci[r.id][i.name]=c)}if(null==c)throw new Error(`Secret "${i.name}" not mapped to this recipe`);r.nextWidget($i,{type:me.String,value:c})},getOutputNames:()=>[{name:$i,type:me.String}],getInputNames:()=>[{name:"read",type:me.Anything}],terminate:async e=>{Ci[e.widgetId]={},Ei({recipePoolId:e.recipePoolId,widgetId:e.widgetId})},initialize:async e=>{const t={name:"",...e.getState()};t.name&&(Ci[e.widgetId]={},ki({recipePoolId:e.recipePoolId,widgetId:e.widgetId,secrets:[{name:t.name}]}))}};const Ai={},Mi=e=>{const{recipePoolId:t,thingId:n,scriptWidgetId:r}=e,i=se(t),o=i?.dbInfo.recipeType,s=Ni(t).uuid,a=le(t,n,r);return{secretsManager:{requestAccess:e=>{a&&(a.secrets={...a.secrets,[e]:{name:e}})},read:async e=>{if(!a)return e.reduce(((e,t)=>(e[t]=null,e)),{});const t=o===ge.Desktop,n={};let i=[];for(const t of e){const e=Ai[r]?.[t];null==e&&i.push(t)}if(t||(i=e),i.length>0){const t=await Oi({recipeUuid:s,secretNames:i});for(const i of e){const e=t?.[i],o=Ai[r]?.[i];n[i]=void 0!==e?e:void 0!==o?o:null}Ai[r]={...Ai[r],...n}}else for(const t of e)n[t]=Ai[r]?.[t]||null;return n}},unregisteredSecrets:()=>{a&&(a.secrets={})}}},Pi=new a;let Di={};const ji="statusValueChanged",Ri="keyRemovedFromWidget",Li=()=>{Di={}},Fi=()=>{Pi.clearListeners()},Ui=e=>{Pi.emit(ji,e)};var Bi=e=>{const{name:t,value:n,sourceWidget:r,widgetId:i,widgetType:o}=e;Di[i]=Di[i]||[];const s=Di[i].find((e=>e.name===t&&e.widgetType===o&&e.widgetId===i));s?s.data=n:Di[i].push({name:t,data:n,sourceWidget:r,widgetId:i,widgetType:o});let a=n;null===n&&(a={type:me.Anything,value:""}),Ui({name:t,value:a,sourceWidget:r,statusWidgetId:i,widgetType:o})},Wi=e=>Pi.on(ji,e),Gi=()=>{Li(),Fi()},Vi=e=>{const t=()=>{const e=[];for(const t in Di)for(const n of Di[t])e.push(n.name);return e},n=t();delete Di[e];(e=>{Pi.emit(Ri,e)})({before:n,after:t()})};const Yi=e=>{const{scriptWidgetId:t}=e;return{statusManager:{set:(e,n)=>{let r=null;r=n&&"object"==typeof n&&"value"in n&&"type"in n||null==n||void 0===n?n:{type:Be(n),value:n},Bi({name:e,sourceWidget:t,widgetId:t,value:r,widgetType:Ke.script})}},clearStatusValues:()=>{Vi(t)}}},Hi=new a,zi=e=>{if(e.includes("."))throw new Error("Variable and group names cannot contain dots")},qi=(e,t)=>{if(!t)throw new Error("name is required");return zi(t),e?`${e}.${t}`:t},Ki=e=>{if(!e)throw new Error("fullPath is required");const t=e.lastIndexOf(".");if(-1===t)return{group:null,name:e};return{group:e.substring(0,t),name:e.substring(t+1)}},Ji=e=>`globalVariableChange_${e}`,Zi=e=>`globalVariableGroupChange_${e}`,Xi=e=>`globalVariableParentGroupStateChange_${e}`,Qi=e=>`globalVariableRenamed_${e}`;let eo={};const to=e=>{const{name:t,notify:n=!0}=e,r=ro(t);if(!r)return;if("group"===r.controlType){const e=oo().filter((e=>!!e.group&&(e.group===t||e.group.startsWith(t+"."))));for(const t of e)to({name:t.name,notify:n})}n&&Hi.emit("globalVariableRemoved",r),delete eo[t]},no=()=>{for(const e in eo)to({name:e,notify:!0})},ro=e=>{let t;t="string"==typeof e?e:qi(e.group,e.name);return eo[t]??null},io=async e=>{const{value:t,lastDataType:n,controlType:r,widgetId:i,doNotOverrideExisting:o=!1,executionContext:s,helpText:a,order:c,forceValueChangeNotification:l=!1,disableChangeNotifications:u=!1,disableDefineNotifications:d=!1,group:h}=e;let{controlSettings:f,name:p}=e;if(!p)throw new Error("name is required");zi(p),p=p.replace(/-/g,"_");const g=qi(h??null,p);let m=ro(g);const y=!m,v=!!m;if(y)m={},f||(f=(e=>{switch(e){case"number":case"slider":return{min:0,max:100,step:1};case"dropdown":case"multiSelect":return{options:[]};case"binaryFile":return{allowedMimeTypes:[]};default:return{}}})(r??"anything"));else if(o)return;const b=n??(t?Be(t):null),w=t!==m.lastValue,S=h!==m.group&&void 0!==h,_=c!==m.order&&void 0!==c;m.lastDataType=b,m.lastValue=t,m.controlType=r??m.controlType??"anything",m.lastChangedByWidgetId=i??null,m.lastExecutionContext=s??null,m.helpText=a??m.helpText,m.controlSettings=f??m.controlSettings,m.name=g,m.order=c??m.order,m.group=void 0!==h?h:m.group,eo[g]=m,u||null!==t&&(w||l)&&(await Hi.emit(Ji(g),m),await Hi.emit("globalVariableChange_any",m)),v&&(S||_)&&await Hi.emit(Zi(g),m),y&&!d&&await Hi.emit("globalVariableDefined",m)},oo=()=>Object.values(eo),so=e=>oo().filter((t=>!!t.group&&(t.group===e||t.group.startsWith(e+".")))),ao={resetAllGlobalVariables:no,getGlobalVariable:ro,setGlobalVariable:io,onGlobalVariableChange:(e,t)=>Hi.on(Ji(e),t),onGlobalVariableParentGroupChange:(e,t)=>Hi.on(Zi(e),t),onVarParentGroupStateChange:(e,t)=>Hi.on(Xi(e),t),notifyGroupMembersOfParentGroupChange:async e=>{const t=so(e),n=ro(e);if(n)for(const e of t)await Hi.emit(Xi(e.name),{variable:e,parentGroup:n})},deleteGlobalVariable:to,onGlobalVariableDefined:e=>Hi.on("globalVariableDefined",e),onGlobalVariableRemoved:e=>Hi.on("globalVariableRemoved",e),onGlobalVariableRenamed:(e,t)=>Hi.on(Qi(e),t),onAnyGlobalVariableChange:e=>Hi.on("globalVariableChange_any",e),getAllVariables:oo,renameVariable:e=>{const{oldName:t,newName:n}=e,r=ro(t);if(!r)throw new Error("Global variable not found");zi(n);const i="group"===r.controlType,{group:o}=Ki(t),s=qi(o,n);if(i){const e=oo().filter((e=>!!e.group&&(e.group===t||e.group.startsWith(t+"."))));for(const n of e){const{group:e,name:r}=Ki(n.name);let i=null;e&&(i=e===t?s:e.startsWith(t+".")?s+e.substring(t.length):e),io({name:r,value:n.lastValue,lastDataType:n.lastDataType??null,controlType:n.controlType,controlSettings:n.controlSettings,widgetId:n.lastChangedByWidgetId??void 0,executionContext:n.lastExecutionContext??void 0,helpText:n.helpText??void 0,order:n.order??void 0,group:i,disableChangeNotifications:!0,disableDefineNotifications:!0})}}to({name:t,notify:!1}),io({name:n,controlSettings:r.controlSettings,value:r.lastValue,lastDataType:r.lastDataType??null,controlType:r.controlType,widgetId:r.lastChangedByWidgetId??void 0,executionContext:r.lastExecutionContext??void 0,helpText:r.helpText??void 0,order:r.order??void 0,group:o}),Hi.emit(Qi(t),{oldName:t,newName:s})},registerGlobalVariables:e=>{no(),eo={};const t=e.map((e=>{if(!e.name.includes(".")){if(e.group){const t=qi(e.group,e.name);return{...e,name:t}}return e}const{name:t}=Ki(e.name);if(t.includes("."))throw new Error(`Invalid variable name: "${e.name}" - display names cannot contain dots`);return e}));for(const e of t)eo[e.name]=e},getVariablesInGroup:so,isGroupVariable:e=>"group"===e.controlType,buildFullPath:qi,parsePath:Ki,validateName:zi},co="kemu.io.scriptHttp",lo=e=>{const{recipePoolId:t,widgetId:n,httpConfig:r}=e,i=pi();let o;const s=(e=>e.find((e=>e.name===co&&e.internal))||null)(i.getCachedServices().available);if(!s)throw new Error("HTTP service not found");const a={listener:{recipeId:t},targetService:{serviceName:co,version:"1.0.0"}};i.subscribeToServiceEvents(a);const c=i.onBroadcastEvent(n,co,"1.0.0",(e=>{const t=e.outputs?.find((e=>"stream"===e.name));if(t){const e=t.value;o=e.requestId,r.onStream&&r.onStream(e)}})),l=de(t),u={currentState:{},recipe:l,recipeType:l.type,widgetId:n,recipeId:t},d=(e,t)=>i.callProcessorHandler(s.sessionId,u,e,t,{timeout:0});return{promise:d("send",r),abort:async()=>{c(),o&&await d("abort",{requestId:o})}}},uo="__command-compile__",ho={};let fo;const po=()=>{throw new Error("Method not implemented")},go=e=>{const{features:t,widgetContext:n,widgetEnvInfo:i}=e,o=(e,...t)=>{const r={...Vr(),...n.getState()}.$$eventListeners[e];r&&r.handler(t)},s={};Object.keys(me).forEach((e=>{s[e]=me[e]}));const a=Mi({recipePoolId:i.recipePoolId,thingId:i.thingId,scriptWidgetId:i.widgetId}),c=Yi({scriptWidgetId:i.widgetId}),l=(e=>{const{scriptWidgetId:t}=e,n=(t,n)=>{if(!e.setState)return void console.warn("Cannot subscribe to global variable changes without a setState function");const r={...Vr(),...e.getState()},i=async e=>{const t={name:e.name,value:e.lastValue,type:e.lastDataType,controlType:e.controlType};try{await n(t)}catch(e){console.error("Error in global variable change handler:",e)}},o=t?ao.onGlobalVariableChange(t,i):ao.onAnyGlobalVariableChange(i),s=t?`globalVar_${t}`:"anyGlobalVar";t&&r.$$eventListeners[s]&&delete r.$$eventListeners[s],r.$$eventListeners[s]={handler:n,abort:async()=>{o()},name:ui},e.setState(r)};return{get:e=>{const t=ao.getGlobalVariable(e);return t?{name:t.name,value:t.lastValue,type:t.lastDataType,controlType:t.controlType}:null},set:async e=>{const n=e.type?e.type:Be(e.value);if(e.name.includes("."))throw new Error("Variable names cannot contain dots");if(e.group){const t=async(n,r)=>{if(ao.getGlobalVariable(n))return;const{group:i,name:o}=Ki(n);i&&await t(i,!1),await ao.setGlobalVariable({name:o,group:i,value:null,controlType:"group",controlSettings:{},helpText:r&&e.groupHelpText||void 0})};await t(e.group,!0)}await ao.setGlobalVariable({name:e.name,value:e.value,lastDataType:n,helpText:e.helpText,order:e.order,controlType:e.controlType??"anything",controlSettings:e.controlSettings,widgetId:t,disableChangeNotifications:!(e.emitChangeEvent??1),disableDefineNotifications:!(e.emitDefineEvent??1),group:e.group})},onValueChange:(e,t)=>{n(e,t)},onAnyValueChange:e=>{n(null,e)}}})({scriptWidgetId:i.widgetId,getState:n.getState,setState:n.setState});a.unregisteredSecrets(),c.clearStatusValues(),ho[i.widgetId]?.abortHttp?.().catch((e=>{console.warn("Error aborting old HTTP instance: ",e)}));return{logger:vo(),dataTypesEnum:s,recipePoolId:i.recipePoolId,widgetId:i.widgetId,http:e=>{const{promise:t,abort:n}=lo({httpConfig:e,recipePoolId:i.recipePoolId,widgetId:i.widgetId});ho[i.widgetId]={abortHttp:n};return t.abort=async()=>{delete ho[i.widgetId],await n()},t},notify:{success:e=>{n.getState()?.$$managedUI?.notify?.success(e)},error:e=>{n.getState()?.$$managedUI?.notify?.error(e)},info:e=>{n.getState()?.$$managedUI?.notify?.info(e)}},variablesManager:t.variablesManager?di({recipePoolId:i.recipePoolId,scriptWidgetId:i.widgetId,thingId:i.thingId,getState:n.getState,setState:n.setState}):{get:po,set:async()=>po(),onValueChange:po,onUIValueChange:po,getUIValue:po},statusManager:c.statusManager,secretsManager:a.secretsManager,globalVariablesManager:l,setTimeout:(e,o,s)=>{if(t.withTimers&&n&&n.setState&&n.registerInterrupt){const t=r(),a={...Vr(),...n.getState()};a.$$eventListeners[t]={handler:e,rejectHandler:s,name:ci},n.setState(a),n.registerInterrupt({type:"timeout",customTargetPortName:t,sourceWidgetId:i.widgetId,config:{timeout:o},customId:t})}},addEventListener:(e,t)=>{if(n.setState){const i=r(),s={...Vr(),...n.getState()};s.$$eventListeners[i]={handler:t,name:e},n.setState(s),window.addEventListener(e,o.bind(i))}else console.warn(`Cannot remove event listener '${e}' because the widget context is not available.`)},removeEventListener:(e,t)=>{if(n.setState){const r={...Vr(),...n.getState()},i=Object.keys(r.$$eventListeners).find((n=>r.$$eventListeners[n].name===e&&r.$$eventListeners[n].handler===t));n.setState(r),i&&removeEventListener(r.$$eventListeners[i].name,r.$$eventListeners[i].handler)}else console.warn(`Cannot remove event listener '${e}' because the widget context is not available.`)}}},mo=(e,t,n)=>{const r={...Vr(),...n.getState()},i=r.pages[Ur].$$compiledCode;if(i)return{compiledModule:i};{const i=go({features:e,widgetContext:n,widgetEnvInfo:t});return Fr(r.pages[Ur].code,i,n.recipeType)}},yo=e=>e.map((e=>({...e,name:e.name.replace("_","")}))),vo=()=>{const e=(e,...t)=>{if(fo)try{return fo[e](...t)}catch(e){return void console.log("Error in custom logger: ",e)}console[e](...t)};return{log:(...t)=>{e("log",...t)},error:(...t)=>{e("error",...t)},warn:(...t)=>{e("warn",...t)},info:(...t)=>{e("info",...t)}}},bo=async(e,t)=>{const n={...e};for(const r in e){if(e[r].name===ci){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},wo=async e=>{const t={...e};for(const r in e){if((n=e[r]).name===li||n.name===ui){const n=e[r]?.abort;if("function"==typeof n)try{await n()}catch(e){console.log("Error in abort interrupt handler: ",e)}delete t[r]}}var n;return t},So=async(e,t,n)=>{let r={...Vr(),...e.getState()};if(void 0!==n){r.pages[Ur]?.$$compiledCode?.onTerminate&&await(r.pages[Ur].$$compiledCode?.onTerminate());let t=await bo(r.$$eventListeners,e);t=await wo(t),r.$$eventListeners=t,r.pages[Ur].$$compiledCode=void 0,r.pages[Ur].code=n,e.setState({...r})}const i=!r.pages[Ur].$$compiledCode,{compiledModule:o,error:s}=mo({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(s){console.log("Failed to compile user code");const t=Yr(s,e.recipeType);return Hr(t,e),null}if(o){let n;r={...e.getState()},r.pages[Ur].$$compiledCode=o;const s=_o(r.pages[Ur].code);s?.name===r.metadata?.name&&s?.description===r.metadata?.description||(r.metadata=s||void 0);const a=e.nextWidget||e.nextGate;if(a&&o.setSendToPortFun(a),e.invokeNextWidget&&o.setSetOutputFn(e.invokeNextWidget),t)try{await o.recipeInit({setState:e.setState,getState:e.getState})}catch(t){n=Yr(t,e.recipeType)}if(a&&i)try{await o.main()}catch(t){n=Yr(t,e.recipeType)}r.$$lastInputs=o.getWidgetInputs?o.getWidgetInputs():[],r.$$lastOutputs=o.getWidgetOutputs?o.getWidgetOutputs():[],e.setState(r),Hr(n,e)}},_o=e=>{const t=e.trimStart().match(/^(?:\/\*\*(?:[^*]|\*(?!\/))*\*\/|\/\*(?:[^*]|\*(?!\/))*\*\/)/);if(!t)return null;const n=t[0].replace(/^\/\*\*?/,"").replace(/\*\/$/,"").split("\n").map((e=>e.replace(/^\s*\*?\s?/,"").trim())).join("\n"),r=n.match(/Name\s*:\s*([^]*?)(?=\n\s*[A-Za-z]+\s*:|$)/i),i=n.match(/Description\s*:\s*([^]*?)(?=\n\s*[A-Za-z]+\s*:|$)/i),o={};return r&&r[1]&&(o.name=r[1].trim()),i&&i[1]&&(o.description=i[1].trim()),Object.keys(o).length>0?o:null};var Io={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),o={...Vr(),...i};if(!o.pages[Ur])return console.warn("Missing default page");if(je(e?.name||""))return o.$$eventListeners[t.name]?(await o.$$eventListeners[t.name].handler(),o.$$eventListeners[t.name].name===ci&&delete o.$$eventListeners[t.name],void r.setState({...o})):void console.log(`Unknown interrupt id [${t.name}] `);const s=t.name===uo;await So(r,!1,s?n.data.value:void 0);const a=o.pages[Ur].$$compiledCode;if(e&&e.name!==uo&&a)try{await a.asyncProcessEvent(t,e,{...n,executionContext:{currentPath:r.currentPath,eventId:r.eventId}})}catch(e){if("UserCodeError"===e.name){const t=Yr(e,r.recipeType);throw Hr(t,r),t}throw e}},getInputNames:(e,t)=>{const n={...Vr(),...e},{compiledModule:r}=mo({},{recipePoolId:t.recipePoolId,thingId:t.thingRecipeId,widgetId:t.widgetId},{getState:()=>n,recipeType:t.recipeType});if(r?.getWidgetInputs){const e=r.getWidgetInputs();return yo(e)}return e.$$lastInputs||[]},getOutputNames:(e,t)=>{const n={...Vr(),...e},{compiledModule:r}=mo({},{recipePoolId:t.recipePoolId,thingId:t.thingRecipeId,widgetId:t.widgetId},{getState:()=>n,recipeType:t.recipeType});if(r?.getWidgetOutputs){const e=r.getWidgetOutputs();return yo(e)}return e.$$lastOutputs||[]},getDefaultState:Vr,initialize:async e=>{const t=e.getState(),n={...Vr(),...t};n.pages[Ur].code&&await So({getState:e.getState,id:e.widgetId,recipePoolId:e.recipePoolId,recipeType:e.recipeType,registerInterrupt:e.registerInterrupt,setState:e.setState,nextWidget:e.nextWidget,invokeNextWidget:e.invokeNextWidget,thingRecipeId:e.thingRecipeId,cancelInterrupt:()=>!0},!0,n.pages[Ur].code)},terminate:async e=>{try{const t=e.getState();t.pages[Ur].$$compiledCode?.onTerminate&&await t.pages[Ur].$$compiledCode.onTerminate();const n=e=>tt.destroyInterrupt(e),r=await bo(t.$$eventListeners,{cancelInterrupt:n});await wo(r);const i=Yi({scriptWidgetId:e.widgetId});Mi({recipePoolId:e.recipePoolId,thingId:e.thingRecipeId,scriptWidgetId:e.widgetId}).unregisteredSecrets(),i.clearStatusValues();for(const e of Object.values(ho))e.abortHttp?.().catch((e=>{console.warn("Error aborting old HTTP instance: ",e)}))}catch(t){console.warn(`Error terminating script widget ${e.widgetId}: `,t)}}};const xo=new Map,ko=e=>(xo.has(e)||xo.set(e,Ee(320,240)),xo.get(e)),Eo=Object.freeze({image:"image"}),Co=Object.freeze({base64:"base64"}),$o=()=>({});var Oo={onParentEvent:async(e,t,n,r)=>{const i={...r.getState()};if(t.name===Co.base64){if("string"!=typeof n.data.value)return;if(n.data.type!==me.String&&n.data.type!==me.Anything)return;const e=n.data.value,t=ko(r.id);try{const n=await ze({base64Str:e,memoryCanvas:t,finalW:i.resize?.width,finalH:i.resize?.height});return r.setState(i),r.nextGate(Eo.image,{type:me.ImageData,value:n})}catch(e){console.log("[base64ToImageData] Error: ",e)}}},getInputNames:()=>[{name:Co.base64,type:me.String}],getOutputNames:()=>[{name:Eo.image,type:me.ImageData}],getDefaultState:$o,initialize:async e=>{ko(e.widgetId)},terminate:async e=>{xo.delete(e.widgetId)}};const No=Object.freeze({object:"object",error:"error"}),To=Object.freeze({string:"string"}),Ao=()=>({outputIsArray:!1});var Mo={onParentEvent:async(e,t,n,r)=>{const i={outputIsArray:!1,...r.getState()};if((n.data.type===me.String||n.data.type===me.Anything)&&"string"==typeof n.data.value)try{const e=JSON.parse(n.data.value),t=Array.isArray(e);return t&&!i.outputIsArray?r.setState({...i,outputIsArray:!0}):!t&&i.outputIsArray&&r.setState({...i,outputIsArray:!1}),r.nextGate("object",{type:t?me.Array:me.JsonObj,value:e})}catch(e){return r.nextGate("error",{type:me.Boolean,value:!0})}},getInputNames:()=>[{name:To.string,type:me.String}],getOutputNames:e=>[{name:No.object,type:[me.JsonObj,me.Array],label:e.outputIsArray?"array":No.object},{name:No.error,type:me.Boolean}],getDefaultState:Ao};const Po=Object.freeze({string:"string",length:"length"}),Do=Object.freeze({trigger:"trigger",setText:"setText"}),jo=()=>({text:"",dispatchOnSet:!1});var Ro={onParentEvent:async(e,t,n,r)=>{const i={text:"",dispatchOnSet:!1,...r.getState()};if(t.name===Do.setText){if(!((n.data.type===me.String||n.data.type===me.Anything)&&"string"==typeof n.data.value))return;if("string"==typeof n.data.value&&(i.text=n.data.value,r.setState(i)),!i.dispatchOnSet)return}const o=r.nextGate(Po.length,{type:me.Number,value:i.text.length}),s=r.nextGate(Po.string,{type:me.String,value:i.text});await Promise.all([o,s])},getInputNames:e=>{const t=[{name:Do.setText,type:me.String}];return e.dispatchOnSet||t.push({name:Do.trigger,type:me.Anything}),t},getOutputNames:()=>[{name:Po.string,type:me.String},{name:Po.length,type:me.Number}],getDefaultState:jo};const Lo=Object.freeze({image:"image"}),Fo=Object.freeze({image:"image",x:"x",y:"y",width:"width",height:"height"}),Uo=()=>({showInputPorts:!1});var Bo={onParentEvent:async(e,t,n,r)=>{const i={showInputPorts:!1,...r.getState()};if("number"==typeof n.data.value)return t.name===Fo.x&&(i.cropX=n.data.value),t.name===Fo.y&&(i.cropY=n.data.value),t.name===Fo.width&&(i.cropWidth=n.data.value),t.name===Fo.height&&(i.cropHeight=n.data.value),void r.setState(i);if(t.name===Fo.image){if(n.data.type!==me.ImageData&&n.data.type!==me.Anything)return;if(!Re(n.data.value))return;const e=n.data.value;if(i.$$memCanvas&&i.$$memCanvas.getContext||(i.$$memCanvas=Ee(320,240),i.$$memCanvasContext=Ce(i.$$memCanvas),r.setState(i)),!i.$$memCanvas||!i.$$memCanvasContext)return void console.error("Failed to get canvas or context");let t=e;return i.$$memCanvas.width=e.width,i.$$memCanvas.height=e.height,(i.cropX||i.cropY||i.cropWidth||i.cropHeight)&&(t=((e,t,n,r)=>{if(!n)return e;const i=Math.max(r.x||0,0),o=Math.max(r.y||0,0),s=e.width,a=e.height,c=Math.min(Math.ceil(r.width||s),s),l=Math.min(Math.ceil(r.height||a),a);return t.width=e.width,t.height=e.height,n.putImageData(e,0,0),n.drawImage(t,i,o,c,l,0,0,c,l),n.getImageData(0,0,c,l)})(e,i.$$memCanvas,i.$$memCanvasContext,{x:i.cropX,y:i.cropY,width:i.cropWidth,height:i.cropHeight})),r.nextGate(Lo.image,{type:me.ImageData,value:t})}},getInputNames:e=>{const t=[{name:Fo.image,type:[me.ImageData]}];return e.showInputPorts&&(t.push({name:Fo.x,type:me.Number}),t.push({name:Fo.y,type:me.Number}),t.push({name:Fo.width,type:me.Number}),t.push({name:Fo.height,type:me.Number})),t},getOutputNames:()=>[{name:Lo.image,type:me.ImageData}],getDefaultState:Uo};const Wo=Object.freeze({image:"image"}),Go=Object.freeze({image:"image",width:"width",height:"height"}),Vo=()=>({showInputPorts:!1});var Yo={onParentEvent:async(e,t,n,r)=>{const i={showInputPorts:!1,...r.getState()};if("number"==typeof n.data.value)return t.name===Go.width&&(i.width=n.data.value),t.name===Go.height&&(i.height=n.data.value),void r.setState(i);if(t.name===Go.image){if(n.data.type!==me.ImageData&&n.data.type!==me.Anything)return;if(!Re(n.data.value))return;const e=n.data.value;if(i.$$memCanvas&&i.$$memCanvas.getContext||(i.$$memCanvas=Ee(320,240),i.$$tempCanvas=Ee(320,240),r.setState(i)),!i.$$memCanvas||!i.$$tempCanvas)return;let t=e;return(i.width||i.height)&&(t=((e,t,n,r,i)=>{if(!r&&!i)return e;r&&!i?i=r*(e.height/e.width):!r&&i&&(r=i*(e.width/e.height));const o=Math.max(1,r||e.width),s=Math.max(1,i||e.height);n.width===e.width&&n.height===e.height||(n.width=e.width,n.height=e.height),t.width=o,t.height=s;const a=Ce(t),c=Ce(n);if(!a||!c)throw new Error("Failed to get canvas context");return c.putImageData(e,0,0),a.drawImage(n,0,0,e.width,e.height,0,0,o,s),a.getImageData(0,0,o,s)})(e,i.$$memCanvas,i.$$tempCanvas,i.width,i.height)),r.nextGate(Wo.image,{type:me.ImageData,value:t})}},getInputNames:e=>{const t=[{name:Go.image,type:me.ImageData}];return e.showInputPorts&&(t.push({name:Go.width,type:me.Number}),t.push({name:Go.height,type:me.Number})),t},getOutputNames:()=>[{name:Wo.image,type:me.ImageData}],getDefaultState:Vo};const Ho=Object.freeze({value:"value"}),zo=Object.freeze({trigger:"trigger",setValue:"setValue"}),qo=()=>({value:0,dispatchOnSet:!1});var Ko={onParentEvent:async(e,t,n,r)=>{const i={value:0,dispatchOnSet:!1,...r.getState()};if(t.name===zo.setValue){const e=n.data.type===me.Number||n.data.type===me.Anything||n.data.type===me.String,t=!isNaN(Number(n.data.value))&&!Array.isArray(n.data.value);if(!e||!t)return;if(i.value=Number(n.data.value),r.setState(i),!i.dispatchOnSet)return}return r.nextGate(Ho.value,{type:me.Number,value:i.value})},getInputNames:e=>{const t=[{name:zo.setValue,type:me.Number}];return e.dispatchOnSet||t.push({name:zo.trigger,type:me.Anything}),t},getOutputNames:()=>[{name:Ho.value,type:me.Number}],getDefaultState:qo};const Jo=Object.freeze({image:"image"}),Zo=Object.freeze({image:"image"}),Xo=()=>({anchors:[],vertices:[],matrix:[]}),Qo={onParentEvent:async(e,t,n,r)=>{const i={anchors:[],vertices:[],matrix:[],...r.getState()},o=window,s=n.data.type===me.ImageData;if(o.Speedy&&s){const e=o.Speedy,t=n.data.value;let s,u,d,h=i.$$private?.canvas,f=i.$$private?.context,p={...i};const g=4===i.anchors.length;if(i.$$private?.pipeline)s=i.$$private?.pipeline,u=i.$$private?.source;else{s=e.Pipeline(),u=e.Image.Source();const n=e.Image.Sink();d=e.Transform.PerspectiveWarp(),h?h.width===t.width&&h.height===t.height||(h.width=t.width,h.height=t.height,f=h.getContext("2d")):(c=t.width,l=t.height,h=Ee(c,l),f=h.getContext("2d")),u.output().connectTo(d.input()),d.output().connectTo(n.input()),s.init(u,n,d);let r=e.Matrix(3,3,[1,0,0,0,1,0,0,0,1]);if(4===i.anchors.length){const t=e.Matrix(2,4,[(a=i.anchors)[0].x,a[0].y,a[1].x,a[1].y,a[2].x,a[2].y,a[3].x,a[3].y]),n=e.Matrix(2,4,i.vertices.reduce(((e,t)=>e.concat([t.x,t.y])),[])),o=e.Matrix.Zeros(3,3);await e.Matrix.perspective(o,t,n);const s=o.read();r=e.Matrix(3,3,s)}d.transform=r,p={...p,$$private:{...p.$$private,canvas:h,context:f,perspective:d,pipeline:s,source:u}}}let m=t;if(g){const e=await(async(e,t)=>{const n=window,r=e.$$private?.source,i=e.$$private?.pipeline;if(n.Speedy&&r&&i){const e=n.Speedy,o=await createImageBitmap(t),s=await e.load(o);return r.media=s,(await i.run()).image.source}return null})(p,m);e&&(h&&f&&(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,h,f)),p.$$private&&r.setState({...p,$$private:{...p.$$private,lastInputImage:t}}))}else p.$$private&&r.setState({...p,$$private:{...p.$$private,lastInputImage:t}});return r.nextGate(Jo.image,{type:me.ImageData,value:m})}var a,c,l;console.log("Environment not supported")},getInputNames:()=>[{name:Zo.image,type:me.ImageData}],getOutputNames:()=>[{name:Jo.image,type:me.ImageData}],getDefaultState:Xo,terminate:async e=>{const t=e.getState();t.$$private?.pipeline.release()}},es=Object.freeze({event:"event"}),ts="1",ns="2",rs="3";var is={onParentEvent:async(e,t,n,r)=>{const i={...r.getState()};r.setState({...i,$$lastEventType:n.data.type}),await r.nextGate(ts,n.data),await r.nextGate(ns,n.data),await r.nextGate(rs,n.data)},getInputNames:()=>[{name:es.event,type:me.Anything}],getOutputNames:e=>{const t={type:{...e}.$$lastEventType??me.Anything};return[{name:ts,...t},{name:ns,...t},{name:rs,...t}]}};const os=()=>({name:"myVar",type:me.Anything,reactive:!0,defaultValue:""}),ss=Object.freeze({set:"set",read:"read"}),as="value";var cs={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),o={...os(),...i};if(t.name!==ss.set){if(t.name===ss.read){const e=oi({variableName:o.name,readerWidgetId:r.id}),t=e?e.value:o.defaultValue;await r.nextWidget(as,{type:o.type,value:t})}}else{if(n.data.type!==o.type&&o.type!==me.Anything)return;await ii({variableName:o.name,value:n.data.value,setByWidgetId:r.id,type:o.type})}},getInputNames:e=>{const t={...e};return[{name:ss.set,type:t.type||me.Anything},{name:ss.read,type:me.Anything}]},getOutputNames:e=>{const t={...e};return[{name:as,type:t.type||me.Anything}]},initialize:async e=>{const t=e.getState(),n={...os(),...t};if(n.$$abortListener)try{n.$$abortListener()}catch(t){console.warn(`Error aborting variable listener for widget ${e.widgetId}: `,t)}ni({variableName:n.name,type:n.type,createdByWidgetId:e.widgetId});const r=si({variableName:n.name,type:n.type,widgetId:e.widgetId,onValueChange:async t=>{const n=e.getState();void 0!==t.value&&(n.type!==me.Anything&&t.type!==n.type||n.reactive&&await e.nextWidget(as,{type:t.type,value:t.value}))}});e.setState({...n,$$abortListener:r})},terminate:async e=>{const t=e.getState(),n={...os(),...t};n.$$abortListener&&n.$$abortListener(),ri({variableName:n.name,createdByWidgetId:e.widgetId})}};const ls=async(e,t=!1)=>{const n=pi();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 us={onParentEvent:async(e,t,n,r)=>{const i={dynamicInputs:{},dynamicOutputs:{},customState:{},...r.getState()};if(!e)return;const o=se(r.recipePoolId);if(!o)throw new Error(`Recipe [${r.recipePoolId}] not found`);const s=pi();let a=i.$$$serviceId;if(!a){const e=s.getCachedServices().available.find((e=>e.name===i.service?.name&&e.version===i.service?.version));if(!e)return;a=e.sessionId,i.$$$serviceId=a,r.setState(i)}const c=i.service?.variants?.find((e=>e.id===i.variantId)),l=c?i.dynamicInputs[c.id]||c?.inputs||[]:i.service?.inputs||[];if(!l?.length)return;if(!c&&i.service?.ignoreParentEvents)return;const u=i.service?.processingTimeoutSec,d=r.eventContext,h=o?.name||"";return s.onParentEvent({recipeId:r.recipePoolId,recipeName:h,data:n.data,targetServiceSessionId:a,currentState:i.customState,targetVariantId:i.variantId,currentPath:r.currentPath,eventId:r.eventId,recipe:{uuid:o.uuid,poolId:r.recipePoolId,name:h,type:r.recipeType,version:o.dbInfo.version,authorId:o.dbInfo.authorId},target:{portName:t.name,widgetId:r.id,widgetType:r.type},source:e,config:{timeout:u?1e3*u:0,async:i.service?.asyncParentEvents},eventContext:d})},getInputNames:async e=>{const t=e.variantId;if(t&&e.dynamicInputs?.[t])return[...e.dynamicInputs[t]||[]];if(!t)return e.service?.inputs||[];{const n=e.service?.variants?.find((e=>e.id===t));if(n)return n.inputs||[]}return[]},getOutputNames:async e=>{const t=e.variantId;if(t&&e.dynamicOutputs?.[t])return[...e.dynamicOutputs[t]||[]];if(!t)return e.service?.outputs||[];{const n=e.service?.variants?.find((e=>e.id===t));if(n)return n.outputs||[]}return[]},initialize:async e=>{const t={dynamicInputs:{},dynamicOutputs:{},customState:{},...e.getState()},n=se(e.recipePoolId),r=n?.name||"",i=pi(),o=await ls(t);if(o)try{return await i.initializeServiceInstance({recipePoolId:e.recipePoolId,sessionId:o,recipeName:r,widgetId:e.widgetId,recipeType:e.recipeType,variantId:t.variantId})}catch(t){if("FNC_NOT_FOUND"!==t?.errCode){if(!!("string"!=typeof t||!t.match('^Function ".*" not found.$')))throw t;console.warn(`Widget [${e.widgetId}] does not have an init function.`)}}else console.log(`Aborting service initialization, "${t.service?.name}" was not found in the current Hub.`)},terminate:async e=>{const t={dynamicInputs:{},dynamicOutputs:{},customState:{},...e.getState()},n=pi(),r=await ls(t,!0);if(r)return n.terminateServiceInstance(r,e.widgetId,e.recipePoolId,t.variantId)}};const ds=Object.freeze({Image:"image"}),hs=Object.freeze({Image:"image"}),fs=()=>({filters:[{name:"grayscale",value:"0.5",id:"d-1"}]});var ps={onParentEvent:async(e,t,n,r)=>{const i={filters:[{name:"grayscale",value:"0.5",id:"d-1"}],...r.getState()};if(t.name===ds.Image&&(n.data.type===me.ImageData||n.data.type===me.Anything)){if(!Re(n.data.value))return void console.log("ImageFilter: Invalid image data type, aborting process");const e=n.data.value;i.$$memCanvas?.getContext||(i.$$memCanvas=Ee(e.width,e.height)),i.$$context?.drawImage||(i.$$context=i.$$memCanvas.getContext("2d")),i.$$memCanvas.width!==e.width&&(i.$$memCanvas.width=e.width),i.$$memCanvas.height!==e.height&&(i.$$memCanvas.height=e.height),r.setState(i),i.$$context.putImageData(e,0,0),i.filters.length?i.$$context.filter=i.filters.map((e=>{let t="";return"blur"===e.name?t="px":"hue-rotate"===e.name&&(t="deg"),`${e.name}(${parseFloat(e.value)}${t})`})).join(" "):i.$$context.filter="none",i.$$context.drawImage(i.$$memCanvas,0,0);const t=i.$$context.getImageData(0,0,e.width,e.height);return r.nextWidget(hs.Image,{type:me.ImageData,value:t})}},getInputNames:()=>[{name:ds.Image,type:me.ImageData}],getOutputNames:()=>[{name:hs.Image,type:me.ImageData}],getDefaultState:fs};const gs="loaded";var ms={onParentEvent:async(e,t,n,r)=>r.nextWidget(gs,{value:!0,type:me.Boolean}),getInputNames:()=>[],getOutputNames:()=>[{name:gs,type:me.Boolean,description:"Triggered when the recipe is fully loaded"}]};var ys={onParentEvent:async()=>{},getInputNames:()=>[],getOutputNames:()=>[],getDefaultState:()=>({text:"",color:"#eac43e",size:{width:300,height:200}})};var vs={onParentEvent:async(e,t,n,r)=>{try{const e=((e,t)=>{switch(t){case me.Number:case me.Boolean:case me.String:return String(e);case me.Array:case me.JsonObj:case me.Rect:case me.Point:return JSON.stringify(e,((e,t)=>"bigint"==typeof t?t.toString():t));case me.ArrayBuffer:if(e instanceof ArrayBuffer){if(ne)return Buffer.from(e).toString("base64");{const t=new Uint8Array(e),n=t.length,r=new Array(n);for(let e=0;e<n;e++)r[e]=String.fromCharCode(t[e]);return btoa(r.join(""))}}throw new Error("Type is ArrayBuffer but value is not an ArrayBuffer");case me.ImageData:if(!Re(e))throw new Error("Expected ImageData");return He(e);default:return String(e)}})(n.data.value,n.data.type);return r.nextWidget("text",{type:me.String,value:e})}catch(e){return r.nextWidget("error",{type:me.String,value:e instanceof Error?e.message:"Failed to stringify object"})}},getInputNames:()=>[{name:"object",type:[me.Number,me.String,me.ArrayBuffer,me.Array,me.Boolean,me.JsonObj,me.Rect,me.Point,me.ImageData]}],getOutputNames:()=>[{name:"text",type:me.String},{name:"error",type:me.String}],getDefaultState:()=>({})};const bs=(e,t)=>{if(!Array.isArray(e)||"number"!=typeof t||t<=0)return[e];const n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n},ws=e=>{const{code:t,enableFnTag:n=!1,context:r={},securityOptions:i={}}=e;if(!n)throw new Error("$fn helper is disabled by default for security reasons. Set enableFnTag: true in options to enable.");if("string"!=typeof t)throw new Error("$fn requires a string argument");const o=((e={})=>{const{restrictionLevel:t="strict",allowedGlobals:n=[],blockedGlobals:r=[]}=e,i={Math:"undefined"!=typeof Math?Math:void 0,Date:"undefined"!=typeof Date?Date:void 0,JSON:"undefined"!=typeof JSON?JSON:void 0,Array:"undefined"!=typeof Array?Array:void 0,Object:"undefined"!=typeof Object?Object:void 0,String:"undefined"!=typeof String?String:void 0,Number:"undefined"!=typeof Number?Number:void 0,Boolean:"undefined"!=typeof Boolean?Boolean:void 0,RegExp:"undefined"!=typeof RegExp?RegExp:void 0,Symbol:"undefined"!=typeof Symbol?Symbol:void 0,Map:"undefined"!=typeof Map?Map:void 0,Set:"undefined"!=typeof Set?Set:void 0,Promise:"undefined"!=typeof Promise?Promise:void 0},o={process:void 0,require:void 0,global:void 0,globalThis:void 0,window:void 0,document:void 0,navigator:void 0,console:void 0,eval:void 0,Function:void 0,setTimeout:void 0,setInterval:void 0,setImmediate:void 0,clearTimeout:void 0,clearInterval:void 0,clearImmediate:void 0,fetch:void 0,XMLHttpRequest:void 0,WebSocket:void 0,Worker:void 0,SharedWorker:void 0,ServiceWorker:void 0,localStorage:void 0,sessionStorage:void 0,indexedDB:void 0};let s={};switch(t){case"strict":case"moderate":s={...i,...o};break;case"permissive":s={...i,process:void 0,require:void 0,eval:void 0,Function:void 0}}if(n.length>0)for(const e of n)"undefined"!=typeof globalThis&&e in globalThis&&(s[e]=globalThis[e]);for(const e of r)s[e]=void 0;return s})(i);o.$vars=r.$vars,o.date=r.date,o.chunkArray=r.chunkArray;const s=new Set(["Math","Date","JSON","Array","Object","String","Number","Boolean","RegExp","Symbol","Map","Set","Promise","eval","Function","require","process","global","globalThis","window","document","navigator","console","$vars","date","chunkArray"]),a=Object.entries(r).filter((([e])=>!s.has(e))),c=a.map((([e])=>e)),l=a.map((([,e])=>e)),u=`\n // Get sandbox environment from the last argument\n const __sandbox = arguments[arguments.length - 1]; // Last argument is the sandbox\n \n // Shadow dangerous globals at the top level (these will be overridden by sandbox if allowed)\n var eval = undefined;\n var Function = undefined;\n var require = undefined;\n var process = undefined;\n var global = undefined;\n var globalThis = undefined;\n var console = __sandbox.console;\n var window = __sandbox.window;\n var document = __sandbox.document;\n var navigator = __sandbox.navigator;\n \n // Make context variables available in local scope\n ${c.map(((e,t)=>`var ${e} = arguments[${t}];`)).join("\n ")}\n \n // Shadow global references to use sandbox versions\n const Math = __sandbox.Math;\n const Date = __sandbox.Date;\n const JSON = __sandbox.JSON;\n const Array = __sandbox.Array;\n const Object = __sandbox.Object;\n const String = __sandbox.String;\n const Number = __sandbox.Number;\n const Boolean = __sandbox.Boolean;\n const RegExp = __sandbox.RegExp;\n const Symbol = __sandbox.Symbol;\n const Map = __sandbox.Map;\n const Set = __sandbox.Set;\n const Promise = __sandbox.Promise;\n \n // Make special context items available\n const $vars = __sandbox.$vars;\n const date = __sandbox.date;\n const chunkArray = __sandbox.chunkArray;\n \n // Execute the user code in strict mode for additional security\n // Use call(null) to ensure 'this' is null/undefined in strict mode\n return (() => {\n "use strict";\n return ${t};\n }).call(null);\n `;try{return new Function(...c,"sandbox",u).call({},...l,o)}catch(e){throw new Error(`Error executing $fn: ${e instanceof Error?e.message:String(e)}`)}},Ss=e=>{const t={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","/":"&#x2F;"};return e.replace(/[&<>"'/]/g,(e=>t[e]))},_s=()=>new Proxy({},{get(e,t){if("string"==typeof t){const e=ao.getGlobalVariable(t);return e?.lastValue??void 0}}}),Is=e=>{const t=new Set,n=e.match(/\$secrets\.([a-zA-Z_$][a-zA-Z0-9_$]*)/g);if(n)for(const e of n){const n=e.substring(9);n&&t.add(n)}const r=e.match(/\$secrets\[['"]([^'"]+)['"]\]/g);if(r)for(const e of r){const n=e.match(/['"]([^'"]+)['"]/);n&&n[1]&&t.add(n[1])}return t},xs=(e=new Date)=>({year:e.getFullYear(),month:e.getMonth()+1,day:e.getDate(),hours:e.getHours(),minutes:e.getMinutes(),seconds:e.getSeconds(),milliseconds:e.getMilliseconds(),time:e.getTime(),dayOfWeek:e.getDay(),dayName:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][e.getDay()],shortDayName:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"][e.getDay()],date:e.getDate(),fullYear:e.getFullYear(),timezoneOffset:e.getTimezoneOffset(),UTCDate:e.getUTCDate(),UTCDay:e.getUTCDay(),UTCFullYear:e.getUTCFullYear(),UTCHours:e.getUTCHours(),UTCMilliseconds:e.getUTCMilliseconds(),UTCMonth:e.getUTCMonth()+1,UTCMinutes:e.getUTCMinutes(),UTCSeconds:e.getUTCSeconds(),isoString:e.toISOString(),localeString:e.toLocaleString()}),ks={$capitalize:e=>"string"==typeof e&&e.length>0?e.charAt(0).toUpperCase()+e.slice(1):e,$uppercase:e=>"string"==typeof e?e.toUpperCase():e,$lowercase:e=>"string"==typeof e?e.toLowerCase():e,$json:e=>{if("string"==typeof e)try{return JSON.parse(e)}catch{return e}return e},$stringify:(e,t,n)=>{try{return void 0!==t||void 0!==n?JSON.stringify(e,t,n):JSON.stringify(e)}catch{return String(e)}},$length:e=>"string"==typeof e||Array.isArray(e)?e.length:0,$compact:e=>Array.isArray(e)?e.filter((e=>null!=e&&""!==e&&!1!==e)):e,$chunk:e=>{if(!Array.isArray(e))return e;const t=[];for(let n=0;n<e.length;n+=2)t.push(e.slice(n,n+2));return t},$isEmpty:e=>Array.isArray(e)||"string"==typeof e?0===e.length:null==e,$isNotEmpty:e=>Array.isArray(e)||"string"==typeof e?e.length>0:null!=e,$first:e=>Array.isArray(e)?e.length>0?e[0]:void 0:"string"==typeof e&&e.length>0?e.charAt(0):void 0,$last:e=>Array.isArray(e)?e.length>0?e[e.length-1]:void 0:"string"==typeof e&&e.length>0?e.charAt(e.length-1):void 0,$base64Decode:e=>{if("string"!=typeof e)return e;try{return ee&&window.atob?window.atob(e):"undefined"!=typeof Buffer?Buffer.from(e,"base64").toString("utf-8"):e}catch{return e}},$base64Encode:e=>{if("string"!=typeof e)return e;try{return"undefined"!=typeof window&&window.btoa?window.btoa(e):"undefined"!=typeof Buffer?Buffer.from(e,"utf-8").toString("base64"):e}catch{return e}},$domain:e=>{if("string"==typeof e)try{const t=e.match(/https?:\/\/[^\s]+/i),n=t?t[0]:e;return new URL(n).hostname}catch{try{const t=new URL("http://"+e.trim());if(t.hostname.includes(".")&&!t.hostname.startsWith("http"))return t.hostname}catch{}return}},$email:e=>{if("string"==typeof e)try{const t=e.match(/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/);return t?t[0]:void 0}catch{return}},$url:e=>{if("string"==typeof e)try{const t=e.match(/https?:\/\/[^\s]+/i);if(t){return new URL(t[0]).toString()}return new URL(e.trim()).toString()}catch{return}},$urlPath:e=>{if("string"==typeof e)try{return new URL(e).pathname}catch{try{return new URL("http://"+e).pathname}catch{return}}},$urlEncode:e=>{if("string"!=typeof e)return e;try{return encodeURIComponent(e)}catch{return e}},$urlDecode:(e,t)=>{if("string"!=typeof e)return e;try{return!0===t?decodeURI(e):decodeURIComponent(e)}catch{return e}}},Es=e=>{const t=[];let n=0;for(;n<e.length;){const r=e.indexOf("{{",n);if(-1===r)break;const i="{{{"===e.slice(r,r+3),o=i?"{{{":"{{",s=i?"}}}":"}}";let a=1,c=!1,l="",u=r+o.length;for(;u<e.length&&a>0;){const t=e[u],n=e[u+1];c?t===l&&"\\"!==e[u-1]&&(c=!1,l=""):'"'===t||"'"===t?(c=!0,l=t):"{"===t&&"{"===n?i&&"{"===e[u+2]?(a++,u+=2):i||(a++,u++):"}"===t&&"}"===n&&(i&&"}"===e[u+2]?(a--,u+=2):i||(a--,u++)),u++}if(0===a){const a=e.slice(r,u),c=e.slice(r+o.length,u-s.length).trim();t.push({expression:c,start:r,end:u,fullMatch:a,escaped:!i}),n=u}else n=r+o.length}return t},Cs=e=>{const t=e.match(/\$\w+\(/);if(!t)return{hasFunctionPropertyAccess:!1};const n=((e,t)=>{let n=0,r=!1,i="",o=t;for(;o<e.length&&"("!==e[o];)o++;if(o>=e.length)return null;const s=t;for(o++,n=1;o<e.length&&n>0;){const t=e[o];r?t===i&&"\\"!==e[o-1]&&(r=!1,i=""):'"'===t||"'"===t?(r=!0,i=t):"("===t?n++:")"===t&&n--,o++}return 0===n?{functionCall:e.slice(s,o),endIndex:o}:null})(e,t.index);if(!n)return{hasFunctionPropertyAccess:!1};const{functionCall:r,endIndex:i}=n,o=e.slice(i).match(/^(\.[a-zA-Z_$][a-zA-Z0-9_$]*|\[\d+\]|\[['"'][^'"]*['"']\])(?:\.[a-zA-Z_$][a-zA-Z0-9_$]*|\[\d+\]|\[['"'][^'"]*['"']\])*/);return o?{hasFunctionPropertyAccess:!0,functionCall:r,propertyPath:o[0],fullMatch:r+o[0]}:{hasFunctionPropertyAccess:!1}},$s=(e,t,n,r)=>{const i=n.evaluate(e,r);if(null==i)return;let o=i;const s=t.match(/\.[a-zA-Z_$][a-zA-Z0-9_$]*|\[\d+\]|\[['"'][^'"]*['"']\]/g)||[];for(const e of s){if(null==o)return;if(e.startsWith(".")){o=o[e.slice(1)]}else if(e.startsWith("[")&&e.endsWith("]")){const t=e.slice(1,-1);if(/^\d+$/.test(t)){o=o[parseInt(t,10)]}else{o=o[t.replace(/^['"]|['"]$/g,"")]}}}return o},Os=e=>{const t=e.match(/^([a-zA-Z_$][a-zA-Z0-9_$]*)\[/);if(!t)return{hasObjectBracketAccess:!1};const n=t[1],r=t.index;if("vars"===n||e.startsWith("$vars["))return{hasObjectBracketAccess:!1};if("secrets"===n||e.startsWith("$secrets["))return{hasObjectBracketAccess:!1};const i=r+n.length,o=e.slice(i).match(/^(?:\[(?:['"'][^'"]*['"]|\d+|[^\]]+)\])+/);if(o){const e=o[0];return{hasObjectBracketAccess:!0,objectName:n,bracketPath:e,fullMatch:n+e}}return{hasObjectBracketAccess:!1}},Ns=(e,t,n,r)=>{const i=r[e];if(null==i)return;const o=t.match(/\[(?:['"'][^'"]*['"]|\d+|[^\]]+)\]/g)||[];if(0===o.length)return;let s=i;for(const e of o){if(null==s)return;const t=e.slice(1,-1);let i;if(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))i=t.slice(1,-1);else if(/^\d+$/.test(t))i=parseInt(t,10);else try{i=n.evaluate(t,r)}catch{return}if("number"==typeof i&&Array.isArray(s))s=s[i];else{if("string"!=typeof i||"object"!=typeof s||null===s)return;s=s[i]}}return s},Ts=e=>{const t=e.match(/\$(?:vars|secrets)\[/);if(!t)return{hasVarsBracketAccess:!1};const n=t.index,r="$secrets["===e.slice(n,n+9)?"$secrets":"$vars",i=n+r.length,o=e.slice(i).match(/^(?:\[(?:['"'][^'"]*['"]|\d+|[^\]]+)\])+/);if(o){const e=o[0];return{hasVarsBracketAccess:!0,bracketPath:e,fullMatch:r+e,objectName:r}}return{hasVarsBracketAccess:!1}},As=(e,t,n,r,i=!1)=>{const o=e.match(/\[(?:['"'][^'"]*['"]|\d+|[^\]]+)\]/g)||[];if(0===o.length)return;const s=o[0],a=s?.slice(1,-1);let c,l;if(a?.startsWith('"')&&a.endsWith('"')||a?.startsWith("'")&&a.endsWith("'"))c=a.slice(1,-1);else if(a&&/^\d+$/.test(a))c=parseInt(a,10);else if(a)try{c=n.evaluate(a,r)}catch{return}if("$vars"===t){if("string"!=typeof c)return;const e=ao.getGlobalVariable(c);l=e?.lastValue??void 0}else{if("$secrets"!==t)return;{if(!i)return;const e=r.$secrets;if(!e)return;if("string"!=typeof c)return;l=e[c]??void 0}}for(let e=1;e<o.length;e++){if(null==l)return;const t=o[e].slice(1,-1);let i;if(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))i=t.slice(1,-1);else if(/^\d+$/.test(t))i=parseInt(t,10);else try{i=n.evaluate(t,r)}catch{return}if("number"==typeof i&&Array.isArray(l))l=l[i];else{if("string"!=typeof i||"object"!=typeof l)return;l=l[i]}}return l},Ms=async e=>{const{template:t,context:n={},options:r={}}=e,{helpers:i={},enableFnTag:o=!1,securityOptions:s={},recipeUuid:a,serviceName:l,enableSecretsBracketNotation:u=!1}=r,d={...ks,...i},h=_s(),f=xs(),p={...n};var g;"input"in p&&(p.input="object"==typeof(g=p.input)&&null!==g?g:{value:g});let m,y={};if(a){const e=(e=>{const t=new Set,n=Es(e);for(const e of n)Is(e.expression).forEach((e=>t.add(e)));return t})(t),n=Array.from(e);if(n.length>0)try{y=await Oi({recipeUuid:a,secretNames:n,serviceName:l})}catch(e){console.error("Failed to fetch secrets for template:",e),y={}}m=y}const v={...p,$vars:h,date:f,chunkArray:bs};void 0!==m&&(v.$secrets=m);const b={...d};b.$fn=e=>ws({code:e,enableFnTag:o,context:v,securityOptions:s});const w=new c({operators:{add:!0,comparison:!0,concatenate:!0,conditional:!0,logical:!0,power:!1,assignment:!1}});for(const[e,t]of Object.entries(b))w.functions[e]=t;const S=Es(t);if(0===S.length)return t;let _="",I=0;for(const e of S){_+=t.slice(I,e.start);try{if(!o&&e.expression.includes("$fn"))throw new Error("$fn helper is disabled by default for security reasons. Set enableFnTag: true in options to enable.");let t;const n=Ts(e.expression);if(n.hasVarsBracketAccess&&n.bracketPath&&n.objectName)t=As(n.bracketPath,n.objectName,w,{...v,...b},u);else{const n=Os(e.expression);if(n.hasObjectBracketAccess&&n.objectName&&n.bracketPath)t=Ns(n.objectName,n.bracketPath,w,{...v,...b});else{const n=Cs(e.expression);t=n.hasFunctionPropertyAccess&&n.functionCall&&n.propertyPath?$s(n.functionCall,n.propertyPath,w,{...v,...b}):w.evaluate(e.expression,{...v,...b})}}null!==t&&"object"==typeof t&&"then"in t&&(t=await t);let r=null==t?"":String(t);e.escaped&&(r=Ss(r)),_+=r}catch(e){if(e instanceof Error&&e.message.includes("undefined variable"))_+="";else{const t=e instanceof Error?e.message:String(e);if(e instanceof Error&&e.message.includes("$fn helper is disabled"))throw e;_+=`[Error: ${t}]`}}I=e.end}return _+=t.slice(I),_},Ps=()=>({text:"",format:"Text"});var Ds={onParentEvent:async(e,t,n,r)=>{const i={text:"",format:"Text",...r.getState()},{uuid:o}=Ni(r.recipePoolId);if(!o)throw new Error(`Recipe [${o}] does not have a valid id]`);const s=await Ms({template:i.text,context:{input:n.data.value},options:{enableFnTag:!0,recipeUuid:o}});return r.nextWidget("text",{type:me.String,value:s})},getInputNames:()=>[{name:"input",type:me.Anything}],getOutputNames:()=>[{name:"text",type:me.String}],getDefaultState:Ps};const js=()=>({expression:""}),Rs=async e=>{const{expression:t,recipeUuid:n,serviceName:r,enableFnTag:i=!0,customContext:o={}}=e,s=Symbol("abort");try{const e={restrictionLevel:"strict"},a=_s(),c=xs();let l;if(n&&t.includes("$secrets")){const e=Array.from(Is(t));if(e.length>0)try{l=await Oi({recipeUuid:n,secretNames:e,serviceName:r})}catch(e){console.error("Failed to fetch secrets for expression:",e),l={}}}const u={...o,abort:s,$vars:a,date:c,chunkArray:bs,...ks};void 0!==l&&(u.$secrets=l);const d=ws({code:t,enableFnTag:i,context:u,securityOptions:e});return d===s?{value:s,error:null}:{value:d,error:null}}catch(e){let t=e instanceof Error?e.message:String(e);return t.startsWith("Error executing $fn: ")&&(t=t.substring(21)),{error:"Error during expression execution: "+t,value:null}}};var Ls={onParentEvent:async(e,t,n,r)=>{const i={expression:"",...r.getState()},{uuid:o}=Ni(r.recipePoolId);if(!o)throw new Error(`Recipe [${o}] does not have a valid id]`);const s=await Rs({customContext:{data:n.data.value},expression:i.expression,recipeUuid:o,serviceName:void 0});if("symbol"==typeof s.value)return;if(s.error)throw new Error(s.error);if(Number.isNaN(s.value))throw new Error("Expression resulted in NaN");if(void 0===s.value||null===s.value)return;const a=Be(s.value);return a!==i.$$lastResultType&&r.setState({...i,$$lastResultType:a}),r.nextWidget("result",{type:a,value:s.value})},getInputNames:()=>[{name:"data",type:me.Anything}],getOutputNames:e=>[{name:"result",type:e.$$lastResultType||me.Anything}],getDefaultState:js};const Fs={};let Us={};const Bs=new a;let Ws=!1,Gs=!1,Vs=!1,Ys=null,Hs=null;const zs="processing-state-change",qs="error-event",Ks={abortRequested:!1,isPaused:!1,pausePromise:null,pausePromiseResolve:null,lastPausedWidgetId:null},Js=e=>(Hs=e,Bs.emit(zs,e)),Zs=(e,t)=>`${e}-${t}`,Xs=(e,t)=>`state-change:${Zs(e,t)}`,Qs=e=>{const{thingId:t,widgetId:n}=e,r=Zs(t,n);return Fs[r]||{isProcessing:!1}},ea=e=>{const t=(e=>{let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t+e.charCodeAt(n);return Math.abs(t).toString(36)})(e.error);return`${e.targetWidgetId}-${e.targetPortName}-${e.sourcePortName}-${t}`};let ta=null;const na={},ra=()=>{Ks.abortRequested=!1,Ks.isPaused=!1},ia=e=>(Ks.pausePromise||(Ks.isPaused=!0,Ks.pausePromise=new Promise((e=>{Ks.pausePromiseResolve=e})),e&&(Ks.lastPausedWidgetId=e),Js({isProcessing:!0,isPaused:!0,...e?{pauseTrapWidgetId:e}:{}})),Ks.pausePromise);var oa=async e=>{const{thingId:t,widgetId:n}=e,r=Zs(t,n),i=Xs(t,n),o=Qs({thingId:t,widgetId:n});if(o.isProcessing)return;const s={isProcessing:!0,isPaused:!1,startTime:Date.now()};Fs[r]=s,Ws||(Ws=!0,Ys=null,await Js({isProcessing:!0,isPaused:!1})),await Bs.emit(i,{thingId:t,widgetId:n,prevState:o,newState:s})},sa=async e=>{const{thingId:t,widgetId:n,error:r}=e,i=Zs(t,n),o=Xs(t,n),s=Qs({thingId:t,widgetId:n}),a={isProcessing:!1,isPaused:!1,startTime:s.startTime,endTime:Date.now(),error:r};Fs[i]=a,await Bs.emit(o,{thingId:t,widgetId:n,prevState:s,newState:a}),r&&(Ys=r,(e=>{const{error:t,stateKey:n}=e,r=ea(t);na[r]={error:t,stateKey:n},ta&&clearTimeout(ta),ta=setTimeout((()=>{for(const e in na)Bs.emit(qs,na[e].error),delete na[e]}),250)})({error:r,stateKey:i})),Ws&&0===Object.values(Fs).filter((e=>e.isProcessing)).length&&(Ws=!1,Gs=!1,ra(),await Js({isProcessing:!1,isPaused:!1}))},aa=e=>Bs.on(zs,e),ca=()=>{Ws=!1;for(const e in Fs)delete Fs[e];Ks.abortRequested=!1,Ks.isPaused=!1,Ks.pausePromise=null,Ks.pausePromiseResolve=null,Ks.lastPausedWidgetId=null,Bs.clearListeners()},la=()=>Ks.abortRequested,ua=e=>{Ks.lastPausedWidgetId=e,Ks.isPaused=!0,Js({isProcessing:!0,isPaused:!0,pauseTrapWidgetId:e})},da=()=>Gs||Vs?null:Ks.pausePromise,ha=e=>Vs?null:Us[e]??null,fa=()=>Gs,pa=e=>ia(e),ga=e=>{const t=ea(e),n=na[t];if(r=Ys,i=n?.error,r?.targetWidgetId===i?.targetWidgetId&&r?.targetPortName===i?.targetPortName&&r?.sourcePortName===i?.sourcePortName&&r?.error===i?.error){if(n){const e=n.stateKey;Fs[e].error=null}Ys=null}var r,i;delete na[t]};var ma={onParentEvent:async(e,t,n,r)=>{const i={...r.getState()};r.setState({...i,$$lastEventType:n.data.type});try{await r.nextWidget("event",n.data)}catch(e){const t=e;t.targetWidgetId&&t.targetPortName&&t.sourcePortName&&ga({targetWidgetId:t.targetWidgetId,targetPortName:t.targetPortName,sourcePortName:t.sourcePortName,error:t.message}),await r.nextWidget("error",{type:me.JsonObj,value:{error:{message:e.message,targetWidgetId:t.targetWidgetId,targetPortName:t.targetPortName,sourcePortName:t.sourcePortName,sourceWidgetId:t.sourceWidgetId,targetWidgetType:t.targetWidgetType,sourceWidgetType:t.sourceWidgetType,stack:e.stack},inputEvent:{type:n.data.type,data:n.data.value}}})}},getInputNames:()=>[{name:"event",type:me.Anything}],getOutputNames:e=>[{name:"event",type:{...e}.$$lastEventType??me.Anything},{name:"error",type:me.JsonObj,jsonShape:{error:me.JsonObj,inputEvent:me.JsonObj}}]};const ya={},va=Object.freeze({output:"output"}),ba=Object.freeze({read:"read",clear:"clear"}),wa=()=>({$$$time:0,totalInputs:1});var Sa={onParentEvent:async(e,t,n,r)=>{const i={$$$time:0,totalInputs:1,...r.getState()};if(ya[r.id]||(ya[r.id]={}),t.name===ba.clear)return ya[r.id]={},void r.setState(i);const o=t.name===ba.read;if(!(o||n.data.type!==me.JsonObj&&n.data.type!==me.Anything&&n.data.type!==me.Rect||"object"!=typeof n.data.value||null===n.data.value||Array.isArray(n.data.value))){const e=ya[r.id]||{};ya[r.id]={...e,...n.data.value}}if(o){const e={...ya[r.id]};return ya[r.id]={},r.setState({...i}),r.nextWidget(va.output,{type:me.JsonObj,value:e})}},getInputNames:e=>{const t={$$$time:0,totalInputs:1,...e},n=Array(t.totalInputs||1).fill(0).map(((e,t)=>({name:`input${t+1}`,type:me.Anything})));return n.push({name:ba.clear,type:me.Anything},{name:ba.read,type:me.Anything,triggerPort:!0}),n},getOutputNames:()=>[{name:va.output,type:me.JsonObj}],getDefaultState:wa,initialize:async e=>{ya[e.widgetId]={}},terminate:async e=>{delete ya[e.widgetId]}};const _a={},Ia=Object.freeze({output:"output",index:"index",finish:"finish"}),xa=Object.freeze({array:"array",next:"next",clear:"clear"}),ka=()=>({autoLoop:!1,autoClear:!1,$$outputType:me.Anything,totalItems:0,currentIndex:0});var Ea={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),o={...ka(),...i};if(t.name===xa.clear)return delete _a[r.id],void r.setState({...ka(),autoLoop:o.autoLoop,autoClear:o.autoClear});if(t.name!==xa.array)t.name===xa.next&&await(async e=>{const t=e.id,n=_a[t],r={...ka(),...e.getState()};if(n&&n.index<n.list.length){const i=n.index,o=n.list[i];await e.nextWidget(Ia.index,{type:me.Number,value:i}),await e.nextWidget(Ia.output,{type:r.$$outputType,value:o}),n.index++,e.setState({...r,currentIndex:n.index}),n.index===n.list.length&&(await e.nextWidget(Ia.finish,{type:me.Boolean,value:!0}),r.autoClear?(delete _a[t],e.setState({...ka()})):(n.index=0,e.setState({...r,currentIndex:0})))}})(r);else if((n.data.type===me.Array||n.data.type===me.Anything)&&Array.isArray(n.data.value)){const e=n.data.value,t=e[0],i=void 0!==t?Be(t):me.Anything,s={list:e,index:0};_a[r.id]=s;const a={...o,$$outputType:i,totalItems:e.length,currentIndex:0};if(r.setState(a),a.autoLoop&&e.length>0){for(const t of e){const e=s.index;r.setState({...a,currentIndex:e}),await r.nextWidget(Ia.index,{type:me.Number,value:e}),await r.nextWidget(Ia.output,{type:a.$$outputType,value:t}),s.index++}await r.nextWidget(Ia.finish,{type:me.Boolean,value:!0}),a.autoClear?(delete _a[r.id],r.setState({...a,$$outputType:me.Anything,totalItems:0,currentIndex:0})):(s.index=0,r.setState({...a,currentIndex:0}))}}},getInputNames:()=>[{name:xa.array,type:me.Array},{name:xa.next,type:me.Anything},{name:xa.clear,type:me.Anything}],getOutputNames:e=>{const t={...ka(),...e};return[{name:Ia.index,type:me.Number},{name:Ia.output,type:t.$$outputType},{name:Ia.finish,type:me.Anything}]},getDefaultState:ka,initialize:async e=>{const t={...ka(),...e.getState()};_a[e.widgetId]={list:[],index:0},e.setState({...t,currentIndex:0,totalItems:0})},terminate:async e=>{delete _a[e.widgetId]}};var Ca={onParentEvent:async(e,t,n,r)=>{const i={name:"",...r.getState()};i.name&&e&&Bi({name:i.name,sourceWidget:e?.sourceWidgetId,widgetId:r.id,widgetType:Ke.status,value:{type:n.data.type,value:n.data.value}})},getOutputNames:()=>[],getInputNames:()=>[{name:"status",type:me.Anything}],terminate:async e=>{Vi(e.widgetId)},initialize:async e=>{const t={name:"",...e.getState()};Bi({name:t.name||"",sourceWidget:"",widgetType:Ke.status,widgetId:e.widgetId,value:null})}};const $a={onParentEvent:async(e,t,n,r)=>{if(!r.eventContext)return;const i=r.eventContext;if(i?.eventKey)return ct(i.eventKey,n.data.value);console.error("No event key found in context event")},getOutputNames:()=>[],getInputNames:()=>[{name:"event",type:me.Anything}]},Oa="read",Na="setValue",Ta=new Map,Aa=new Map,Ma=(e,t)=>{const n=`${e}_${t}`,r=Ta.get(n);r&&(r(),Ta.delete(n))},Pa=(e,t,n)=>{const r=`${e}_${t}`;n?Ta.set(r,n):Ta.delete(r)};var Da={onParentEvent:async(e,t,n,r)=>{const i={name:"",reactive:!1,lastConfiguration:null,...r.getState()};if(!i.name)return;const o=ao.getGlobalVariable(i.name);if(o)if(t.name===Oa)o&&null!==o.lastValue&&null!==o.lastDataType&&await r.invokeNextWidget({port:"value",data:{type:o.lastDataType,value:o.lastValue}});else if(t.name===Na){let e=n.data.value;if(("number"===o.controlType||"slider"===o.controlType)&&(e=Number(e),isNaN(e)))throw new Error("Expected event value to be a number");if("binaryFile"===o.controlType&&n.data.type!==me.BinaryFile||"image"===o.controlType&&n.data.type!==me.ImageData||("text"===o.controlType||"multilineText"===o.controlType)&&n.data.type!==me.String||"checkbox"===o.controlType&&n.data.type!==me.Boolean&&n.data.type!==me.Number||"button"===o.controlType&&n.data.type!==me.Boolean)throw new Error(`Invalid type, expected event value to be a ${(e=>{switch(e){case"number":case"slider":return"Number";case"text":case"dropdown":case"multilineText":return"String";case"image":return"ImageData";case"binaryFile":return"Binary File";case"checkbox":return"Boolean or Number";case"button":return"Boolean"}return"Anything"})(o.controlType)}`);i.lastConfiguration?.controlSettings===o.controlSettings&&i.lastConfiguration?.controlType===o.controlType&&i.lastConfiguration?.helpText===o.helpText&&i.lastConfiguration?.group===o.group||(i.lastConfiguration={controlType:o.controlType,controlSettings:o.controlSettings,helpText:o.helpText,group:o.group},r.setState({...i})),Aa.set(r.id,{eventId:r.eventId,varName:i.name,type:n.data.type});const{group:t,name:s}=Ki(i.name);await ao.setGlobalVariable({name:s,group:t,value:e,lastDataType:n.data.type,widgetId:r.id,executionContext:{eventId:r.eventId,currentPath:r.currentPath}}),i.reactive&&await r.invokeNextWidget({port:"value",executionContext:{currentPath:r.currentPath,eventId:r.eventId},data:{type:n.data.type,value:e}})}},getOutputNames:e=>{const t={name:"",reactive:!1,lastConfiguration:null,...e};let n=me.Anything;if(t.name){const e=ao.getGlobalVariable(t.name);e?.lastDataType&&(n=e.lastDataType)}return[{name:"value",type:n}]},getInputNames:()=>[{name:Oa,type:me.Anything},{name:Na,type:me.Anything}],terminate:async e=>{Ma(e.widgetId,"variable"),Ma(e.widgetId,"group"),Ma(e.widgetId,"parentGroup"),Aa.delete(e.widgetId)},initialize:async e=>{const t={name:"",reactive:!1,lastConfiguration:null,...e.getState()};Ma(e.widgetId,"variable"),Ma(e.widgetId,"group"),Ma(e.widgetId,"parentGroup"),Aa.set(e.widgetId,null);let n=t.name;t.name&&!t.name.includes(".")&&t.lastConfiguration?.group&&(n=qi(t.lastConfiguration.group,t.name),e.setState({...t,name:n}));const r=ao.getGlobalVariable(n);if(!r&&t.lastConfiguration?.controlType){const{group:r,name:i}=Ki(n);if(r){if(!ao.getGlobalVariable(r)){const{name:e,group:n}=Ki(r);await ao.setGlobalVariable({name:e,group:n,helpText:t.lastConfiguration.groupHelpText??void 0,controlType:"group",value:null,disableChangeNotifications:!0,disableDefineNotifications:!1})}}await ao.setGlobalVariable({name:i,helpText:t.lastConfiguration.helpText,controlType:t.lastConfiguration.controlType,controlSettings:t.lastConfiguration.controlSettings,order:t.lastConfiguration.order,value:null,group:r,disableChangeNotifications:!0,disableDefineNotifications:!1});const o=qi(r,i);e.setState({...t,name:o})}else r&&e.setState({...t,name:n,lastConfiguration:{...t.lastConfiguration,controlType:r.controlType,controlSettings:r.controlSettings,helpText:r.helpText,group:r.group}});if(n){const t=ao.onGlobalVariableParentGroupChange(n,(async t=>{const n=e.getState();let r;if(t.group){const e=ao.getGlobalVariable(t.group);e&&(r=e.helpText??void 0)}const i=t.name;e.setState({...n,name:i,lastConfiguration:{controlType:t.controlType,controlSettings:t.controlSettings,helpText:t.helpText,group:t.group,groupHelpText:r,order:t.order}})}));Pa(e.widgetId,"group",t)}if(n){const t=ao.onVarParentGroupStateChange(n,(async t=>{const r=e.getState(),{name:i}=Ki(n),o=qi(t.parentGroup.name,i);e.setState({...r,name:o,lastConfiguration:{...r.lastConfiguration??{},group:t.parentGroup.name,groupHelpText:t.parentGroup.helpText??void 0}})}));Pa(e.widgetId,"parentGroup",t)}if(t.reactive&&n){const t=ao.onGlobalVariableChange(n,(async t=>{const n=e.getState();if(n.lastConfiguration?.controlType===t.controlType&&n.lastConfiguration?.controlSettings===t.controlSettings&&n.lastConfiguration?.helpText===t.helpText&&n.lastConfiguration?.group===t.group||e.setState({...n,lastConfiguration:{controlType:t.controlType,controlSettings:t.controlSettings,helpText:t.helpText,group:t.group}}),null!==t.lastValue&&null!==t.lastDataType){const n=Aa.get(e.widgetId);if(n?.varName===t.name&&n.type===t.lastDataType&&n.eventId===t.lastExecutionContext?.eventId)return void Aa.set(e.widgetId,null);await e.invokeNextWidget({port:"value",...t.lastExecutionContext?{executionContext:{...t.lastExecutionContext}}:void 0,data:{type:t.lastDataType,value:t.lastValue}})}}));Pa(e.widgetId,"variable",t)}}};const ja=Object.freeze({input:"input"}),Ra="out",La="else",Fa=()=>({conditions:[{expression:"",output:"input"},{expression:"",output:"input"}],multipleOutputs:!0}),Ua=e=>null!=e&&("number"==typeof e?0!==e&&!Number.isNaN(e):"string"==typeof e?e.length>0:Boolean(e));var Ba={onParentEvent:async(e,t,n,r)=>{const i={conditions:[{expression:"",output:"input"},{expression:"",output:"input"}],multipleOutputs:!0,...r.getState()};if(t.name!==ja.input)return;let o;try{o=Ni(r.recipePoolId).uuid}catch{o=void 0}const s=i.conditions||[];for(let e=0;e<s.length;e++){const t=s[e],a=await Rs({customContext:{input:n.data.value},expression:t.expression||"",recipeUuid:o,enableFnTag:!0});if("symbol"!=typeof a.value){if(a.error)throw new Error(a.error);if(Ua(a.value)){let a=n.data.value;if(t.output&&"input"!==t.output){const e=await Rs({customContext:{input:n.data.value},expression:t.output,recipeUuid:o,enableFnTag:!0});if(e.error)throw new Error(e.error);"symbol"!=typeof e.value&&(a=e.value)}else a=n.data.value;const c=Be(a);if(i.multipleOutputs){const n=[...s];n[e]={...t,$lastOutputType:c},r.setState({...i,conditions:n})}const l=i.multipleOutputs?String(e+1):Ra;return i.multipleOutputs||i.$lastOutputType===c||r.setState({...i,$lastOutputType:c}),r.invokeNextWidget({port:l,data:{type:c,value:a}})}}}return r.invokeNextWidget({port:La,data:{type:n.data.type,value:n.data.value}})},getInputNames:()=>[{name:ja.input,type:me.Anything}],getOutputNames:e=>{if(!e.multipleOutputs)return[{name:Ra,type:e.$lastOutputType||me.Anything},{name:La,type:e.$lastElseOutputType||me.Anything}];const t=Math.max(1,e.conditions?.length||0),n=[];for(let r=0;r<t;r++){const t=e.conditions?.[r]?.$lastOutputType||me.Anything;n.push({name:String(r+1),type:t})}return n.push({name:La,type:e.$lastElseOutputType||me.Anything}),n},getDefaultState:Fa};const Wa=new Map;var Ga={registerFunctionHandler:(e,t)=>{Wa.set(e,t)},invokeFunction:async e=>{const{eventId:t,functionName:n,functionParams:r}=e,i=Wa.get(n);if(i)try{const e=await i(r,t);if("function"==typeof e)throw new Error("Functions are not allowed as return types");return e}catch(e){throw console.error(`Error invoking edge function [${n}]:`,e),e}},unregisterFunctionHandler:e=>{Wa.delete(e)},clearAllHandlers:()=>{Wa.clear()}};const Va=()=>({functionName:""}),Ya="result";var Ha={onParentEvent:async(e,t,n,r)=>{const i={functionName:"",...r.getState()};if(!i.functionName||!e)return;const o=r.eventId,s=await Ga.invokeFunction({eventId:o,functionName:i.functionName,functionParams:n.data.value});if(null!=s){const e=Be(s);await r.invokeNextWidget({port:Ya,data:{type:e,value:s}})}},getOutputNames:()=>[{name:Ya,type:me.Anything}],getInputNames:()=>[{name:"params",type:me.Anything}],getDefaultState:Va};const za=new Map,qa="read",Ka="setValue",Ja="value",Za=(e,t,n)=>{const r=ce({recipeId:e,widgetId:n});if(!r)return null;const i=r.groupId;if(!i)return null;const o=ce({recipeId:e,widgetId:i});return o&&o.type===Ke.widgetGroup?{widget:o,thingRecipeId:t}:null};var Xa={onParentEvent:async(e,t,n,r)=>{const i={fieldName:"",reactive:!1,...r.getState()};if(!i.fieldName)return;const o=Za(r.recipePoolId,r.thingRecipeId,r.id);if(!o)return;const s=o.widget,a=s.state,c=a.settings||[],l=c.find((e=>e.variableName===i.fieldName));if(l)if(t.name===qa){const e=l.config,t=e.customValue??e.defaultValue;if(void 0!==t){const e=Be(t);await r.invokeNextWidget({port:Ja,data:{type:e,value:t}})}}else if(t.name===Ka){const e=c.map((e=>{if(e.variableName===i.fieldName){const t={...e.config,customValue:n.data.value};return{...e,config:t}}return e}));s.state={...a,settings:e};const t=ti(i.fieldName);await ii({variableName:t,setByWidgetId:s.id,value:n.data.value,type:n.data.type})}},getOutputNames:()=>{const e=me.Anything;return[{name:Ja,type:e}]},getInputNames:()=>[{name:qa,type:me.Anything},{name:Ka,type:me.Anything}],initialize:async e=>{const t={fieldName:"",reactive:!1,...e.getState()},n=za.get(e.widgetId);if(n&&(n(),za.delete(e.widgetId)),t.reactive&&t.fieldName){const n=Za(e.recipePoolId,e.thingRecipeId,e.widgetId);if(!n)return;const r=n.widget,i=ti(t.fieldName),o=si({variableName:i,type:me.Anything,widgetId:e.widgetId,onValueChange:async t=>{if(t.setByWidgetType===Ke.widgetGroup&&t.setByWidgetId===r.id){if(!{fieldName:"",reactive:!1,...e.getState()}.reactive)return;if(void 0===t.value)return;await e.invokeNextWidget({port:Ja,data:{type:t.type,value:t.value}})}}});za.set(e.widgetId,o)}},terminate:async e=>{const t=za.get(e.widgetId);t&&(t(),za.delete(e.widgetId))}};const Qa={input:dt,counter:pt,elapsed:yt,ifGate:St,skipEvent:kt,between:Ot,map:At,parser:jt,slider:Ft,suspend:Gt,display:Yt,json:qt,arrayItem:Zt,extractImage:nn,imageConvolution:cn,firstEvent:hn,pixelDraw:wn,randomBetween:xn,arrayCombine:On,clock:Mn,delay:Un,multiplication:Vn,object:Jn,widgetGroup:er,script:Io,base64ToImageData:Oo,jsonParse:Mo,text:Ro,imageCrop:Bo,imageResize:Yo,value:Ko,imageWarp:Qo,sequence:is,variable:cs,hubService:us,imageFilter:ps,recipeLoad:ms,note:ys,stringify:vs,templateString:Ds,expressionEval:Ls,rescue:ma,objectCombine:Sa,loop:Ea,status:Ca,secret:Ti,output:$a,globalVariable:Da,switch:Ba,edgeFunction:Ha,fieldValue:Xa,play:{getInputNames:()=>[],onParentEvent:()=>Promise.resolve(),getOutputNames:()=>[{name:"out",type:me.Boolean}]}},ec={},tc=async()=>{if(!Object.keys(ec).length)for(const e in Qa){const t=Qa[e];ec[e]=Object.freeze({...t})}};var nc,rc,ic=e=>{if(ec[e])return ec[e];throw new Error(it(rt,e))},oc=tc;!function(e){e.ServiceCreationLog="service-creation-log"}(nc||(nc={})),function(e){e.Service="service",e.ServiceUI="serviceUI"}(rc||(rc={}));let sc={},ac=0,cc=null;const lc=(e,t)=>{if(e.type===Ke.hubService){if(t.type!==Ke.hubService)return!1;const n=e.state,r=t.state,i=n.service?.name,o=r.service?.name;return!(!i||!o||i!==o)}return e.type===Ke.output&&t.type===Ke.input},uc=e=>{const{widgetId:t,widgets:n,currentPath:r}=e,i=n[t];if(!i)return[];const o=new Map;for(let e=0;e<r.length;e++){const t=r.slice(0,e+1),s=t.join("/"),a=sc[s];if(a){const c=n[a.widgetId];if(c){const n=a.path,l=r.join("/").startsWith(n);lc(i,c)&&l&&(o.has(s)||o.set(s,{path:s,data:a,pathSegments:t.length,pathIndex:e,invocationOrder:a.invocationOrder,timestamp:a.timestamp}))}}}const s=Array.from(o.values()).sort(((e,t)=>e.pathIndex-t.pathIndex));return s},dc=e=>{const{context:t,widgetId:n,currentPath:r,executionId:i="default"}=e;if(ac++,0===r.length)throw new Error("Current path cannot be empty");if(!r[r.length-1].includes(n))throw new Error("The widget id is expected to be part of the path");const o=r.join("/");sc[o]={path:o,eventContext:t,widgetId:n,invocationOrder:ac,timestamp:Date.now(),executionId:i}},hc=e=>{const t=uc(e);return t.length>0?t[t.length-1]:null},fc=()=>{sc={},ac=0},pc=e=>{cc=e},gc=()=>{sc={},ac=0};let mc,yc,vc,bc=!1,wc=0,Sc=0;const _c=async e=>{const{widgetId:t,thingId:n,recipeId:r,targetPortName:i,data:o}=e,s=ae(r,n);if(!s)return;const a=s.gates[t];if(!a||a.disabled)return;const c={...o,timestamp:Date.now()},l=ic(a.type);Sc+=1;const u=Cc({gateId:t,originalEvent:c,blockRecipeId:s.recipeId,blockDbId:s.id,blockVersion:s.version,recipeId:r,sourceWidgetId:void 0,currentPath:[],eventId:Sc});if(u&&l.onParentEvent){const e={name:i};return mc&&await mc({recipeId:r,blockId:s.recipeId,gateId:t,targetPort:e.name,data:o}),l.onParentEvent(null,e,{originalEvent:c,data:{...c}},u)}},Ic=async e=>{const{eventContext:t,interruptDriven:n,childGateId:r,recipeId:i,sourcePortName:o,targetPort:s,data:a,sourceOutputNames:c,sourceWidgetId:l,bypassHistoryRecording:u,eventId:d}=e;let{originalEvent:h,block:f}=e;if(!n&&!l)throw new Error("Missing parameter ['sourceGateId']");if(!n&&!h)throw new Error("Missing parameter ['originalEvent']");n&&(h={timestamp:Date.now(),type:me.Boolean,value:!0});const p=h;if("string"==typeof f){const e=ae(i,f);if(!e)return;f=e}const g=f.gates[r];if(!g||g.disabled)return;const m=c.findIndex((e=>e.name===o)),y=ic(g.type),v=[...e.currentPath];if(l){0===v.length?v.push(`${l}:${d?.toString()}`):v.push(l)}if(t){const e=ce({recipeId:i,widgetId:l});e?.type!==Ke.hubService&&e?.type!==Ke.input||dc({context:t,widgetId:l,currentPath:v,executionId:d?.toString()})}const b=Cc({gateId:r,originalEvent:p,blockRecipeId:f.recipeId,blockDbId:f.id,blockVersion:f.version,recipeId:i,sourceWidgetId:l,currentPath:v,eventId:d});if(b&&y.onParentEvent&&-1!==m){mc&&await mc({recipeId:i,blockId:f.recipeId,gateId:r,targetPort:s.name,data:a,sourceGate:n?"interrupt_widget":l,sourcePort:n?he:o});const e={name:c[m].name,type:c[m].type,...c[m].jsonShape?{jsonShape:c[m].jsonShape}:void 0,sourceWidgetId:l};return u||Ii({thingId:f.recipeId,widgetId:r,sourceOutputNames:c,targetPortName:s.name,currentPath:v,eventId:d,data:a,originalEvent:p,recipeId:i,source:l?{widgetId:l,portName:o}:void 0}),y.onParentEvent(e,s,{originalEvent:p,data:a},b)}},xc=async e=>{const{portName:t,originalEvent:n,data:r,currentGateId:i,blockRecipeId:o,thingDbId:s,thingVersion:a,recipeId:c,eventContext:l,currentPath:u}=e;let{eventId:d}=e;const h=se(c);if(!h)throw new Error(`Failed to find recipe "${c}" in cache`);const f=h.dbInfo.recipeType,p=le(c,o,i);if(!p)return;const g={...r,timestamp:n.timestamp},m=ic(p.type);let y;y=p.type===Ke.input?m.getOutputNames(p.state,{thingRecipeId:o,thingDbId:s,thingVersion:a,id:i,recipeId:c,recipeType:f,recipePoolId:c}):await m.getOutputNames(p.state,{recipePoolId:c,recipeType:f,thingRecipeId:o,widgetId:i});if(-1!==y.findIndex((e=>e.name===t))){const e=ae(c,o);if(!e)return;null===d&&(Sc+=1,d=Sc),_i({thingId:o,widgetId:i,sourceOutputNames:y,sourcePortName:t,currentPath:u,data:g,recipeId:c,eventId:d});let r=null;const s=p.children.length,a=u;try{for(let u=0;u<s;u++){const s=e.gates[p.children[u].childId];if(s?.disabled)continue;const h=Ve(p.children[u]?.sourcePort),m=Ve(p.children[u]?.targetPort);if(h.portName===t&&s&&!s.disabled){if(bc&&da()&&(ua(s.id),await da()),ha(s.id)&&!fa()&&"innerInput"!==m?.portType){const e=pa(s.id);await e}if(bc&&la())break;const u=ic(s.type);let h;const v={recipePoolId:c,recipeType:f,thingRecipeId:o,widgetId:i};h=s.type===Ke.hubService?await u.getInputNames(s.state,v):u.getInputNames(s.state,v);const b=h.find((e=>e.name===m.portName));if(b){bc&&await oa({thingId:o,widgetId:s.id}),wc++;if(!await Ic({eventContext:l,interruptDriven:!1,childGateId:s.id,block:e,recipeId:c,sourcePortName:t,currentPath:a,eventId:d,targetPort:{name:b.name},data:p.returnOriginalEvent?n:g,sourceOutputNames:y,sourceWidgetId:p.id,originalEvent:n}).then((()=>!0)).catch((e=>{const n=s.type===Ke.hubService&&"CHILD_WIDGET_ERROR"===e.errCode;if(e instanceof jr)throw e;if(n&&e.errData){const t=e.errData;throw new jr(e.error||e.message||("string"==typeof e?e:JSON.stringify(e)),{targetWidgetId:t.targetWidgetId,targetPortName:t.targetPortName,sourcePortName:t.sourcePortName,sourceWidgetId:t.sourceWidgetId,targetWidgetType:t.targetWidgetType,sourceWidgetType:t.sourceWidgetType})}if(!r){const n="string"==typeof e?e:e.message||JSON.stringify(e);r={targetWidgetId:s.id,targetPortName:b.name,sourcePortName:t,error:n}}throw new jr(e.message||("string"==typeof e?e:JSON.stringify(e)),{stack:e.stack,targetWidgetId:s.id,targetPortName:b.name,sourcePortName:t,sourceWidgetId:p.id,targetWidgetType:s.type,sourceWidgetType:p.type})})).finally((()=>{if(wc--,bc)return sa({thingId:o,widgetId:s.id,error:r})})))break}}}}catch(e){if(e instanceof jr)throw e;console.error(`Error processing next widget [${i}]: ${e}`)}finally{wc<0&&(console.warn("Active execution counter is negative, this should never happen"),wc=0),0===wc&&fc()}}},kc=async(e,t,n,r)=>{const i=se(r);if(!i)return null;const o=ae(r,n);if(!o)return o;const s=o.gates,a=o.gates[t],c=ic(a.type),l=await c.getInputNames(a.state,{recipePoolId:r,recipeType:i.dbInfo.recipeType,thingRecipeId:n,widgetId:t}),u=l.findIndex((t=>t.name===e));if(-1!==u){const e=((e,t,n)=>{for(const r in n){const i=n[r],o=i.children.length;for(let n=0;n<o;n++){const r=i.children[n],o=Ve(r.targetPort);if(r.childId===e&&o.portName===t)return i}}return null})(t,l[u].name,s);if(e){const t=ic(e.type);return{getValue:()=>"function"==typeof t.getValue?t.getValue():null}}}return null},Ec=e=>{const{gateId:t,originalEvent:n,thingRecipeId:r,thingDbId:i,thingVersion:o,recipeId:s,currentPath:a,eventId:c}=e;if(!se(s))throw new Error(`Failed to find recipe "${s}" in cache`);if(!le(s,r,t))throw console.warn(`Gate ${t} not found in block ${r} for recipe ${s}`),new Error(`Gate ${t} not found in block ${r} for recipe ${s}`);return async e=>xc({portName:e.port,originalEvent:n||{timestamp:Date.now(),type:e.data.type,value:e.data.value},data:e.data,currentGateId:t,blockRecipeId:r,thingDbId:i,thingVersion:o,recipeId:s,eventContext:e.eventContext,currentPath:e.executionContext?.currentPath||a,eventId:e.executionContext?.eventId||c})},Cc=e=>{const{gateId:t,originalEvent:n,blockRecipeId:r,blockDbId:i,blockVersion:o,recipeId:s,currentPath:a,eventId:c}=e,l=se(s);if(!l)throw new Error(`Failed to find recipe "${s}" in cache`);const u=le(s,r,t);if(!u)return console.warn(`Gate ${t} not found in block ${r} for recipe ${s}`),null;const d=Ec({gateId:t,originalEvent:n,thingRecipeId:r,thingDbId:i,thingVersion:o,recipeId:s,currentPath:a,eventId:c}),h=hc({widgetId:t,widgets:l.blocks[r].gates,currentPath:e.currentPath}),f=(e,t,n,r)=>d({port:e,data:t,eventContext:n,executionContext:r}),p={id:t,type:u.type,recipePoolId:s,thingRecipeId:r,recipeType:l.dbInfo.recipeType,returnOriginalEvent:!!u.returnOriginalEvent,currentPath:e.currentPath,eventId:c,eventContext:h?.data.eventContext||void 0,registerInterrupt:e=>{const{type:n,customTargetPortName:i,config:o,sourceWidgetId:a,interruptData:c,customId:l}=e;return tt.createInterrupt({type:n,recipePoolId:s,thingId:r,targetWidgetId:t,sourceWidgetId:a,portName:i,config:o,data:c,customId:l})},cancelInterrupt:e=>tt.destroyInterrupt(e),invokeNextWidget:d,nextWidget:f,nextGate:f,getParentAtPort:e=>kc(e,t,r,s),getState:()=>Object.freeze({...u.state,...u.type===Ke.input&&{customInputs:[]}}),setState:e=>{if("object"!=typeof e)return void console.warn(`Invalid state type [${typeof e}]. Expected an 'object'`);const n={...e,...u.type===Ke.input&&!e.customInputs&&{customInputs:[]}},i={...u.state};u.state=n,yc&&yc({blockId:r,gateId:t,prevState:i,newState:{...n},recipeId:s})}};return p};tt.setInvokeChildGateCb(Ic),tt.setConsumeEventCounterCb((()=>++Sc));const $c=(e,t,n,r,i)=>{const o=le(e,n,r);if(!o)return console.warn(`Gate ${r} not found in block ${n} for recipe ${e}`),null;const s=t=>{const{type:i,customTargetPortName:o,config:s,data:a}=t;return tt.createInterrupt({type:i,recipePoolId:e,thingId:n,targetWidgetId:r,sourceWidgetId:r,portName:o,config:s,data:a})},a=()=>Object.freeze({...o.state,...o.type===Ke.input&&{customInputs:[]}}),c=e=>{if("object"!=typeof e)return void console.warn(`Invalid state type [${typeof e}]. Expected an 'object'`);const t={...e,...o.type===Ke.input&&!e.customInputs&&{customInputs:[]}};o.state=t},l=async t=>{const r=((e,t,n)=>{const r=se(e);if(!r)throw new Error(`Recipe [${e} does not exist]`);if(!r.storage)return null;const i=ae(e,t);if(!i)throw new Error(`The Thing "${t}" does not exist in recipe ${e}`);if(!(i.storageUnits||[]).includes(n))throw new Error(`The Thing "${t}" has no access to storage unit "${n}"`);return r.storage[n]||null})(e,n,t);return r};if(i){const i=Ec({gateId:r,thingRecipeId:n,thingDbId:o.id,thingVersion:"default",recipeId:e,currentPath:[],eventId:null});return{getState:a,setState:c,registerInterrupt:s,getStorageData:l,nextWidget:(e,t,n)=>i({port:e,data:t,eventContext:n}),invokeNextWidget:i,recipePoolId:e,recipeType:t,thingRecipeId:n,widgetId:r}}return{getState:a,setState:c,recipePoolId:e,widgetId:r,thingRecipeId:n}},Oc=new a,Nc="invoked",Tc="state",Ac=()=>{tt.destroyAllInterrupts()},Mc=async(e,t,n)=>{const r=se(e),i=le(e,t,n);if(i&&r){const o=ic(i.type);if(o&&"function"==typeof o.terminate){const i=((e,t,n,r)=>$c(e,t,n,r))(e,r.dbInfo.recipeType,t,n);if(i)try{await o.terminate(i)}catch(e){console.warn(`Error terminating widget "${n}" in thing "${t}". Failing silently: `,e)}}}},Pc=async e=>{const{recipePoolId:t,thingRecipeId:n,widgetRecipeId:r,options:i}=e,o=se(t),s=le(t,n,r);if(s&&o){const e=ic(s.type);if(e&&"function"==typeof e.initialize){const a=((e,t,n,r)=>$c(e,t,n,r,!0))(t,o.dbInfo.recipeType,n,r);if(a){const t=e.initialize;try{(e=>{if(e.type===Ke.script){const t=e.state;if((t.version||0)<2){const n=Object.keys(e.variablesListener||{});for(const t of n)if(e.variablesListener){const n=ti(t);e.variablesListener[n]=e.variablesListener[t],delete e.variablesListener[t],delete e.variables}t.version=2}}})(s),await t(a,i||{})}catch(e){throw console.warn(`Error initializing widget "${r}" in thing "${n}": `,e),e}}}}},Dc=(e,t)=>{const n=se(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},jc=(e,t="",n="")=>`block:${t}:gate:${n||""}:${e}`,Rc=e=>{Oc.emit(jc(Tc),e),Oc.emit(jc(Tc,e.blockId,e.gateId),e)};mc=async e=>{await Oc.emit(jc(Nc),e),await Oc.emit(jc(Nc,e.blockId,e.gateId),e)},(e=>{yc=e})(Rc);var Lc=async(e,t,n,r,i)=>{const o=ue(e,{id:t,authorId:r,version:n,recipeType:i});xi(),gc(),pc(i),e.globalVariables&&ao.registerGlobalVariables(e.globalVariables);const s=se(o);return s&&(s.startedAt=Date.now(),s.retryAttempts=0,s.execCounter=0,s.status=Q.STARTING,s.addLog("recipe registered")),o},Fc=async e=>{const t=se(e);if(!t)return null;t.addLog("terminating recipe"),Ac(),ca();for(const n in t.blocks){const r=t.blocks[n];for(const t in r.gates)await Mc(e,n,t)}(e=>{!!re[e]&&delete re[e]})(e)},Uc=async(e,t)=>{const n=se(e),r=[],i=[];if(n){Gi(),ai({recipePoolId:e,thingId:pe});for(const o in n.blocks){const s=n.blocks[o];if(!t||!Array.isArray(t)||t.includes(o))for(const t in s.gates)try{if(n.dbInfo?.recipeType===mr.Desktop){const e=s.gates[t];if(e.type===Ke.hubService){const r=e.state;if(r?.service?.webOnly){n?.addLog(`skipping initialization of web-only widget "${t}"`);continue}}e.type===Ke.recipeLoad&&i.push(e)}await Pc({recipePoolId:e,thingRecipeId:o,widgetRecipeId:t,options:{keepCurrentState:!0}})}catch(e){r.push({widgetId:t,error:e.message})}}}return{failed:r,sendToInputWidget:t=>{const{inputName:n,data:r,thingId:i=pe,waitForOutputChild:o=!0}=t;return(async e=>{const{inputName:t,data:n,recipePoolId:r,thingId:i,waitForOutputChild:o=!0}=e,s=se(r),a=ae(r,i),c=Date.now();if(a&&s){Sc+=1;for(const e in a.gates){const s=a.gates[e];if(s.type===Ke.input&&!s.disabled){const l=s.state.inputName||"";if(l===t){const t=ic(s.type),u={...n,timestamp:c},d=Cc({gateId:e,originalEvent:u,blockRecipeId:i,blockDbId:a.id,blockVersion:a.version,recipeId:r,sourceWidgetId:void 0,currentPath:[],eventId:Sc});if(d&&t.processEvent){const s={...d,getState:d.getState,waitForOutputChild:o};if(mc&&await mc({recipeId:r,blockId:i,gateId:e,targetPort:ut,data:n}),!vc)return await t.processEvent(u,s);await vc(i,r,l,n)}continue}}}}})({inputName:n,data:r,recipePoolId:e,thingId:i,waitForOutputChild:o})},invokeRecipeLoadedWidgets:async()=>{for(const t of i)await _c({widgetId:t.id,thingId:pe,recipeId:e,targetPortName:gs,data:{type:me.Boolean,value:!0}})}}},Bc=e=>{fi(e)},Wc=(e,t,n,r=!1)=>{const i=Dc(t,e);if(i){const{widget:o,thing:s}=i,a={...o.state};o.state=n,r&&Rc({blockId:s.recipeId,gateId:t,recipeId:e,newState:{...n},prevState:a})}},Gc=(e,t)=>{const n=Dc(t,e);return n?n.widget.state:null},Vc=async e=>{const{recipePoolId:t,currentGateId:n,sourcePortName:r,originalEvent:i,data:o,eventContext:s,currentPath:a,eventId:c}=e,l=Dc(n,t);if(l)return xc({portName:r,originalEvent:i,data:o,currentGateId:n,blockRecipeId:l.thing.recipeId,thingDbId:l.thing.id,thingVersion:l.thing.version,recipeId:t,eventContext:s,currentPath:a,eventId:c})},Yc=()=>{bc=!0},Hc=ki;const zc=async e=>{const t=async(e,n)=>{if(null==e)return null;switch(n){case"image":return await ze({base64Str:e});case"binaryFile":{const t=e;let n;const r=((e,{minLength:t=4,maxChars:n=1e4,allowDataURI:r=!0,allowBase64Prefix:i=!0,sliceAndTest:o=!0}={})=>{if("string"!=typeof e)return!1;let s=e.trim();if(!s)return!1;if(r){const e=s.match(/^data:([^;,]+)?;base64,(.*)$/i);if(e){const t=e[2]??"";if(/[\r\n]/.test(t))return!1;s=t}}if(i&&s.startsWith("base64:")&&(s=s.substring(7)),s=s.replace(/\s+/g,""),!s)return!1;if(s.length>n){if(!o)return!1;s=s.slice(0,n)}const a=/[+/]/.test(s),c=/[-_]/.test(s);if(a&&c)return!1;if(c?!/^[A-Za-z0-9_-]*={0,2}$/.test(s):!/^[A-Za-z0-9+/]*={0,2}$/.test(s))return!1;const l=s.match(/=+$/)?.[0].length??0;if(l>2)return!1;if(/=/.test(s.slice(0,s.length-l)))return!1;if(s.length<Math.max(4,t))return!1;let u,d=c?s.replace(/-/g,"+").replace(/_/g,"/"):s;s.length%4&&(d=d.padEnd(d.length+(4-d.length%4),"="));try{if("undefined"!=typeof Buffer&&"function"==typeof Buffer.from)u=new Uint8Array(Buffer.from(d,"base64"));else{if("function"!=typeof atob)return!1;{const e=atob(d);u=new Uint8Array(e.length);for(let t=0;t<e.length;t++)u[t]=e.charCodeAt(t)}}}catch{return!1}if(0===u.length)return!1;let h=(e=>{if("undefined"!=typeof Buffer)return Buffer.from(e).toString("base64");let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)})(u);c&&(h=h.replace(/\+/g,"-").replace(/\//g,"_"));const f=e=>e.replace(/=+$/g,""),p=f(h)===f(s);if(!p)return!1;const g=String.fromCharCode(...u),m=/^[\x09\x0A\x0D\x20-\x7E]*$/.test(g);return!(s.length<=20&&!m||s.length<=20&&/^[A-Za-z0-9_-]+$/.test(s)&&m&&!p||s.length<=50&&/^[A-Za-z0-9][A-Za-z0-9._-]*\/[A-Za-z0-9._+-]+$/.test(s)&&m||s.length>20&&/^[A-Za-z0-9_-]+$/.test(s)&&!/=/.test(s)&&m&&!p||s.length>20&&/^[A-Za-z0-9_-]+$/.test(s)&&!/=/.test(s)&&!m)})(t.data);if(r)n=await(e=>{if(ne){const t=Buffer.from(e,"base64"),n=new ArrayBuffer(t.byteLength);return new Uint8Array(n).set(t),n}{if("function"==typeof Uint8Array.fromBase64){const t=Uint8Array.fromBase64(e),n=new ArrayBuffer(t.byteLength);return new Uint8Array(n).set(t),n}const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);const r=new ArrayBuffer(n.byteLength);return new Uint8Array(r).set(n),r}})(t.data);else{if("string"!=typeof t.data)return console.error("The BinaryFile variable value data is not a string. Unable to deserialize the variable."),null;try{n=(new TextEncoder).encode(t.data).buffer}catch(e){return console.error("Failed to convert the BinaryFile variable value data to an ArrayBuffer. Unable to deserialize the variable.",e),null}}return{...t,data:n}}case"anything":if(Array.isArray(e)){const r=e.map((e=>t(e,n)));return await Promise.all(r)}if("object"==typeof e){const r=e,i={};for(const e in r){const o=r[e];null!=o&&(i[e]=await t(o,n))}return i}return e;default:return e}},n=await Promise.all(e.map((async e=>({...e,lastValue:await t(e.lastValue,e.controlType).catch((e=>(console.error("Failed to deserialize the value of the global variable.",e),null)))}))));return n},qc=(e,t)=>{if(!e.uuid)throw new Error("Recipe file not compatible with this version of the Kemu Edge.");return((e,t,n)=>{const r=Buffer.from(n,"base64"),i=r.subarray(0,16),o=r.subarray(16).toString("base64"),s=u(e,t,32),a=d("aes-256-cbc",s,i);let c=a.update(o,"base64","utf8");return c+=a.final("utf8"),c})(e.uuid,"kemu",t)},Kc=e=>{try{return JSON.parse(e)}catch(e){return null}},Jc="undefined"!=typeof window,Zc={protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8},Xc={protocolPrefix:4,txtLength:4},Qc=Object.values(Zc).reduce(((e,t)=>e+t),0),el=Object.values(Xc).reduce(((e,t)=>e+t),0),tl=["width","height","colorSpace"],nl=(e,t)=>{const n={},r=[];let i=0,o=Array.isArray(e)?[]:{};const s=(e,o)=>{const a=(e=>{const t="undefined"!=typeof Buffer&&e instanceof Buffer,n=e instanceof ArrayBuffer,r=e instanceof Uint8ClampedArray,i=e instanceof Uint8Array,o=e instanceof Int8Array;return t?"Buffer":n?"ArrayBuffer":r?"Uint8ClampedArray":i?"Uint8Array":o?"Int8Array":null})(e);if(!a){if(Array.isArray(e)){const t=[];for(let n=0;n<e.length;n++)t[n]=s(e[n],`${o}[${n}]`);return t}if("object"==typeof e){const t={},n=(e=>{const t=e instanceof Int16Array,n=e instanceof Uint16Array,r=e instanceof Int32Array,i=e instanceof Uint32Array,o=e instanceof Float32Array,s=e instanceof Float64Array,a=e instanceof BigInt64Array,c=e instanceof BigUint64Array;return t?"Int16Array":n?"Uint16Array":r?"Int32Array":i?"Uint32Array":o?"Float32Array":s?"Float64Array":a?"BigInt64Array":c?"BigUint64Array":null})(e);if(n)throw new Error(`Unsupported binary type [${n}] at path "${o}"`);for(const n in e)Object.hasOwn(e,n)||tl.includes(n)||console.warn(`Allowing inherited property: ${n} from path: ${o}`),t[n]=s(e[n],`${o.length?`${o}.`:""}${n}`);return t}return e}n[o]={index:i,length:e.byteLength,binaryType:a},"Buffer"===t?r.push(Buffer.from(e)):"ArrayBuffer"===a?r.push(e):r.push(e.buffer),i+=e.byteLength};o=s(e,"");let a=null;if(r.length>1)if("ArrayBuffer"===t){const e=r.reduce(((e,t)=>e+t.byteLength),0),t=new Uint8Array(e);let n=0;for(let e=0;e<r.length;e++)t.set(new Uint8Array(r[e]),n),n+=r[e].byteLength;a=t.buffer}else{a=Buffer.concat(r)}else 1===r.length&&(a=r[0]);return a?{map:n,combinedData:a,sourceCopy:o}:null},rl=(e,t,n)=>{const r=t.match(/(\[\d+\])|([^[\].]+)/g)||[];let i=e;for(let e=0;e<r.length;e++){let t=r[e];const o=t.startsWith("[")&&t.endsWith("]"),s=e===r.length-1;if(o){t=t.slice(1,-1);const o=parseInt(t,10);if(!Array.isArray(i))throw new Error(`Expected an array at key "${r.slice(0,e).join(".")}" but found an object.`);s?i[o]=n:(i[o]||(i[o]=r[e+1].startsWith("[")?[]:{}),i=i[o])}else s?i[t]=n:(i[t]||(i[t]=r[e+1].startsWith("[")?[]:{}),i=i[t])}return e},il=(e,t,n)=>{const r="undefined"!=typeof Buffer,i=t instanceof Uint8Array;for(const o in n)if(Object.hasOwn(n,o)){const{index:s,length:a,binaryType:c}=n[o];let l=null;if(r&&t instanceof Buffer)switch(c){case"Buffer":l=t.subarray(s,s+a);break;case"ArrayBuffer":l=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(s,s+a);break;case"Uint8Array":l=new Uint8Array(t.subarray(s,s+a));break;case"Uint8ClampedArray":l=new Uint8ClampedArray(t.subarray(s,s+a));break;case"Int8Array":l=new Int8Array(t.subarray(s,s+a))}else if(t instanceof ArrayBuffer||t instanceof Uint8Array)switch(c){case"Buffer":if(r){l=Buffer.from(t.slice(s,s+a));break}case"ArrayBuffer":l=i?t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(s,s+a):t.slice(s,s+a);break;case"Uint8Array":l=i?t.slice(s,s+a):new Uint8Array(t.slice(s,s+a));break;case"Uint8ClampedArray":l=new Uint8ClampedArray(t.slice(s,s+a));break;case"Int8Array":l=new Int8Array(t.slice(s,s+a))}l&&rl(e,o,l)}return e},ol=e=>p(e),sl="KMSG",al="KCMD",cl=ol("klProtocol");var ll={encode:(e,t,n)=>{const r={json:e.json},i=nl(r.json,"Buffer"),o=i?.combinedData;i&&(r.jsonBinaryMap=i.map,r.json=i.sourceCopy);const s=o?o.byteLength:0,a=JSON.stringify(r),c=Buffer.from(a),l=c.byteLength,u=Zc.protocolPrefix+Zc.protocolVersion+Zc.jsonLength+Zc.binaryLength+Zc.fromServiceId+Zc.toServiceId+Zc.sentAt+l+s,d=Buffer.alloc(u),h=Date.now();let f=0;return d.write(sl,f),f+=Zc.protocolPrefix,d.writeUInt8(1,f),f+=Zc.protocolVersion,d.writeUInt32LE(l,f),f+=Zc.jsonLength,d.writeUInt32LE(s,f),f+=Zc.binaryLength,d.writeUInt32LE(t,f),f+=Zc.fromServiceId,d.writeUInt32LE(n,f),f+=Zc.toServiceId,d.writeBigInt64LE(BigInt(h),f),f+=Zc.sentAt,c.copy(d,f),f+=l,o&&s&&o.copy(d,f),d},decodeHeader:e=>{let t=0;const n=e.toString("utf-8",t,Zc.protocolPrefix);if(t+=Zc.protocolPrefix,n!==sl)return null;if(e.byteLength<Qc)return cl(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const r=e.readUInt8(t);t+=Zc.protocolVersion;const i=e.readUInt32LE(t);t+=Zc.jsonLength;const o=e.readUInt32LE(t);t+=Zc.binaryLength;const s=e.readUInt32LE(t);t+=Zc.fromServiceId;const a=e.readUInt32LE(t);t+=Zc.toServiceId;const c=e.readBigInt64LE(t);t+=Zc.sentAt;const l=i+o,u=e.subarray(t,t+l),d=e.subarray(0,Qc);let h=null;return e.byteLength-Qc-i-o>0&&(h=e.subarray(Qc+i+o)),{header:{protocolVersion:r,jsonLength:i,binaryLength:o,fromServiceId:s,toServiceId:a,sentAt:new Date(Number(c)),packages:[u],headerPackage:d},remaining:h}},decodeFullKlMessage:e=>{const t=Buffer.concat(e.packages),n=t.subarray(0,e.jsonLength).toString(),r=t.subarray(e.jsonLength,e.jsonLength+e.binaryLength),i=Kc(n);if(!i?.json)return cl("Invalid JSON in KL message"),null;i.jsonBinaryMap&&r.byteLength&&il(i.json,r,i.jsonBinaryMap);const o=Buffer.concat([e.headerPackage,t]);let s=o,a=null;const c=Qc+e.jsonLength+e.binaryLength;return o.byteLength>c&&(a=o.subarray(c),s=o.subarray(0,c)),{message:{json:i.json,rawMessage:s},remaining:a}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<Qc)return cl("Invalid Header Size"),e;let n=0;return n+=Zc.protocolPrefix,n+=Zc.protocolVersion,n+=Zc.jsonLength,n+=Zc.binaryLength,void 0!==t.fromServiceId&&e.writeUInt32LE(t.fromServiceId,n),n+=Zc.fromServiceId,void 0!==t.toServiceId&&e.writeUInt32LE(t.toServiceId,n),e},encodeCommand:e=>{let t=0;const n=Buffer.from(e),r=n.byteLength,i=el+r,o=Buffer.alloc(i);return o.write(al,t),t+=Xc.protocolPrefix,o.writeUint32LE(r,t),t+=Xc.txtLength,n.copy(o,t),o},decodeCommand:e=>{let t=0;if(e.byteLength<el)return{command:null};const n=e.toString("utf-8",t,Xc.protocolPrefix);if(t+=Xc.protocolPrefix,n!==al)return{command:null};const r=e.readUInt32LE(t);t+=Xc.txtLength;const i=e.toString("utf-8",t,t+r),o=e.byteLength-el-r;let s=null;o>0&&(s=e.subarray(el+r));let a=0;return o<0&&(a=Math.abs(o)),{command:i,remainingData:s,missing:a}}};const ul="KMSG",dl="KCMD",hl=ol("klProtocol"),fl=new TextEncoder;var pl={encode:(e,t,n)=>{const r={json:e.json},i=nl(e.json,"ArrayBuffer"),o=i?.combinedData;i&&(r.jsonBinaryMap=i.map,r.json=i.sourceCopy);const s=o?o.byteLength:0,a=JSON.stringify(r),c=fl.encode(a),l=c.byteLength,u=new ArrayBuffer(Zc.protocolPrefix+Zc.protocolVersion+Zc.jsonLength+Zc.binaryLength+Zc.fromServiceId+Zc.toServiceId+Zc.sentAt+l+s),d=new DataView(u),h=new Uint8Array(u),f=Date.now();let p=0;for(let e=0;e<4;++e)h[p++]=ul.charCodeAt(e);return d.setUint8(p,1),p+=Zc.protocolVersion,d.setUint32(p,l,!0),p+=Zc.jsonLength,d.setUint32(p,s,!0),p+=Zc.binaryLength,d.setUint32(p,t,!0),p+=Zc.fromServiceId,d.setUint32(p,n,!0),p+=Zc.toServiceId,d.setBigInt64(p,BigInt(f),!0),p+=Zc.sentAt,h.set(c,p),p+=l,o&&s&&h.set(new Uint8Array(o),p),u},decodeHeader:e=>{const t=new DataView(e);let n=0,r="";for(let e=0;e<Zc.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==ul)return null;if(e.byteLength<Qc)return hl.log(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const i=t.getUint8(n);n+=Zc.protocolVersion;const o=t.getUint32(n,!0);n+=Zc.jsonLength;const s=t.getUint32(n,!0);n+=Zc.binaryLength;const a=t.getUint32(n,!0);n+=Zc.fromServiceId;const c=t.getUint32(n,!0);n+=Zc.toServiceId;const l=t.getBigInt64(n,!0);n+=Zc.sentAt;const u=o+s,d=e.slice(n,n+u),h=new Uint8Array(e,0,Qc);let f=null;if(e.byteLength-Qc-o-s>0){f=new Uint8Array(e,Qc+o+s).slice().buffer}return{header:{protocolVersion:i,jsonLength:o,binaryLength:s,fromServiceId:a,toServiceId:c,sentAt:new Date(Number(l)),packages:[d],headerPackage:h.slice().buffer},remaining:f}},decodeFullKlMessage:e=>{const t=e.packages.reduce(((e,t)=>e+t.byteLength),0),n=new Uint8Array(t);let r,i=0;for(const t of e.packages)r=new Uint8Array(t),n.set(r,i),i+=r.byteLength;const o=(new TextDecoder).decode(n.subarray(0,e.jsonLength)),s=n.subarray(e.jsonLength,e.jsonLength+e.binaryLength),a=Kc(o);if(!a?.json)return hl.log("Invalid JSON in KL message"),null;a.jsonBinaryMap&&s.byteLength&&il(a.json,s,a.jsonBinaryMap);const c=new Uint8Array(e.headerPackage.byteLength+n.byteLength);c.set(new Uint8Array(e.headerPackage),0),c.set(n,e.headerPackage.byteLength);let l=c,u=null;const d=Qc+e.jsonLength+e.binaryLength;return c.byteLength>d&&(u=c.subarray(d),l=c.subarray(0,d)),{message:{json:a.json,...s.length?{binaryData:s.buffer}:{},rawMessage:l.buffer},remaining:u?.buffer??null}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<Qc)return hl("Invalid Header Size"),e;let n=0;n+=Zc.protocolPrefix,n+=Zc.protocolVersion,n+=Zc.jsonLength,n+=Zc.binaryLength;const r=new DataView(e);return void 0!==t.fromServiceId&&r.setUint32(n,t.fromServiceId,!0),n+=Zc.fromServiceId,void 0!==t.toServiceId&&r.setUint32(n,t.toServiceId,!0),e},encodeCommand:e=>{let t=0;const n=fl.encode(e),r=n.byteLength,i=new ArrayBuffer(el+r),o=new DataView(i),s=new Uint8Array(i);for(let e=0;e<4;++e)s[t++]=dl.charCodeAt(e);return o.setUint32(t,r,!0),t+=Xc.txtLength,s.set(n,t),i},decodeCommand:e=>{const t=new DataView(e);let n=0;if(e.byteLength<el)return{command:null};let r="";for(let e=0;e<Xc.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==dl)return{command:null};const i=t.getUint32(n,!0);n+=Xc.txtLength;const o=e.byteLength-el-i,s=new Uint8Array(e,n,Math.min(i,e.byteLength-el)),a=(new TextDecoder).decode(s);let c=null;o>0&&(c=e.slice(el+i));let l=0;return o<0&&(l=Math.abs(o)),{command:a,remainingData:c,missing:l}}};let gl=ll;Jc&&(gl=pl);var ml,yl=gl;!function(e){e.FunctionNotFound="FNC_NOT_FOUND",e.FunctionNotAllowed="FNC_NOT_ALLOWED",e.ParentEventCallbackError="PARENT_EVENT_CALLBACK_ERROR"}(ml||(ml={}));let vl=Math.ceil(Date.now()/1e3);let bl,wl,Sl,_l,Il,xl=!1;var kl=()=>{xl=!0},El=()=>{xl=!1},Cl=(e,t)=>{if(!bl)throw new Error("Memory connection not set.");bl.sendBuf(e,t)},$l=e=>wl=e,Ol=e=>Il=e,Nl=e=>Sl=e,Tl=e=>_l=e;const Al=async(e,t=2)=>{const n=async(e,r)=>{if(Array.isArray(e))for(let i=0;i<e.length;i++){const o=e[i];if(o&&"object"==typeof o)if(Array.isArray(o))await n(o,r+1);else{const s=o._kemuType;void 0!==s?s===me.ImageData&&(e[i]=await Ye(o)):r<t&&await n(o,r+1)}}else if("object"==typeof e&&null!==e){const i=Object.keys(e);for(const o of i){const i=e[o];if(i&&"object"==typeof i){const s=i._kemuType;void 0!==s?s===me.ImageData&&(e[o]=await Ye(i)):r<t&&await n(i,r+1)}}}};return await n(e,1),e};ol("klTransmissionManager"),ol("ipcClient"),ol("kemuWidgetService"),_(process.argv.slice(2));const Ml=e=>p(`runner:${e}`),Pl=Ml("connectionManager"),Dl=Ml("remoteInvoke"),jl=new function(e){const t={};let n,r=console.log;const i={};let o=e||String(Date.now());const s={},a=e=>!s[e],c=(e,t,n,r,i,o)=>{let s=Jc?new ArrayBuffer(0):Buffer.alloc(0);const c={json:{functionName:e,args:o.success?o.success:[o],messageId:t,type:o.success?"response":"error"}};return a(r)&&(s=yl.encode(c,n,r)),i(s,{msg:c,sourceServiceId:n,targetServiceId:r})};return{setLogger:e=>{r=e},processMessage:(e,o,s,a)=>{if(!a)return!1;const l=a;if(t[l.messageId]){const e=t[l.messageId];return e&&(clearTimeout(e.timer),e.fulfilled||(e.fulfilled=!0,"response"===l.type?e.resolve(l.args):"error"===l.type&&e.reject(l.args[0])),delete t[l.messageId]),!0}if("execute"!==l.type&&r&&r(`No pending execution found for message id "${l.messageId}"`),"execute"===l.type){const t=i[l.functionName];if(t){const i=e=>{c(l.functionName,l.messageId,s.targetServiceId,s.sourceServiceId,o,e)};if(!(!n||n({args:l.args,functionName:l.functionName,transport:e,messageId:l.messageId,sourceServiceId:s.sourceServiceId,reply:i,send:o})))return r&&r(`Function "${l.functionName}" not allowed to be invoked by client [${s.sourceServiceId}]`),i({error:"Function not allowed",errCode:"FNC_NOT_ALLOWED"}),!0;t({transport:e,args:l.args,reply:i,messageId:l.messageId,sourceServiceId:s.sourceServiceId,send:o})}else{const e=`Function "${l.functionName}" not found.`;r&&r(e),c(l.functionName,l.messageId,s.targetServiceId,s.sourceServiceId,o,{error:e,errCode:"FNC_NOT_FOUND"})}return!0}return!1},execute:async(e,n,i,s,c,l)=>{if(!i){const e="No send buffer function provided.";throw r&&r(e),e}vl+=1;const u=`${o}-${vl}-exec-${e.substring(0,10)}`,d={messageId:u,functionName:e,send:i,sourceServiceId:s,targetServiceId:c,args:n||[],fulfilled:!1,resolve:()=>{},reject:()=>{}};d.promise=new Promise(((e,t)=>{d.resolve=e,d.reject=t}));let h=Jc?new ArrayBuffer(0):Buffer.alloc(0);const f={json:{functionName:e,args:n,messageId:u,type:"execute"}};a(c)&&(h=yl.encode(f,s,c)),t[u]=d,r&&r(`Calling remote function "${e}" with message id "${u}"`);const p="true"===process.env.NO_INVOKE_TIMEOUT;return l?.async?(d.fulfilled=!0,d.resolve([void 0]),delete t[u]):0===l?.timeout||p||(d.timer=setTimeout((()=>{r&&r(`Remote function ${u} timed out`);const n=t[u];n&&!n.fulfilled&&(n.fulfilled=!0,d.reject(`Function ${e} Timed out`)),delete t[u]}),l?.timeout||3e4)),i(h,{sourceServiceId:s,targetServiceId:c,msg:f}),d.promise},sendResponse:c,registerFunction:(e,t)=>{i[e]=t},registerFunctionsMiddleware:e=>{n=e},unregisterAllFunctions:()=>{Object.keys(i).forEach((e=>{delete i[e]}))},getTransportSendFunction:e=>{const n=t[e];return n?n.send:null},setServiceName:e=>{o=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,n,i)=>{vl+=1;const s=`${o}-${vl}-multicast-${e.substring(0,10)}`;let c=Jc?new ArrayBuffer(0):Buffer.alloc(0);const l={json:{functionName:e,args:t,messageId:s,type:"execute"}};let u=a(n[0].serviceId);u&&(c=yl.encode(l,i,n[0].serviceId));for(let t=0;t<n.length;t++)try{const o=n[t];r&&r(`Broadcasting function "${e}" with message id "${s}" to client [${o.serviceId}]`),0!==t&&(u=a(o.serviceId),u&&(c=yl.patchEncodedHeader(c,{toServiceId:o.serviceId}))),o.sendFn(c,{msg:l,sourceServiceId:i,targetServiceId:o.serviceId})}catch(e){r&&r(`Error broadcasting to client at index ${t}`)}},disableServiceEncoding:(e,t)=>{s[e]=t}}}("kweb");jl.setLogger(Dl);const Rl=new a,Ll=new a;let Fl,Ul=null,Bl=null,Wl=null,Gl=null;const Vl={},Yl=()=>Gl?{...Gl}:null,Hl=(e,t,n)=>{const r=`${e}_${t}`,i={contents:n,lastRequestedAt:Date.now(),contentsChecksum:""};return Vl[r]=i,i},zl=(e,t)=>Vl[`${e}_${t}`]||null,ql=async(e,t)=>{if(!Ul)return Pl("Hub Link has not been acknowledged. Cannot get services."),null;const n=[{serviceName:e,version:t}];return(await jl.execute(we.GetServiceContents,n,Zl,Ul,0))[0]},Kl=new Map,Jl=async(e,t,n=!1)=>{if(!e||!t)return null;const r=`${e}:${t}`;if(!n){const e=Kl.get(r);if(e)return e}const i=zl(e,t);if(!i||n){const n=i||Hl(e,t),o=(async()=>{try{const r=await ql(e,t);return r&&(n.contents=r.uiContent,n.contentsChecksum=r.uiContentsChecksum||""),n.contents||null}catch(n){return Pl(`Failed to fetch service contents for ${e} v${t}`,n),null}finally{Kl.delete(r)}})();return Kl.set(r,o),o}return i?.contents||null},Zl=Cl,Xl=()=>{Pl("Disconnected from the server"),Ul=null,Wl=null,jl.rejectAllPending("Disconnected from the server"),Rl.emit("disconnected")},Ql=()=>{Pl("Connected to the server"),Rl.emit("connected")},eu=()=>Bl,tu=(e,t,n,r)=>`${e}_${t}_${n}_${r}`,nu=async()=>{const e=eu();if(e){const t=se(e)?.blocks;if(t){const n={};for(const r in t){const i=t[r];for(const t in i.gates){const r=i.gates[t];if(r.type===Ke.hubService){const t=r.state;if(t.service?.eventEmitter){const r=`${t.service.name}_${t.service.version}`;if(!n[r])try{Pl(`Re-issuing subscription for service ${t.service.name} (${t.service.version})`),n[r]=!0,await ku({listener:{recipeId:e},targetService:{serviceName:t.service.name,version:t.service.version}})}catch(e){Pl(`Failed to re-issue subscription for service ${t.service.name} (${t.service.version})`,e)}}}}}}}},ru=async()=>{Fl=void 0;const e=await vu();Rl.emit("services-changed",e)},iu=async()=>(Pl("Services list changed"),ru()),ou=async e=>{if(!e)return void Pl("Hub sent ACK request without service id");const t=eu();if(!t)return void Pl("Hub sent ACK request without recipe pool id");if(!se(t))throw new Error("Hub sent ACK request without recipe");const n=Yl(),r={apiKey:n?.apiKey,recipe:de(t),user:n,ackSessionId:e};await jl.execute(we.SocketAckResponse,[r],Zl,e,0),Pl("Hub Link acknowledged"),Ul=e,Rl.emit("acknowledged"),await Pu(),nu()},su=async()=>{await El()},au=async e=>{const t=e.args[0],{widgetId:n,recipePoolId:r,waitForResponse:i}=t;return e.reply({success:[`message received by recipe ok target widget "${n}", recipe pool id "${r}", waitForResponse "${i}"`]})},cu=async e=>{const t=e.args[0],n=tu("broadcast",`hub_${t.type}`,(0).toString(),"");await Ll.emit(n,t)},lu=async e=>{const t=e.args[0],n=eu(),r=t.targetRecipePoolId||t.targetRecipeId;if(!r||r===n){for(const e of t.outputs||[])e.type===me.ImageData&&Re(e.value)&&(e.value=await Ye(e.value));if(n){const r=se(n);if(r){const i=async e=>{const n=tu("broadcast",t.source.serviceName,t.source.serviceVersion,e);try{await Ll.emit(n,t)}catch(t){Pl(`Failed to emit broadcast event for target ${e}`,t)}};await i("app");for(const o in r.blocks){const s=r.blocks[o];for(const r in s.gates){const o=s.gates[r];if(o.disabled)continue;if(t.targetWidgetId&&t.targetWidgetId!==r)continue;const a=o.state;if(o.type!==Ke.script){if(o.type===Ke.hubService&&a.service?.name===t.source.serviceName&&a.service?.version===t.source.serviceVersion&&a.variantId===t.variantId){await i(r);for(const i of t.outputs||[])if(null!==i.value&&void 0!==i.value){const o={type:i.type,value:i.value,timestamp:Date.now()};Pl(`Sending data to output ${i.name} requested by messageId ${e.messageId}`),await Vc({recipePoolId:n,currentGateId:r,sourcePortName:i.name,originalEvent:o,data:o,eventContext:t.eventContext,currentPath:t.currentPath||[],eventId:t.eventId||null})}}}else await i(r)}}}}}},uu=async e=>{const t=e.args[0],{finalState:n,recipeId:r,widgetId:i}=t,o=Gc(r,i);let s=o;if(n&&s&&o&&(s={...o,customState:n},Wc(r,i,s,!0)),s?.service)try{const e=tu("setOutputs",s.service.name,s.service.version,i);await Ll.emit(e,t.outputs)}catch(e){Pl(`Failed to emit setOutputs event for widget ${i}`,e)}let a=null;for(const n of t.outputs)if(null!==n.value&&void 0!==n.value){if(n.type===me.ImageData){if(!Re(n.value)){Pl(`Invalid ImageData value received for output ${n.name}. Expected an ImageData-like object`);continue}n.value=await Ye(n.value)}else n.type!==me.JsonObj&&n.type!==me.Array||await Al(n.value);const o={type:n.type,value:n.value,timestamp:Date.now()};Pl(`Sending data to output ${n.name} requested by messageId ${e.messageId}`);try{await Vc({recipePoolId:r,currentGateId:i,sourcePortName:n.name,originalEvent:o,data:o,eventContext:t.eventContext,currentPath:t.currentPath||[],eventId:t.eventId||null})}catch(e){Pl(`Failed to trigger next global widget for output ${n.name}`,e),a=e;break}}if(a){const t=a instanceof jr,n=a;e.reply({error:a.message,errCode:t?"CHILD_WIDGET_ERROR":"INVOKING_ERROR",errData:{targetWidgetId:n.targetWidgetId,targetPortName:n.targetPortName,sourcePortName:n.sourcePortName,sourceWidgetId:n.sourceWidgetId,targetWidgetType:n.targetWidgetType,sourceWidgetType:n.sourceWidgetType}})}else e.reply({success:[]})},du=async e=>{const t=e.args[0],{newState:n,recipeId:r,widgetId:i}=t,o=Gc(r,i);if(o){const t={...o,customState:{...o.customState,...n}};return Wc(r,i,t,!0),e.reply({success:[]})}},hu=async({args:e,reply:t})=>{const n=e[0],{recipeId:r,widgetId:i,path:o,key:s}=n;Pl(`Received request to set a dependency path for "${s}" on widget "${i}" in recipe "${r}"`);const a=Gc(r,i);if(a){const e={...a};e.dependencies=e.dependencies||{},e.dependencies[s]={path:o},Wc(r,i,e,!0)}return t({success:[]})},fu=async({args:e,reply:t})=>{const n=e[0],{recipeId:r,widgetId:i,key:o}=n;Pl(`Received request to get a dependency path for "${o}" on widget "${i}" in recipe "${r}"`);const s=Gc(r,i);if(s){const e=s.dependencies?.[o]?.path;return Pl(`Returning dependency path for "${o}" on widget "${i}": "${e}"`),t({success:[e||null]})}return t({error:"Widget not found",errCode:"WIDGET_NOT_FOUND"})},pu=async({args:e,reply:t})=>{const n=e[0];if(!n.expressions)return t({error:"Expression is required",errCode:"EXPRESSION_REQUIRED"});const r=ce({recipeId:n.recipePoolId,widgetId:n.widgetId});if(!r)return t({error:"Widget not found",errCode:"WIDGET_NOT_FOUND"});if(r.type!==Ke.hubService)return t({error:"Widget is not a hub service",errCode:"WIDGET_NOT_A_HUB_SERVICE"});const i=r.state,{uuid:o}=(e=>{const t=se(e);if(!t)throw new Error(`Recipe [${e} does not exist]`);return{uuid:t.uuid,recipeType:t.dbInfo?.recipeType}})(n.recipePoolId);return t({success:[{expressions:await Promise.all(n.expressions.map((async e=>await Ms({template:e.text,context:e.context||{},options:{enableFnTag:!1,recipeUuid:o,serviceName:i.service?.name,securityOptions:{restrictionLevel:"strict"}}}))))}]})},gu=async({args:e,reply:t})=>{const n=e[0],r=ao.getAllVariables().filter((e=>!n.filterTypes||n.filterTypes.includes(e.controlType))).map((e=>({name:e.name,type:e.controlType})));return t({success:[{variables:r}]})},mu=async({args:e,reply:t})=>{const n=e[0];if(!n.names||0===n.names.length)return t({error:"Variable names are required",errCode:"VARIABLE_NAMES_REQUIRED"});const r=ao.getAllVariables().filter((e=>n.names.includes(e.name))).map((e=>({name:e.name,value:e.lastValue})));return t({success:[{values:r}]})},yu=async({args:e,reply:t})=>{const n=e[0];if(!n.values||0===n.values.length)return t({error:"Variable values are required",errCode:"VARIABLE_VALUES_REQUIRED"});try{const{values:e}=n;for(const t of e)await ao.setGlobalVariable({name:t.name,value:t.value});return t({success:[]})}catch(e){return Pl(`Failed to set global variable values: ${e}`),t({error:"Failed to set some of the global variable values",errCode:"FAILED_TO_SET_GLOBAL_VARIABLE_VALUES",errData:e.message})}},vu=async()=>{if(Pl(`Requesting services on ${(new Date).toISOString()}`),!Ul)return Pl("Hub Link has not been acknowledged. Cannot get services."),{available:[],installed:[],failed:[]};const[e]=await jl.execute(we.GetServices,[],Zl,Ul,0);Fl=e;for(const t of e.available){if(t.internal)continue;const e=zl(t.name,t.version);if(!e||e?.contentsChecksum!==t.uiContentChecksum)try{const n=e||Hl(t.name,t.version);Pl(`Service ${t.name} v${t.version} contents have changed, fetching new contents`);const r=await ql(t.name,t.version);r&&(n.contents=r.uiContent,n.contentsChecksum=t.uiContentChecksum||"")}catch(e){Pl(`Failed to update service contents for ${t.name} v${t.version}`,e)}}return e},bu=()=>Fl||{available:[],installed:[],failed:[]},wu=()=>!!Fl,Su=async e=>{const{targetServiceSessionId:t}=e;if(!Ul)return void Pl("No target service session id provided");Pl(`Forwarding "onParentEvent" to service ${t}`);const n=await jl.execute(we.OnParentEvent,[e],Zl,Ul,t,e.config).catch((e=>{throw Pl(`Error invoking onParentEvent callback: ${e}`),e.errCode===ml.ParentEventCallbackError?e.error:e}));return n},_u=async e=>{if(!Ul)return Pl("Hub Link has not been acknowledged. Cannot get services."),{};const[t]=await jl.execute(we.GetDefaultState,[],Zl,Ul,e);return t},Iu=async(e,t,n,r,i)=>{if(!Ul)return Pl("Hub Link has not been acknowledged. Cannot get services."),null;const[o]=await jl.execute(we.UIEvent,[t,n,r],Zl,Ul,e,i);return o},xu=(e,t)=>{const n=(...e)=>{t(...e)};return Rl.on(e,n),()=>Rl.off(e,n)},ku=async e=>{if(Ul)return jl.execute(we.SubscribeToService,[e],Zl,Ul,0);Pl("Hub Link has not been acknowledged. Cannot subscribe to services.")},Eu=async e=>{if(Ul)return jl.execute(we.UnsubscribeFromService,[e],Zl,Ul,0);Pl("Hub Link has not been acknowledged. Cannot subscribe to services.")},Cu=(e,t,n,r)=>{const i=tu("broadcast",t,n,e);return Ll.on(i,r)},$u=(e,t,n,r)=>{const i=tu("setOutputs",t,n,e);return Ll.on(i,r)},Ou=async(e,t,n)=>Ul?jl.execute(e,t,Zl,Ul,0,n):(Pl("Hub Link has not been acknowledged. Cannot execute function."),null),Nu=async e=>{if(!Ul)return void Pl("Hub Link has not been acknowledged. Cannot execute function.");const t=Gc(e.recipePoolId,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)),{});if(!se(e.recipePoolId))throw new Error("Recipe not found. Cannot initialize service instance.");const r=Yl(),i=[{currentState:t.customState,recipeId:e.recipePoolId,recipe:de(e.recipePoolId),widgetId:e.widgetId,variantId:e.variantId,recipeType:e.recipeType,recipeName:e.recipeName,currentDependencies:n,kemuApiKey:r?.apiKey}],[o,s,a]=await jl.execute(we.InitializeInstance,i,Zl,Ul,e.sessionId);if(s&&s.length>0){const n=s.filter((e=>e.name&&e.name.length>0)).map((e=>({...e,hubServiceName:t.service?.name})));Hc({clearExistingSecrets:!0,recipePoolId:e.recipePoolId,widgetId:e.widgetId,secrets:n})}if(a&&a.length>0&&await Promise.all(a.map((async t=>{await ao.setGlobalVariable({name:t.name,value:t.value,controlType:t.controlType,controlSettings:t.controlSettings,helpText:t.helpText,order:t.order,disableChangeNotifications:!1===t.emitChangeEvent,disableDefineNotifications:!1===t.emitDefineEvent,doNotOverrideExisting:t.doNotOverrideExisting??!1,widgetId:e.widgetId})}))),o){const t=Gc(e.recipePoolId,e.widgetId);if(t){const n={...t,customState:o};Wc(e.recipePoolId,e.widgetId,n,!0)}}},Tu=async(e,t,n,r)=>{if(!Ul)return void Pl("Hub Link has not been acknowledged. Cannot execute function.");const i=Gc(n,t);if(!i)throw new Error("Widget or recipe pool not found. Cannot initialize service instance.");const o=se(n);if(!o)throw new Error("Recipe not found. Cannot terminate service instance.");const s=[{currentState:i.customState,recipeId:n,recipe:{poolId:n,uuid:o.uuid,name:o.name,type:o.dbInfo.recipeType,dbId:o.dbInfo.id,version:o.dbInfo.version,authorId:o.dbInfo.authorId},widgetId:t,variantId:r}];await jl.execute(we.TerminateInstance,s,Zl,Ul,e)},Au=async(e,t,n="^",r)=>{const i=["^","~",">=",">","<=","<","="];if(!i.includes(n))throw new Error(`Invalid compare mode "${n}". Must be one of ${i.join(", ")}`);const o=wu(),s=r||!o?await vu():bu();for(const r of s.available)if(r.name===e){if(r.version===t)return r;if(f(r.version,`${n}${t}`))return r}return null},Mu=async(e=!1)=>{if(!Ul)return Pl("Hub Link has not been acknowledged. Cannot get services."),null;if(Wl&&!e)return Wl;const[t]=await jl.execute(we.GetSystemInfo,[],Zl,Ul,0).catch((e=>(Pl("Failed to get system info",e),[null])));return Wl=t,t},Pu=async()=>{Wl=await Mu()};var Du,ju,Ru,Lu,Fu,Uu,Bu,Wu,Gu=async e=>{if(!e.apiKey)throw new Error("an API key is required to connect to the hub");Gl=e,e.apiKey,Nl(Ql),Tl(Xl),Ol((({json:e,transmission:t})=>{jl.processMessage("websocket",Zl,t,e)})),await su(),jl.unregisterAllFunctions(),jl.registerFunction(we.SetState,du),jl.registerFunction(we.SetOutputs,uu),jl.registerFunction(we.BroadcastEvent,lu),jl.registerFunction(we.HubBroadcastEvent,cu),jl.registerFunction(we.SendToRecipe,au),jl.registerFunction(Se.SetDependencyPath,hu),jl.registerFunction(Se.GetDependencyPath,fu),jl.registerFunction(Se.ParseStringExpression,pu),jl.registerFunction(Se.GetGlobalVariableNames,gu),jl.registerFunction(Se.GetGlobalVariableValues,mu),jl.registerFunction(Se.SetGlobalVariableValues,yu),$l((e=>{((e,t)=>{const n=be.SocketAcknowledge,r=be.IpcAcknowledge,i=e.startsWith(n);if(e===r)return t&&t(),0;if(i){const o=e.split(i?n:r),s=parseInt(o[1]);return t&&t(s),s}})(e,ou),((e,t)=>{e===be.ServicesListChanged&&(t&&t())})(e,iu)})),await kl()},Vu=(e,t)=>{Rl.on(e,t)},Yu=()=>({getServices:vu,getServiceContents:Jl,onParentEvent:Su,onCommand:xu,getDefaultState:_u,getCachedServices:bu,areServicesCached:wu,subscribeToServiceEvents:ku,unsubscribeFromServiceEvents:Eu,callProcessorHandler:Iu,onBroadcastEvent:Cu,onSetOutputsEvent:$u,executeHubFunction:Ou,initializeServiceInstance:Nu,terminateServiceInstance:Tu,getCompatibleService:Au,getHubSystemInfo:Mu}),Hu=e=>{Bl=e},zu=()=>jl;!function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(Du||(Du={})),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"}(ju||(ju={})),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"}(Ru||(Ru={})),function(e){e.Javascript="js",e.Python="py",e.Executable="exe"}(Lu||(Lu={})),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:"}(Fu||(Fu={})),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.AddServiceSecret="addServiceSecret",e.OnParentEvent="onParentEvent",e.GetDefaultState="getDefaultState",e.BroadcastEvent="broadcastEvent",e.HubBroadcastEvent="hubBroadcastEvent",e.ServiceManifest="serviceManifest",e.SendToRecipe="sendToRecipe",e.KemuComposerDisconnected="kemu-composer-disconnected",e.GetState="getState",e.SetState="setState",e.SetOutputs="setOutputs",e.UIEvent="uiEvent",e.GetSystemInfo="getSystemInfo",e.InitializeInstance="initializeInstance",e.TerminateInstance="terminateInstance",e.UninstallService="uninstallService",e.ChooseDirectoryDialog="chooseDirectoryDialog",e.ChooseFileDialog="chooseFileDialog",e.SaveRecipeToFile="saveRecipeToFile",e.GetUniqueId="getUniqueId",e.RebootToInstallUpdate="rebootToInstallUpdate",e.GetFileContentFromCacheId="getFileContentFromCacheId",e.GetDecryptedEdgeApiKey="getDecryptedEdgeApiKey",e.GetHubConfig="getHubConfig",e.GetRecipeDecryptedSecretsValues="getRecipeDecryptedSecretsValues",e.GetRecipeSecretMappings="getRecipeSecretMappings",e.AddRecipeSecretMapping="addRecipeSecretMapping",e.DeleteRecipeSecretMapping="deleteRecipeSecretMapping",e.GetHubSecrets="getHubSecrets",e.AddHubSecrets="addHubSecrets",e.DeleteHubSecret="deleteHubSecret"}(Uu||(Uu={})),function(e){e.SetDependencyPath="setDependencyPath",e.GetDependencyPath="getDependencyPath"}(Bu||(Bu={})),function(e){e.IPC="ipc",e.WS="ws"}(Wu||(Wu={}));const qu=e=>{try{return JSON.parse(e)}catch(e){return null}},Ku=()=>{const e=(()=>{switch(process.arch){case"x64":return"x64";case"ia32":return"x86";case"arm":return"arm";case"arm64":return"arm64";default:return""}})();if(!e)throw new Error(`Unsupported architecture: ${process.arch}`);switch(process.platform){case"win32":return`win-${e}`;case"darwin":return`osx-${e}`;case"linux":{let t="generic";try{const e=C.readFileSync("/etc/os-release","utf-8").split("\n").reduce(((e,t)=>{const[n,...r]=t.split("=");if(n&&r.length>0){let t=r.join("=").trim();t.startsWith('"')&&t.endsWith('"')&&(t=t.substring(1,t.length-1)),e[n.trim()]=t}return e}),{}),n=e.ID,r=e.ID_LIKE?.split(/\s+/)||[];"debian"===n||r.includes("debian")?t="debian":"rhel"===n||"fedora"===n||"centos"===n||r.includes("rhel")||r.includes("fedora")?t="rhel":("arch"===n||r.includes("arch"))&&(t="arch")}catch(e){}return`linux-${t}-${e}`}default:throw new Error(`Unsupported platform: ${process.platform}`)}},Ju=/^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i,Zu=e=>{if("string"!=typeof e)throw new TypeError("Invalid argument expected string");const t=e.match(Ju);if(!t)throw new Error(`Invalid argument not valid semver ('${e}' received)`);return t.shift(),t},Xu=e=>"*"===e||"x"===e||"X"===e,Qu=e=>{const t=parseInt(e,10);return isNaN(t)?e:t},ed=(e,t)=>{if(Xu(e)||Xu(t))return 0;const[n,r]=((e,t)=>typeof e!=typeof t?[String(e),String(t)]:[e,t])(Qu(e),Qu(t));return n>r?1:n<r?-1:0},td=(e,t)=>{for(let n=0;n<Math.max(e.length,t.length);n++){const r=ed(e[n]||"0",t[n]||"0");if(0!==r)return r}return 0},nd=(e,t,n)=>{od(n);const r=((e,t)=>{const n=Zu(e),r=Zu(t),i=n.pop(),o=r.pop(),s=td(n,r);return 0!==s?s:i&&o?td(i.split("."),o.split(".")):i||o?i?-1:1:0})(e,t);return rd[n].includes(r)},rd={">":[1],">=":[0,1],"=":[0],"<=":[-1,0],"<":[-1],"!=":[-1,1]},id=Object.keys(rd),od=e=>{if(-1===id.indexOf(e))throw new Error(`Invalid operator, expected one of ${id.join("|")}`)};var sd="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function ad(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var cd,ld,ud,dd,hd,fd={exports:{}},pd={exports:{}};function gd(){if(ld)return cd;ld=1;var e=1e3,t=60*e,n=60*t,r=24*n,i=7*r;function o(e,t,n,r){var i=t>=1.5*n;return Math.round(e/n)+" "+r+(i?"s":"")}return cd=function(s,a){a=a||{};var c=typeof s;if("string"===c&&s.length>0)return function(o){if(!((o=String(o)).length>100)){var s=/^(-?(?:\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(s){var a=parseFloat(s[1]);switch((s[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*a;case"weeks":case"week":case"w":return a*i;case"days":case"day":case"d":return a*r;case"hours":case"hour":case"hrs":case"hr":case"h":return a*n;case"minutes":case"minute":case"mins":case"min":case"m":return a*t;case"seconds":case"second":case"secs":case"sec":case"s":return a*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return a;default:return}}}}(s);if("number"===c&&isFinite(s))return a.long?function(i){var s=Math.abs(i);return s>=r?o(i,s,r,"day"):s>=n?o(i,s,n,"hour"):s>=t?o(i,s,t,"minute"):s>=e?o(i,s,e,"second"):i+" ms"}(s):function(i){var o=Math.abs(i);return o>=r?Math.round(i/r)+"d":o>=n?Math.round(i/n)+"h":o>=t?Math.round(i/t)+"m":o>=e?Math.round(i/e)+"s":i+"ms"}(s);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(s))}}function md(){return dd||(dd=1,ud=function(e){function t(e){let r,i,o,s=null;function a(...e){if(!a.enabled)return;const n=a,i=Number(new Date),o=i-(r||i);n.diff=o,n.prev=r,n.curr=i,r=i,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let s=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((r,i)=>{if("%%"===r)return"%";s++;const o=t.formatters[i];if("function"==typeof o){const t=e[s];r=o.call(n,t),e.splice(s,1),s--}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!==s?s:(i!==t.namespaces&&(i=t.namespaces,o=t.enabled(e)),o),set:e=>{s=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){return e instanceof Error?e.stack||e.message:e},t.disable=function(){const e=[...t.names.map(r),...t.skips.map(r).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let n;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const r=("string"==typeof e?e:"").split(/[\s,]+/),i=r.length;for(n=0;n<i;n++)r[n]&&("-"===(e=r[n].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.slice(1)+"$")):t.names.push(new RegExp("^"+e+"$")))},t.enabled=function(e){if("*"===e[e.length-1])return!0;let n,r;for(n=0,r=t.skips.length;n<r;n++)if(t.skips[n].test(e))return!1;for(n=0,r=t.names.length;n<r;n++)if(t.names[n].test(e))return!0;return!1},t.humanize=gd(),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}),ud}var yd,vd,bd,wd,Sd,_d={exports:{}};"undefined"==typeof process||"renderer"===process.type||!0===process.browser||process.__nwjs?fd.exports=(hd||(hd=1,function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const n="color: "+this.color;t.splice(1,0,n,"color: inherit");let r=0,i=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(r++,"%c"===e&&(i=r))})),t.splice(i,0,n)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")}catch(e){}return!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG),e},t.useColors=function(){return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type&&!window.process.__nwjs)||("undefined"==typeof navigator||!navigator.userAgent||!navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=md()(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(pd,pd.exports)),pd.exports):fd.exports=(Sd||(Sd=1,function(e,t){const n=O,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:i}=this;if(i){const t=this.color,i="[3"+(t<8?t:"8;5;"+t),o=` ${i};1m${r} `;n[0]=o+n[0].split("\n").join("\n"+o),n.push(i+"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(wd)return bd;wd=1;const e=N,t=O,n=vd?yd:(vd=1,yd=(e,t=process.argv)=>{const n=e.startsWith("-")?"":1===e.length?"-":"--",r=t.indexOf(n+e),i=t.indexOf("--");return-1!==r&&(-1===i||r<i)}),{env:r}=process;let i;function o(e){return 0!==e&&{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function s(t,o){if(0===i)return 0;if(n("color=16m")||n("color=full")||n("color=truecolor"))return 3;if(n("color=256"))return 2;if(t&&!o&&void 0===i)return 0;const s=i||0;if("dumb"===r.TERM)return s;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:s;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:s}return n("no-color")||n("no-colors")||n("color=false")||n("color=never")?i=0:(n("color")||n("colors")||n("color=true")||n("color=always"))&&(i=1),"FORCE_COLOR"in r&&(i="true"===r.FORCE_COLOR?1:"false"===r.FORCE_COLOR?0:0===r.FORCE_COLOR.length?1:Math.min(parseInt(r.FORCE_COLOR,10),3)),bd={supportsColor:function(e){return o(s(e,e&&e.isTTY))},stdout:o(s(!0,t.isatty(1))),stderr:o(s(!0,t.isatty(2)))},bd}();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=md()(t);const{formatters:o}=e.exports;o.o=function(e){return this.inspectOpts.colors=this.useColors,r.inspect(e,this.inspectOpts).split("\n").map((e=>e.trim())).join(" ")},o.O=function(e){return this.inspectOpts.colors=this.useColors,r.inspect(e,this.inspectOpts)}}(_d,_d.exports)),_d.exports);var Id=ad(fd.exports);const xd=e=>Id(e);var kd={},Ed={};class Cd extends Error{constructor(e){super(`Format functions must be synchronous taking a two arguments: (info, opts)\nFound: ${e.toString().split("\n")[0]}\n`),Error.captureStackTrace(this,Cd)}}var $d,Od,Nd,Td,Ad,Md=e=>{if(e.length>2)throw new Cd(e);function t(e={}){this.options=e}function n(e){return new t(e)}return t.prototype.transform=e,n.Format=t,n},Pd={exports:{}},Dd={exports:{}},jd={exports:{}},Rd={exports:{}};function Ld(){if(Ad)return Td;Ad=1;var e=N,t=Nd?Od:(Nd=1,Od=function(e,t){var n=(t=t||process.argv||[]).indexOf("--"),r=/^-{1,2}/.test(e)?"":"--",i=t.indexOf(r+e);return-1!==i&&(-1===n||i<n)}),n=process.env,r=void 0;function i(i){var o=function(i){if(!1===r)return 0;if(t("color=16m")||t("color=full")||t("color=truecolor"))return 3;if(t("color=256"))return 2;if(i&&!i.isTTY&&!0!==r)return 0;var o=r?1:0;if("win32"===process.platform){var s=e.release().split(".");return Number(process.versions.node.split(".")[0])>=8&&Number(s[0])>=10&&Number(s[2])>=10586?Number(s[2])>=14931?3:2:1}if("CI"in n)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI"].some((function(e){return e in n}))||"codeship"===n.CI_NAME?1:o;if("TEAMCITY_VERSION"in n)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(n.TEAMCITY_VERSION)?1:0;if("TERM_PROGRAM"in n){var a=parseInt((n.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(n.TERM_PROGRAM){case"iTerm.app":return a>=3?3:2;case"Hyper":return 3;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(n.TERM)?2:/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(n.TERM)||"COLORTERM"in n?1:(n.TERM,o)}(i);return function(e){return 0!==e&&{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}(o)}return t("no-color")||t("no-colors")||t("color=false")?r=!1:(t("color")||t("colors")||t("color=true")||t("color=always"))&&(r=!0),"FORCE_COLOR"in n&&(r=0===n.FORCE_COLOR.length||0!==parseInt(n.FORCE_COLOR,10)),Td={supportsColor:i,stdout:i(process.stdout),stderr:i(process.stderr)}}var Fd,Ud,Bd,Wd,Gd,Vd,Yd,Hd,zd={exports:{}},qd={exports:{}},Kd={exports:{}},Jd={exports:{}},Zd={exports:{}},Xd={exports:{}};function Qd(){return Yd||(Yd=1,function(){var e={};jd.exports=e,e.themes={};var t=i,n=e.styles=($d||($d=1,function(){var e={};Rd.exports=e;var t={reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29],black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],gray:[90,39],grey:[90,39],brightRed:[91,39],brightGreen:[92,39],brightYellow:[93,39],brightBlue:[94,39],brightMagenta:[95,39],brightCyan:[96,39],brightWhite:[97,39],bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgGray:[100,49],bgGrey:[100,49],bgBrightRed:[101,49],bgBrightGreen:[102,49],bgBrightYellow:[103,49],bgBrightBlue:[104,49],bgBrightMagenta:[105,49],bgBrightCyan:[106,49],bgBrightWhite:[107,49],blackBG:[40,49],redBG:[41,49],greenBG:[42,49],yellowBG:[43,49],blueBG:[44,49],magentaBG:[45,49],cyanBG:[46,49],whiteBG:[47,49]};Object.keys(t).forEach((function(n){var r=t[n],i=e[n]=[];i.open="["+r[0]+"m",i.close="["+r[1]+"m"}))}()),Rd.exports),r=Object.defineProperties,o=new RegExp(/[\r\n]+/g);e.supportsColor=Ld().supportsColor,void 0===e.enabled&&(e.enabled=!1!==e.supportsColor()),e.enable=function(){e.enabled=!0},e.disable=function(){e.enabled=!1},e.stripColors=e.strip=function(e){return(""+e).replace(/\x1B\[\d+m/g,"")},e.stylize=function(t,r){if(!e.enabled)return t+"";var i=n[r];return!i&&r in e?e[r](t):i.open+t+i.close};var s=/[|\\{}()[\]^$+*?.]/g;function a(e){var t=function e(){return d.apply(e,arguments)};return t._styles=e,t.__proto__=u,t}var c,l=(c={},n.grey=n.gray,Object.keys(n).forEach((function(e){n[e].closeRe=new RegExp(function(e){if("string"!=typeof e)throw new TypeError("Expected a string");return e.replace(s,"\\$&")}(n[e].close),"g"),c[e]={get:function(){return a(this._styles.concat(e))}}})),c),u=r((function(){}),l);function d(){var r=Array.prototype.slice.call(arguments).map((function(e){return null!=e&&e.constructor===String?e:t.inspect(e)})).join(" ");if(!e.enabled||!r)return r;for(var i=-1!=r.indexOf("\n"),s=this._styles,a=s.length;a--;){var c=n[s[a]];r=c.open+r.replace(c.closeRe,c.open)+c.close,i&&(r=r.replace(o,(function(e){return c.close+e+c.open})))}return r}e.setTheme=function(t){if("string"!=typeof t)for(var n in t)!function(n){e[n]=function(r){if("object"==typeof t[n]){var i=r;for(var o in t[n])i=e[t[n][o]](i);return i}return e[t[n]](r)}}(n);else console.log("colors.setTheme now only accepts an object, not a string. If you are trying to set a theme from a file, it is now your (the caller's) responsibility to require the file. The old syntax looked like colors.setTheme(__dirname + '/../themes/generic-logging.js'); The new syntax looks like colors.setTheme(require(__dirname + '/../themes/generic-logging.js'));")};var h=function(e,t){var n=t.split("");return(n=n.map(e)).join("")};for(var f in e.trap=(Fd||(Fd=1,zd.exports=function(e){var t="";e=(e=e||"Run the trap, drop the bass").split("");var n={a:["@","Ą","Ⱥ","Ʌ","Δ","Λ","Д"],b:["ß","Ɓ","Ƀ","ɮ","β","฿"],c:["©","Ȼ","Ͼ"],d:["Ð","Ɗ","Ԁ","ԁ","Ԃ","ԃ"],e:["Ë","ĕ","Ǝ","ɘ","Σ","ξ","Ҽ","੬"],f:["Ӻ"],g:["ɢ"],h:["Ħ","ƕ","Ң","Һ","Ӈ","Ԋ"],i:["༏"],j:["Ĵ"],k:["ĸ","Ҡ","Ӄ","Ԟ"],l:["Ĺ"],m:["ʍ","Ӎ","ӎ","Ԡ","ԡ","൩"],n:["Ñ","ŋ","Ɲ","Ͷ","Π","Ҋ"],o:["Ø","õ","ø","Ǿ","ʘ","Ѻ","ם","۝","๏"],p:["Ƿ","Ҏ"],q:["্"],r:["®","Ʀ","Ȑ","Ɍ","ʀ","Я"],s:["§","Ϟ","ϟ","Ϩ"],t:["Ł","Ŧ","ͳ"],u:["Ʊ","Ս"],v:["ט"],w:["Ш","Ѡ","Ѽ","൰"],x:["Ҳ","Ӿ","Ӽ","ӽ"],y:["¥","Ұ","Ӌ"],z:["Ƶ","ɀ"]};return e.forEach((function(e){e=e.toLowerCase();var r=n[e]||[" "],i=Math.floor(Math.random()*r.length);t+=void 0!==n[e]?n[e][i]:e})),t}),zd.exports),e.zalgo=(Ud||(Ud=1,qd.exports=function(e,t){e=e||" he is here ";var n={up:["̍","̎","̄","̅","̿","̑","̆","̐","͒","͗","͑","̇","̈","̊","͂","̓","̈","͊","͋","͌","̃","̂","̌","͐","̀","́","̋","̏","̒","̓","̔","̽","̉","ͣ","ͤ","ͥ","ͦ","ͧ","ͨ","ͩ","ͪ","ͫ","ͬ","ͭ","ͮ","ͯ","̾","͛","͆","̚"],down:["̖","̗","̘","̙","̜","̝","̞","̟","̠","̤","̥","̦","̩","̪","̫","̬","̭","̮","̯","̰","̱","̲","̳","̹","̺","̻","̼","ͅ","͇","͈","͉","͍","͎","͓","͔","͕","͖","͙","͚","̣"],mid:["̕","̛","̀","́","͘","̡","̢","̧","̨","̴","̵","̶","͜","͝","͞","͟","͠","͢","̸","̷","͡"," ҉"]},r=[].concat(n.up,n.down,n.mid);function i(e){return Math.floor(Math.random()*e)}function o(e){var t=!1;return r.filter((function(n){t=n===e})),t}return function(e,t){var r,s,a="";for(s in(t=t||{}).up=void 0===t.up||t.up,t.mid=void 0===t.mid||t.mid,t.down=void 0===t.down||t.down,t.size=void 0!==t.size?t.size:"maxi",e=e.split(""))if(!o(s)){switch(a+=e[s],r={up:0,down:0,mid:0},t.size){case"mini":r.up=i(8),r.mid=i(2),r.down=i(8);break;case"maxi":r.up=i(16)+3,r.mid=i(4)+1,r.down=i(64)+3;break;default:r.up=i(8)+1,r.mid=i(6)/2,r.down=i(8)+1}var c=["up","mid","down"];for(var l in c)for(var u=c[l],d=0;d<=r[u];d++)t[u]&&(a+=n[u][i(n[u].length)])}return a}(e,t)}),qd.exports),e.maps={},e.maps.america=(Bd||(Bd=1,Kd.exports=function(e){return function(t,n){if(" "===t)return t;switch(n%3){case 0:return e.red(t);case 1:return e.white(t);case 2:return e.blue(t)}}}),Kd.exports)(e),e.maps.zebra=(Wd||(Wd=1,Jd.exports=function(e){return function(t,n){return n%2==0?t:e.inverse(t)}}),Jd.exports)(e),e.maps.rainbow=(Gd||(Gd=1,Zd.exports=function(e){var t=["red","yellow","green","blue","magenta"];return function(n,r){return" "===n?n:e[t[r++%t.length]](n)}}),Zd.exports)(e),e.maps.random=(Vd||(Vd=1,Xd.exports=function(e){var t=["underline","inverse","grey","yellow","red","green","blue","white","cyan","magenta","brightYellow","brightRed","brightGreen","brightBlue","brightWhite","brightCyan","brightMagenta"];return function(n){return" "===n?n:e[t[Math.round(Math.random()*(t.length-2))]](n)}}),Xd.exports)(e),e.maps)!function(t){e[t]=function(n){return h(e.maps[t],n)}}(f);r(e,function(){var e={};return Object.keys(l).forEach((function(t){e[t]={get:function(){return a([t])}}})),e}())}()),jd.exports}function eh(){return Hd||(Hd=1,function(e){var t=Qd();e.exports=t}(Dd)),Dd.exports}var th,nh,rh={},ih={},oh={};function sh(){if(nh)return Pd.exports;nh=1;const e=eh(),{LEVEL:t,MESSAGE:n}=rh;e.enabled=!0;const r=/\s+/;class i{constructor(e={}){e.colors&&this.addColors(e.colors),this.options=e}static addColors(e){const t=Object.keys(e).reduce(((t,n)=>(t[n]=r.test(e[n])?e[n].split(r):e[n],t)),{});return i.allColors=Object.assign({},i.allColors||{},t),i.allColors}addColors(e){return i.addColors(e)}colorize(t,n,r){if(void 0===r&&(r=n),!Array.isArray(i.allColors[t]))return e[i.allColors[t]](r);for(let n=0,o=i.allColors[t].length;n<o;n++)r=e[i.allColors[t][n]](r);return r}transform(e,r){return r.all&&"string"==typeof e[n]&&(e[n]=this.colorize(e[t],e.level,e[n])),(r.level||r.all||!r.message)&&(e.level=this.colorize(e[t],e.level)),(r.all||r.message)&&(e.message=this.colorize(e[t],e.level,e.message)),e}}return Pd.exports=e=>new i(e),Pd.exports.Colorizer=Pd.exports.Format=i,Pd.exports}oh.levels={emerg:0,alert:1,crit:2,error:3,warning:4,notice:5,info:6,debug:7},oh.colors={emerg:"red",alert:"yellow",crit:"red",error:"red",warning:"red",notice:"yellow",info:"green",debug:"blue"},th=ih,Object.defineProperty(th,"cli",{value:{levels:{error:0,warn:1,help:2,data:3,info:4,debug:5,prompt:6,verbose:7,input:8,silly:9},colors:{error:"red",warn:"yellow",help:"cyan",data:"grey",info:"green",debug:"blue",prompt:"grey",verbose:"cyan",input:"grey",silly:"magenta"}}}),Object.defineProperty(th,"npm",{value:{levels:{error:0,warn:1,info:2,http:3,verbose:4,debug:5,silly:6},colors:{error:"red",warn:"yellow",info:"green",http:"green",verbose:"cyan",debug:"blue",silly:"magenta"}}}),Object.defineProperty(th,"syslog",{value:oh}),function(e){Object.defineProperty(e,"LEVEL",{value:Symbol.for("level")}),Object.defineProperty(e,"MESSAGE",{value:Symbol.for("message")}),Object.defineProperty(e,"SPLAT",{value:Symbol.for("splat")}),Object.defineProperty(e,"configs",{value:ih})}(rh);const{Colorizer:ah}=sh();var ch,lh,uh,dh,hh,fh,ph={exports:{}},gh={exports:{}};function mh(){if(hh)return gh.exports;hh=1;const{configs:e,LEVEL:t,MESSAGE:n}=rh;class r{constructor(t={levels:e.npm.levels}){this.paddings=r.paddingForLevels(t.levels,t.filler),this.options=t}static getLongestLevel(e){const t=Object.keys(e).map((e=>e.length));return Math.max(...t)}static paddingForLevel(e,t,n){const r=n+1-e.length,i=Math.floor(r/t.length);return`${t}${t.repeat(i)}`.slice(0,r)}static paddingForLevels(e,t=" "){const n=r.getLongestLevel(e);return Object.keys(e).reduce(((e,i)=>(e[i]=r.paddingForLevel(i,t,n),e)),{})}transform(e,r){return e.message=`${this.paddings[e[t]]}${e.message}`,e[n]&&(e[n]=`${this.paddings[e[t]]}${e[n]}`),e}}return gh.exports=e=>new r(e),gh.exports.Padder=gh.exports.Format=r,gh.exports}var yh,vh,bh,wh,Sh,_h,Ih,xh,kh,Eh,Ch,$h,Oh,Nh,Th={exports:{}},Ah={exports:{}};function Mh(){return vh||(vh=1,function(e,t){const{hasOwnProperty:n}=Object.prototype,r=h();r.configure=h,r.stringify=r,r.default=r,t.stringify=r,t.configure=h,e.exports=r;const i=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function o(e){return e.length<5e3&&!i.test(e)?`"${e}"`:JSON.stringify(e)}function s(e,t){if(e.length>200||t)return e.sort(t);for(let t=1;t<e.length;t++){const n=e[t];let r=t;for(;0!==r&&e[r-1]>n;)e[r]=e[r-1],r--;e[r]=n}return e}const a=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function c(e){return void 0!==a.call(e)&&0!==e.length}function l(e,t,n){e.length<n&&(n=e.length);const r=","===t?"":" ";let i=`"0":${r}${e[0]}`;for(let o=1;o<n;o++)i+=`${t}"${o}":${r}${e[o]}`;return i}function u(e,t){let r;if(n.call(e,t)){if(r=e[t],"number"!=typeof r)throw new TypeError(`The "${t}" argument must be of type number`);if(!Number.isInteger(r))throw new TypeError(`The "${t}" argument must be an integer`);if(r<1)throw new RangeError(`The "${t}" argument must be >= 1`)}return void 0===r?1/0:r}function d(e){return 1===e?"1 item":`${e} items`}function h(e){const t=function(e){if(n.call(e,"strict")){const t=e.strict;if("boolean"!=typeof t)throw new TypeError('The "strict" argument must be of type boolean');if(t)return e=>{let t="Object can not safely be stringified. Received type "+typeof e;throw"function"!=typeof e&&(t+=` (${e.toString()})`),new Error(t)}}}(e={...e});t&&(void 0===e.bigint&&(e.bigint=!1),"circularValue"in e||(e.circularValue=Error));const r=function(e){if(n.call(e,"circularValue")){const t=e.circularValue;if("string"==typeof t)return`"${t}"`;if(null==t)return t;if(t===Error||t===TypeError)return{toString(){throw new TypeError("Converting circular structure to JSON")}};throw new TypeError('The "circularValue" argument must be of type string or the value null or undefined')}return'"[Circular]"'}(e),i=function(e,t){let r;if(n.call(e,t)&&(r=e[t],"boolean"!=typeof r))throw new TypeError(`The "${t}" argument must be of type boolean`);return void 0===r||r}(e,"bigint"),a=function(e){let t;if(n.call(e,"deterministic")&&(t=e.deterministic,"boolean"!=typeof t&&"function"!=typeof t))throw new TypeError('The "deterministic" argument must be of type boolean or comparator function');return void 0===t||t}(e),h="function"==typeof a?a:void 0,f=u(e,"maximumDepth"),p=u(e,"maximumBreadth");function g(e,n,l,u,m,y){let v=n[e];switch("object"==typeof v&&null!==v&&"function"==typeof v.toJSON&&(v=v.toJSON(e)),v=u.call(n,e,v),typeof v){case"string":return o(v);case"object":{if(null===v)return"null";if(-1!==l.indexOf(v))return r;let e="",t=",";const n=y;if(Array.isArray(v)){if(0===v.length)return"[]";if(f<l.length+1)return'"[Array]"';l.push(v),""!==m&&(e+=`\n${y+=m}`,t=`,\n${y}`);const r=Math.min(v.length,p);let i=0;for(;i<r-1;i++){const n=g(String(i),v,l,u,m,y);e+=void 0!==n?n:"null",e+=t}const o=g(String(i),v,l,u,m,y);return e+=void 0!==o?o:"null",v.length-1>p&&(e+=`${t}"... ${d(v.length-p-1)} not stringified"`),""!==m&&(e+=`\n${n}`),l.pop(),`[${e}]`}let i=Object.keys(v);const b=i.length;if(0===b)return"{}";if(f<l.length+1)return'"[Object]"';let w="",S="";""!==m&&(t=`,\n${y+=m}`,w=" ");const _=Math.min(b,p);a&&!c(v)&&(i=s(i,h)),l.push(v);for(let n=0;n<_;n++){const r=i[n],s=g(r,v,l,u,m,y);void 0!==s&&(e+=`${S}${o(r)}:${w}${s}`,S=t)}return b>p&&(e+=`${S}"...":${w}"${d(b-p)} not stringified"`,S=t),""!==m&&S.length>1&&(e=`\n${y}${e}\n${n}`),l.pop(),`{${e}}`}case"number":return isFinite(v)?String(v):t?t(v):"null";case"boolean":return!0===v?"true":"false";case"undefined":return;case"bigint":if(i)return String(v);default:return t?t(v):void 0}}function m(e,n,s,a,c,l){switch("object"==typeof n&&null!==n&&"function"==typeof n.toJSON&&(n=n.toJSON(e)),typeof n){case"string":return o(n);case"object":{if(null===n)return"null";if(-1!==s.indexOf(n))return r;const e=l;let t="",i=",";if(Array.isArray(n)){if(0===n.length)return"[]";if(f<s.length+1)return'"[Array]"';s.push(n),""!==c&&(t+=`\n${l+=c}`,i=`,\n${l}`);const r=Math.min(n.length,p);let o=0;for(;o<r-1;o++){const e=m(String(o),n[o],s,a,c,l);t+=void 0!==e?e:"null",t+=i}const u=m(String(o),n[o],s,a,c,l);return t+=void 0!==u?u:"null",n.length-1>p&&(t+=`${i}"... ${d(n.length-p-1)} not stringified"`),""!==c&&(t+=`\n${e}`),s.pop(),`[${t}]`}s.push(n);let u="";""!==c&&(i=`,\n${l+=c}`,u=" ");let h="";for(const e of a){const r=m(e,n[e],s,a,c,l);void 0!==r&&(t+=`${h}${o(e)}:${u}${r}`,h=i)}return""!==c&&h.length>1&&(t=`\n${l}${t}\n${e}`),s.pop(),`{${t}}`}case"number":return isFinite(n)?String(n):t?t(n):"null";case"boolean":return!0===n?"true":"false";case"undefined":return;case"bigint":if(i)return String(n);default:return t?t(n):void 0}}function y(e,n,u,g,m){switch(typeof n){case"string":return o(n);case"object":{if(null===n)return"null";if("function"==typeof n.toJSON){if("object"!=typeof(n=n.toJSON(e)))return y(e,n,u,g,m);if(null===n)return"null"}if(-1!==u.indexOf(n))return r;const t=m;if(Array.isArray(n)){if(0===n.length)return"[]";if(f<u.length+1)return'"[Array]"';u.push(n);let e=`\n${m+=g}`;const r=`,\n${m}`,i=Math.min(n.length,p);let o=0;for(;o<i-1;o++){const t=y(String(o),n[o],u,g,m);e+=void 0!==t?t:"null",e+=r}const s=y(String(o),n[o],u,g,m);return e+=void 0!==s?s:"null",n.length-1>p&&(e+=`${r}"... ${d(n.length-p-1)} not stringified"`),e+=`\n${t}`,u.pop(),`[${e}]`}let i=Object.keys(n);const v=i.length;if(0===v)return"{}";if(f<u.length+1)return'"[Object]"';const b=`,\n${m+=g}`;let w="",S="",_=Math.min(v,p);c(n)&&(w+=l(n,b,p),i=i.slice(n.length),_-=n.length,S=b),a&&(i=s(i,h)),u.push(n);for(let e=0;e<_;e++){const t=i[e],r=y(t,n[t],u,g,m);void 0!==r&&(w+=`${S}${o(t)}: ${r}`,S=b)}return v>p&&(w+=`${S}"...": "${d(v-p)} not stringified"`,S=b),""!==S&&(w=`\n${m}${w}\n${t}`),u.pop(),`{${w}}`}case"number":return isFinite(n)?String(n):t?t(n):"null";case"boolean":return!0===n?"true":"false";case"undefined":return;case"bigint":if(i)return String(n);default:return t?t(n):void 0}}function v(e,n,u){switch(typeof n){case"string":return o(n);case"object":{if(null===n)return"null";if("function"==typeof n.toJSON){if("object"!=typeof(n=n.toJSON(e)))return v(e,n,u);if(null===n)return"null"}if(-1!==u.indexOf(n))return r;let t="";const i=void 0!==n.length;if(i&&Array.isArray(n)){if(0===n.length)return"[]";if(f<u.length+1)return'"[Array]"';u.push(n);const e=Math.min(n.length,p);let r=0;for(;r<e-1;r++){const e=v(String(r),n[r],u);t+=void 0!==e?e:"null",t+=","}const i=v(String(r),n[r],u);return t+=void 0!==i?i:"null",n.length-1>p&&(t+=`,"... ${d(n.length-p-1)} not stringified"`),u.pop(),`[${t}]`}let g=Object.keys(n);const m=g.length;if(0===m)return"{}";if(f<u.length+1)return'"[Object]"';let y="",b=Math.min(m,p);i&&c(n)&&(t+=l(n,",",p),g=g.slice(n.length),b-=n.length,y=","),a&&(g=s(g,h)),u.push(n);for(let e=0;e<b;e++){const r=g[e],i=v(r,n[r],u);void 0!==i&&(t+=`${y}${o(r)}:${i}`,y=",")}return m>p&&(t+=`${y}"...":"${d(m-p)} not stringified"`),u.pop(),`{${t}}`}case"number":return isFinite(n)?String(n):t?t(n):"null";case"boolean":return!0===n?"true":"false";case"undefined":return;case"bigint":if(i)return String(n);default:return t?t(n):void 0}}return function(e,t,n){if(arguments.length>1){let r="";if("number"==typeof n?r=" ".repeat(Math.min(n,10)):"string"==typeof n&&(r=n.slice(0,10)),null!=t){if("function"==typeof t)return g("",{"":e},[],t,r,"");if(Array.isArray(t))return m("",e,[],function(e){const t=new Set;for(const n of e)"string"!=typeof n&&"number"!=typeof n||t.add(String(n));return t}(t),r,"")}if(0!==r.length)return y("",e,[],r,"")}return v("",e,[])}}}(Ah,Ah.exports)),Ah.exports}function Ph(){if(wh)return bh;wh=1;const e=Md,{MESSAGE:t}=rh,n=Mh();function r(e,t){return"bigint"==typeof t?t.toString():t}return bh=e(((e,i)=>{const o=n.configure(i);return e[t]=o(e,i.replacer||r,i.space),e}))}var Dh,jh,Rh,Lh,Fh,Uh={exports:{}},Bh=/d{1,4}|M{1,4}|YY(?:YY)?|S{1,3}|Do|ZZ|Z|([HhMsDm])\1?|[aA]|"[^"]*"|'[^']*'/g,Wh="\\d\\d?",Gh="\\d\\d",Vh="[^\\s]+",Yh=/\[([^]*?)\]/gm;function Hh(e,t){for(var n=[],r=0,i=e.length;r<i;r++)n.push(e[r].substr(0,t));return n}var zh=function(e){return function(t,n){var r=n[e].map((function(e){return e.toLowerCase()})),i=r.indexOf(t.toLowerCase());return i>-1?i:null}};function qh(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];for(var r=0,i=t;r<i.length;r++){var o=i[r];for(var s in o)e[s]=o[s]}return e}var Kh=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],Jh=["January","February","March","April","May","June","July","August","September","October","November","December"],Zh=Hh(Jh,3),Xh={dayNamesShort:Hh(Kh,3),dayNames:Kh,monthNamesShort:Zh,monthNames:Jh,amPm:["am","pm"],DoFn:function(e){return e+["th","st","nd","rd"][e%10>3?0:(e-e%10!=10?1:0)*e%10]}},Qh=qh({},Xh),ef=function(e){return Qh=qh(Qh,e)},tf=function(e){return e.replace(/[|\\{()[^$+*?.-]/g,"\\$&")},nf=function(e,t){for(void 0===t&&(t=2),e=String(e);e.length<t;)e="0"+e;return e},rf={D:function(e){return String(e.getDate())},DD:function(e){return nf(e.getDate())},Do:function(e,t){return t.DoFn(e.getDate())},d:function(e){return String(e.getDay())},dd:function(e){return nf(e.getDay())},ddd:function(e,t){return t.dayNamesShort[e.getDay()]},dddd:function(e,t){return t.dayNames[e.getDay()]},M:function(e){return String(e.getMonth()+1)},MM:function(e){return nf(e.getMonth()+1)},MMM:function(e,t){return t.monthNamesShort[e.getMonth()]},MMMM:function(e,t){return t.monthNames[e.getMonth()]},YY:function(e){return nf(String(e.getFullYear()),4).substr(2)},YYYY:function(e){return nf(e.getFullYear(),4)},h:function(e){return String(e.getHours()%12||12)},hh:function(e){return nf(e.getHours()%12||12)},H:function(e){return String(e.getHours())},HH:function(e){return nf(e.getHours())},m:function(e){return String(e.getMinutes())},mm:function(e){return nf(e.getMinutes())},s:function(e){return String(e.getSeconds())},ss:function(e){return nf(e.getSeconds())},S:function(e){return String(Math.round(e.getMilliseconds()/100))},SS:function(e){return nf(Math.round(e.getMilliseconds()/10),2)},SSS:function(e){return nf(e.getMilliseconds(),3)},a:function(e,t){return e.getHours()<12?t.amPm[0]:t.amPm[1]},A:function(e,t){return e.getHours()<12?t.amPm[0].toUpperCase():t.amPm[1].toUpperCase()},ZZ:function(e){var t=e.getTimezoneOffset();return(t>0?"-":"+")+nf(100*Math.floor(Math.abs(t)/60)+Math.abs(t)%60,4)},Z:function(e){var t=e.getTimezoneOffset();return(t>0?"-":"+")+nf(Math.floor(Math.abs(t)/60),2)+":"+nf(Math.abs(t)%60,2)}},of=function(e){return+e-1},sf=[null,Wh],af=[null,Vh],cf=["isPm",Vh,function(e,t){var n=e.toLowerCase();return n===t.amPm[0]?0:n===t.amPm[1]?1:null}],lf=["timezoneOffset","[^\\s]*?[\\+\\-]\\d\\d:?\\d\\d|[^\\s]*?Z?",function(e){var t=(e+"").match(/([+-]|\d\d)/gi);if(t){var n=60*+t[1]+parseInt(t[2],10);return"+"===t[0]?n:-n}return 0}],uf={D:["day",Wh],DD:["day",Gh],Do:["day",Wh+Vh,function(e){return parseInt(e,10)}],M:["month",Wh,of],MM:["month",Gh,of],YY:["year",Gh,function(e){var t=+(""+(new Date).getFullYear()).substr(0,2);return+(""+(+e>68?t-1:t)+e)}],h:["hour",Wh,void 0,"isPm"],hh:["hour",Gh,void 0,"isPm"],H:["hour",Wh],HH:["hour",Gh],m:["minute",Wh],mm:["minute",Gh],s:["second",Wh],ss:["second",Gh],YYYY:["year","\\d{4}"],S:["millisecond","\\d",function(e){return 100*+e}],SS:["millisecond",Gh,function(e){return 10*+e}],SSS:["millisecond","\\d{3}"],d:sf,dd:sf,ddd:af,dddd:af,MMM:["month",Vh,zh("monthNamesShort")],MMMM:["month",Vh,zh("monthNames")],a:cf,A:cf,ZZ:lf,Z:lf},df={default:"ddd MMM DD YYYY HH:mm:ss",shortDate:"M/D/YY",mediumDate:"MMM D, YYYY",longDate:"MMMM D, YYYY",fullDate:"dddd, MMMM D, YYYY",isoDate:"YYYY-MM-DD",isoDateTime:"YYYY-MM-DDTHH:mm:ssZ",shortTime:"HH:mm",mediumTime:"HH:mm:ss",longTime:"HH:mm:ss.SSS"},hf=function(e){return qh(df,e)},ff=function(e,t,n){if(void 0===t&&(t=df.default),void 0===n&&(n={}),"number"==typeof e&&(e=new Date(e)),"[object Date]"!==Object.prototype.toString.call(e)||isNaN(e.getTime()))throw new Error("Invalid Date pass to format");var r=[];t=(t=df[t]||t).replace(Yh,(function(e,t){return r.push(t),"@@@"}));var i=qh(qh({},Qh),n);return(t=t.replace(Bh,(function(t){return rf[t](e,i)}))).replace(/@@@/g,(function(){return r.shift()}))};function pf(e,t,n){if(void 0===n&&(n={}),"string"!=typeof t)throw new Error("Invalid format in fecha parse");if(t=df[t]||t,e.length>1e3)return null;var r={year:(new Date).getFullYear(),month:0,day:1,hour:0,minute:0,second:0,millisecond:0,isPm:null,timezoneOffset:null},i=[],o=[],s=t.replace(Yh,(function(e,t){return o.push(tf(t)),"@@@"})),a={},c={};s=tf(s).replace(Bh,(function(e){var t=uf[e],n=t[0],r=t[1],o=t[3];if(a[n])throw new Error("Invalid format. "+n+" specified twice in format");return a[n]=!0,o&&(c[o]=!0),i.push(t),"("+r+")"})),Object.keys(c).forEach((function(e){if(!a[e])throw new Error("Invalid format. "+e+" is required in specified format")})),s=s.replace(/@@@/g,(function(){return o.shift()}));var l=e.match(new RegExp(s,"i"));if(!l)return null;for(var u,d=qh(qh({},Qh),n),h=1;h<l.length;h++){var f=i[h-1],p=f[0],g=f[2],m=g?g(l[h],d):+l[h];if(null==m)return null;r[p]=m}if(1===r.isPm&&null!=r.hour&&12!=+r.hour?r.hour=+r.hour+12:0===r.isPm&&12==+r.hour&&(r.hour=0),null==r.timezoneOffset){u=new Date(r.year,r.month,r.day,r.hour,r.minute,r.second,r.millisecond);for(var y=[["month","getMonth"],["day","getDate"],["hour","getHours"],["minute","getMinutes"],["second","getSeconds"]],v=(h=0,y.length);h<v;h++)if(a[y[h][0]]&&r[y[h][0]]!==u[y[h][1]]())return null}else if(u=new Date(Date.UTC(r.year,r.month,r.day,r.hour,r.minute-r.timezoneOffset,r.second,r.millisecond)),r.month>11||r.month<0||r.day>31||r.day<1||r.hour>23||r.hour<0||r.minute>59||r.minute<0||r.second>59||r.second<0)return null;return u}var gf,mf,yf,vf,bf={format:ff,parse:pf,defaultI18n:Xh,setGlobalDateI18n:ef,setGlobalDateMasks:hf},wf=function(e){if(e.__esModule)return e;var t=e.default;if("function"==typeof t){var n=function e(){return this instanceof e?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach((function(t){var r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(n,t,r.get?r:{enumerable:!0,get:function(){return e[t]}})})),n}(Object.freeze({__proto__:null,assign:qh,default:bf,defaultI18n:Xh,format:ff,parse:pf,setGlobalDateI18n:ef,setGlobalDateMasks:hf}));const Sf=Ed.format=Md;function _f(e,t){Object.defineProperty(Sf,e,{get:()=>t(),configurable:!0})}Ed.levels=e=>(ah.addColors(e.colors||e),e),_f("align",(function(){return lh?ch:(lh=1,ch=Md((e=>(e.message=`\t${e.message}`,e))))})),_f("errors",(function(){return function(){if(dh)return uh;dh=1;const e=Md,{LEVEL:t,MESSAGE:n}=rh;return uh=e(((e,{stack:r,cause:i})=>{if(e instanceof Error){const o=Object.assign({},e,{level:e.level,[t]:e[t]||e.level,message:e.message,[n]:e[n]||e.message});return r&&(o.stack=e.stack),i&&(o.cause=e.cause),o}if(!(e.message instanceof Error))return e;const o=e.message;return Object.assign(e,o),e.message=o.message,e[n]=o.message,r&&(e.stack=o.stack),i&&(e.cause=o.cause),e}))}()})),_f("cli",(function(){return function(){if(fh)return ph.exports;fh=1;const{Colorizer:e}=sh(),{Padder:t}=mh(),{configs:n,MESSAGE:r}=rh;class i{constructor(r={}){r.levels||(r.levels=n.cli.levels),this.colorizer=new e(r),this.padder=new t(r),this.options=r}transform(e,t){return this.colorizer.transform(this.padder.transform(e,t),t),e[r]=`${e.level}:${e.message}`,e}}return ph.exports=e=>new i(e),ph.exports.Format=i,ph.exports}()})),_f("combine",(function(){return function(){if(yh)return Th.exports;yh=1;const e=Md;function t(e){if(e.every(n))return t=>{let n=t;for(let t=0;t<e.length;t++)if(n=e[t].transform(n,e[t].options),!n)return!1;return n}}function n(e){if("function"!=typeof e.transform)throw new Error(["No transform function found on format. Did you create a format instance?","const myFormat = format(formatFn);","const instance = myFormat();"].join("\n"));return!0}return Th.exports=(...n)=>{const r=e(t(n)),i=r();return i.Format=r.Format,i},Th.exports.cascade=t,Th.exports}()})),_f("colorize",(function(){return sh()})),_f("json",(function(){return Ph()})),_f("label",(function(){return _h?Sh:(_h=1,Sh=Md(((e,t)=>t.message?(e.message=`[${t.label}] ${e.message}`,e):(e.label=t.label,e))))})),_f("logstash",(function(){return function(){if(xh)return Ih;xh=1;const e=Md,{MESSAGE:t}=rh,n=Mh();return Ih=e((e=>{const r={};return e.message&&(r["@message"]=e.message,delete e.message),e.timestamp&&(r["@timestamp"]=e.timestamp,delete e.timestamp),r["@fields"]=e,e[t]=n(r),e}))}()})),_f("metadata",(function(){return Eh?kh:(Eh=1,kh=Md(((e,t={})=>{let n="metadata";t.key&&(n=t.key);let r=[];return t.fillExcept||t.fillWith||(r.push("level"),r.push("message")),t.fillExcept&&(r=t.fillExcept),r.length>0?function(e,t,n){const r=t.reduce(((t,n)=>(t[n]=e[n],delete e[n],t)),{}),i=Object.keys(e).reduce(((t,n)=>(t[n]=e[n],delete e[n],t)),{});return Object.assign(e,r,{[n]:i}),e}(e,r,n):t.fillWith?function(e,t,n){return e[n]=t.reduce(((t,n)=>(t[n]=e[n],delete e[n],t)),{}),e}(e,t.fillWith,n):e})))})),_f("ms",(function(){return function(){if($h)return Ch;$h=1;const e=Md,t=gd();return Ch=e((e=>{const n=+new Date;return this.diff=n-(this.prevTime||n),this.prevTime=n,e.ms=`+${t(this.diff)}`,e}))}()})),_f("padLevels",(function(){return mh()})),_f("prettyPrint",(function(){return function(){if(Nh)return Oh;Nh=1;const e=i.inspect,t=Md,{LEVEL:n,MESSAGE:r,SPLAT:o}=rh;return Oh=t(((t,i={})=>{const s=Object.assign({},t);return delete s[n],delete s[r],delete s[o],t[r]=e(s,!1,i.depth||null,i.colorize),t}))}()})),_f("printf",(function(){return function(){if(Dh)return Uh.exports;Dh=1;const{MESSAGE:e}=rh;class t{constructor(e){this.template=e}transform(t){return t[e]=this.template(t),t}}return Uh.exports=e=>new t(e),Uh.exports.Printf=Uh.exports.Format=t,Uh.exports}()})),_f("simple",(function(){return function(){if(Rh)return jh;Rh=1;const e=Md,{MESSAGE:t}=rh,n=Mh();return jh=e((e=>{const r=n(Object.assign({},e,{level:void 0,message:void 0,splat:void 0})),i=e.padding&&e.padding[e.level]||"";return e[t]="{}"!==r?`${e.level}:${i} ${e.message} ${r}`:`${e.level}:${i} ${e.message}`,e}))}()})),_f("splat",(function(){return function(){if(Fh)return Lh;Fh=1;const e=i,{SPLAT:t}=rh,n=/%[scdjifoO%]/g,r=/%%/g;class o{constructor(e){this.options=e}_splat(n,i){const o=n.message,s=n[t]||n.splat||[],a=o.match(r),c=a&&a.length||0,l=i.length-c-s.length,u=l<0?s.splice(l,-1*l):[],d=u.length;if(d)for(let e=0;e<d;e++)Object.assign(n,u[e]);return n.message=e.format(o,...s),n}transform(e){const r=e.message,i=e[t]||e.splat;if(!i||!i.length)return e;const o=r&&r.match&&r.match(n);if(!o&&(i||i.length)){const t=i.length>1?i.splice(0):i,n=t.length;if(n)for(let r=0;r<n;r++)Object.assign(e,t[r]);return e}return o?this._splat(e,o):e}}return Lh=e=>new o(e)}()})),_f("timestamp",(function(){return function(){if(mf)return gf;mf=1;const e=wf;return gf=Md(((t,n={})=>(n.format&&(t.timestamp="function"==typeof n.format?n.format():e.format(new Date,n.format)),t.timestamp||(t.timestamp=(new Date).toISOString()),n.alias&&(t[n.alias]=t.timestamp),t)))}()})),_f("uncolorize",(function(){return function(){if(vf)return yf;vf=1;const e=eh(),t=Md,{MESSAGE:n}=rh;return yf=t(((t,r)=>(!1!==r.level&&(t.level=e.strip(t.level)),!1!==r.message&&(t.message=e.strip(String(t.message))),!1!==r.raw&&t[n]&&(t[n]=e.strip(String(t[n]))),t)))}()}));var If={};!function(e){const{format:t}=i;e.warn={deprecated:e=>()=>{throw new Error(t("{ %s } was removed in winston@3.0.0.",e))},useFormat:e=>()=>{throw new Error([t("{ %s } was removed in winston@3.0.0.",e),"Use a custom winston.format = winston.format(function) instead."].join("\n"))},forFunctions(t,n,r){r.forEach((r=>{t[r]=e.warn[n](r)}))},forProperties(t,n,r){r.forEach((r=>{const i=e.warn[n](r);Object.defineProperty(t,r,{get:i,set:i})}))}}}(If);var xf,kf,Ef,Cf,$f,Of,Nf={},Tf={exports:{}},Af={exports:{}};function Mf(){return Cf?Ef:(Cf=1,Ef=M)}function Pf(){if(Of)return $f;function e(e,r){n(e,r),t(e)}function t(e){e._writableState&&!e._writableState.emitClose||e._readableState&&!e._readableState.emitClose||e.emit("close")}function n(e,t){e.emit("error",t)}return Of=1,$f={destroy:function(r,i){var o=this,s=this._readableState&&this._readableState.destroyed,a=this._writableState&&this._writableState.destroyed;return s||a?(i?i(r):r&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,process.nextTick(n,this,r)):process.nextTick(n,this,r)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(r||null,(function(n){!i&&n?o._writableState?o._writableState.errorEmitted?process.nextTick(t,o):(o._writableState.errorEmitted=!0,process.nextTick(e,o,n)):process.nextTick(e,o,n):i?(process.nextTick(t,o),i(n)):process.nextTick(t,o)})),this)},undestroy:function(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)},errorOrDestroy:function(e,t){var n=e._readableState,r=e._writableState;n&&n.autoDestroy||r&&r.autoDestroy?e.destroy(t):e.emit("error",t)}},$f}var Df,jf,Rf,Lf={};function Ff(){if(Df)return Lf;Df=1;const e={};function t(t,n,r){r||(r=Error);class i extends r{constructor(e,t,r){super(function(e,t,r){return"string"==typeof n?n:n(e,t,r)}(e,t,r))}}i.prototype.name=r.name,i.prototype.code=t,e[t]=i}function n(e,t){if(Array.isArray(e)){const n=e.length;return e=e.map((e=>String(e))),n>2?`one of ${t} ${e.slice(0,n-1).join(", ")}, or `+e[n-1]:2===n?`one of ${t} ${e[0]} or ${e[1]}`:`of ${t} ${e[0]}`}return`of ${t} ${String(e)}`}return t("ERR_INVALID_OPT_VALUE",(function(e,t){return'The value "'+t+'" is invalid for option "'+e+'"'}),TypeError),t("ERR_INVALID_ARG_TYPE",(function(e,t,r){let i;var o;let s;if("string"==typeof t&&(o="not ",t.substr(0,4)===o)?(i="must not be",t=t.replace(/^not /,"")):i="must be",function(e,t,n){return(void 0===n||n>e.length)&&(n=e.length),e.substring(n-9,n)===t}(e," argument"))s=`The ${e} ${i} ${n(t,"type")}`;else{const r=function(e,t,n){return"number"!=typeof n&&(n=0),!(n+1>e.length)&&-1!==e.indexOf(".",n)}(e)?"property":"argument";s=`The "${e}" ${r} ${i} ${n(t,"type")}`}return s+=". Received type "+typeof r,s}),TypeError),t("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),t("ERR_METHOD_NOT_IMPLEMENTED",(function(e){return"The "+e+" method is not implemented"})),t("ERR_STREAM_PREMATURE_CLOSE","Premature close"),t("ERR_STREAM_DESTROYED",(function(e){return"Cannot call "+e+" after a stream was destroyed"})),t("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),t("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),t("ERR_STREAM_WRITE_AFTER_END","write after end"),t("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),t("ERR_UNKNOWN_ENCODING",(function(e){return"Unknown encoding: "+e}),TypeError),t("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),Lf.codes=e,Lf}function Uf(){if(Rf)return jf;Rf=1;var e=Ff().codes.ERR_INVALID_OPT_VALUE;return jf={getHighWaterMark:function(t,n,r,i){var o=function(e,t,n){return null!=e.highWaterMark?e.highWaterMark:t?e[n]:null}(n,i,r);if(null!=o){if(!isFinite(o)||Math.floor(o)!==o||o<0)throw new e(i?r:"highWaterMark",o);return Math.floor(o)}return t.objectMode?16:16384}}}var Bf,Wf,Gf,Vf,Yf={exports:{}},Hf={exports:{}};function zf(){if(Wf)return Yf.exports;Wf=1;try{var e=require("util");if("function"!=typeof e.inherits)throw"";Yf.exports=e.inherits}catch(e){Yf.exports=(Bf||(Bf=1,"function"==typeof Object.create?Hf.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:Hf.exports=function(e,t){if(t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}}),Hf.exports)}return Yf.exports}function qf(){if(Vf)return Gf;function e(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function t(t){for(var r=1;r<arguments.length;r++){var i=null!=arguments[r]?arguments[r]:{};r%2?e(Object(i),!0).forEach((function(e){n(t,e,i[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):e(Object(i)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(i,e))}))}return t}function n(e,t,n){return(t=r(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function r(e){var t=function(e){if("object"!=typeof e||null===e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:String(t)}Vf=1;var o=P.Buffer,s=i.inspect,a=s&&s.custom||"inspect";function c(e,t,n){o.prototype.copy.call(e,t,n)}return Gf=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.head=null,this.tail=null,this.length=0}return function(e,t){t&&function(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,r(i.key),i)}}(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1})}(e,[{key:"push",value:function(e){var t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length}},{key:"unshift",value:function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length}},{key:"shift",value:function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(e){if(0===this.length)return"";for(var t=this.head,n=""+t.data;t=t.next;)n+=e+t.data;return n}},{key:"concat",value:function(e){if(0===this.length)return o.alloc(0);for(var t=o.allocUnsafe(e>>>0),n=this.head,r=0;n;)c(n.data,t,r),r+=n.data.length,n=n.next;return t}},{key:"consume",value:function(e,t){var n;return e<this.head.data.length?(n=this.head.data.slice(0,e),this.head.data=this.head.data.slice(e)):n=e===this.head.data.length?this.shift():t?this._getString(e):this._getBuffer(e),n}},{key:"first",value:function(){return this.head.data}},{key:"_getString",value:function(e){var t=this.head,n=1,r=t.data;for(e-=r.length;t=t.next;){var i=t.data,o=e>i.length?i.length:e;if(o===i.length?r+=i:r+=i.slice(0,e),0==(e-=o)){o===i.length?(++n,t.next?this.head=t.next:this.head=this.tail=null):(this.head=t,t.data=i.slice(o));break}++n}return this.length-=n,r}},{key:"_getBuffer",value:function(e){var t=o.allocUnsafe(e),n=this.head,r=1;for(n.data.copy(t),e-=n.data.length;n=n.next;){var i=n.data,s=e>i.length?i.length:e;if(i.copy(t,t.length-e,0,s),0==(e-=s)){s===i.length?(++r,n.next?this.head=n.next:this.head=this.tail=null):(this.head=n,n.data=i.slice(s));break}++r}return this.length-=r,t}},{key:a,value:function(e,n){return s(this,t(t({},n),{},{depth:0,customInspect:!1}))}}]),e}()}var Kf,Jf,Zf,Xf,Qf,ep,tp,np,rp,ip,op,sp,ap,cp,lp={},up={exports:{}};function dp(){if(Jf)return lp;Jf=1;var e=(Kf||(Kf=1,function(e,t){var n=P,r=n.Buffer;function i(e,t){for(var n in e)t[n]=e[n]}function o(e,t,n){return r(e,t,n)}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?e.exports=n:(i(n,t),t.Buffer=o),o.prototype=Object.create(r.prototype),i(r,o),o.from=function(e,t,n){if("number"==typeof e)throw new TypeError("Argument must not be a number");return r(e,t,n)},o.alloc=function(e,t,n){if("number"!=typeof e)throw new TypeError("Argument must be a number");var i=r(e);return void 0!==t?"string"==typeof n?i.fill(t,n):i.fill(t):i.fill(0),i},o.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return r(e)},o.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n.SlowBuffer(e)}}(up,up.exports)),up.exports).Buffer,t=e.isEncoding||function(e){switch((e=""+e)&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function n(n){var r;switch(this.encoding=function(n){var r=function(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}(n);if("string"!=typeof r&&(e.isEncoding===t||!t(n)))throw new Error("Unknown encoding: "+n);return r||n}(n),this.encoding){case"utf16le":this.text=o,this.end=s,r=4;break;case"utf8":this.fillLast=i,r=4;break;case"base64":this.text=a,this.end=c,r=3;break;default:return this.write=l,void(this.end=u)}this.lastNeed=0,this.lastTotal=0,this.lastChar=e.allocUnsafe(r)}function r(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function i(e){var t=this.lastTotal-this.lastNeed,n=function(e,t){if(128!=(192&t[0]))return e.lastNeed=0,"�";if(e.lastNeed>1&&t.length>1){if(128!=(192&t[1]))return e.lastNeed=1,"�";if(e.lastNeed>2&&t.length>2&&128!=(192&t[2]))return e.lastNeed=2,"�"}}(this,e);return void 0!==n?n:this.lastNeed<=e.length?(e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,t,0,e.length),void(this.lastNeed-=e.length))}function o(e,t){if((e.length-t)%2==0){var n=e.toString("utf16le",t);if(n){var r=n.charCodeAt(n.length-1);if(r>=55296&&r<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],n.slice(0,-1)}return n}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function s(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var n=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,n)}return t}function a(e,t){var n=(e.length-t)%3;return 0===n?e.toString("base64",t):(this.lastNeed=3-n,this.lastTotal=3,1===n?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-n))}function c(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function l(e){return e.toString(this.encoding)}function u(e){return e&&e.length?this.write(e):""}return lp.StringDecoder=n,n.prototype.write=function(e){if(0===e.length)return"";var t,n;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";n=this.lastNeed,this.lastNeed=0}else n=0;return n<e.length?t?t+this.text(e,n):this.text(e,n):t||""},n.prototype.end=function(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+"�":t},n.prototype.text=function(e,t){var n=function(e,t,n){var i=t.length-1;if(i<n)return 0;var o=r(t[i]);return o>=0?(o>0&&(e.lastNeed=o-1),o):--i<n||-2===o?0:(o=r(t[i]))>=0?(o>0&&(e.lastNeed=o-2),o):--i<n||-2===o?0:(o=r(t[i]))>=0?(o>0&&(2===o?o=0:e.lastNeed=o-3),o):0}(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=n;var i=e.length-(n-this.lastNeed);return e.copy(this.lastChar,0,i),e.toString("utf8",t,i)},n.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length},lp}function hp(){if(Xf)return Zf;Xf=1;var e=Ff().codes.ERR_STREAM_PREMATURE_CLOSE;function t(){}return Zf=function n(r,i,o){if("function"==typeof i)return n(r,null,i);i||(i={}),o=function(e){var t=!1;return function(){if(!t){t=!0;for(var n=arguments.length,r=new Array(n),i=0;i<n;i++)r[i]=arguments[i];e.apply(this,r)}}}(o||t);var s=i.readable||!1!==i.readable&&r.readable,a=i.writable||!1!==i.writable&&r.writable,c=function(){r.writable||u()},l=r._writableState&&r._writableState.finished,u=function(){a=!1,l=!0,s||o.call(r)},d=r._readableState&&r._readableState.endEmitted,h=function(){s=!1,d=!0,a||o.call(r)},f=function(e){o.call(r,e)},p=function(){var t;return s&&!d?(r._readableState&&r._readableState.ended||(t=new e),o.call(r,t)):a&&!l?(r._writableState&&r._writableState.ended||(t=new e),o.call(r,t)):void 0},g=function(){r.req.on("finish",u)};return function(e){return e.setHeader&&"function"==typeof e.abort}(r)?(r.on("complete",u),r.on("abort",p),r.req?g():r.on("request",g)):a&&!r._writableState&&(r.on("end",c),r.on("close",c)),r.on("end",h),r.on("finish",u),!1!==i.error&&r.on("error",f),r.on("close",p),function(){r.removeListener("complete",u),r.removeListener("abort",p),r.removeListener("request",g),r.req&&r.req.removeListener("finish",u),r.removeListener("end",c),r.removeListener("close",c),r.removeListener("finish",u),r.removeListener("end",h),r.removeListener("error",f),r.removeListener("close",p)}},Zf}function fp(){if(ip)return rp;var e;ip=1,rp=_,_.ReadableState=S,D.EventEmitter;var t,n=function(e,t){return e.listeners(t).length},r=Mf(),o=P.Buffer,s=(void 0!==sd?sd:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{}).Uint8Array||function(){},a=i;t=a&&a.debuglog?a.debuglog("stream"):function(){};var c,l,u,d=qf(),h=Pf(),f=Uf().getHighWaterMark,p=Ff().codes,g=p.ERR_INVALID_ARG_TYPE,m=p.ERR_STREAM_PUSH_AFTER_EOF,y=p.ERR_METHOD_NOT_IMPLEMENTED,v=p.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;zf()(_,r);var b=h.errorOrDestroy,w=["error","close","destroy","pause","resume"];function S(t,n,r){e=e||pp(),t=t||{},"boolean"!=typeof r&&(r=n instanceof e),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.readableObjectMode),this.highWaterMark=f(this,t,"readableHighWaterMark",r),this.buffer=new d,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=!1!==t.emitClose,this.autoDestroy=!!t.autoDestroy,this.destroyed=!1,this.defaultEncoding=t.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,t.encoding&&(c||(c=dp().StringDecoder),this.decoder=new c(t.encoding),this.encoding=t.encoding)}function _(t){if(e=e||pp(),!(this instanceof _))return new _(t);var n=this instanceof e;this._readableState=new S(t,this,n),this.readable=!0,t&&("function"==typeof t.read&&(this._read=t.read),"function"==typeof t.destroy&&(this._destroy=t.destroy)),r.call(this)}function I(e,n,r,i,a){t("readableAddChunk",n);var c,l=e._readableState;if(null===n)l.reading=!1,function(e,n){if(t("onEofChunk"),!n.ended){if(n.decoder){var r=n.decoder.end();r&&r.length&&(n.buffer.push(r),n.length+=n.objectMode?1:r.length)}n.ended=!0,n.sync?C(e):(n.needReadable=!1,n.emittedReadable||(n.emittedReadable=!0,$(e)))}}(e,l);else if(a||(c=function(e,t){var n,r;return r=t,o.isBuffer(r)||r instanceof s||"string"==typeof t||void 0===t||e.objectMode||(n=new g("chunk",["string","Buffer","Uint8Array"],t)),n}(l,n)),c)b(e,c);else if(l.objectMode||n&&n.length>0)if("string"==typeof n||l.objectMode||Object.getPrototypeOf(n)===o.prototype||(n=function(e){return o.from(e)}(n)),i)l.endEmitted?b(e,new v):x(e,l,n,!0);else if(l.ended)b(e,new m);else{if(l.destroyed)return!1;l.reading=!1,l.decoder&&!r?(n=l.decoder.write(n),l.objectMode||0!==n.length?x(e,l,n,!1):O(e,l)):x(e,l,n,!1)}else i||(l.reading=!1,O(e,l));return!l.ended&&(l.length<l.highWaterMark||0===l.length)}function x(e,t,n,r){t.flowing&&0===t.length&&!t.sync?(t.awaitDrain=0,e.emit("data",n)):(t.length+=t.objectMode?1:n.length,r?t.buffer.unshift(n):t.buffer.push(n),t.needReadable&&C(e)),O(e,t)}Object.defineProperty(_.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._readableState&&this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}}),_.prototype.destroy=h.destroy,_.prototype._undestroy=h.undestroy,_.prototype._destroy=function(e,t){t(e)},_.prototype.push=function(e,t){var n,r=this._readableState;return r.objectMode?n=!0:"string"==typeof e&&((t=t||r.defaultEncoding)!==r.encoding&&(e=o.from(e,t),t=""),n=!0),I(this,e,t,!1,n)},_.prototype.unshift=function(e){return I(this,e,null,!0,!1)},_.prototype.isPaused=function(){return!1===this._readableState.flowing},_.prototype.setEncoding=function(e){c||(c=dp().StringDecoder);var t=new c(e);this._readableState.decoder=t,this._readableState.encoding=this._readableState.decoder.encoding;for(var n=this._readableState.buffer.head,r="";null!==n;)r+=t.write(n.data),n=n.next;return this._readableState.buffer.clear(),""!==r&&this._readableState.buffer.push(r),this._readableState.length=r.length,this};var k=1073741824;function E(e,t){return e<=0||0===t.length&&t.ended?0:t.objectMode?1:e!=e?t.flowing&&t.length?t.buffer.head.data.length:t.length:(e>t.highWaterMark&&(t.highWaterMark=function(e){return e>=k?e=k:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function C(e){var n=e._readableState;t("emitReadable",n.needReadable,n.emittedReadable),n.needReadable=!1,n.emittedReadable||(t("emitReadable",n.flowing),n.emittedReadable=!0,process.nextTick($,e))}function $(e){var n=e._readableState;t("emitReadable_",n.destroyed,n.length,n.ended),n.destroyed||!n.length&&!n.ended||(e.emit("readable"),n.emittedReadable=!1),n.needReadable=!n.flowing&&!n.ended&&n.length<=n.highWaterMark,j(e)}function O(e,t){t.readingMore||(t.readingMore=!0,process.nextTick(N,e,t))}function N(e,n){for(;!n.reading&&!n.ended&&(n.length<n.highWaterMark||n.flowing&&0===n.length);){var r=n.length;if(t("maybeReadMore read 0"),e.read(0),r===n.length)break}n.readingMore=!1}function T(e){var t=e._readableState;t.readableListening=e.listenerCount("readable")>0,t.resumeScheduled&&!t.paused?t.flowing=!0:e.listenerCount("data")>0&&e.resume()}function A(e){t("readable nexttick read 0"),e.read(0)}function M(e,n){t("resume",n.reading),n.reading||e.read(0),n.resumeScheduled=!1,e.emit("resume"),j(e),n.flowing&&!n.reading&&e.read(0)}function j(e){var n=e._readableState;for(t("flow",n.flowing);n.flowing&&null!==e.read(););}function R(e,t){return 0===t.length?null:(t.objectMode?n=t.buffer.shift():!e||e>=t.length?(n=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):n=t.buffer.consume(e,t.decoder),n);var n}function L(e){var n=e._readableState;t("endReadable",n.endEmitted),n.endEmitted||(n.ended=!0,process.nextTick(F,n,e))}function F(e,n){if(t("endReadableNT",e.endEmitted,e.length),!e.endEmitted&&0===e.length&&(e.endEmitted=!0,n.readable=!1,n.emit("end"),e.autoDestroy)){var r=n._writableState;(!r||r.autoDestroy&&r.finished)&&n.destroy()}}function U(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1}return _.prototype.read=function(e){t("read",e),e=parseInt(e,10);var n=this._readableState,r=e;if(0!==e&&(n.emittedReadable=!1),0===e&&n.needReadable&&((0!==n.highWaterMark?n.length>=n.highWaterMark:n.length>0)||n.ended))return t("read: emitReadable",n.length,n.ended),0===n.length&&n.ended?L(this):C(this),null;if(0===(e=E(e,n))&&n.ended)return 0===n.length&&L(this),null;var i,o=n.needReadable;return t("need readable",o),(0===n.length||n.length-e<n.highWaterMark)&&t("length less than watermark",o=!0),n.ended||n.reading?t("reading or ended",o=!1):o&&(t("do read"),n.reading=!0,n.sync=!0,0===n.length&&(n.needReadable=!0),this._read(n.highWaterMark),n.sync=!1,n.reading||(e=E(r,n))),null===(i=e>0?R(e,n):null)?(n.needReadable=n.length<=n.highWaterMark,e=0):(n.length-=e,n.awaitDrain=0),0===n.length&&(n.ended||(n.needReadable=!0),r!==e&&n.ended&&L(this)),null!==i&&this.emit("data",i),i},_.prototype._read=function(){b(this,new y("_read()"))},_.prototype.pipe=function(e,r){var i=this,o=this._readableState;switch(o.pipesCount){case 0:o.pipes=e;break;case 1:o.pipes=[o.pipes,e];break;default:o.pipes.push(e)}o.pipesCount+=1,t("pipe count=%d opts=%j",o.pipesCount,r);var s=r&&!1===r.end||e===process.stdout||e===process.stderr?p:a;function a(){t("onend"),e.end()}o.endEmitted?process.nextTick(s):i.once("end",s),e.on("unpipe",(function n(r,s){t("onunpipe"),r===i&&s&&!1===s.hasUnpiped&&(s.hasUnpiped=!0,t("cleanup"),e.removeListener("close",h),e.removeListener("finish",f),e.removeListener("drain",c),e.removeListener("error",d),e.removeListener("unpipe",n),i.removeListener("end",a),i.removeListener("end",p),i.removeListener("data",u),l=!0,!o.awaitDrain||e._writableState&&!e._writableState.needDrain||c())}));var c=function(e){return function(){var r=e._readableState;t("pipeOnDrain",r.awaitDrain),r.awaitDrain&&r.awaitDrain--,0===r.awaitDrain&&n(e,"data")&&(r.flowing=!0,j(e))}}(i);e.on("drain",c);var l=!1;function u(n){t("ondata");var r=e.write(n);t("dest.write",r),!1===r&&((1===o.pipesCount&&o.pipes===e||o.pipesCount>1&&-1!==U(o.pipes,e))&&!l&&(t("false write response, pause",o.awaitDrain),o.awaitDrain++),i.pause())}function d(r){t("onerror",r),p(),e.removeListener("error",d),0===n(e,"error")&&b(e,r)}function h(){e.removeListener("finish",f),p()}function f(){t("onfinish"),e.removeListener("close",h),p()}function p(){t("unpipe"),i.unpipe(e)}return i.on("data",u),function(e,t,n){if("function"==typeof e.prependListener)return e.prependListener(t,n);e._events&&e._events[t]?Array.isArray(e._events[t])?e._events[t].unshift(n):e._events[t]=[n,e._events[t]]:e.on(t,n)}(e,"error",d),e.once("close",h),e.once("finish",f),e.emit("pipe",i),o.flowing||(t("pipe resume"),i.resume()),e},_.prototype.unpipe=function(e){var t=this._readableState,n={hasUnpiped:!1};if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes||(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,n)),this;if(!e){var r=t.pipes,i=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var o=0;o<i;o++)r[o].emit("unpipe",this,{hasUnpiped:!1});return this}var s=U(t.pipes,e);return-1===s||(t.pipes.splice(s,1),t.pipesCount-=1,1===t.pipesCount&&(t.pipes=t.pipes[0]),e.emit("unpipe",this,n)),this},_.prototype.on=function(e,n){var i=r.prototype.on.call(this,e,n),o=this._readableState;return"data"===e?(o.readableListening=this.listenerCount("readable")>0,!1!==o.flowing&&this.resume()):"readable"===e&&(o.endEmitted||o.readableListening||(o.readableListening=o.needReadable=!0,o.flowing=!1,o.emittedReadable=!1,t("on readable",o.length,o.reading),o.length?C(this):o.reading||process.nextTick(A,this))),i},_.prototype.addListener=_.prototype.on,_.prototype.removeListener=function(e,t){var n=r.prototype.removeListener.call(this,e,t);return"readable"===e&&process.nextTick(T,this),n},_.prototype.removeAllListeners=function(e){var t=r.prototype.removeAllListeners.apply(this,arguments);return"readable"!==e&&void 0!==e||process.nextTick(T,this),t},_.prototype.resume=function(){var e=this._readableState;return e.flowing||(t("resume"),e.flowing=!e.readableListening,function(e,t){t.resumeScheduled||(t.resumeScheduled=!0,process.nextTick(M,e,t))}(this,e)),e.paused=!1,this},_.prototype.pause=function(){return t("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(t("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},_.prototype.wrap=function(e){var n=this,r=this._readableState,i=!1;for(var o in e.on("end",(function(){if(t("wrapped end"),r.decoder&&!r.ended){var e=r.decoder.end();e&&e.length&&n.push(e)}n.push(null)})),e.on("data",(function(o){t("wrapped data"),r.decoder&&(o=r.decoder.write(o)),r.objectMode&&null==o||(r.objectMode||o&&o.length)&&(n.push(o)||(i=!0,e.pause()))})),e)void 0===this[o]&&"function"==typeof e[o]&&(this[o]=function(t){return function(){return e[t].apply(e,arguments)}}(o));for(var s=0;s<w.length;s++)e.on(w[s],this.emit.bind(this,w[s]));return this._read=function(n){t("wrapped _read",n),i&&(i=!1,e.resume())},this},"function"==typeof Symbol&&(_.prototype[Symbol.asyncIterator]=function(){return void 0===l&&(l=function(){if(ep)return Qf;var e;function t(e,t,n){return(t=function(e){var t=function(e){if("object"!=typeof e||null===e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:String(t)}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}ep=1;var n=hp(),r=Symbol("lastResolve"),i=Symbol("lastReject"),o=Symbol("error"),s=Symbol("ended"),a=Symbol("lastPromise"),c=Symbol("handlePromise"),l=Symbol("stream");function u(e,t){return{value:e,done:t}}function d(e){var t=e[r];if(null!==t){var n=e[l].read();null!==n&&(e[a]=null,e[r]=null,e[i]=null,t(u(n,!1)))}}function h(e){process.nextTick(d,e)}var f=Object.getPrototypeOf((function(){})),p=Object.setPrototypeOf((e={get stream(){return this[l]},next:function(){var e=this,t=this[o];if(null!==t)return Promise.reject(t);if(this[s])return Promise.resolve(u(void 0,!0));if(this[l].destroyed)return new Promise((function(t,n){process.nextTick((function(){e[o]?n(e[o]):t(u(void 0,!0))}))}));var n,r=this[a];if(r)n=new Promise(function(e,t){return function(n,r){e.then((function(){t[s]?n(u(void 0,!0)):t[c](n,r)}),r)}}(r,this));else{var i=this[l].read();if(null!==i)return Promise.resolve(u(i,!1));n=new Promise(this[c])}return this[a]=n,n}},t(e,Symbol.asyncIterator,(function(){return this})),t(e,"return",(function(){var e=this;return new Promise((function(t,n){e[l].destroy(null,(function(e){e?n(e):t(u(void 0,!0))}))}))})),e),f);return Qf=function(e){var d,f=Object.create(p,(t(d={},l,{value:e,writable:!0}),t(d,r,{value:null,writable:!0}),t(d,i,{value:null,writable:!0}),t(d,o,{value:null,writable:!0}),t(d,s,{value:e._readableState.endEmitted,writable:!0}),t(d,c,{value:function(e,t){var n=f[l].read();n?(f[a]=null,f[r]=null,f[i]=null,e(u(n,!1))):(f[r]=e,f[i]=t)},writable:!0}),d));return f[a]=null,n(e,(function(e){if(e&&"ERR_STREAM_PREMATURE_CLOSE"!==e.code){var t=f[i];return null!==t&&(f[a]=null,f[r]=null,f[i]=null,t(e)),void(f[o]=e)}var n=f[r];null!==n&&(f[a]=null,f[r]=null,f[i]=null,n(u(void 0,!0))),f[s]=!0})),e.on("readable",h.bind(null,f)),f},Qf}()),l(this)}),Object.defineProperty(_.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(_.prototype,"readableBuffer",{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(_.prototype,"readableFlowing",{enumerable:!1,get:function(){return this._readableState.flowing},set:function(e){this._readableState&&(this._readableState.flowing=e)}}),_._fromList=R,Object.defineProperty(_.prototype,"readableLength",{enumerable:!1,get:function(){return this._readableState.length}}),"function"==typeof Symbol&&(_.from=function(e,t){return void 0===u&&(u=function(){if(np)return tp;function e(e,t,n,r,i,o,s){try{var a=e[o](s),c=a.value}catch(e){return void n(e)}a.done?t(c):Promise.resolve(c).then(r,i)}function t(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function n(e,t,n){return(t=function(e){var t=function(e){if("object"!=typeof e||null===e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:String(t)}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}np=1;var r=Ff().codes.ERR_INVALID_ARG_TYPE;return tp=function(i,o,s){var a;if(o&&"function"==typeof o.next)a=o;else if(o&&o[Symbol.asyncIterator])a=o[Symbol.asyncIterator]();else{if(!o||!o[Symbol.iterator])throw new r("iterable",["Iterable"],o);a=o[Symbol.iterator]()}var c=new i(function(e){for(var r=1;r<arguments.length;r++){var i=null!=arguments[r]?arguments[r]:{};r%2?t(Object(i),!0).forEach((function(t){n(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):t(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}({objectMode:!0},s)),l=!1;function u(){return d.apply(this,arguments)}function d(){var t;return t=function*(){try{var e=yield a.next(),t=e.value;e.done?c.push(null):c.push(yield t)?u():l=!1}catch(e){c.destroy(e)}},d=function(){var n=this,r=arguments;return new Promise((function(i,o){var s=t.apply(n,r);function a(t){e(s,i,o,a,c,"next",t)}function c(t){e(s,i,o,a,c,"throw",t)}a(void 0)}))},d.apply(this,arguments)}return c._read=function(){l||(l=!0,u())},c},tp}()),u(_,e,t)}),rp}function pp(){if(sp)return op;sp=1;var e=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t};op=s;var t=fp(),n=gp();zf()(s,t);for(var r=e(n.prototype),i=0;i<r.length;i++){var o=r[i];s.prototype[o]||(s.prototype[o]=n.prototype[o])}function s(e){if(!(this instanceof s))return new s(e);t.call(this,e),n.call(this,e),this.allowHalfOpen=!0,e&&(!1===e.readable&&(this.readable=!1),!1===e.writable&&(this.writable=!1),!1===e.allowHalfOpen&&(this.allowHalfOpen=!1,this.once("end",a)))}function a(){this._writableState.ended||process.nextTick(c,this)}function c(e){e.end()}return Object.defineProperty(s.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(s.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(s.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(s.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._readableState&&void 0!==this._writableState&&this._readableState.destroyed&&this._writableState.destroyed},set:function(e){void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed=e,this._writableState.destroyed=e)}}),op}function gp(){if(cp)return ap;function e(e){var t=this;this.next=null,this.entry=null,this.finish=function(){!function(e,t){var n=e.entry;for(e.entry=null;n;){var r=n.callback;t.pendingcb--,r(undefined),n=n.next}t.corkedRequestsFree.next=e}(t,e)}}var t;cp=1,ap=_,_.WritableState=S;var n,r={deprecate:kf?xf:(kf=1,xf=i.deprecate)},o=Mf(),s=P.Buffer,a=(void 0!==sd?sd:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{}).Uint8Array||function(){},c=Pf(),l=Uf().getHighWaterMark,u=Ff().codes,d=u.ERR_INVALID_ARG_TYPE,h=u.ERR_METHOD_NOT_IMPLEMENTED,f=u.ERR_MULTIPLE_CALLBACK,p=u.ERR_STREAM_CANNOT_PIPE,g=u.ERR_STREAM_DESTROYED,m=u.ERR_STREAM_NULL_VALUES,y=u.ERR_STREAM_WRITE_AFTER_END,v=u.ERR_UNKNOWN_ENCODING,b=c.errorOrDestroy;function w(){}function S(n,r,i){t=t||pp(),n=n||{},"boolean"!=typeof i&&(i=r instanceof t),this.objectMode=!!n.objectMode,i&&(this.objectMode=this.objectMode||!!n.writableObjectMode),this.highWaterMark=l(this,n,"writableHighWaterMark",i),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var o=!1===n.decodeStrings;this.decodeStrings=!o,this.defaultEncoding=n.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){!function(e,t){var n=e._writableState,r=n.sync,i=n.writecb;if("function"!=typeof i)throw new f;if(function(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}(n),t)!function(e,t,n,r,i){--t.pendingcb,n?(process.nextTick(i,r),process.nextTick($,e,t),e._writableState.errorEmitted=!0,b(e,r)):(i(r),e._writableState.errorEmitted=!0,b(e,r),$(e,t))}(e,n,r,t,i);else{var o=E(n)||e.destroyed;o||n.corked||n.bufferProcessing||!n.bufferedRequest||k(e,n),r?process.nextTick(x,e,n,o,i):x(e,n,o,i)}}(r,e)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!1!==n.emitClose,this.autoDestroy=!!n.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new e(this)}function _(e){var r=this instanceof(t=t||pp());if(!r&&!n.call(_,this))return new _(e);this._writableState=new S(e,this,r),this.writable=!0,e&&("function"==typeof e.write&&(this._write=e.write),"function"==typeof e.writev&&(this._writev=e.writev),"function"==typeof e.destroy&&(this._destroy=e.destroy),"function"==typeof e.final&&(this._final=e.final)),o.call(this)}function I(e,t,n,r,i,o,s){t.writelen=r,t.writecb=s,t.writing=!0,t.sync=!0,t.destroyed?t.onwrite(new g("write")):n?e._writev(i,t.onwrite):e._write(i,o,t.onwrite),t.sync=!1}function x(e,t,n,r){n||function(e,t){0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}(e,t),t.pendingcb--,r(),$(e,t)}function k(t,n){n.bufferProcessing=!0;var r=n.bufferedRequest;if(t._writev&&r&&r.next){var i=n.bufferedRequestCount,o=new Array(i),s=n.corkedRequestsFree;s.entry=r;for(var a=0,c=!0;r;)o[a]=r,r.isBuf||(c=!1),r=r.next,a+=1;o.allBuffers=c,I(t,n,!0,n.length,o,"",s.finish),n.pendingcb++,n.lastBufferedRequest=null,s.next?(n.corkedRequestsFree=s.next,s.next=null):n.corkedRequestsFree=new e(n),n.bufferedRequestCount=0}else{for(;r;){var l=r.chunk,u=r.encoding,d=r.callback;if(I(t,n,!1,n.objectMode?1:l.length,l,u,d),r=r.next,n.bufferedRequestCount--,n.writing)break}null===r&&(n.lastBufferedRequest=null)}n.bufferedRequest=r,n.bufferProcessing=!1}function E(e){return e.ending&&0===e.length&&null===e.bufferedRequest&&!e.finished&&!e.writing}function C(e,t){e._final((function(n){t.pendingcb--,n&&b(e,n),t.prefinished=!0,e.emit("prefinish"),$(e,t)}))}function $(e,t){var n=E(t);if(n&&(function(e,t){t.prefinished||t.finalCalled||("function"!=typeof e._final||t.destroyed?(t.prefinished=!0,e.emit("prefinish")):(t.pendingcb++,t.finalCalled=!0,process.nextTick(C,e,t)))}(e,t),0===t.pendingcb&&(t.finished=!0,e.emit("finish"),t.autoDestroy))){var r=e._readableState;(!r||r.autoDestroy&&r.endEmitted)&&e.destroy()}return n}return zf()(_,o),S.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(S.prototype,"buffer",{get:r.deprecate((function(){return this.getBuffer()}),"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(e){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(n=Function.prototype[Symbol.hasInstance],Object.defineProperty(_,Symbol.hasInstance,{value:function(e){return!!n.call(this,e)||this===_&&e&&e._writableState instanceof S}})):n=function(e){return e instanceof this},_.prototype.pipe=function(){b(this,new p)},_.prototype.write=function(e,t,n){var r,i=this._writableState,o=!1,c=!i.objectMode&&(r=e,s.isBuffer(r)||r instanceof a);return c&&!s.isBuffer(e)&&(e=function(e){return s.from(e)}(e)),"function"==typeof t&&(n=t,t=null),c?t="buffer":t||(t=i.defaultEncoding),"function"!=typeof n&&(n=w),i.ending?function(e,t){var n=new y;b(e,n),process.nextTick(t,n)}(this,n):(c||function(e,t,n,r){var i;return null===n?i=new m:"string"==typeof n||t.objectMode||(i=new d("chunk",["string","Buffer"],n)),!i||(b(e,i),process.nextTick(r,i),!1)}(this,i,e,n))&&(i.pendingcb++,o=function(e,t,n,r,i,o){if(!n){var a=function(e,t,n){return e.objectMode||!1===e.decodeStrings||"string"!=typeof t||(t=s.from(t,n)),t}(t,r,i);r!==a&&(n=!0,i="buffer",r=a)}var c=t.objectMode?1:r.length;t.length+=c;var l=t.length<t.highWaterMark;if(l||(t.needDrain=!0),t.writing||t.corked){var u=t.lastBufferedRequest;t.lastBufferedRequest={chunk:r,encoding:i,isBuf:n,callback:o,next:null},u?u.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1}else I(e,t,!1,c,r,i,o);return l}(this,i,c,e,t,n)),o},_.prototype.cork=function(){this._writableState.corked++},_.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,e.writing||e.corked||e.bufferProcessing||!e.bufferedRequest||k(this,e))},_.prototype.setDefaultEncoding=function(e){if("string"==typeof e&&(e=e.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new v(e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(_.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(_.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),_.prototype._write=function(e,t,n){n(new h("_write()"))},_.prototype._writev=null,_.prototype.end=function(e,t,n){var r=this._writableState;return"function"==typeof e?(n=e,e=null,t=null):"function"==typeof t&&(n=t,t=null),null!=e&&this.write(e,t),r.corked&&(r.corked=1,this.uncork()),r.ending||function(e,t,n){t.ending=!0,$(e,t),n&&(t.finished?process.nextTick(n):e.once("finish",n)),t.ended=!0,e.writable=!1}(this,r,n),this},Object.defineProperty(_.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(_.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),_.prototype.destroy=c.destroy,_.prototype._undestroy=c.undestroy,_.prototype._destroy=function(e,t){t(e)},ap}const mp=i,yp=gp(),{LEVEL:vp}=rh,bp=Af.exports=function(e={}){yp.call(this,{objectMode:!0,highWaterMark:e.highWaterMark}),this.format=e.format,this.level=e.level,this.handleExceptions=e.handleExceptions,this.handleRejections=e.handleRejections,this.silent=e.silent,e.log&&(this.log=e.log),e.logv&&(this.logv=e.logv),e.close&&(this.close=e.close),this.once("pipe",(e=>{this.levels=e.levels,this.parent=e})),this.once("unpipe",(e=>{e===this.parent&&(this.parent=null,this.close&&this.close())}))};mp.inherits(bp,yp),bp.prototype._write=function(e,t,n){if(this.silent||!0===e.exception&&!this.handleExceptions)return n(null);const r=this.level||this.parent&&this.parent.level;if(!r||this.levels[r]>=this.levels[e[vp]]){if(e&&!this.format)return this.log(e,n);let t,r;try{r=this.format.transform(Object.assign({},e),this.format.options)}catch(e){t=e}if(t||!r){if(n(),t)throw t;return}return this.log(r,n)}return this._writableState.sync=!1,n(null)},bp.prototype._writev=function(e,t){if(this.logv){const n=e.filter(this._accept,this);return n.length?this.logv(n,t):t(null)}for(let n=0;n<e.length;n++){if(!this._accept(e[n]))continue;if(e[n].chunk&&!this.format){this.log(e[n].chunk,e[n].callback);continue}let r,i;try{i=this.format.transform(Object.assign({},e[n].chunk),this.format.options)}catch(e){r=e}if(r||!i){if(e[n].callback(),r)throw t(null),r}else this.log(i,e[n].callback)}return t(null)},bp.prototype._accept=function(e){const t=e.chunk;if(this.silent)return!1;const n=this.level||this.parent&&this.parent.level;return!(!0!==t.exception&&n&&!(this.levels[n]>=this.levels[t[vp]])||!this.handleExceptions&&!0===t.exception)},bp.prototype._nop=function(){};var wp=Af.exports,Sp={exports:{}};const _p=i,{LEVEL:Ip}=rh,xp=wp,kp=Sp.exports=function(e={}){if(xp.call(this,e),!e.transport||"function"!=typeof e.transport.log)throw new Error("Invalid transport, must be an object with a log method.");this.transport=e.transport,this.level=this.level||e.transport.level,this.handleExceptions=this.handleExceptions||e.transport.handleExceptions,this._deprecated(),this.transport.__winstonError||(this.transport.__winstonError=function(e){this.emit("error",e,this.transport)}.bind(this),this.transport.on("error",this.transport.__winstonError))};_p.inherits(kp,xp),kp.prototype._write=function(e,t,n){if(this.silent||!0===e.exception&&!this.handleExceptions)return n(null);(!this.level||this.levels[this.level]>=this.levels[e[Ip]])&&this.transport.log(e[Ip],e.message,e,this._nop),n(null)},kp.prototype._writev=function(e,t){for(let t=0;t<e.length;t++)this._accept(e[t])&&(this.transport.log(e[t].chunk[Ip],e[t].chunk.message,e[t].chunk,this._nop),e[t].callback());return t(null)},kp.prototype._deprecated=function(){console.error([`${this.transport.name} is a legacy winston transport. Consider upgrading: `,"- Upgrade docs: https://github.com/winstonjs/winston/blob/master/UPGRADE-3.0.md"].join("\n"))},kp.prototype.close=function(){this.transport.close&&this.transport.close(),this.transport.__winstonError&&(this.transport.removeListener("error",this.transport.__winstonError),this.transport.__winstonError=null)};var Ep=Sp.exports;Tf.exports=wp,Tf.exports.LegacyTransportStream=Ep;var Cp,$p,Op=Tf.exports,Np={exports:{}},Tp={exports:{}},Ap={exports:{}};!function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return e&&"number"==typeof e.length&&e.length>=0&&e.length%1==0},e.exports=t.default}(Ap,Ap.exports);var Mp=Ap.exports,Pp={},Dp={exports:{}},jp={exports:{}};!function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return function(...t){var n=t.pop();return e.call(this,t,n)}},e.exports=t.default}(jp,jp.exports);var Rp=jp.exports,Lp={};Object.defineProperty(Lp,"__esModule",{value:!0}),Lp.fallback=Yp,Lp.wrap=Hp;var Fp,Up,Bp,Wp=Lp.hasQueueMicrotask="function"==typeof queueMicrotask&&queueMicrotask,Gp=Lp.hasSetImmediate="function"==typeof setImmediate&&setImmediate,Vp=Lp.hasNextTick="object"==typeof process&&"function"==typeof process.nextTick;function Yp(e){setTimeout(e,0)}function Hp(e){return(t,...n)=>e((()=>t(...n)))}function zp(){if(Bp)return Pp;Bp=1,Object.defineProperty(Pp,"__esModule",{value:!0}),Pp.isAsyncIterable=Pp.isAsyncGenerator=Pp.isAsync=void 0;var e,t=(Up||(Up=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return(0,i.isAsync)(e)?function(...t){const n=t.pop();return s(e.apply(this,t),n)}:(0,n.default)((function(t,n){var r;try{r=e.apply(this,t)}catch(e){return n(e)}if(r&&"function"==typeof r.then)return s(r,n);n(null,r)}))};var n=o(Rp),r=o(Lp),i=zp();function o(e){return e&&e.__esModule?e:{default:e}}function s(e,t){return e.then((e=>{a(t,null,e)}),(e=>{a(t,e&&(e instanceof Error||e.message)?e:new Error(e))}))}function a(e,t,n){try{e(t,n)}catch(e){(0,r.default)((e=>{throw e}),e)}}e.exports=t.default}(Dp,Dp.exports)),Dp.exports),n=(e=t)&&e.__esModule?e:{default:e};function r(e){return"AsyncFunction"===e[Symbol.toStringTag]}return Pp.default=function(e){if("function"!=typeof e)throw new Error("expected a function");return r(e)?(0,n.default)(e):e},Pp.isAsync=r,Pp.isAsyncGenerator=function(e){return"AsyncGenerator"===e[Symbol.toStringTag]},Pp.isAsyncIterable=function(e){return"function"==typeof e[Symbol.asyncIterator]},Pp}Fp=Wp?queueMicrotask:Gp?setImmediate:Vp?process.nextTick:Yp,Lp.default=Hp(Fp);var qp={exports:{}};!function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t){if(t||(t=e.length),!t)throw new Error("arity is undefined");return function(...n){return"function"==typeof n[t-1]?e.apply(this,n):new Promise(((r,i)=>{n[t-1]=(e,...t)=>{if(e)return i(e);r(t.length>1?t:t[0])},e.apply(this,n)}))}},e.exports=t.default}(qp,qp.exports);var Kp,Jp=qp.exports,Zp={exports:{}},Xp={exports:{}},Qp={exports:{}},eg={exports:{}};!function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){function t(...t){if(null!==e){var n=e;e=null,n.apply(this,t)}}return Object.assign(t,e),t},e.exports=t.default}(eg,eg.exports);var tg=eg.exports,ng={exports:{}},rg={exports:{}};!function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return e[Symbol.iterator]&&e[Symbol.iterator]()},e.exports=t.default}(rg,rg.exports);var ig=rg.exports;!function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){if((0,n.default)(e))return function(e){var t=-1,n=e.length;return function(){return++t<n?{value:e[t],key:t}:null}}(e);var t,i,o,s,a=(0,r.default)(e);return a?function(e){var t=-1;return function(){var n=e.next();return n.done?null:(t++,{value:n.value,key:t})}}(a):(i=(t=e)?Object.keys(t):[],o=-1,s=i.length,function e(){var n=i[++o];return"__proto__"===n?e():o<s?{value:t[n],key:n}:null})};var n=i(Mp),r=i(ig);function i(e){return e&&e.__esModule?e:{default:e}}e.exports=t.default}(ng,ng.exports);var og=ng.exports,sg={exports:{}};!function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return function(...t){if(null===e)throw new Error("Callback was already called.");var n=e;e=null,n.apply(this,t)}},e.exports=t.default}(sg,sg.exports);var ag=sg.exports,cg={exports:{}},lg={exports:{}};!function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default={},e.exports=t.default}(lg,lg.exports);var ug=lg.exports;!function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t,n,i){let o=!1,s=!1,a=!1,c=0,l=0;function u(){c>=t||a||o||(a=!0,e.next().then((({value:e,done:t})=>{if(!s&&!o){if(a=!1,t)return o=!0,void(c<=0&&i(null));c++,n(e,l,d),l++,u()}})).catch(h))}function d(e,t){if(c-=1,!s)return e?h(e):!1===e?(o=!0,void(s=!0)):t===r.default||o&&c<=0?(o=!0,i(null)):void u()}function h(e){s||(a=!1,o=!0,i(e))}u()};var n,r=(n=ug)&&n.__esModule?n:{default:n};e.exports=t.default}(cg,cg.exports);var dg=cg.exports;!function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var n=c(tg),r=c(og),i=c(ag),o=zp(),s=c(dg),a=c(ug);function c(e){return e&&e.__esModule?e:{default:e}}t.default=e=>(t,c,l)=>{if(l=(0,n.default)(l),e<=0)throw new RangeError("concurrency limit cannot be less than 1");if(!t)return l(null);if((0,o.isAsyncGenerator)(t))return(0,s.default)(t,e,c,l);if((0,o.isAsyncIterable)(t))return(0,s.default)(t[Symbol.asyncIterator](),e,c,l);var u=(0,r.default)(t),d=!1,h=!1,f=0,p=!1;function g(e,t){if(!h)if(f-=1,e)d=!0,l(e);else if(!1===e)d=!0,h=!0;else{if(t===a.default||d&&f<=0)return d=!0,l(null);p||m()}}function m(){for(p=!0;f<e&&!d;){var t=u();if(null===t)return d=!0,void(f<=0&&l(null));f+=1,c(t.value,t.key,(0,i.default)(g))}p=!1}m()},e.exports=t.default}(Qp,Qp.exports);var hg=Qp.exports;!function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var n=o(hg),r=o(zp()),i=o(Jp);function o(e){return e&&e.__esModule?e:{default:e}}t.default=(0,i.default)((function(e,t,i,o){return(0,n.default)(t)(e,(0,r.default)(i),o)}),4),e.exports=t.default}(Xp,Xp.exports);var fg,pg,gg=Xp.exports;var mg,yg,vg,bg,wg,Sg,_g={exports:{}};function Ig(){if(yg)return mg;yg=1,mg=a;var e=Ff().codes,t=e.ERR_METHOD_NOT_IMPLEMENTED,n=e.ERR_MULTIPLE_CALLBACK,r=e.ERR_TRANSFORM_ALREADY_TRANSFORMING,i=e.ERR_TRANSFORM_WITH_LENGTH_0,o=pp();function s(e,t){var r=this._transformState;r.transforming=!1;var i=r.writecb;if(null===i)return this.emit("error",new n);r.writechunk=null,r.writecb=null,null!=t&&this.push(t),i(e);var o=this._readableState;o.reading=!1,(o.needReadable||o.length<o.highWaterMark)&&this._read(o.highWaterMark)}function a(e){if(!(this instanceof a))return new a(e);o.call(this,e),this._transformState={afterTransform:s.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,e&&("function"==typeof e.transform&&(this._transform=e.transform),"function"==typeof e.flush&&(this._flush=e.flush)),this.on("prefinish",c)}function c(){var e=this;"function"!=typeof this._flush||this._readableState.destroyed?l(this,null,null):this._flush((function(t,n){l(e,t,n)}))}function l(e,t,n){if(t)return e.emit("error",t);if(null!=n&&e.push(n),e._writableState.length)throw new i;if(e._transformState.transforming)throw new r;return e.push(null)}return zf()(a,o),a.prototype.push=function(e,t){return this._transformState.needTransform=!1,o.prototype.push.call(this,e,t)},a.prototype._transform=function(e,n,r){r(new t("_transform()"))},a.prototype._write=function(e,t,n){var r=this._transformState;if(r.writecb=n,r.writechunk=e,r.writeencoding=t,!r.transforming){var i=this._readableState;(r.needTransform||i.needReadable||i.length<i.highWaterMark)&&this._read(i.highWaterMark)}},a.prototype._read=function(){var e=this._transformState;null===e.writechunk||e.transforming?e.needTransform=!0:(e.transforming=!0,this._transform(e.writechunk,e.writeencoding,e.afterTransform))},a.prototype._destroy=function(e,t){o.prototype._destroy.call(this,e,(function(e){t(e)}))},mg}!function(e,t){var n=M;"disable"===process.env.READABLE_STREAM&&n?(e.exports=n.Readable,Object.assign(e.exports,n),e.exports.Stream=n):((t=e.exports=fp()).Stream=n||t,t.Readable=t,t.Writable=gp(),t.Duplex=pp(),t.Transform=Ig(),t.PassThrough=function(){if(bg)return vg;bg=1,vg=t;var e=Ig();function t(n){if(!(this instanceof t))return new t(n);e.call(this,n)}return zf()(t,e),t.prototype._transform=function(e,t,n){n(null,e)},vg}(),t.finished=hp(),t.pipeline=function(){if(Sg)return wg;var e;Sg=1;var t=Ff().codes,n=t.ERR_MISSING_ARGS,r=t.ERR_STREAM_DESTROYED;function i(e){if(e)throw e}function o(e){e()}function s(e,t){return e.pipe(t)}return wg=function(){for(var t=arguments.length,a=new Array(t),c=0;c<t;c++)a[c]=arguments[c];var l,u=function(e){return e.length?"function"!=typeof e[e.length-1]?i:e.pop():i}(a);if(Array.isArray(a[0])&&(a=a[0]),a.length<2)throw new n("streams");var d=a.map((function(t,n){var i=n<a.length-1;return function(t,n,i,o){o=function(e){var t=!1;return function(){t||(t=!0,e.apply(void 0,arguments))}}(o);var s=!1;t.on("close",(function(){s=!0})),void 0===e&&(e=hp()),e(t,{readable:n,writable:i},(function(e){if(e)return o(e);s=!0,o()}));var a=!1;return function(e){if(!s&&!a)return a=!0,function(e){return e.setHeader&&"function"==typeof e.abort}(t)?t.abort():"function"==typeof t.destroy?t.destroy():void o(e||new r("pipe"))}}(t,i,n>0,(function(e){l||(l=e),e&&d.forEach(o),i||(d.forEach(o),u(l))}))}));return a.reduce(s)},wg}())}(_g,_g.exports);var xg,kg,Eg,Cg,$g=_g.exports,Og={exports:{}};function Ng(){if(kg)return xg;kg=1;var e=[],t=[],n=function(){};function r(t){return!~e.indexOf(t)&&(e.push(t),!0)}function i(e){n=e}function o(t){for(var n=[],r=0;r<e.length;r++)if(e[r].async)n.push(e[r]);else if(e[r](t))return!0;return!!n.length&&new Promise((function(e){Promise.all(n.map((function(e){return e(t)}))).then((function(t){e(t.some(Boolean))}))}))}function s(e){return!~t.indexOf(e)&&(t.push(e),!0)}function a(){n.apply(n,arguments)}function c(e){for(var n=0;n<t.length;n++)e=t[n].apply(t[n],arguments);return e}function l(e,t){var n=Object.prototype.hasOwnProperty;for(var r in t)n.call(t,r)&&(e[r]=t[r]);return e}function u(e){return e.enabled=!1,e.modify=s,e.set=i,e.use=r,l((function(){return!1}),e)}function d(e){return e.enabled=!0,e.modify=s,e.set=i,e.use=r,l((function(){var t=Array.prototype.slice.call(arguments,0);return a.call(a,e,c(t,e)),!0}),e)}return xg=function(e){return e.introduce=l,e.enabled=o,e.process=c,e.modify=s,e.write=a,e.nope=u,e.yep=d,e.set=i,e.use=r,e}}var Tg,Ag,Mg,Pg,Dg,jg,Rg={exports:{}},Lg={exports:{}};function Fg(){if(jg)return Rg.exports;jg=1;var e=Ag?Tg:(Ag=1,Tg={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]}),t=function(){if(Dg)return Lg.exports;Dg=1;var e=Pg?Mg:(Pg=1,Mg=function(e){return!(!e||"string"==typeof e)&&(e instanceof Array||Array.isArray(e)||e.length>=0&&(e.splice instanceof Function||Object.getOwnPropertyDescriptor(e,e.length-1)&&"String"!==e.constructor.name))}),t=Array.prototype.concat,n=Array.prototype.slice,r=Lg.exports=function(r){for(var i=[],o=0,s=r.length;o<s;o++){var a=r[o];e(a)?i=t.call(i,n.call(a)):i.push(a)}return i};return r.wrap=function(e){return function(){return e(r(arguments))}},Lg.exports}(),n=Object.hasOwnProperty,r=Object.create(null);for(var i in e)n.call(e,i)&&(r[e[i]]=i);var o=Rg.exports={to:{},get:{}};function s(e,t,n){return Math.min(Math.max(t,e),n)}function a(e){var t=Math.round(e).toString(16).toUpperCase();return t.length<2?"0"+t:t}return o.get=function(e){var t,n;switch(e.substring(0,3).toLowerCase()){case"hsl":t=o.get.hsl(e),n="hsl";break;case"hwb":t=o.get.hwb(e),n="hwb";break;default:t=o.get.rgb(e),n="rgb"}return t?{model:n,value:t}:null},o.get.rgb=function(t){if(!t)return null;var r,i,o,a=[0,0,0,1];if(r=t.match(/^#([a-f0-9]{6})([a-f0-9]{2})?$/i)){for(o=r[2],r=r[1],i=0;i<3;i++){var c=2*i;a[i]=parseInt(r.slice(c,c+2),16)}o&&(a[3]=parseInt(o,16)/255)}else if(r=t.match(/^#([a-f0-9]{3,4})$/i)){for(o=(r=r[1])[3],i=0;i<3;i++)a[i]=parseInt(r[i]+r[i],16);o&&(a[3]=parseInt(o+o,16)/255)}else if(r=t.match(/^rgba?\(\s*([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)\s*(?:[,|\/]\s*([+-]?[\d\.]+)(%?)\s*)?\)$/)){for(i=0;i<3;i++)a[i]=parseInt(r[i+1],0);r[4]&&(r[5]?a[3]=.01*parseFloat(r[4]):a[3]=parseFloat(r[4]))}else{if(!(r=t.match(/^rgba?\(\s*([+-]?[\d\.]+)\%\s*,?\s*([+-]?[\d\.]+)\%\s*,?\s*([+-]?[\d\.]+)\%\s*(?:[,|\/]\s*([+-]?[\d\.]+)(%?)\s*)?\)$/)))return(r=t.match(/^(\w+)$/))?"transparent"===r[1]?[0,0,0,0]:n.call(e,r[1])?((a=e[r[1]])[3]=1,a):null:null;for(i=0;i<3;i++)a[i]=Math.round(2.55*parseFloat(r[i+1]));r[4]&&(r[5]?a[3]=.01*parseFloat(r[4]):a[3]=parseFloat(r[4]))}for(i=0;i<3;i++)a[i]=s(a[i],0,255);return a[3]=s(a[3],0,1),a},o.get.hsl=function(e){if(!e)return null;var t=e.match(/^hsla?\(\s*([+-]?(?:\d{0,3}\.)?\d+)(?:deg)?\s*,?\s*([+-]?[\d\.]+)%\s*,?\s*([+-]?[\d\.]+)%\s*(?:[,|\/]\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/);if(t){var n=parseFloat(t[4]);return[(parseFloat(t[1])%360+360)%360,s(parseFloat(t[2]),0,100),s(parseFloat(t[3]),0,100),s(isNaN(n)?1:n,0,1)]}return null},o.get.hwb=function(e){if(!e)return null;var t=e.match(/^hwb\(\s*([+-]?\d{0,3}(?:\.\d+)?)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/);if(t){var n=parseFloat(t[4]);return[(parseFloat(t[1])%360+360)%360,s(parseFloat(t[2]),0,100),s(parseFloat(t[3]),0,100),s(isNaN(n)?1:n,0,1)]}return null},o.to.hex=function(){var e=t(arguments);return"#"+a(e[0])+a(e[1])+a(e[2])+(e[3]<1?a(Math.round(255*e[3])):"")},o.to.rgb=function(){var e=t(arguments);return e.length<4||1===e[3]?"rgb("+Math.round(e[0])+", "+Math.round(e[1])+", "+Math.round(e[2])+")":"rgba("+Math.round(e[0])+", "+Math.round(e[1])+", "+Math.round(e[2])+", "+e[3]+")"},o.to.rgb.percent=function(){var e=t(arguments),n=Math.round(e[0]/255*100),r=Math.round(e[1]/255*100),i=Math.round(e[2]/255*100);return e.length<4||1===e[3]?"rgb("+n+"%, "+r+"%, "+i+"%)":"rgba("+n+"%, "+r+"%, "+i+"%, "+e[3]+")"},o.to.hsl=function(){var e=t(arguments);return e.length<4||1===e[3]?"hsl("+e[0]+", "+e[1]+"%, "+e[2]+"%)":"hsla("+e[0]+", "+e[1]+"%, "+e[2]+"%, "+e[3]+")"},o.to.hwb=function(){var e=t(arguments),n="";return e.length>=4&&1!==e[3]&&(n=", "+e[3]),"hwb("+e[0]+", "+e[1]+"%, "+e[2]+"%"+n+")"},o.to.keyword=function(e){return r[e.slice(0,3)]},Rg.exports}var Ug,Bg,Wg,Gg,Vg,Yg,Hg,zg,qg,Kg,Jg,Zg,Xg,Qg,em,tm,nm,rm,im,om,sm,am,cm,lm,um,dm,hm,fm={exports:{}};function pm(){if(Wg)return fm.exports;Wg=1;var e=Bg?Ug:(Bg=1,Ug={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]}),t={};for(var n in e)e.hasOwnProperty(n)&&(t[e[n]]=n);var r=fm.exports={rgb:{channels:3,labels:"rgb"},hsl:{channels:3,labels:"hsl"},hsv:{channels:3,labels:"hsv"},hwb:{channels:3,labels:"hwb"},cmyk:{channels:4,labels:"cmyk"},xyz:{channels:3,labels:"xyz"},lab:{channels:3,labels:"lab"},lch:{channels:3,labels:"lch"},hex:{channels:1,labels:["hex"]},keyword:{channels:1,labels:["keyword"]},ansi16:{channels:1,labels:["ansi16"]},ansi256:{channels:1,labels:["ansi256"]},hcg:{channels:3,labels:["h","c","g"]},apple:{channels:3,labels:["r16","g16","b16"]},gray:{channels:1,labels:["gray"]}};for(var i in r)if(r.hasOwnProperty(i)){if(!("channels"in r[i]))throw new Error("missing channels property: "+i);if(!("labels"in r[i]))throw new Error("missing channel labels property: "+i);if(r[i].labels.length!==r[i].channels)throw new Error("channel and label counts mismatch: "+i);var o=r[i].channels,s=r[i].labels;delete r[i].channels,delete r[i].labels,Object.defineProperty(r[i],"channels",{value:o}),Object.defineProperty(r[i],"labels",{value:s})}return r.rgb.hsl=function(e){var t,n,r=e[0]/255,i=e[1]/255,o=e[2]/255,s=Math.min(r,i,o),a=Math.max(r,i,o),c=a-s;return a===s?t=0:r===a?t=(i-o)/c:i===a?t=2+(o-r)/c:o===a&&(t=4+(r-i)/c),(t=Math.min(60*t,360))<0&&(t+=360),n=(s+a)/2,[t,100*(a===s?0:n<=.5?c/(a+s):c/(2-a-s)),100*n]},r.rgb.hsv=function(e){var t,n,r,i,o,s=e[0]/255,a=e[1]/255,c=e[2]/255,l=Math.max(s,a,c),u=l-Math.min(s,a,c),d=function(e){return(l-e)/6/u+.5};return 0===u?i=o=0:(o=u/l,t=d(s),n=d(a),r=d(c),s===l?i=r-n:a===l?i=1/3+t-r:c===l&&(i=2/3+n-t),i<0?i+=1:i>1&&(i-=1)),[360*i,100*o,100*l]},r.rgb.hwb=function(e){var t=e[0],n=e[1],i=e[2];return[r.rgb.hsl(e)[0],1/255*Math.min(t,Math.min(n,i))*100,100*(i=1-1/255*Math.max(t,Math.max(n,i)))]},r.rgb.cmyk=function(e){var t,n=e[0]/255,r=e[1]/255,i=e[2]/255;return[100*((1-n-(t=Math.min(1-n,1-r,1-i)))/(1-t)||0),100*((1-r-t)/(1-t)||0),100*((1-i-t)/(1-t)||0),100*t]},r.rgb.keyword=function(n){var r=t[n];if(r)return r;var i,o,s,a=1/0;for(var c in e)if(e.hasOwnProperty(c)){var l=(o=n,s=e[c],Math.pow(o[0]-s[0],2)+Math.pow(o[1]-s[1],2)+Math.pow(o[2]-s[2],2));l<a&&(a=l,i=c)}return i},r.keyword.rgb=function(t){return e[t]},r.rgb.xyz=function(e){var t=e[0]/255,n=e[1]/255,r=e[2]/255;return[100*(.4124*(t=t>.04045?Math.pow((t+.055)/1.055,2.4):t/12.92)+.3576*(n=n>.04045?Math.pow((n+.055)/1.055,2.4):n/12.92)+.1805*(r=r>.04045?Math.pow((r+.055)/1.055,2.4):r/12.92)),100*(.2126*t+.7152*n+.0722*r),100*(.0193*t+.1192*n+.9505*r)]},r.rgb.lab=function(e){var t=r.rgb.xyz(e),n=t[0],i=t[1],o=t[2];return i/=100,o/=108.883,n=(n/=95.047)>.008856?Math.pow(n,1/3):7.787*n+16/116,[116*(i=i>.008856?Math.pow(i,1/3):7.787*i+16/116)-16,500*(n-i),200*(i-(o=o>.008856?Math.pow(o,1/3):7.787*o+16/116))]},r.hsl.rgb=function(e){var t,n,r,i,o,s=e[0]/360,a=e[1]/100,c=e[2]/100;if(0===a)return[o=255*c,o,o];t=2*c-(n=c<.5?c*(1+a):c+a-c*a),i=[0,0,0];for(var l=0;l<3;l++)(r=s+1/3*-(l-1))<0&&r++,r>1&&r--,o=6*r<1?t+6*(n-t)*r:2*r<1?n:3*r<2?t+(n-t)*(2/3-r)*6:t,i[l]=255*o;return i},r.hsl.hsv=function(e){var t=e[0],n=e[1]/100,r=e[2]/100,i=n,o=Math.max(r,.01);return n*=(r*=2)<=1?r:2-r,i*=o<=1?o:2-o,[t,100*(0===r?2*i/(o+i):2*n/(r+n)),(r+n)/2*100]},r.hsv.rgb=function(e){var t=e[0]/60,n=e[1]/100,r=e[2]/100,i=Math.floor(t)%6,o=t-Math.floor(t),s=255*r*(1-n),a=255*r*(1-n*o),c=255*r*(1-n*(1-o));switch(r*=255,i){case 0:return[r,c,s];case 1:return[a,r,s];case 2:return[s,r,c];case 3:return[s,a,r];case 4:return[c,s,r];case 5:return[r,s,a]}},r.hsv.hsl=function(e){var t,n,r,i=e[0],o=e[1]/100,s=e[2]/100,a=Math.max(s,.01);return r=(2-o)*s,n=o*a,[i,100*(n=(n/=(t=(2-o)*a)<=1?t:2-t)||0),100*(r/=2)]},r.hwb.rgb=function(e){var t,n,r,i,o,s,a,c=e[0]/360,l=e[1]/100,u=e[2]/100,d=l+u;switch(d>1&&(l/=d,u/=d),r=6*c-(t=Math.floor(6*c)),1&t&&(r=1-r),i=l+r*((n=1-u)-l),t){default:case 6:case 0:o=n,s=i,a=l;break;case 1:o=i,s=n,a=l;break;case 2:o=l,s=n,a=i;break;case 3:o=l,s=i,a=n;break;case 4:o=i,s=l,a=n;break;case 5:o=n,s=l,a=i}return[255*o,255*s,255*a]},r.cmyk.rgb=function(e){var t=e[0]/100,n=e[1]/100,r=e[2]/100,i=e[3]/100;return[255*(1-Math.min(1,t*(1-i)+i)),255*(1-Math.min(1,n*(1-i)+i)),255*(1-Math.min(1,r*(1-i)+i))]},r.xyz.rgb=function(e){var t,n,r,i=e[0]/100,o=e[1]/100,s=e[2]/100;return n=-.9689*i+1.8758*o+.0415*s,r=.0557*i+-.204*o+1.057*s,t=(t=3.2406*i+-1.5372*o+-.4986*s)>.0031308?1.055*Math.pow(t,1/2.4)-.055:12.92*t,n=n>.0031308?1.055*Math.pow(n,1/2.4)-.055:12.92*n,r=r>.0031308?1.055*Math.pow(r,1/2.4)-.055:12.92*r,[255*(t=Math.min(Math.max(0,t),1)),255*(n=Math.min(Math.max(0,n),1)),255*(r=Math.min(Math.max(0,r),1))]},r.xyz.lab=function(e){var t=e[0],n=e[1],r=e[2];return n/=100,r/=108.883,t=(t/=95.047)>.008856?Math.pow(t,1/3):7.787*t+16/116,[116*(n=n>.008856?Math.pow(n,1/3):7.787*n+16/116)-16,500*(t-n),200*(n-(r=r>.008856?Math.pow(r,1/3):7.787*r+16/116))]},r.lab.xyz=function(e){var t,n,r,i=e[0];t=e[1]/500+(n=(i+16)/116),r=n-e[2]/200;var o=Math.pow(n,3),s=Math.pow(t,3),a=Math.pow(r,3);return n=o>.008856?o:(n-16/116)/7.787,t=s>.008856?s:(t-16/116)/7.787,r=a>.008856?a:(r-16/116)/7.787,[t*=95.047,n*=100,r*=108.883]},r.lab.lch=function(e){var t,n=e[0],r=e[1],i=e[2];return(t=360*Math.atan2(i,r)/2/Math.PI)<0&&(t+=360),[n,Math.sqrt(r*r+i*i),t]},r.lch.lab=function(e){var t,n=e[0],r=e[1];return t=e[2]/360*2*Math.PI,[n,r*Math.cos(t),r*Math.sin(t)]},r.rgb.ansi16=function(e){var t=e[0],n=e[1],i=e[2],o=1 in arguments?arguments[1]:r.rgb.hsv(e)[2];if(0===(o=Math.round(o/50)))return 30;var s=30+(Math.round(i/255)<<2|Math.round(n/255)<<1|Math.round(t/255));return 2===o&&(s+=60),s},r.hsv.ansi16=function(e){return r.rgb.ansi16(r.hsv.rgb(e),e[2])},r.rgb.ansi256=function(e){var t=e[0],n=e[1],r=e[2];return t===n&&n===r?t<8?16:t>248?231:Math.round((t-8)/247*24)+232:16+36*Math.round(t/255*5)+6*Math.round(n/255*5)+Math.round(r/255*5)},r.ansi16.rgb=function(e){var t=e%10;if(0===t||7===t)return e>50&&(t+=3.5),[t=t/10.5*255,t,t];var n=.5*(1+~~(e>50));return[(1&t)*n*255,(t>>1&1)*n*255,(t>>2&1)*n*255]},r.ansi256.rgb=function(e){if(e>=232){var t=10*(e-232)+8;return[t,t,t]}var n;return e-=16,[Math.floor(e/36)/5*255,Math.floor((n=e%36)/6)/5*255,n%6/5*255]},r.rgb.hex=function(e){var t=(((255&Math.round(e[0]))<<16)+((255&Math.round(e[1]))<<8)+(255&Math.round(e[2]))).toString(16).toUpperCase();return"000000".substring(t.length)+t},r.hex.rgb=function(e){var t=e.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);if(!t)return[0,0,0];var n=t[0];3===t[0].length&&(n=n.split("").map((function(e){return e+e})).join(""));var r=parseInt(n,16);return[r>>16&255,r>>8&255,255&r]},r.rgb.hcg=function(e){var t,n=e[0]/255,r=e[1]/255,i=e[2]/255,o=Math.max(Math.max(n,r),i),s=Math.min(Math.min(n,r),i),a=o-s;return t=a<=0?0:o===n?(r-i)/a%6:o===r?2+(i-n)/a:4+(n-r)/a+4,t/=6,[360*(t%=1),100*a,100*(a<1?s/(1-a):0)]},r.hsl.hcg=function(e){var t,n=e[1]/100,r=e[2]/100,i=0;return(t=r<.5?2*n*r:2*n*(1-r))<1&&(i=(r-.5*t)/(1-t)),[e[0],100*t,100*i]},r.hsv.hcg=function(e){var t=e[1]/100,n=e[2]/100,r=t*n,i=0;return r<1&&(i=(n-r)/(1-r)),[e[0],100*r,100*i]},r.hcg.rgb=function(e){var t=e[0]/360,n=e[1]/100,r=e[2]/100;if(0===n)return[255*r,255*r,255*r];var i,o=[0,0,0],s=t%1*6,a=s%1,c=1-a;switch(Math.floor(s)){case 0:o[0]=1,o[1]=a,o[2]=0;break;case 1:o[0]=c,o[1]=1,o[2]=0;break;case 2:o[0]=0,o[1]=1,o[2]=a;break;case 3:o[0]=0,o[1]=c,o[2]=1;break;case 4:o[0]=a,o[1]=0,o[2]=1;break;default:o[0]=1,o[1]=0,o[2]=c}return i=(1-n)*r,[255*(n*o[0]+i),255*(n*o[1]+i),255*(n*o[2]+i)]},r.hcg.hsv=function(e){var t=e[1]/100,n=t+e[2]/100*(1-t),r=0;return n>0&&(r=t/n),[e[0],100*r,100*n]},r.hcg.hsl=function(e){var t=e[1]/100,n=e[2]/100*(1-t)+.5*t,r=0;return n>0&&n<.5?r=t/(2*n):n>=.5&&n<1&&(r=t/(2*(1-n))),[e[0],100*r,100*n]},r.hcg.hwb=function(e){var t=e[1]/100,n=t+e[2]/100*(1-t);return[e[0],100*(n-t),100*(1-n)]},r.hwb.hcg=function(e){var t=e[1]/100,n=1-e[2]/100,r=n-t,i=0;return r<1&&(i=(n-r)/(1-r)),[e[0],100*r,100*i]},r.apple.rgb=function(e){return[e[0]/65535*255,e[1]/65535*255,e[2]/65535*255]},r.rgb.apple=function(e){return[e[0]/255*65535,e[1]/255*65535,e[2]/255*65535]},r.gray.rgb=function(e){return[e[0]/100*255,e[0]/100*255,e[0]/100*255]},r.gray.hsl=r.gray.hsv=function(e){return[0,0,e[0]]},r.gray.hwb=function(e){return[0,100,e[0]]},r.gray.cmyk=function(e){return[0,0,0,e[0]]},r.gray.lab=function(e){return[e[0],0,0]},r.gray.hex=function(e){var t=255&Math.round(e[0]/100*255),n=((t<<16)+(t<<8)+t).toString(16).toUpperCase();return"000000".substring(n.length)+n},r.rgb.gray=function(e){return[(e[0]+e[1]+e[2])/3/255*100]},fm.exports}function gm(){if(Hg)return Yg;Hg=1;var e=pm(),t=function(){if(Vg)return Gg;Vg=1;var e=pm();function t(t){var n=function(){for(var t={},n=Object.keys(e),r=n.length,i=0;i<r;i++)t[n[i]]={distance:-1,parent:null};return t}(),r=[t];for(n[t].distance=0;r.length;)for(var i=r.pop(),o=Object.keys(e[i]),s=o.length,a=0;a<s;a++){var c=o[a],l=n[c];-1===l.distance&&(l.distance=n[i].distance+1,l.parent=i,r.unshift(c))}return n}function n(e,t){return function(n){return t(e(n))}}function r(t,r){for(var i=[r[t].parent,t],o=e[r[t].parent][t],s=r[t].parent;r[s].parent;)i.unshift(r[s].parent),o=n(e[r[s].parent][s],o),s=r[s].parent;return o.conversion=i,o}return Gg=function(e){for(var n=t(e),i={},o=Object.keys(n),s=o.length,a=0;a<s;a++){var c=o[a];null!==n[c].parent&&(i[c]=r(c,n))}return i}}(),n={};return Object.keys(e).forEach((function(r){n[r]={},Object.defineProperty(n[r],"channels",{value:e[r].channels}),Object.defineProperty(n[r],"labels",{value:e[r].labels});var i=t(r);Object.keys(i).forEach((function(e){var t=i[e];n[r][e]=function(e){var t=function(t){if(null==t)return t;arguments.length>1&&(t=Array.prototype.slice.call(arguments));var n=e(t);if("object"==typeof n)for(var r=n.length,i=0;i<r;i++)n[i]=Math.round(n[i]);return n};return"conversion"in e&&(t.conversion=e.conversion),t}(t),n[r][e].raw=function(e){var t=function(t){return null==t?t:(arguments.length>1&&(t=Array.prototype.slice.call(arguments)),e(t))};return"conversion"in e&&(t.conversion=e.conversion),t}(t)}))})),Yg=n}function mm(){if(Xg)return Zg;Xg=1;var e=function(){if(qg)return zg;qg=1;var e=Fg(),t=gm(),n=[].slice,r=["keyword","gray","hex"],i={};Object.keys(t).forEach((function(e){i[n.call(t[e].labels).sort().join("")]=e}));var o={};function s(a,c){if(!(this instanceof s))return new s(a,c);if(c&&c in r&&(c=null),c&&!(c in t))throw new Error("Unknown model: "+c);var u,d;if(null==a)this.model="rgb",this.color=[0,0,0],this.valpha=1;else if(a instanceof s)this.model=a.model,this.color=a.color.slice(),this.valpha=a.valpha;else if("string"==typeof a){var h=e.get(a);if(null===h)throw new Error("Unable to parse color from string: "+a);this.model=h.model,d=t[this.model].channels,this.color=h.value.slice(0,d),this.valpha="number"==typeof h.value[d]?h.value[d]:1}else if(a.length){this.model=c||"rgb",d=t[this.model].channels;var f=n.call(a,0,d);this.color=l(f,d),this.valpha="number"==typeof a[d]?a[d]:1}else if("number"==typeof a)a&=16777215,this.model="rgb",this.color=[a>>16&255,a>>8&255,255&a],this.valpha=1;else{this.valpha=1;var p=Object.keys(a);"alpha"in a&&(p.splice(p.indexOf("alpha"),1),this.valpha="number"==typeof a.alpha?a.alpha:0);var g=p.sort().join("");if(!(g in i))throw new Error("Unable to parse color from object: "+JSON.stringify(a));this.model=i[g];var m=t[this.model].labels,y=[];for(u=0;u<m.length;u++)y.push(a[m[u]]);this.color=l(y)}if(o[this.model])for(d=t[this.model].channels,u=0;u<d;u++){var v=o[this.model][u];v&&(this.color[u]=v(this.color[u]))}this.valpha=Math.max(0,Math.min(1,this.valpha)),Object.freeze&&Object.freeze(this)}function a(e,t,n){return(e=Array.isArray(e)?e:[e]).forEach((function(e){(o[e]||(o[e]=[]))[t]=n})),e=e[0],function(r){var i;return arguments.length?(n&&(r=n(r)),(i=this[e]()).color[t]=r,i):(i=this[e]().color[t],n&&(i=n(i)),i)}}function c(e){return function(t){return Math.max(0,Math.min(e,t))}}function l(e,t){for(var n=0;n<t;n++)"number"!=typeof e[n]&&(e[n]=0);return e}return s.prototype={toString:function(){return this.string()},toJSON:function(){return this[this.model]()},string:function(t){var n=this.model in e.to?this:this.rgb(),r=1===(n=n.round("number"==typeof t?t:1)).valpha?n.color:n.color.concat(this.valpha);return e.to[n.model](r)},percentString:function(t){var n=this.rgb().round("number"==typeof t?t:1),r=1===n.valpha?n.color:n.color.concat(this.valpha);return e.to.rgb.percent(r)},array:function(){return 1===this.valpha?this.color.slice():this.color.concat(this.valpha)},object:function(){for(var e={},n=t[this.model].channels,r=t[this.model].labels,i=0;i<n;i++)e[r[i]]=this.color[i];return 1!==this.valpha&&(e.alpha=this.valpha),e},unitArray:function(){var e=this.rgb().color;return e[0]/=255,e[1]/=255,e[2]/=255,1!==this.valpha&&e.push(this.valpha),e},unitObject:function(){var e=this.rgb().object();return e.r/=255,e.g/=255,e.b/=255,1!==this.valpha&&(e.alpha=this.valpha),e},round:function(e){return e=Math.max(e||0,0),new s(this.color.map(function(e){return function(t){return function(e,t){return Number(e.toFixed(t))}(t,e)}}(e)).concat(this.valpha),this.model)},alpha:function(e){return arguments.length?new s(this.color.concat(Math.max(0,Math.min(1,e))),this.model):this.valpha},red:a("rgb",0,c(255)),green:a("rgb",1,c(255)),blue:a("rgb",2,c(255)),hue:a(["hsl","hsv","hsl","hwb","hcg"],0,(function(e){return(e%360+360)%360})),saturationl:a("hsl",1,c(100)),lightness:a("hsl",2,c(100)),saturationv:a("hsv",1,c(100)),value:a("hsv",2,c(100)),chroma:a("hcg",1,c(100)),gray:a("hcg",2,c(100)),white:a("hwb",1,c(100)),wblack:a("hwb",2,c(100)),cyan:a("cmyk",0,c(100)),magenta:a("cmyk",1,c(100)),yellow:a("cmyk",2,c(100)),black:a("cmyk",3,c(100)),x:a("xyz",0,c(100)),y:a("xyz",1,c(100)),z:a("xyz",2,c(100)),l:a("lab",0,c(100)),a:a("lab",1),b:a("lab",2),keyword:function(e){return arguments.length?new s(e):t[this.model].keyword(this.color)},hex:function(t){return arguments.length?new s(t):e.to.hex(this.rgb().round().color)},rgbNumber:function(){var e=this.rgb().color;return(255&e[0])<<16|(255&e[1])<<8|255&e[2]},luminosity:function(){for(var e=this.rgb().color,t=[],n=0;n<e.length;n++){var r=e[n]/255;t[n]=r<=.03928?r/12.92:Math.pow((r+.055)/1.055,2.4)}return.2126*t[0]+.7152*t[1]+.0722*t[2]},contrast:function(e){var t=this.luminosity(),n=e.luminosity();return t>n?(t+.05)/(n+.05):(n+.05)/(t+.05)},level:function(e){var t=this.contrast(e);return t>=7.1?"AAA":t>=4.5?"AA":""},isDark:function(){var e=this.rgb().color;return(299*e[0]+587*e[1]+114*e[2])/1e3<128},isLight:function(){return!this.isDark()},negate:function(){for(var e=this.rgb(),t=0;t<3;t++)e.color[t]=255-e.color[t];return e},lighten:function(e){var t=this.hsl();return t.color[2]+=t.color[2]*e,t},darken:function(e){var t=this.hsl();return t.color[2]-=t.color[2]*e,t},saturate:function(e){var t=this.hsl();return t.color[1]+=t.color[1]*e,t},desaturate:function(e){var t=this.hsl();return t.color[1]-=t.color[1]*e,t},whiten:function(e){var t=this.hwb();return t.color[1]+=t.color[1]*e,t},blacken:function(e){var t=this.hwb();return t.color[2]+=t.color[2]*e,t},grayscale:function(){var e=this.rgb().color,t=.3*e[0]+.59*e[1]+.11*e[2];return s.rgb(t,t,t)},fade:function(e){return this.alpha(this.valpha-this.valpha*e)},opaquer:function(e){return this.alpha(this.valpha+this.valpha*e)},rotate:function(e){var t=this.hsl(),n=t.color[0];return n=(n=(n+e)%360)<0?360+n:n,t.color[0]=n,t},mix:function(e,t){if(!e||!e.rgb)throw new Error('Argument to "mix" was not a Color instance, but rather an instance of '+typeof e);var n=e.rgb(),r=this.rgb(),i=void 0===t?.5:t,o=2*i-1,a=n.alpha()-r.alpha(),c=((o*a==-1?o:(o+a)/(1+o*a))+1)/2,l=1-c;return s.rgb(c*n.red()+l*r.red(),c*n.green()+l*r.green(),c*n.blue()+l*r.blue(),n.alpha()*i+r.alpha()*(1-i))}},Object.keys(t).forEach((function(e){if(-1===r.indexOf(e)){var i=t[e].channels;s.prototype[e]=function(){if(this.model===e)return new s(this);if(arguments.length)return new s(arguments,e);var n,r="number"==typeof arguments[i]?i:this.valpha;return new s((n=t[this.model][e].raw(this.color),Array.isArray(n)?n:[n]).concat(r),e)},s[e]=function(t){return"number"==typeof t&&(t=l(n.call(arguments),i)),new s(t,e)}}})),zg=s}(),t=(Jg||(Jg=1,Kg=function(e){for(var t=0,n=0;t<e.length;n=e.charCodeAt(t++)+((n<<5)-n));var r=Math.floor(Math.abs(1e4*Math.sin(n)%1*16777216)).toString(16);return"#"+Array(6-r.length+1).join("0")+r}),Kg);return Zg=function(n,r){var i=n.split(r||":"),o=t(i[0]);if(!i.length)return o;for(var s=0,a=i.length-1;s<a;s++)o=e(o).mix(e(t(i[s+1]))).saturate(1).hex();return o},Zg}function ym(){if(cm)return am;cm=1;var e=function(){if(sm)return om;sm=1;var e=(im||(im=1,rm=function(e,t){if(!t)return!1;for(var n=t.split(/[\s,]+/),r=0;r<n.length;r++)if("-"!==(t=n[r].replace("*",".*?")).charAt(0)){if(new RegExp("^"+t+"$").test(e))return!0}else if(new RegExp("^"+t.substr(1)+"$").test(e))return!1;return!1}),rm);return om=function(t){return function(n){try{return e(n,t())}catch(e){}return!1}}}();return am=e((function(){return process.env.DEBUG||process.env.DIAGNOSTICS}))}"production"===process.env.NODE_ENV?Og.exports=function(){if(Cg)return Eg;Cg=1;var e=Ng()((function e(t,n){return(n=n||{}).namespace=t,n.prod=!0,n.dev=!1,n.force||e.force?e.yep(n):e.nope(n)}));return Eg=e}():Og.exports=function(){if(hm)return dm;hm=1;var e=Ng(),t=O.isatty(1),n=e((function e(n,r){return(r=r||{}).colors="colors"in r?r.colors:t,r.namespace=n,r.prod=!1,r.dev=!0,e.enabled(n)||r.force||e.force?e.yep(r):e.nope(r)}));return n.modify(function(){if(nm)return tm;nm=1;var e=mm(),t=function(){if(em)return Qg;function e(t,n){return n?new e(t).style(n):this instanceof e?void(this.text=t):new e(t)}return em=1,e.prototype.prefix="[",e.prototype.suffix="m",e.prototype.hex=function(e){3===(e="#"===e[0]?e.substring(1):e).length&&((e=e.split(""))[5]=e[2],e[4]=e[2],e[3]=e[1],e[2]=e[1],e[1]=e[0],e=e.join(""));var t=e.substring(0,2),n=e.substring(2,4),r=e.substring(4,6);return[parseInt(t,16),parseInt(n,16),parseInt(r,16)]},e.prototype.rgb=function(e,t,n){var r=e/255*5,i=t/255*5,o=n/255*5;return this.ansi(r,i,o)},e.prototype.ansi=function(e,t,n){return 16+36*Math.round(e)+6*Math.round(t)+Math.round(n)},e.prototype.reset=function(){return this.prefix+"39;49"+this.suffix},e.prototype.style=function(e){return this.prefix+"38;5;"+this.rgb.apply(this,this.hex(e))+this.suffix+this.text+this.reset()},Qg=e}();return tm=function(n,r){var i=r.namespace,o=!1!==r.colors?t(i+":",e(i)):i+":";return n[0]=o+" "+n[0],n}}()),n.use(ym()),n.set(um?lm:(um=1,lm=function(e,t){try{Function.prototype.apply.call(console.log,console,t)}catch(e){}})),dm=n}();var vm,bm,wm,Sm,_m,Im,xm=Og.exports;function km(){if(Sm)return wm;Sm=1;const e=$,t=I,n=(pg||(pg=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t){return(0,r.default)(o.default,e,t)};var n=(Kp||(Kp=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var n=o(Mp),r=o(zp()),i=o(Jp);function o(e){return e&&e.__esModule?e:{default:e}}t.default=(0,i.default)(((e,t,i)=>{var o=(0,n.default)(t)?[]:{};e(t,((e,t,n)=>{(0,r.default)(e)(((e,...r)=>{r.length<2&&([r]=r),o[t]=r,n(e)}))}),(e=>i(e,o)))}),3),e.exports=t.default}(Tp,Tp.exports)),Tp.exports),r=s(n),i=(fg||(fg=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var n=i(gg),r=i(Jp);function i(e){return e&&e.__esModule?e:{default:e}}t.default=(0,r.default)((function(e,t,r){return(0,n.default)(e,1,t,r)}),3),e.exports=t.default}(Zp,Zp.exports)),Zp.exports),o=s(i);function s(e){return e&&e.__esModule?e:{default:e}}e.exports=t.default}(Np,Np.exports)),Np.exports),r=j,{MESSAGE:i}=rh,{Stream:o,PassThrough:s}=$g,a=Op,c=xm("winston:file"),l=N,u=function(){if(bm)return vm;bm=1;const e=$,{StringDecoder:t}=R,{Stream:n}=$g;function r(){}return vm=(i,o)=>{const s=Buffer.alloc(65536),a=new t("utf8"),c=new n;let l="",u=0,d=0;return-1===i.start&&delete i.start,c.readable=!0,c.destroy=()=>{c.destroyed=!0,c.emit("end"),c.emit("close")},e.open(i.file,"a+","0644",((t,n)=>{if(t)return o?o(t):c.emit("error",t),void c.destroy();!function t(){if(!c.destroyed)return e.read(n,s,0,s.length,u,((e,n)=>{if(e)return o?o(e):c.emit("error",e),void c.destroy();if(!n)return l&&((null==i.start||d>i.start)&&(o?o(null,l):c.emit("line",l)),d++,l=""),setTimeout(t,1e3);let r=a.write(s.slice(0,n));o||c.emit("data",r),r=(l+r).split(/\n+/);const h=r.length-1;let f=0;for(;f<h;f++)(null==i.start||d>i.start)&&(o?o(null,r[f]):c.emit("line",r[f])),d++;return l=r[h],u+=n,t()}));e.close(n,r)}()})),o?c.destroy:c},vm}();return wm=class extends a{constructor(e={}){function n(t,...n){n.slice(1).forEach((n=>{if(e[n])throw new Error(`Cannot set ${n} and ${t} together`)}))}if(super(e),this.name=e.name||"file",this._stream=new s,this._stream.setMaxListeners(30),this._onError=this._onError.bind(this),e.filename||e.dirname)n("filename or dirname","stream"),this._basename=this.filename=e.filename?t.basename(e.filename):"winston.log",this.dirname=e.dirname||t.dirname(e.filename),this.options=e.options||{flags:"a"};else{if(!e.stream)throw new Error("Cannot log to file without filename or stream.");console.warn("options.stream will be removed in winston@4. Use winston.transports.Stream"),n("stream","filename","maxsize"),this._dest=this._stream.pipe(this._setupStream(e.stream)),this.dirname=t.dirname(this._dest.path)}this.maxsize=e.maxsize||null,this.rotationFormat=e.rotationFormat||!1,this.zippedArchive=e.zippedArchive||!1,this.maxFiles=e.maxFiles||null,this.eol="string"==typeof e.eol?e.eol:l.EOL,this.tailable=e.tailable||!1,this.lazy=e.lazy||!1,this._size=0,this._pendingSize=0,this._created=0,this._drain=!1,this._opening=!1,this._ending=!1,this._fileExist=!1,this.dirname&&this._createLogDirIfNotExist(this.dirname),this.lazy||this.open()}finishIfEnding(){this._ending&&(this._opening?this.once("open",(()=>{this._stream.once("finish",(()=>this.emit("finish"))),setImmediate((()=>this._stream.end()))})):(this._stream.once("finish",(()=>this.emit("finish"))),setImmediate((()=>this._stream.end()))))}log(e,t=()=>{}){if(this.silent)return t(),!0;if(this._drain)return void this._stream.once("drain",(()=>{this._drain=!1,this.log(e,t)}));if(this._rotate)return void this._stream.once("rotate",(()=>{this._rotate=!1,this.log(e,t)}));if(this.lazy){if(!this._fileExist)return this._opening||this.open(),void this.once("open",(()=>{this._fileExist=!0,this.log(e,t)}));if(this._needsNewFile(this._pendingSize))return void this._dest.once("close",(()=>{this._opening||this.open(),this.once("open",(()=>{this.log(e,t)}))}))}const n=`${e[i]}${this.eol}`,r=Buffer.byteLength(n);this._pendingSize+=r,this._opening&&!this.rotatedWhileOpening&&this._needsNewFile(this._size+this._pendingSize)&&(this.rotatedWhileOpening=!0);const o=this._stream.write(n,function(){this._size+=r,this._pendingSize-=r,c("logged %s %s",this._size,n),this.emit("logged",e),this._rotate||this._opening||this._needsNewFile()&&(this.lazy?this._endStream((()=>{this.emit("fileclosed")})):(this._rotate=!0,this._endStream((()=>this._rotateFile()))))}.bind(this));return o?t():(this._drain=!0,this._stream.once("drain",(()=>{this._drain=!1,t()}))),c("written",o,this._drain),this.finishIfEnding(),o}query(n,r){"function"==typeof n&&(r=n,n={}),n=function(e){return(e=e||{}).rows=e.rows||e.limit||10,e.start=e.start||0,e.until=e.until||new Date,"object"!=typeof e.until&&(e.until=new Date(e.until)),e.from=e.from||e.until-864e5,"object"!=typeof e.from&&(e.from=new Date(e.from)),e.order=e.order||"desc",e}(n);const i=t.join(this.dirname,this.filename);let o="",s=[],a=0;const c=e.createReadStream(i,{encoding:"utf8"});function l(e,t){try{const t=JSON.parse(e);(function(e){if(!e)return;if("object"!=typeof e)return;const t=new Date(e.timestamp);return!(n.from&&t<n.from||n.until&&t>n.until||n.level&&n.level!==e.level)||void 0})(t)&&function(e){n.rows&&s.length>=n.rows&&"desc"!==n.order?c.readable&&c.destroy():(n.fields&&(e=n.fields.reduce(((t,n)=>(t[n]=e[n],t)),{})),"desc"===n.order&&s.length>=n.rows&&s.shift(),s.push(e))}(t)}catch(e){t||c.emit("error",e)}}c.on("error",(e=>{if(c.readable&&c.destroy(),r)return"ENOENT"!==e.code?r(e):r(null,s)})),c.on("data",(e=>{const t=(e=(o+e).split(/\n+/)).length-1;let r=0;for(;r<t;r++)(!n.start||a>=n.start)&&l(e[r]),a++;o=e[t]})),c.on("close",(()=>{o&&l(o,!0),"desc"===n.order&&(s=s.reverse()),r&&r(null,s)}))}stream(e={}){const n=t.join(this.dirname,this.filename),r=new o,i={file:n,start:e.start};return r.destroy=u(i,((e,t)=>{if(e)return r.emit("error",e);try{r.emit("data",t),t=JSON.parse(t),r.emit("log",t)}catch(e){r.emit("error",e)}})),r}open(){this.filename&&(this._opening||(this._opening=!0,this.stat(((e,t)=>{if(e)return this.emit("error",e);c("stat done: %s { size: %s }",this.filename,t),this._size=t,this._dest=this._createStream(this._stream),this._opening=!1,this.once("open",(()=>{this._stream.emit("rotate")||(this._rotate=!1)}))}))))}stat(n){const r=this._getFile(),i=t.join(this.dirname,r);e.stat(i,((e,t)=>e&&"ENOENT"===e.code?(c("ENOENT ok",i),this.filename=r,n(null,0)):e?(c(`err ${e.code} ${i}`),n(e)):!t||this._needsNewFile(t.size)?this._incFile((()=>this.stat(n))):(this.filename=r,void n(null,t.size))))}close(e){this._stream&&this._stream.end((()=>{e&&e(),this.emit("flush"),this.emit("closed")}))}_needsNewFile(e){return e=e||this._size,this.maxsize&&e>=this.maxsize}_onError(e){this.emit("error",e)}_setupStream(e){return e.on("error",this._onError),e}_cleanupStream(e){return e.removeListener("error",this._onError),e.destroy(),e}_rotateFile(){this._incFile((()=>this.open()))}_endStream(e=()=>{}){this._dest?(this._stream.unpipe(this._dest),this._dest.end((()=>{this._cleanupStream(this._dest),e()}))):e()}_createStream(n){const r=t.join(this.dirname,this.filename);c("create stream start",r,this.options);const i=e.createWriteStream(r,this.options).on("error",(e=>c(e))).on("close",(()=>c("close",i.path,i.bytesWritten))).on("open",(()=>{c("file open ok",r),this.emit("open",r),n.pipe(i),this.rotatedWhileOpening&&(this._stream=new s,this._stream.setMaxListeners(30),this._rotateFile(),this.rotatedWhileOpening=!1,this._cleanupStream(i),n.end())}));return c("create stream ok",r),i}_incFile(e){c("_incFile",this.filename);const r=t.extname(this._basename),i=t.basename(this._basename,r),o=[];this.zippedArchive&&o.push(function(e){const n=this._created>0&&!this.tailable?this._created:"";this._compressFile(t.join(this.dirname,`${i}${n}${r}`),t.join(this.dirname,`${i}${n}${r}.gz`),e)}.bind(this)),o.push(function(e){this.tailable?this._checkMaxFilesTailable(r,i,e):(this._created+=1,this._checkMaxFilesIncrementing(r,i,e))}.bind(this)),n(o,e)}_getFile(){const e=t.extname(this._basename),n=t.basename(this._basename,e),r=this.rotationFormat?this.rotationFormat():this._created;return!this.tailable&&this._created?`${n}${r}${e}`:`${n}${e}`}_checkMaxFilesIncrementing(n,r,i){if(!this.maxFiles||this._created<this.maxFiles)return setImmediate(i);const o=this._created-this.maxFiles,s=`${r}${0!==o?o:""}${n}${this.zippedArchive?".gz":""}`,a=t.join(this.dirname,s);e.unlink(a,i)}_checkMaxFilesTailable(r,i,o){const s=[];if(!this.maxFiles)return;const a=this.zippedArchive?".gz":"";for(let n=this.maxFiles-1;n>1;n--)s.push(function(n,o){let s=`${i}${n-1}${r}${a}`;const c=t.join(this.dirname,s);e.exists(c,(l=>{if(!l)return o(null);s=`${i}${n}${r}${a}`,e.rename(c,t.join(this.dirname,s),o)}))}.bind(this,n));n(s,(()=>{e.rename(t.join(this.dirname,`${i}${r}${a}`),t.join(this.dirname,`${i}1${r}${a}`),o)}))}_compressFile(t,n,i){e.access(t,e.F_OK,(o=>{if(o)return i();var s=r.createGzip(),a=e.createReadStream(t),c=e.createWriteStream(n);c.on("finish",(()=>{e.unlink(t,i)})),a.pipe(s).pipe(c)}))}_createLogDirIfNotExist(t){e.existsSync(t)||e.mkdirSync(t,{recursive:!0})}},wm}const Em=e=>null!==e&&"object"==typeof e&&"function"==typeof e.pipe;Em.writable=e=>Em(e)&&!1!==e.writable&&"function"==typeof e._write&&"object"==typeof e._writableState,Em.readable=e=>Em(e)&&!1!==e.readable&&"function"==typeof e._read&&"object"==typeof e._readableState,Em.duplex=e=>Em.writable(e)&&Em.readable(e),Em.transform=e=>Em.duplex(e)&&"function"==typeof e._transform;var Cm,$m,Om=Em;!function(e){Object.defineProperty(e,"Console",{configurable:!0,enumerable:!0,get:()=>function(){if($p)return Cp;$p=1;const e=N,{LEVEL:t,MESSAGE:n}=rh,r=Op;return Cp=class extends r{constructor(t={}){super(t),this.name=t.name||"console",this.stderrLevels=this._stringArrayToSet(t.stderrLevels),this.consoleWarnLevels=this._stringArrayToSet(t.consoleWarnLevels),this.eol="string"==typeof t.eol?t.eol:e.EOL,this.forceConsole=t.forceConsole||!1,this._consoleLog=console.log.bind(console),this._consoleWarn=console.warn.bind(console),this._consoleError=console.error.bind(console),this.setMaxListeners(30)}log(e,r){return setImmediate((()=>this.emit("logged",e))),this.stderrLevels[e[t]]?(console._stderr&&!this.forceConsole?console._stderr.write(`${e[n]}${this.eol}`):this._consoleError(e[n]),void(r&&r())):this.consoleWarnLevels[e[t]]?(console._stderr&&!this.forceConsole?console._stderr.write(`${e[n]}${this.eol}`):this._consoleWarn(e[n]),void(r&&r())):(console._stdout&&!this.forceConsole?console._stdout.write(`${e[n]}${this.eol}`):this._consoleLog(e[n]),void(r&&r()))}_stringArrayToSet(e,t){if(!e)return{};if(t=t||"Cannot make set from type other than Array of string elements",!Array.isArray(e))throw new Error(t);return e.reduce(((e,n)=>{if("string"!=typeof n)throw new Error(t);return e[n]=!0,e}),{})}}}()}),Object.defineProperty(e,"File",{configurable:!0,enumerable:!0,get:()=>km()}),Object.defineProperty(e,"Http",{configurable:!0,enumerable:!0,get:()=>function(){if(Im)return _m;Im=1;const e=L,t=F,{Stream:n}=$g,r=Op,{configure:i}=Mh();return _m=class extends r{constructor(e={}){super(e),this.options=e,this.name=e.name||"http",this.ssl=!!e.ssl,this.host=e.host||"localhost",this.port=e.port,this.auth=e.auth,this.path=e.path||"",this.maximumDepth=e.maximumDepth,this.agent=e.agent,this.headers=e.headers||{},this.headers["content-type"]="application/json",this.batch=e.batch||!1,this.batchInterval=e.batchInterval||5e3,this.batchCount=e.batchCount||10,this.batchOptions=[],this.batchTimeoutID=-1,this.batchCallback={},this.port||(this.port=this.ssl?443:80)}log(e,t){this._request(e,null,null,((t,n)=>{n&&200!==n.statusCode&&(t=new Error(`Invalid HTTP Status Code: ${n.statusCode}`)),t?this.emit("warn",t):this.emit("logged",e)})),t&&setImmediate(t)}query(e,t){"function"==typeof e&&(t=e,e={});const n=(e={method:"query",params:this.normalizeQuery(e)}).params.auth||null;delete e.params.auth;const r=e.params.path||null;delete e.params.path,this._request(e,n,r,((e,n,r)=>{if(n&&200!==n.statusCode&&(e=new Error(`Invalid HTTP Status Code: ${n.statusCode}`)),e)return t(e);if("string"==typeof r)try{r=JSON.parse(r)}catch(e){return t(e)}t(null,r)}))}stream(e={}){const t=new n,r=(e={method:"stream",params:e}).params.path||null;delete e.params.path;const i=e.params.auth||null;delete e.params.auth;let o="";const s=this._request(e,i,r);return t.destroy=()=>s.destroy(),s.on("data",(e=>{const n=(e=(o+e).split(/\n+/)).length-1;let r=0;for(;r<n;r++)try{t.emit("log",JSON.parse(e[r]))}catch(e){t.emit("error",e)}o=e[n]})),s.on("error",(e=>t.emit("error",e))),t}_request(e,t,n,r){e=e||{},t=t||this.auth,n=n||this.path||"",this.batch?this._doBatch(e,r,t,n):this._doRequest(e,r,t,n)}_doBatch(e,t,n,r){if(this.batchOptions.push(e),1===this.batchOptions.length){const e=this;this.batchCallback=t,this.batchTimeoutID=setTimeout((function(){e.batchTimeoutID=-1,e._doBatchRequest(e.batchCallback,n,r)}),this.batchInterval)}this.batchOptions.length===this.batchCount&&this._doBatchRequest(this.batchCallback,n,r)}_doBatchRequest(e,t,n){this.batchTimeoutID>0&&(clearTimeout(this.batchTimeoutID),this.batchTimeoutID=-1);const r=this.batchOptions.slice();this.batchOptions=[],this._doRequest(r,e,t,n)}_doRequest(n,r,o,s){const a=Object.assign({},this.headers);o&&o.bearer&&(a.Authorization=`Bearer ${o.bearer}`);const c=(this.ssl?t:e).request({...this.options,method:"POST",host:this.host,port:this.port,path:`/${s.replace(/^\//,"")}`,headers:a,auth:o&&o.username&&o.password?`${o.username}:${o.password}`:"",agent:this.agent});c.on("error",r),c.on("response",(e=>e.on("end",(()=>r(null,e))).resume()));const l=i({...this.maximumDepth&&{maximumDepth:this.maximumDepth}});c.end(Buffer.from(l(n,this.options.replacer),"utf8"))}},_m}()}),Object.defineProperty(e,"Stream",{configurable:!0,enumerable:!0,get:()=>function(){if($m)return Cm;$m=1;const e=Om,{MESSAGE:t}=rh,n=N,r=Op;return Cm=class extends r{constructor(t={}){if(super(t),!t.stream||!e(t.stream))throw new Error("options.stream is required.");this._stream=t.stream,this._stream.setMaxListeners(1/0),this.isObjectMode=t.stream._writableState.objectMode,this.eol="string"==typeof t.eol?t.eol:n.EOL}log(e,n){if(setImmediate((()=>this.emit("logged",e))),this.isObjectMode)return this._stream.write(e),void(n&&n());this._stream.write(`${e[t]}${this.eol}`),n&&n()}}}()})}(Nf);var Nm={};const Tm=Ed,{configs:Am}=rh;Nm.cli=Tm.levels(Am.cli),Nm.npm=Tm.levels(Am.npm),Nm.syslog=Tm.levels(Am.syslog),Nm.addColors=Tm.levels;var Mm={exports:{}},Pm={exports:{}};!function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var n=l(Mp),r=l(ug),i=l(gg),o=l(tg),s=l(ag),a=l(zp()),c=l(Jp);function l(e){return e&&e.__esModule?e:{default:e}}function u(e,t,n){n=(0,o.default)(n);var i=0,a=0,{length:c}=e,l=!1;function u(e,t){!1===e&&(l=!0),!0!==l&&(e?n(e):++a!==c&&t!==r.default||n(null))}for(0===c&&n(null);i<c;i++)t(e[i],i,(0,s.default)(u))}function d(e,t,n){return(0,i.default)(e,1/0,t,n)}t.default=(0,c.default)((function(e,t,r){return((0,n.default)(e)?u:d)(e,(0,a.default)(t),r)}),3),e.exports=t.default}(Pm,Pm.exports);var Dm=Pm.exports,jm={exports:{}};!function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return(t,n,r)=>e(t,r)},e.exports=t.default}(jm,jm.exports);var Rm=jm.exports;!function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var n=s(Dm),r=s(Rm),i=s(zp()),o=s(Jp);function s(e){return e&&e.__esModule?e:{default:e}}t.default=(0,o.default)((function(e,t,o){return(0,n.default)(e,(0,r.default)((0,i.default)(t)),o)}),3),e.exports=t.default}(Mm,Mm.exports);var Lm=Mm.exports,Fm=Object.prototype.toString,Um=function(e){var t,n=0;function r(){return n||(n=1,t=e.apply(this,arguments),e=null),t}return r.displayName=function(e){if("string"==typeof e.displayName&&e.constructor.name)return e.displayName;if("string"==typeof e.name&&e.name)return e.name;if("object"==typeof e&&e.constructor&&"string"==typeof e.constructor.name)return e.constructor.name;var t=e.toString(),n=Fm.call(e).slice(8,-1);return(t="Function"===n?t.substring(t.indexOf("(")+1,t.indexOf(")")):n)||"anonymous"}(e),r},Bm={};!function(e){function t(e){for(var t in e)this[t]=e[t]}e.get=function(t){var n=Error.stackTraceLimit;Error.stackTraceLimit=1/0;var r={},i=Error.prepareStackTrace;Error.prepareStackTrace=function(e,t){return t},Error.captureStackTrace(r,t||e.get);var o=r.stack;return Error.prepareStackTrace=i,Error.stackTraceLimit=n,o},e.parse=function(e){if(!e.stack)return[];var t=this;return e.stack.split("\n").slice(1).map((function(e){if(e.match(/^\s*[-]{4,}$/))return t._createParsedCallSite({fileName:e,lineNumber:null,functionName:null,typeName:null,methodName:null,columnNumber:null,native:null});var n=e.match(/at (?:(.+)\s+\()?(?:(.+?):(\d+)(?::(\d+))?|([^)]+))\)?/);if(n){var r=null,i=null,o=null,s=null,a=null,c="native"===n[5];if(n[1]){var l=(o=n[1]).lastIndexOf(".");if("."==o[l-1]&&l--,l>0){r=o.substr(0,l),i=o.substr(l+1);var u=r.indexOf(".Module");u>0&&(o=o.substr(u+1),r=r.substr(0,u))}s=null}i&&(s=r,a=i),"<anonymous>"===i&&(a=null,o=null);var d={fileName:n[2]||null,lineNumber:parseInt(n[3],10)||null,functionName:o,typeName:s,methodName:a,columnNumber:parseInt(n[4],10)||null,native:c};return t._createParsedCallSite(d)}})).filter((function(e){return!!e}))},["this","typeName","functionName","methodName","fileName","lineNumber","columnNumber","function","evalOrigin"].forEach((function(e){t.prototype[e]=null,t.prototype["get"+e[0].toUpperCase()+e.substr(1)]=function(){return this[e]}})),["topLevel","eval","native","constructor"].forEach((function(e){t.prototype[e]=!1,t.prototype["is"+e[0].toUpperCase()+e.substr(1)]=function(){return this[e]}})),e._createParsedCallSite=function(e){return new t(e)}}(Bm);const{Writable:Wm}=$g,Gm=N,Vm=Lm,Ym=xm("winston:exception"),Hm=Um,zm=Bm,qm=class extends Wm{constructor(e){if(super({objectMode:!0}),!e)throw new Error("ExceptionStream requires a TransportStream instance.");this.handleExceptions=!0,this.transport=e}_write(e,t,n){return e.exception?this.transport.log(e,n):(n(),!0)}};var Km=class{constructor(e){if(!e)throw new Error("Logger is required to handle exceptions");this.logger=e,this.handlers=new Map}handle(...e){e.forEach((e=>{if(Array.isArray(e))return e.forEach((e=>this._addHandler(e)));this._addHandler(e)})),this.catcher||(this.catcher=this._uncaughtException.bind(this),process.on("uncaughtException",this.catcher))}unhandle(){this.catcher&&(process.removeListener("uncaughtException",this.catcher),this.catcher=!1,Array.from(this.handlers.values()).forEach((e=>this.logger.unpipe(e))))}getAllInfo(e){let t=null;return e&&(t="string"==typeof e?e:e.message),{error:e,level:"error",message:[`uncaughtException: ${t||"(no error message)"}`,e&&e.stack||" No stack trace"].join("\n"),stack:e&&e.stack,exception:!0,date:(new Date).toString(),process:this.getProcessInfo(),os:this.getOsInfo(),trace:this.getTrace(e)}}getProcessInfo(){return{pid:process.pid,uid:process.getuid?process.getuid():null,gid:process.getgid?process.getgid():null,cwd:process.cwd(),execPath:process.execPath,version:process.version,argv:process.argv,memoryUsage:process.memoryUsage()}}getOsInfo(){return{loadavg:Gm.loadavg(),uptime:Gm.uptime()}}getTrace(e){return(e?zm.parse(e):zm.get()).map((e=>({column:e.getColumnNumber(),file:e.getFileName(),function:e.getFunctionName(),line:e.getLineNumber(),method:e.getMethodName(),native:e.isNative()})))}_addHandler(e){if(!this.handlers.has(e)){e.handleExceptions=!0;const t=new qm(e);this.handlers.set(e,t),this.logger.pipe(t)}}_uncaughtException(e){const t=this.getAllInfo(e),n=this._getExceptionHandlers();let r,i="function"==typeof this.logger.exitOnError?this.logger.exitOnError(e):this.logger.exitOnError;function o(){Ym("doExit",i),Ym("process._exiting",process._exiting),i&&!process._exiting&&(r&&clearTimeout(r),process.exit(1))}if(!n.length&&i&&(console.warn("winston: exitOnError cannot be true with no exception handlers."),console.warn("winston: not exiting process."),i=!1),!n||0===n.length)return process.nextTick(o);Vm(n,((e,t)=>{const n=Hm(t),r=e.transport||e;function i(e){return()=>{Ym(e),n()}}r._ending=!0,r.once("finish",i("finished")),r.once("error",i("error"))}),(()=>i&&o())),this.logger.log(t),i&&(r=setTimeout(o,3e3))}_getExceptionHandlers(){return this.logger.transports.filter((e=>(e.transport||e).handleExceptions))}};const{Writable:Jm}=$g,Zm=N,Xm=Lm,Qm=xm("winston:rejection"),ey=Um,ty=Bm,ny=class extends Jm{constructor(e){if(super({objectMode:!0}),!e)throw new Error("RejectionStream requires a TransportStream instance.");this.handleRejections=!0,this.transport=e}_write(e,t,n){return e.rejection?this.transport.log(e,n):(n(),!0)}};var ry,iy,oy,sy,ay=class{constructor(e){if(!e)throw new Error("Logger is required to handle rejections");this.logger=e,this.handlers=new Map}handle(...e){e.forEach((e=>{if(Array.isArray(e))return e.forEach((e=>this._addHandler(e)));this._addHandler(e)})),this.catcher||(this.catcher=this._unhandledRejection.bind(this),process.on("unhandledRejection",this.catcher))}unhandle(){this.catcher&&(process.removeListener("unhandledRejection",this.catcher),this.catcher=!1,Array.from(this.handlers.values()).forEach((e=>this.logger.unpipe(e))))}getAllInfo(e){let t=null;return e&&(t="string"==typeof e?e:e.message),{error:e,level:"error",message:[`unhandledRejection: ${t||"(no error message)"}`,e&&e.stack||" No stack trace"].join("\n"),stack:e&&e.stack,rejection:!0,date:(new Date).toString(),process:this.getProcessInfo(),os:this.getOsInfo(),trace:this.getTrace(e)}}getProcessInfo(){return{pid:process.pid,uid:process.getuid?process.getuid():null,gid:process.getgid?process.getgid():null,cwd:process.cwd(),execPath:process.execPath,version:process.version,argv:process.argv,memoryUsage:process.memoryUsage()}}getOsInfo(){return{loadavg:Zm.loadavg(),uptime:Zm.uptime()}}getTrace(e){return(e?ty.parse(e):ty.get()).map((e=>({column:e.getColumnNumber(),file:e.getFileName(),function:e.getFunctionName(),line:e.getLineNumber(),method:e.getMethodName(),native:e.isNative()})))}_addHandler(e){if(!this.handlers.has(e)){e.handleRejections=!0;const t=new ny(e);this.handlers.set(e,t),this.logger.pipe(t)}}_unhandledRejection(e){const t=this.getAllInfo(e),n=this._getRejectionHandlers();let r,i="function"==typeof this.logger.exitOnError?this.logger.exitOnError(e):this.logger.exitOnError;function o(){Qm("doExit",i),Qm("process._exiting",process._exiting),i&&!process._exiting&&(r&&clearTimeout(r),process.exit(1))}if(!n.length&&i&&(console.warn("winston: exitOnError cannot be true with no rejection handlers."),console.warn("winston: not exiting process."),i=!1),!n||0===n.length)return process.nextTick(o);Xm(n,((e,t)=>{const n=ey(t),r=e.transport||e;function i(e){return()=>{Qm(e),n()}}r._ending=!0,r.once("finish",i("finished")),r.once("error",i("error"))}),(()=>i&&o())),this.logger.log(t),i&&(r=setTimeout(o,3e3))}_getRejectionHandlers(){return this.logger.transports.filter((e=>(e.transport||e).handleRejections))}};function cy(){if(sy)return oy;sy=1;const{Stream:e,Transform:t}=$g,n=Lm,{LEVEL:r,SPLAT:i}=rh,o=Om,s=Km,a=ay,c=Ep,l=(iy||(iy=1,ry=class{constructor(e){const t=cy();if("object"!=typeof e||Array.isArray(e)||!(e instanceof t))throw new Error("Logger is required for profiling");this.logger=e,this.start=Date.now()}done(...e){"function"==typeof e[e.length-1]&&(console.warn("Callback function no longer supported as of winston@3.0.0"),e.pop());const t="object"==typeof e[e.length-1]?e.pop():{};return t.level=t.level||"info",t.durationMs=Date.now()-this.start,this.logger.write(t)}}),ry),{warn:u}=If,d=Nm,h=/%[scdjifoO%]/g;class f extends t{constructor(e){super({objectMode:!0}),this.configure(e)}child(e){const t=this;return Object.create(t,{write:{value:function(n){const r=Object.assign({},e,n);n instanceof Error&&(r.stack=n.stack,r.message=n.message),t.write(r)}}})}configure({silent:e,format:t,defaultMeta:n,levels:r,level:i="info",exitOnError:o=!0,transports:c,colors:l,emitErrs:u,formatters:h,padLevels:f,rewriters:p,stripColors:g,exceptionHandlers:m,rejectionHandlers:y}={}){if(this.transports.length&&this.clear(),this.silent=e,this.format=t||this.format||Ph()(),this.defaultMeta=n||null,this.levels=r||this.levels||d.npm.levels,this.level=i,this.exceptions&&this.exceptions.unhandle(),this.rejections&&this.rejections.unhandle(),this.exceptions=new s(this),this.rejections=new a(this),this.profilers={},this.exitOnError=o,c&&(c=Array.isArray(c)?c:[c]).forEach((e=>this.add(e))),l||u||h||f||p||g)throw new Error(["{ colors, emitErrs, formatters, padLevels, rewriters, stripColors } were removed in winston@3.0.0.","Use a custom winston.format(function) instead.","See: https://github.com/winstonjs/winston/tree/master/UPGRADE-3.0.md"].join("\n"));m&&this.exceptions.handle(m),y&&this.rejections.handle(y)}isLevelEnabled(e){const t=p(this.levels,e);if(null===t)return!1;const n=p(this.levels,this.level);return null!==n&&(this.transports&&0!==this.transports.length?-1!==this.transports.findIndex((e=>{let r=p(this.levels,e.level);return null===r&&(r=n),r>=t})):n>=t)}log(e,t,...n){if(1===arguments.length)return e[r]=e.level,this._addDefaultMeta(e),this.write(e),this;if(2===arguments.length)return t&&"object"==typeof t?(t[r]=t.level=e,this._addDefaultMeta(t),this.write(t),this):(t={[r]:e,level:e,message:t},this._addDefaultMeta(t),this.write(t),this);const[o]=n;if("object"==typeof o&&null!==o&&!(t&&t.match&&t.match(h))){const s=Object.assign({},this.defaultMeta,o,{[r]:e,[i]:n,level:e,message:t});return o.message&&(s.message=`${s.message} ${o.message}`),o.stack&&(s.stack=o.stack),o.cause&&(s.cause=o.cause),this.write(s),this}return this.write(Object.assign({},this.defaultMeta,{[r]:e,[i]:n,level:e,message:t})),this}_transform(e,t,n){if(this.silent)return n();e[r]||(e[r]=e.level),this.levels[e[r]]||0===this.levels[e[r]]||console.error("[winston] Unknown logger level: %s",e[r]),this._readableState.pipes||console.error("[winston] Attempt to write logs with no transports, which can increase memory usage: %j",e);try{this.push(this.format.transform(e,this.format.options))}finally{this._writableState.sync=!1,n()}}_final(e){const t=this.transports.slice();n(t,((e,t)=>{if(!e||e.finished)return setImmediate(t);e.once("finish",t),e.end()}),e)}add(e){const t=!o(e)||e.log.length>2?new c({transport:e}):e;if(!t._writableState||!t._writableState.objectMode)throw new Error("Transports must WritableStreams in objectMode. Set { objectMode: true }.");return this._onEvent("error",t),this._onEvent("warn",t),this.pipe(t),e.handleExceptions&&this.exceptions.handle(),e.handleRejections&&this.rejections.handle(),this}remove(e){if(!e)return this;let t=e;return(!o(e)||e.log.length>2)&&(t=this.transports.filter((t=>t.transport===e))[0]),t&&this.unpipe(t),this}clear(){return this.unpipe(),this}close(){return this.exceptions.unhandle(),this.rejections.unhandle(),this.clear(),this.emit("close"),this}setLevels(){u.deprecated("setLevels")}query(e,t){"function"==typeof e&&(t=e,e={}),e=e||{};const r={},i=Object.assign({},e.query||{});n(this.transports.filter((e=>!!e.query)),(function(t,n){!function(t,n){e.query&&"function"==typeof t.formatQuery&&(e.query=t.formatQuery(i)),t.query(e,((r,i)=>{if(r)return n(r);"function"==typeof t.formatResults&&(i=t.formatResults(i,e.format)),n(null,i)}))}(t,((e,i)=>{n&&((i=e||i)&&(r[t.name]=i),n()),n=null}))}),(()=>t(null,r)))}stream(t={}){const n=new e,r=[];return n._streams=r,n.destroy=()=>{let e=r.length;for(;e--;)r[e].destroy()},this.transports.filter((e=>!!e.stream)).forEach((e=>{const i=e.stream(t);i&&(r.push(i),i.on("log",(t=>{t.transport=t.transport||[],t.transport.push(e.name),n.emit("log",t)})),i.on("error",(t=>{t.transport=t.transport||[],t.transport.push(e.name),n.emit("error",t)})))})),n}startTimer(){return new l(this)}profile(e,...t){const n=Date.now();if(this.profilers[e]){const r=this.profilers[e];delete this.profilers[e],"function"==typeof t[t.length-2]&&(console.warn("Callback function no longer supported as of winston@3.0.0"),t.pop());const i="object"==typeof t[t.length-1]?t.pop():{};return i.level=i.level||"info",i.durationMs=n-r,i.message=i.message||e,this.write(i)}return this.profilers[e]=n,this}handleExceptions(...e){console.warn("Deprecated: .handleExceptions() will be removed in winston@4. Use .exceptions.handle()"),this.exceptions.handle(...e)}unhandleExceptions(...e){console.warn("Deprecated: .unhandleExceptions() will be removed in winston@4. Use .exceptions.unhandle()"),this.exceptions.unhandle(...e)}cli(){throw new Error(["Logger.cli() was removed in winston@3.0.0","Use a custom winston.formats.cli() instead.","See: https://github.com/winstonjs/winston/tree/master/UPGRADE-3.0.md"].join("\n"))}_onEvent(e,t){t["__winston"+e]||(t["__winston"+e]=function(n){"error"!==e||this.transports.includes(t)||this.add(t),this.emit(e,n,t)}.bind(this),t.on(e,t["__winston"+e]))}_addDefaultMeta(e){this.defaultMeta&&Object.assign(e,this.defaultMeta)}}function p(e,t){const n=e[t];return n||0===n?n:null}return Object.defineProperty(f.prototype,"transports",{configurable:!1,enumerable:!0,get(){const{pipes:e}=this._readableState;return Array.isArray(e)?e:[e].filter(Boolean)}}),oy=f}const{LEVEL:ly}=rh,uy=Nm,dy=cy(),hy=xm("winston:create-logger");var fy=function(e={}){e.levels=e.levels||uy.npm.levels;class t extends dy{constructor(e){super(e)}}const n=new t(e);return Object.keys(e.levels).forEach((function(e){hy('Define prototype method for "%s"',e),"log"!==e?(t.prototype[e]=function(...t){const r=this||n;if(1===t.length){const[i]=t,o=i&&i.message&&i||{message:i};return o.level=o[ly]=e,r._addDefaultMeta(o),r.write(o),this||n}return 0===t.length?(r.log(e,""),r):r.log(e,...t)},t.prototype[function(e){return"is"+e.charAt(0).toUpperCase()+e.slice(1)+"Enabled"}(e)]=function(){return(this||n).isLevelEnabled(e)}):console.warn('Level "log" not defined: conflicts with the method "log". Use a different level name.')})),n};const py=fy;var gy=class{constructor(e={}){this.loggers=new Map,this.options=e}add(e,t){if(!this.loggers.has(e)){const n=(t=Object.assign({},t||this.options)).transports||this.options.transports;t.transports=n?Array.isArray(n)?n.slice():[n]:[];const r=py(t);r.on("close",(()=>this._delete(e))),this.loggers.set(e,r)}return this.loggers.get(e)}get(e,t){return this.add(e,t)}has(e){return!!this.loggers.has(e)}close(e){if(e)return this._removeLogger(e);this.loggers.forEach(((e,t)=>this._removeLogger(t)))}_removeLogger(e){this.loggers.has(e)&&(this.loggers.get(e).close(),this._delete(e))}_delete(e){this.loggers.delete(e)}};!function(e){const t=Ed,{warn:n}=If;e.version="3.17.0",e.transports=Nf,e.config=Nm,e.addColors=t.levels,e.format=t.format,e.createLogger=fy,e.Logger=cy(),e.ExceptionHandler=Km,e.RejectionHandler=ay,e.Container=gy,e.Transport=Op,e.loggers=new e.Container;const r=e.createLogger();Object.keys(e.config.npm.levels).concat(["log","query","stream","add","remove","clear","profile","startTimer","handleExceptions","unhandleExceptions","handleRejections","unhandleRejections","configure","child"]).forEach((t=>e[t]=(...e)=>r[t](...e))),Object.defineProperty(e,"level",{get:()=>r.level,set(e){r.level=e}}),Object.defineProperty(e,"exceptions",{get:()=>r.exceptions}),Object.defineProperty(e,"rejections",{get:()=>r.rejections}),["exitOnError"].forEach((t=>{Object.defineProperty(e,t,{get:()=>r[t],set(e){r[t]=e}})})),Object.defineProperty(e,"default",{get:()=>({exceptionHandlers:r.exceptionHandlers,rejectionHandlers:r.rejectionHandlers,transports:r.transports})}),n.deprecated(e,"setLevels"),n.forFunctions(e,"useFormat",["cli"]),n.forProperties(e,"useFormat",["padLevels","stripColors"]),n.forFunctions(e,"deprecated",["addRewriter","addFilter","clone","extend"]),n.forProperties(e,"deprecated",["emitErrs","levelLength"])}(kd);var my=ad(kd),yy={exports:{}};!function(e,t){var n=l;function r(e,t){return function(e,t){var r;if(void 0===(r="passthrough"!==t.algorithm?n.createHash(t.algorithm):new u).write&&(r.write=r.update,r.end=r.update),c(t,r).dispatch(e),r.update||r.end(""),r.digest)return r.digest("buffer"===t.encoding?void 0:t.encoding);var i=r.read();return"buffer"===t.encoding?i:i.toString(t.encoding)}(e,t=s(e,t))}(t=yy.exports=r).sha1=function(e){return r(e)},t.keys=function(e){return r(e,{excludeValues:!0,algorithm:"sha1",encoding:"hex"})},t.MD5=function(e){return r(e,{algorithm:"md5",encoding:"hex"})},t.keysMD5=function(e){return r(e,{algorithm:"md5",encoding:"hex",excludeValues:!0})};var i=n.getHashes?n.getHashes().slice():["sha1","md5"];i.push("passthrough");var o=["buffer","hex","binary","base64"];function s(e,t){t=t||{};var n={};if(n.algorithm=t.algorithm||"sha1",n.encoding=t.encoding||"hex",n.excludeValues=!!t.excludeValues,n.algorithm=n.algorithm.toLowerCase(),n.encoding=n.encoding.toLowerCase(),n.ignoreUnknown=!0===t.ignoreUnknown,n.respectType=!1!==t.respectType,n.respectFunctionNames=!1!==t.respectFunctionNames,n.respectFunctionProperties=!1!==t.respectFunctionProperties,n.unorderedArrays=!0===t.unorderedArrays,n.unorderedSets=!1!==t.unorderedSets,n.unorderedObjects=!1!==t.unorderedObjects,n.replacer=t.replacer||void 0,n.excludeKeys=t.excludeKeys||void 0,void 0===e)throw new Error("Object argument required.");for(var r=0;r<i.length;++r)i[r].toLowerCase()===n.algorithm.toLowerCase()&&(n.algorithm=i[r]);if(-1===i.indexOf(n.algorithm))throw new Error('Algorithm "'+n.algorithm+'" not supported. supported values: '+i.join(", "));if(-1===o.indexOf(n.encoding)&&"passthrough"!==n.algorithm)throw new Error('Encoding "'+n.encoding+'" not supported. supported values: '+o.join(", "));return n}function a(e){return"function"==typeof e&&null!=/^function\s+\w*\s*\(\s*\)\s*{\s+\[native code\]\s+}$/i.exec(Function.prototype.toString.call(e))}function c(e,t,n){n=n||[];var r=function(e){return t.update?t.update(e,"utf8"):t.write(e,"utf8")};return{dispatch:function(t){e.replacer&&(t=e.replacer(t));var n=typeof t;return null===t&&(n="null"),this["_"+n](t)},_object:function(t){var i,o=Object.prototype.toString.call(t),s=/\[object (.*)\]/i.exec(o);if(s=(s=s?s[1]:"unknown:["+o+"]").toLowerCase(),(i=n.indexOf(t))>=0)return this.dispatch("[CIRCULAR:"+i+"]");if(n.push(t),"undefined"!=typeof Buffer&&Buffer.isBuffer&&Buffer.isBuffer(t))return r("buffer:"),r(t);if("object"===s||"function"===s||"asyncfunction"===s){var c=Object.keys(t);e.unorderedObjects&&(c=c.sort()),!1===e.respectType||a(t)||c.splice(0,0,"prototype","__proto__","constructor"),e.excludeKeys&&(c=c.filter((function(t){return!e.excludeKeys(t)}))),r("object:"+c.length+":");var l=this;return c.forEach((function(n){l.dispatch(n),r(":"),e.excludeValues||l.dispatch(t[n]),r(",")}))}if(!this["_"+s]){if(e.ignoreUnknown)return r("["+s+"]");throw new Error('Unknown object type "'+s+'"')}this["_"+s](t)},_array:function(t,i){i=void 0!==i?i:!1!==e.unorderedArrays;var o=this;if(r("array:"+t.length+":"),!i||t.length<=1)return t.forEach((function(e){return o.dispatch(e)}));var s=[],a=t.map((function(t){var r=new u,i=n.slice();return c(e,r,i).dispatch(t),s=s.concat(i.slice(n.length)),r.read().toString()}));return n=n.concat(s),a.sort(),this._array(a,!1)},_date:function(e){return r("date:"+e.toJSON())},_symbol:function(e){return r("symbol:"+e.toString())},_error:function(e){return r("error:"+e.toString())},_boolean:function(e){return r("bool:"+e.toString())},_string:function(e){r("string:"+e.length+":"),r(e.toString())},_function:function(t){r("fn:"),a(t)?this.dispatch("[native]"):this.dispatch(t.toString()),!1!==e.respectFunctionNames&&this.dispatch("function-name:"+String(t.name)),e.respectFunctionProperties&&this._object(t)},_number:function(e){return r("number:"+e.toString())},_xml:function(e){return r("xml:"+e.toString())},_null:function(){return r("Null")},_undefined:function(){return r("Undefined")},_regexp:function(e){return r("regex:"+e.toString())},_uint8array:function(e){return r("uint8array:"),this.dispatch(Array.prototype.slice.call(e))},_uint8clampedarray:function(e){return r("uint8clampedarray:"),this.dispatch(Array.prototype.slice.call(e))},_int8array:function(e){return r("int8array:"),this.dispatch(Array.prototype.slice.call(e))},_uint16array:function(e){return r("uint16array:"),this.dispatch(Array.prototype.slice.call(e))},_int16array:function(e){return r("int16array:"),this.dispatch(Array.prototype.slice.call(e))},_uint32array:function(e){return r("uint32array:"),this.dispatch(Array.prototype.slice.call(e))},_int32array:function(e){return r("int32array:"),this.dispatch(Array.prototype.slice.call(e))},_float32array:function(e){return r("float32array:"),this.dispatch(Array.prototype.slice.call(e))},_float64array:function(e){return r("float64array:"),this.dispatch(Array.prototype.slice.call(e))},_arraybuffer:function(e){return r("arraybuffer:"),this.dispatch(new Uint8Array(e))},_url:function(e){return r("url:"+e.toString())},_map:function(t){r("map:");var n=Array.from(t);return this._array(n,!1!==e.unorderedSets)},_set:function(t){r("set:");var n=Array.from(t);return this._array(n,!1!==e.unorderedSets)},_file:function(e){return r("file:"),this.dispatch([e.name,e.size,e.type,e.lastModfied])},_blob:function(){if(e.ignoreUnknown)return r("[blob]");throw Error('Hashing Blob objects is currently not supported\n(see https://github.com/puleos/object-hash/issues/26)\nUse "options.replacer" or "options.ignoreUnknown"\n')},_domwindow:function(){return r("domwindow")},_bigint:function(e){return r("bigint:"+e.toString())},_process:function(){return r("process")},_timer:function(){return r("timer")},_pipe:function(){return r("pipe")},_tcp:function(){return r("tcp")},_udp:function(){return r("udp")},_tty:function(){return r("tty")},_statwatcher:function(){return r("statwatcher")},_securecontext:function(){return r("securecontext")},_connection:function(){return r("connection")},_zlib:function(){return r("zlib")},_context:function(){return r("context")},_nodescript:function(){return r("nodescript")},_httpparser:function(){return r("httpparser")},_dataview:function(){return r("dataview")},_signal:function(){return r("signal")},_fsevent:function(){return r("fsevent")},_tlswrap:function(){return r("tlswrap")}}}function u(){return{buf:"",write:function(e){this.buf+=e},end:function(e){this.buf+=e},read:function(){return this.buf}}}t.writeToStream=function(e,t,n){return void 0===n&&(n=t,t={}),c(t=s(e,t),n).dispatch(e)}}(0,yy.exports);var vy,by,wy,Sy={exports:{}};function _y(){return vy||(vy=1,(e=Sy).exports=function(){var t,n;function r(){return t.apply(null,arguments)}function i(e){return e instanceof Array||"[object Array]"===Object.prototype.toString.call(e)}function o(e){return null!=e&&"[object Object]"===Object.prototype.toString.call(e)}function s(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function a(e){if(Object.getOwnPropertyNames)return 0===Object.getOwnPropertyNames(e).length;var t;for(t in e)if(s(e,t))return!1;return!0}function c(e){return void 0===e}function l(e){return"number"==typeof e||"[object Number]"===Object.prototype.toString.call(e)}function u(e){return e instanceof Date||"[object Date]"===Object.prototype.toString.call(e)}function d(e,t){var n,r=[],i=e.length;for(n=0;n<i;++n)r.push(t(e[n],n));return r}function h(e,t){for(var n in t)s(t,n)&&(e[n]=t[n]);return s(t,"toString")&&(e.toString=t.toString),s(t,"valueOf")&&(e.valueOf=t.valueOf),e}function f(e,t,n,r){return Dt(e,t,n,r,!0).utc()}function p(e){return null==e._pf&&(e._pf={empty:!1,unusedTokens:[],unusedInput:[],overflow:-2,charsLeftOver:0,nullInput:!1,invalidEra:null,invalidMonth:null,invalidFormat:!1,userInvalidated:!1,iso:!1,parsedDateParts:[],era:null,meridiem:null,rfc2822:!1,weekdayMismatch:!1}),e._pf}function g(e){var t=null,r=!1,i=e._d&&!isNaN(e._d.getTime());return i&&(t=p(e),r=n.call(t.parsedDateParts,(function(e){return null!=e})),i=t.overflow<0&&!t.empty&&!t.invalidEra&&!t.invalidMonth&&!t.invalidWeekday&&!t.weekdayMismatch&&!t.nullInput&&!t.invalidFormat&&!t.userInvalidated&&(!t.meridiem||t.meridiem&&r),e._strict&&(i=i&&0===t.charsLeftOver&&0===t.unusedTokens.length&&void 0===t.bigHour)),null!=Object.isFrozen&&Object.isFrozen(e)?i:(e._isValid=i,e._isValid)}function m(e){var t=f(NaN);return null!=e?h(p(t),e):p(t).userInvalidated=!0,t}n=Array.prototype.some?Array.prototype.some:function(e){var t,n=Object(this),r=n.length>>>0;for(t=0;t<r;t++)if(t in n&&e.call(this,n[t],t,n))return!0;return!1};var y=r.momentProperties=[],v=!1;function b(e,t){var n,r,i,o=y.length;if(c(t._isAMomentObject)||(e._isAMomentObject=t._isAMomentObject),c(t._i)||(e._i=t._i),c(t._f)||(e._f=t._f),c(t._l)||(e._l=t._l),c(t._strict)||(e._strict=t._strict),c(t._tzm)||(e._tzm=t._tzm),c(t._isUTC)||(e._isUTC=t._isUTC),c(t._offset)||(e._offset=t._offset),c(t._pf)||(e._pf=p(t)),c(t._locale)||(e._locale=t._locale),o>0)for(n=0;n<o;n++)c(i=t[r=y[n]])||(e[r]=i);return e}function w(e){b(this,e),this._d=new Date(null!=e._d?e._d.getTime():NaN),this.isValid()||(this._d=new Date(NaN)),!1===v&&(v=!0,r.updateOffset(this),v=!1)}function S(e){return e instanceof w||null!=e&&null!=e._isAMomentObject}function _(e){!1===r.suppressDeprecationWarnings&&"undefined"!=typeof console&&console.warn&&console.warn("Deprecation warning: "+e)}function I(e,t){var n=!0;return h((function(){if(null!=r.deprecationHandler&&r.deprecationHandler(null,e),n){var i,o,a,c=[],l=arguments.length;for(o=0;o<l;o++){if(i="","object"==typeof arguments[o]){for(a in i+="\n["+o+"] ",arguments[0])s(arguments[0],a)&&(i+=a+": "+arguments[0][a]+", ");i=i.slice(0,-2)}else i=arguments[o];c.push(i)}_(e+"\nArguments: "+Array.prototype.slice.call(c).join("")+"\n"+(new Error).stack),n=!1}return t.apply(this,arguments)}),t)}var x,k={};function E(e,t){null!=r.deprecationHandler&&r.deprecationHandler(e,t),k[e]||(_(t),k[e]=!0)}function C(e){return"undefined"!=typeof Function&&e instanceof Function||"[object Function]"===Object.prototype.toString.call(e)}function $(e,t){var n,r=h({},e);for(n in t)s(t,n)&&(o(e[n])&&o(t[n])?(r[n]={},h(r[n],e[n]),h(r[n],t[n])):null!=t[n]?r[n]=t[n]:delete r[n]);for(n in e)s(e,n)&&!s(t,n)&&o(e[n])&&(r[n]=h({},r[n]));return r}function O(e){null!=e&&this.set(e)}r.suppressDeprecationWarnings=!1,r.deprecationHandler=null,x=Object.keys?Object.keys:function(e){var t,n=[];for(t in e)s(e,t)&&n.push(t);return n};function N(e,t,n){var r=""+Math.abs(e),i=t-r.length;return(e>=0?n?"+":"":"-")+Math.pow(10,Math.max(0,i)).toString().substr(1)+r}var T=/(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|N{1,5}|YYYYYY|YYYYY|YYYY|YY|y{2,4}|yo?|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g,A=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,M={},P={};function D(e,t,n,r){var i=r;"string"==typeof r&&(i=function(){return this[r]()}),e&&(P[e]=i),t&&(P[t[0]]=function(){return N(i.apply(this,arguments),t[1],t[2])}),n&&(P[n]=function(){return this.localeData().ordinal(i.apply(this,arguments),e)})}function j(e){return e.match(/\[[\s\S]/)?e.replace(/^\[|\]$/g,""):e.replace(/\\/g,"")}function R(e,t){return e.isValid()?(t=L(t,e.localeData()),M[t]=M[t]||function(e){var t,n,r=e.match(T);for(t=0,n=r.length;t<n;t++)P[r[t]]?r[t]=P[r[t]]:r[t]=j(r[t]);return function(t){var i,o="";for(i=0;i<n;i++)o+=C(r[i])?r[i].call(t,e):r[i];return o}}(t),M[t](e)):e.localeData().invalidDate()}function L(e,t){var n=5;function r(e){return t.longDateFormat(e)||e}for(A.lastIndex=0;n>=0&&A.test(e);)e=e.replace(A,r),A.lastIndex=0,n-=1;return e}var F={D:"date",dates:"date",date:"date",d:"day",days:"day",day:"day",e:"weekday",weekdays:"weekday",weekday:"weekday",E:"isoWeekday",isoweekdays:"isoWeekday",isoweekday:"isoWeekday",DDD:"dayOfYear",dayofyears:"dayOfYear",dayofyear:"dayOfYear",h:"hour",hours:"hour",hour:"hour",ms:"millisecond",milliseconds:"millisecond",millisecond:"millisecond",m:"minute",minutes:"minute",minute:"minute",M:"month",months:"month",month:"month",Q:"quarter",quarters:"quarter",quarter:"quarter",s:"second",seconds:"second",second:"second",gg:"weekYear",weekyears:"weekYear",weekyear:"weekYear",GG:"isoWeekYear",isoweekyears:"isoWeekYear",isoweekyear:"isoWeekYear",w:"week",weeks:"week",week:"week",W:"isoWeek",isoweeks:"isoWeek",isoweek:"isoWeek",y:"year",years:"year",year:"year"};function U(e){return"string"==typeof e?F[e]||F[e.toLowerCase()]:void 0}function B(e){var t,n,r={};for(n in e)s(e,n)&&(t=U(n))&&(r[t]=e[n]);return r}var W={date:9,day:11,weekday:11,isoWeekday:11,dayOfYear:4,hour:13,millisecond:16,minute:14,month:8,quarter:7,second:15,weekYear:1,isoWeekYear:1,week:5,isoWeek:5,year:1};var G,V=/\d/,Y=/\d\d/,H=/\d{3}/,z=/\d{4}/,q=/[+-]?\d{6}/,K=/\d\d?/,J=/\d\d\d\d?/,Z=/\d\d\d\d\d\d?/,X=/\d{1,3}/,Q=/\d{1,4}/,ee=/[+-]?\d{1,6}/,te=/\d+/,ne=/[+-]?\d+/,re=/Z|[+-]\d\d:?\d\d/gi,ie=/Z|[+-]\d\d(?::?\d\d)?/gi,oe=/[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i,se=/^[1-9]\d?/,ae=/^([1-9]\d|\d)/;function ce(e,t,n){G[e]=C(t)?t:function(e){return e&&n?n:t}}function le(e,t){return s(G,e)?G[e](t._strict,t._locale):new RegExp(function(e){return ue(e.replace("\\","").replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g,(function(e,t,n,r,i){return t||n||r||i})))}(e))}function ue(e){return e.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")}function de(e){return e<0?Math.ceil(e)||0:Math.floor(e)}function he(e){var t=+e,n=0;return 0!==t&&isFinite(t)&&(n=de(t)),n}G={};var fe={};function pe(e,t){var n,r,i=t;for("string"==typeof e&&(e=[e]),l(t)&&(i=function(e,n){n[t]=he(e)}),r=e.length,n=0;n<r;n++)fe[e[n]]=i}function ge(e,t){pe(e,(function(e,n,r,i){r._w=r._w||{},t(e,r._w,r,i)}))}function me(e,t,n){null!=t&&s(fe,e)&&fe[e](t,n._a,n,e)}function ye(e){return e%4==0&&e%100!=0||e%400==0}var ve=0,be=1,we=2,Se=3,_e=4,Ie=5,xe=6,ke=7,Ee=8;function Ce(e){return ye(e)?366:365}D("Y",0,0,(function(){var e=this.year();return e<=9999?N(e,4):"+"+e})),D(0,["YY",2],0,(function(){return this.year()%100})),D(0,["YYYY",4],0,"year"),D(0,["YYYYY",5],0,"year"),D(0,["YYYYYY",6,!0],0,"year"),ce("Y",ne),ce("YY",K,Y),ce("YYYY",Q,z),ce("YYYYY",ee,q),ce("YYYYYY",ee,q),pe(["YYYYY","YYYYYY"],ve),pe("YYYY",(function(e,t){t[ve]=2===e.length?r.parseTwoDigitYear(e):he(e)})),pe("YY",(function(e,t){t[ve]=r.parseTwoDigitYear(e)})),pe("Y",(function(e,t){t[ve]=parseInt(e,10)})),r.parseTwoDigitYear=function(e){return he(e)+(he(e)>68?1900:2e3)};var $e,Oe=Ne("FullYear",!0);function Ne(e,t){return function(n){return null!=n?(Ae(this,e,n),r.updateOffset(this,t),this):Te(this,e)}}function Te(e,t){if(!e.isValid())return NaN;var n=e._d,r=e._isUTC;switch(t){case"Milliseconds":return r?n.getUTCMilliseconds():n.getMilliseconds();case"Seconds":return r?n.getUTCSeconds():n.getSeconds();case"Minutes":return r?n.getUTCMinutes():n.getMinutes();case"Hours":return r?n.getUTCHours():n.getHours();case"Date":return r?n.getUTCDate():n.getDate();case"Day":return r?n.getUTCDay():n.getDay();case"Month":return r?n.getUTCMonth():n.getMonth();case"FullYear":return r?n.getUTCFullYear():n.getFullYear();default:return NaN}}function Ae(e,t,n){var r,i,o,s,a;if(e.isValid()&&!isNaN(n)){switch(r=e._d,i=e._isUTC,t){case"Milliseconds":return void(i?r.setUTCMilliseconds(n):r.setMilliseconds(n));case"Seconds":return void(i?r.setUTCSeconds(n):r.setSeconds(n));case"Minutes":return void(i?r.setUTCMinutes(n):r.setMinutes(n));case"Hours":return void(i?r.setUTCHours(n):r.setHours(n));case"Date":return void(i?r.setUTCDate(n):r.setDate(n));case"FullYear":break;default:return}o=n,s=e.month(),a=29!==(a=e.date())||1!==s||ye(o)?a:28,i?r.setUTCFullYear(o,s,a):r.setFullYear(o,s,a)}}function Me(e,t){if(isNaN(e)||isNaN(t))return NaN;var n=function(e,t){return(e%t+t)%t}(t,12);return e+=(t-n)/12,1===n?ye(e)?29:28:31-n%7%2}$e=Array.prototype.indexOf?Array.prototype.indexOf:function(e){var t;for(t=0;t<this.length;++t)if(this[t]===e)return t;return-1},D("M",["MM",2],"Mo",(function(){return this.month()+1})),D("MMM",0,0,(function(e){return this.localeData().monthsShort(this,e)})),D("MMMM",0,0,(function(e){return this.localeData().months(this,e)})),ce("M",K,se),ce("MM",K,Y),ce("MMM",(function(e,t){return t.monthsShortRegex(e)})),ce("MMMM",(function(e,t){return t.monthsRegex(e)})),pe(["M","MM"],(function(e,t){t[be]=he(e)-1})),pe(["MMM","MMMM"],(function(e,t,n,r){var i=n._locale.monthsParse(e,r,n._strict);null!=i?t[be]=i:p(n).invalidMonth=e}));var Pe="January_February_March_April_May_June_July_August_September_October_November_December".split("_"),De="Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),je=/D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/,Re=oe,Le=oe;function Fe(e,t,n){var r,i,o,s=e.toLocaleLowerCase();if(!this._monthsParse)for(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[],r=0;r<12;++r)o=f([2e3,r]),this._shortMonthsParse[r]=this.monthsShort(o,"").toLocaleLowerCase(),this._longMonthsParse[r]=this.months(o,"").toLocaleLowerCase();return n?"MMM"===t?-1!==(i=$e.call(this._shortMonthsParse,s))?i:null:-1!==(i=$e.call(this._longMonthsParse,s))?i:null:"MMM"===t?-1!==(i=$e.call(this._shortMonthsParse,s))||-1!==(i=$e.call(this._longMonthsParse,s))?i:null:-1!==(i=$e.call(this._longMonthsParse,s))||-1!==(i=$e.call(this._shortMonthsParse,s))?i:null}function Ue(e,t){if(!e.isValid())return e;if("string"==typeof t)if(/^\d+$/.test(t))t=he(t);else if(!l(t=e.localeData().monthsParse(t)))return e;var n=t,r=e.date();return r=r<29?r:Math.min(r,Me(e.year(),n)),e._isUTC?e._d.setUTCMonth(n,r):e._d.setMonth(n,r),e}function Be(e){return null!=e?(Ue(this,e),r.updateOffset(this,!0),this):Te(this,"Month")}function We(){function e(e,t){return t.length-e.length}var t,n,r,i,o=[],s=[],a=[];for(t=0;t<12;t++)n=f([2e3,t]),r=ue(this.monthsShort(n,"")),i=ue(this.months(n,"")),o.push(r),s.push(i),a.push(i),a.push(r);o.sort(e),s.sort(e),a.sort(e),this._monthsRegex=new RegExp("^("+a.join("|")+")","i"),this._monthsShortRegex=this._monthsRegex,this._monthsStrictRegex=new RegExp("^("+s.join("|")+")","i"),this._monthsShortStrictRegex=new RegExp("^("+o.join("|")+")","i")}function Ge(e,t,n,r,i,o,s){var a;return e<100&&e>=0?(a=new Date(e+400,t,n,r,i,o,s),isFinite(a.getFullYear())&&a.setFullYear(e)):a=new Date(e,t,n,r,i,o,s),a}function Ve(e){var t,n;return e<100&&e>=0?((n=Array.prototype.slice.call(arguments))[0]=e+400,t=new Date(Date.UTC.apply(null,n)),isFinite(t.getUTCFullYear())&&t.setUTCFullYear(e)):t=new Date(Date.UTC.apply(null,arguments)),t}function Ye(e,t,n){var r=7+t-n;return-(7+Ve(e,0,r).getUTCDay()-t)%7+r-1}function He(e,t,n,r,i){var o,s,a=1+7*(t-1)+(7+n-r)%7+Ye(e,r,i);return a<=0?s=Ce(o=e-1)+a:a>Ce(e)?(o=e+1,s=a-Ce(e)):(o=e,s=a),{year:o,dayOfYear:s}}function ze(e,t,n){var r,i,o=Ye(e.year(),t,n),s=Math.floor((e.dayOfYear()-o-1)/7)+1;return s<1?r=s+qe(i=e.year()-1,t,n):s>qe(e.year(),t,n)?(r=s-qe(e.year(),t,n),i=e.year()+1):(i=e.year(),r=s),{week:r,year:i}}function qe(e,t,n){var r=Ye(e,t,n),i=Ye(e+1,t,n);return(Ce(e)-r+i)/7}D("w",["ww",2],"wo","week"),D("W",["WW",2],"Wo","isoWeek"),ce("w",K,se),ce("ww",K,Y),ce("W",K,se),ce("WW",K,Y),ge(["w","ww","W","WW"],(function(e,t,n,r){t[r.substr(0,1)]=he(e)}));function Ke(e,t){return e.slice(t,7).concat(e.slice(0,t))}D("d",0,"do","day"),D("dd",0,0,(function(e){return this.localeData().weekdaysMin(this,e)})),D("ddd",0,0,(function(e){return this.localeData().weekdaysShort(this,e)})),D("dddd",0,0,(function(e){return this.localeData().weekdays(this,e)})),D("e",0,0,"weekday"),D("E",0,0,"isoWeekday"),ce("d",K),ce("e",K),ce("E",K),ce("dd",(function(e,t){return t.weekdaysMinRegex(e)})),ce("ddd",(function(e,t){return t.weekdaysShortRegex(e)})),ce("dddd",(function(e,t){return t.weekdaysRegex(e)})),ge(["dd","ddd","dddd"],(function(e,t,n,r){var i=n._locale.weekdaysParse(e,r,n._strict);null!=i?t.d=i:p(n).invalidWeekday=e})),ge(["d","e","E"],(function(e,t,n,r){t[r]=he(e)}));var Je="Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),Ze="Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),Xe="Su_Mo_Tu_We_Th_Fr_Sa".split("_"),Qe=oe,et=oe,tt=oe;function nt(e,t,n){var r,i,o,s=e.toLocaleLowerCase();if(!this._weekdaysParse)for(this._weekdaysParse=[],this._shortWeekdaysParse=[],this._minWeekdaysParse=[],r=0;r<7;++r)o=f([2e3,1]).day(r),this._minWeekdaysParse[r]=this.weekdaysMin(o,"").toLocaleLowerCase(),this._shortWeekdaysParse[r]=this.weekdaysShort(o,"").toLocaleLowerCase(),this._weekdaysParse[r]=this.weekdays(o,"").toLocaleLowerCase();return n?"dddd"===t?-1!==(i=$e.call(this._weekdaysParse,s))?i:null:"ddd"===t?-1!==(i=$e.call(this._shortWeekdaysParse,s))?i:null:-1!==(i=$e.call(this._minWeekdaysParse,s))?i:null:"dddd"===t?-1!==(i=$e.call(this._weekdaysParse,s))||-1!==(i=$e.call(this._shortWeekdaysParse,s))||-1!==(i=$e.call(this._minWeekdaysParse,s))?i:null:"ddd"===t?-1!==(i=$e.call(this._shortWeekdaysParse,s))||-1!==(i=$e.call(this._weekdaysParse,s))||-1!==(i=$e.call(this._minWeekdaysParse,s))?i:null:-1!==(i=$e.call(this._minWeekdaysParse,s))||-1!==(i=$e.call(this._weekdaysParse,s))||-1!==(i=$e.call(this._shortWeekdaysParse,s))?i:null}function rt(){function e(e,t){return t.length-e.length}var t,n,r,i,o,s=[],a=[],c=[],l=[];for(t=0;t<7;t++)n=f([2e3,1]).day(t),r=ue(this.weekdaysMin(n,"")),i=ue(this.weekdaysShort(n,"")),o=ue(this.weekdays(n,"")),s.push(r),a.push(i),c.push(o),l.push(r),l.push(i),l.push(o);s.sort(e),a.sort(e),c.sort(e),l.sort(e),this._weekdaysRegex=new RegExp("^("+l.join("|")+")","i"),this._weekdaysShortRegex=this._weekdaysRegex,this._weekdaysMinRegex=this._weekdaysRegex,this._weekdaysStrictRegex=new RegExp("^("+c.join("|")+")","i"),this._weekdaysShortStrictRegex=new RegExp("^("+a.join("|")+")","i"),this._weekdaysMinStrictRegex=new RegExp("^("+s.join("|")+")","i")}function it(){return this.hours()%12||12}function ot(e,t){D(e,0,0,(function(){return this.localeData().meridiem(this.hours(),this.minutes(),t)}))}function st(e,t){return t._meridiemParse}D("H",["HH",2],0,"hour"),D("h",["hh",2],0,it),D("k",["kk",2],0,(function(){return this.hours()||24})),D("hmm",0,0,(function(){return""+it.apply(this)+N(this.minutes(),2)})),D("hmmss",0,0,(function(){return""+it.apply(this)+N(this.minutes(),2)+N(this.seconds(),2)})),D("Hmm",0,0,(function(){return""+this.hours()+N(this.minutes(),2)})),D("Hmmss",0,0,(function(){return""+this.hours()+N(this.minutes(),2)+N(this.seconds(),2)})),ot("a",!0),ot("A",!1),ce("a",st),ce("A",st),ce("H",K,ae),ce("h",K,se),ce("k",K,se),ce("HH",K,Y),ce("hh",K,Y),ce("kk",K,Y),ce("hmm",J),ce("hmmss",Z),ce("Hmm",J),ce("Hmmss",Z),pe(["H","HH"],Se),pe(["k","kk"],(function(e,t){var n=he(e);t[Se]=24===n?0:n})),pe(["a","A"],(function(e,t,n){n._isPm=n._locale.isPM(e),n._meridiem=e})),pe(["h","hh"],(function(e,t,n){t[Se]=he(e),p(n).bigHour=!0})),pe("hmm",(function(e,t,n){var r=e.length-2;t[Se]=he(e.substr(0,r)),t[_e]=he(e.substr(r)),p(n).bigHour=!0})),pe("hmmss",(function(e,t,n){var r=e.length-4,i=e.length-2;t[Se]=he(e.substr(0,r)),t[_e]=he(e.substr(r,2)),t[Ie]=he(e.substr(i)),p(n).bigHour=!0})),pe("Hmm",(function(e,t){var n=e.length-2;t[Se]=he(e.substr(0,n)),t[_e]=he(e.substr(n))})),pe("Hmmss",(function(e,t){var n=e.length-4,r=e.length-2;t[Se]=he(e.substr(0,n)),t[_e]=he(e.substr(n,2)),t[Ie]=he(e.substr(r))}));var at=Ne("Hours",!0);var ct,lt={calendar:{sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"},longDateFormat:{LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A"},invalidDate:"Invalid date",ordinal:"%d",dayOfMonthOrdinalParse:/\d{1,2}/,relativeTime:{future:"in %s",past:"%s ago",s:"a few seconds",ss:"%d seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",w:"a week",ww:"%d weeks",M:"a month",MM:"%d months",y:"a year",yy:"%d years"},months:Pe,monthsShort:De,week:{dow:0,doy:6},weekdays:Je,weekdaysMin:Xe,weekdaysShort:Ze,meridiemParse:/[ap]\.?m?\.?/i},ut={},dt={};function ht(e,t){var n,r=Math.min(e.length,t.length);for(n=0;n<r;n+=1)if(e[n]!==t[n])return n;return r}function ft(e){return e?e.toLowerCase().replace("_","-"):e}function pt(t){var n=null;if(void 0===ut[t]&&e&&e.exports&&function(e){return!(!e||!e.match("^[^/\\\\]*$"))}(t))try{n=ct._abbr,function(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}("./locale/"+t),gt(n)}catch(e){ut[t]=null}return ut[t]}function gt(e,t){var n;return e&&((n=c(t)?yt(e):mt(e,t))?ct=n:"undefined"!=typeof console&&console.warn&&console.warn("Locale "+e+" not found. Did you forget to load it?")),ct._abbr}function mt(e,t){if(null!==t){var n,r=lt;if(t.abbr=e,null!=ut[e])E("defineLocaleOverride","use moment.updateLocale(localeName, config) to change an existing locale. moment.defineLocale(localeName, config) should only be used for creating a new locale See http://momentjs.com/guides/#/warnings/define-locale/ for more info."),r=ut[e]._config;else if(null!=t.parentLocale)if(null!=ut[t.parentLocale])r=ut[t.parentLocale]._config;else{if(null==(n=pt(t.parentLocale)))return dt[t.parentLocale]||(dt[t.parentLocale]=[]),dt[t.parentLocale].push({name:e,config:t}),null;r=n._config}return ut[e]=new O($(r,t)),dt[e]&&dt[e].forEach((function(e){mt(e.name,e.config)})),gt(e),ut[e]}return delete ut[e],null}function yt(e){var t;if(e&&e._locale&&e._locale._abbr&&(e=e._locale._abbr),!e)return ct;if(!i(e)){if(t=pt(e))return t;e=[e]}return function(e){for(var t,n,r,i,o=0;o<e.length;){for(t=(i=ft(e[o]).split("-")).length,n=(n=ft(e[o+1]))?n.split("-"):null;t>0;){if(r=pt(i.slice(0,t).join("-")))return r;if(n&&n.length>=t&&ht(i,n)>=t-1)break;t--}o++}return ct}(e)}function vt(e){var t,n=e._a;return n&&-2===p(e).overflow&&(t=n[be]<0||n[be]>11?be:n[we]<1||n[we]>Me(n[ve],n[be])?we:n[Se]<0||n[Se]>24||24===n[Se]&&(0!==n[_e]||0!==n[Ie]||0!==n[xe])?Se:n[_e]<0||n[_e]>59?_e:n[Ie]<0||n[Ie]>59?Ie:n[xe]<0||n[xe]>999?xe:-1,p(e)._overflowDayOfYear&&(t<ve||t>we)&&(t=we),p(e)._overflowWeeks&&-1===t&&(t=ke),p(e)._overflowWeekday&&-1===t&&(t=Ee),p(e).overflow=t),e}var bt=/^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/,wt=/^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d|))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/,St=/Z|[+-]\d\d(?::?\d\d)?/,_t=[["YYYYYY-MM-DD",/[+-]\d{6}-\d\d-\d\d/],["YYYY-MM-DD",/\d{4}-\d\d-\d\d/],["GGGG-[W]WW-E",/\d{4}-W\d\d-\d/],["GGGG-[W]WW",/\d{4}-W\d\d/,!1],["YYYY-DDD",/\d{4}-\d{3}/],["YYYY-MM",/\d{4}-\d\d/,!1],["YYYYYYMMDD",/[+-]\d{10}/],["YYYYMMDD",/\d{8}/],["GGGG[W]WWE",/\d{4}W\d{3}/],["GGGG[W]WW",/\d{4}W\d{2}/,!1],["YYYYDDD",/\d{7}/],["YYYYMM",/\d{6}/,!1],["YYYY",/\d{4}/,!1]],It=[["HH:mm:ss.SSSS",/\d\d:\d\d:\d\d\.\d+/],["HH:mm:ss,SSSS",/\d\d:\d\d:\d\d,\d+/],["HH:mm:ss",/\d\d:\d\d:\d\d/],["HH:mm",/\d\d:\d\d/],["HHmmss.SSSS",/\d\d\d\d\d\d\.\d+/],["HHmmss,SSSS",/\d\d\d\d\d\d,\d+/],["HHmmss",/\d\d\d\d\d\d/],["HHmm",/\d\d\d\d/],["HH",/\d\d/]],xt=/^\/?Date\((-?\d+)/i,kt=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/,Et={UT:0,GMT:0,EDT:-240,EST:-300,CDT:-300,CST:-360,MDT:-360,MST:-420,PDT:-420,PST:-480};function Ct(e){var t,n,r,i,o,s,a=e._i,c=bt.exec(a)||wt.exec(a),l=_t.length,u=It.length;if(c){for(p(e).iso=!0,t=0,n=l;t<n;t++)if(_t[t][1].exec(c[1])){i=_t[t][0],r=!1!==_t[t][2];break}if(null==i)return void(e._isValid=!1);if(c[3]){for(t=0,n=u;t<n;t++)if(It[t][1].exec(c[3])){o=(c[2]||" ")+It[t][0];break}if(null==o)return void(e._isValid=!1)}if(!r&&null!=o)return void(e._isValid=!1);if(c[4]){if(!St.exec(c[4]))return void(e._isValid=!1);s="Z"}e._f=i+(o||"")+(s||""),Mt(e)}else e._isValid=!1}function $t(e){var t=parseInt(e,10);return t<=49?2e3+t:t<=999?1900+t:t}function Ot(e){var t,n=kt.exec(function(e){return e.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").replace(/^\s\s*/,"").replace(/\s\s*$/,"")}(e._i));if(n){if(t=function(e,t,n,r,i,o){var s=[$t(e),De.indexOf(t),parseInt(n,10),parseInt(r,10),parseInt(i,10)];return o&&s.push(parseInt(o,10)),s}(n[4],n[3],n[2],n[5],n[6],n[7]),!function(e,t,n){return!e||Ze.indexOf(e)===new Date(t[0],t[1],t[2]).getDay()||(p(n).weekdayMismatch=!0,n._isValid=!1,!1)}(n[1],t,e))return;e._a=t,e._tzm=function(e,t,n){if(e)return Et[e];if(t)return 0;var r=parseInt(n,10),i=r%100;return(r-i)/100*60+i}(n[8],n[9],n[10]),e._d=Ve.apply(null,e._a),e._d.setUTCMinutes(e._d.getUTCMinutes()-e._tzm),p(e).rfc2822=!0}else e._isValid=!1}function Nt(e,t,n){return null!=e?e:null!=t?t:n}function Tt(e){var t=new Date(r.now());return e._useUTC?[t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate()]:[t.getFullYear(),t.getMonth(),t.getDate()]}function At(e){var t,n,r,i,o,s=[];if(!e._d){for(r=Tt(e),e._w&&null==e._a[we]&&null==e._a[be]&&function(e){var t,n,r,i,o,s,a,c,l;null!=(t=e._w).GG||null!=t.W||null!=t.E?(o=1,s=4,n=Nt(t.GG,e._a[ve],ze(jt(),1,4).year),r=Nt(t.W,1),((i=Nt(t.E,1))<1||i>7)&&(c=!0)):(o=e._locale._week.dow,s=e._locale._week.doy,l=ze(jt(),o,s),n=Nt(t.gg,e._a[ve],l.year),r=Nt(t.w,l.week),null!=t.d?((i=t.d)<0||i>6)&&(c=!0):null!=t.e?(i=t.e+o,(t.e<0||t.e>6)&&(c=!0)):i=o),r<1||r>qe(n,o,s)?p(e)._overflowWeeks=!0:null!=c?p(e)._overflowWeekday=!0:(a=He(n,r,i,o,s),e._a[ve]=a.year,e._dayOfYear=a.dayOfYear)}(e),null!=e._dayOfYear&&(o=Nt(e._a[ve],r[ve]),(e._dayOfYear>Ce(o)||0===e._dayOfYear)&&(p(e)._overflowDayOfYear=!0),n=Ve(o,0,e._dayOfYear),e._a[be]=n.getUTCMonth(),e._a[we]=n.getUTCDate()),t=0;t<3&&null==e._a[t];++t)e._a[t]=s[t]=r[t];for(;t<7;t++)e._a[t]=s[t]=null==e._a[t]?2===t?1:0:e._a[t];24===e._a[Se]&&0===e._a[_e]&&0===e._a[Ie]&&0===e._a[xe]&&(e._nextDay=!0,e._a[Se]=0),e._d=(e._useUTC?Ve:Ge).apply(null,s),i=e._useUTC?e._d.getUTCDay():e._d.getDay(),null!=e._tzm&&e._d.setUTCMinutes(e._d.getUTCMinutes()-e._tzm),e._nextDay&&(e._a[Se]=24),e._w&&void 0!==e._w.d&&e._w.d!==i&&(p(e).weekdayMismatch=!0)}}function Mt(e){if(e._f!==r.ISO_8601)if(e._f!==r.RFC_2822){e._a=[],p(e).empty=!0;var t,n,i,o,s,a,c,l=""+e._i,u=l.length,d=0;for(c=(i=L(e._f,e._locale).match(T)||[]).length,t=0;t<c;t++)o=i[t],(n=(l.match(le(o,e))||[])[0])&&((s=l.substr(0,l.indexOf(n))).length>0&&p(e).unusedInput.push(s),l=l.slice(l.indexOf(n)+n.length),d+=n.length),P[o]?(n?p(e).empty=!1:p(e).unusedTokens.push(o),me(o,n,e)):e._strict&&!n&&p(e).unusedTokens.push(o);p(e).charsLeftOver=u-d,l.length>0&&p(e).unusedInput.push(l),e._a[Se]<=12&&!0===p(e).bigHour&&e._a[Se]>0&&(p(e).bigHour=void 0),p(e).parsedDateParts=e._a.slice(0),p(e).meridiem=e._meridiem,e._a[Se]=function(e,t,n){var r;return null==n?t:null!=e.meridiemHour?e.meridiemHour(t,n):null!=e.isPM?((r=e.isPM(n))&&t<12&&(t+=12),r||12!==t||(t=0),t):t}(e._locale,e._a[Se],e._meridiem),null!==(a=p(e).era)&&(e._a[ve]=e._locale.erasConvertYear(a,e._a[ve])),At(e),vt(e)}else Ot(e);else Ct(e)}function Pt(e){var t=e._i,n=e._f;return e._locale=e._locale||yt(e._l),null===t||void 0===n&&""===t?m({nullInput:!0}):("string"==typeof t&&(e._i=t=e._locale.preparse(t)),S(t)?new w(vt(t)):(u(t)?e._d=t:i(n)?function(e){var t,n,r,i,o,s,a=!1,c=e._f.length;if(0===c)return p(e).invalidFormat=!0,void(e._d=new Date(NaN));for(i=0;i<c;i++)o=0,s=!1,t=b({},e),null!=e._useUTC&&(t._useUTC=e._useUTC),t._f=e._f[i],Mt(t),g(t)&&(s=!0),o+=p(t).charsLeftOver,o+=10*p(t).unusedTokens.length,p(t).score=o,a?o<r&&(r=o,n=t):(null==r||o<r||s)&&(r=o,n=t,s&&(a=!0));h(e,n||t)}(e):n?Mt(e):function(e){var t=e._i;c(t)?e._d=new Date(r.now()):u(t)?e._d=new Date(t.valueOf()):"string"==typeof t?function(e){var t=xt.exec(e._i);null===t?(Ct(e),!1===e._isValid&&(delete e._isValid,Ot(e),!1===e._isValid&&(delete e._isValid,e._strict?e._isValid=!1:r.createFromInputFallback(e)))):e._d=new Date(+t[1])}(e):i(t)?(e._a=d(t.slice(0),(function(e){return parseInt(e,10)})),At(e)):o(t)?function(e){if(!e._d){var t=B(e._i),n=void 0===t.day?t.date:t.day;e._a=d([t.year,t.month,n,t.hour,t.minute,t.second,t.millisecond],(function(e){return e&&parseInt(e,10)})),At(e)}}(e):l(t)?e._d=new Date(t):r.createFromInputFallback(e)}(e),g(e)||(e._d=null),e))}function Dt(e,t,n,r,s){var c={};return!0!==t&&!1!==t||(r=t,t=void 0),!0!==n&&!1!==n||(r=n,n=void 0),(o(e)&&a(e)||i(e)&&0===e.length)&&(e=void 0),c._isAMomentObject=!0,c._useUTC=c._isUTC=s,c._l=n,c._i=e,c._f=t,c._strict=r,function(e){var t=new w(vt(Pt(e)));return t._nextDay&&(t.add(1,"d"),t._nextDay=void 0),t}(c)}function jt(e,t,n,r){return Dt(e,t,n,r,!1)}r.createFromInputFallback=I("value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.",(function(e){e._d=new Date(e._i+(e._useUTC?" UTC":""))})),r.ISO_8601=function(){},r.RFC_2822=function(){};var Rt=I("moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/",(function(){var e=jt.apply(null,arguments);return this.isValid()&&e.isValid()?e<this?this:e:m()})),Lt=I("moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/",(function(){var e=jt.apply(null,arguments);return this.isValid()&&e.isValid()?e>this?this:e:m()}));function Ft(e,t){var n,r;if(1===t.length&&i(t[0])&&(t=t[0]),!t.length)return jt();for(n=t[0],r=1;r<t.length;++r)t[r].isValid()&&!t[r][e](n)||(n=t[r]);return n}var Ut=["year","quarter","month","week","day","hour","minute","second","millisecond"];function Bt(e){var t,n,r=!1,i=Ut.length;for(t in e)if(s(e,t)&&(-1===$e.call(Ut,t)||null!=e[t]&&isNaN(e[t])))return!1;for(n=0;n<i;++n)if(e[Ut[n]]){if(r)return!1;parseFloat(e[Ut[n]])!==he(e[Ut[n]])&&(r=!0)}return!0}function Wt(e){var t=B(e),n=t.year||0,r=t.quarter||0,i=t.month||0,o=t.week||t.isoWeek||0,s=t.day||0,a=t.hour||0,c=t.minute||0,l=t.second||0,u=t.millisecond||0;this._isValid=Bt(t),this._milliseconds=+u+1e3*l+6e4*c+1e3*a*60*60,this._days=+s+7*o,this._months=+i+3*r+12*n,this._data={},this._locale=yt(),this._bubble()}function Gt(e){return e instanceof Wt}function Vt(e){return e<0?-1*Math.round(-1*e):Math.round(e)}function Yt(e,t){D(e,0,0,(function(){var e=this.utcOffset(),n="+";return e<0&&(e=-e,n="-"),n+N(~~(e/60),2)+t+N(~~e%60,2)}))}Yt("Z",":"),Yt("ZZ",""),ce("Z",ie),ce("ZZ",ie),pe(["Z","ZZ"],(function(e,t,n){n._useUTC=!0,n._tzm=zt(ie,e)}));var Ht=/([\+\-]|\d\d)/gi;function zt(e,t){var n,r,i=(t||"").match(e);return null===i?null:0===(r=60*(n=((i[i.length-1]||[])+"").match(Ht)||["-",0,0])[1]+he(n[2]))?0:"+"===n[0]?r:-r}function qt(e,t){var n,i;return t._isUTC?(n=t.clone(),i=(S(e)||u(e)?e.valueOf():jt(e).valueOf())-n.valueOf(),n._d.setTime(n._d.valueOf()+i),r.updateOffset(n,!1),n):jt(e).local()}function Kt(e){return-Math.round(e._d.getTimezoneOffset())}function Jt(){return!!this.isValid()&&this._isUTC&&0===this._offset}r.updateOffset=function(){};var Zt=/^(-|\+)?(?:(\d*)[. ])?(\d+):(\d+)(?::(\d+)(\.\d*)?)?$/,Xt=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;function Qt(e,t){var n,r,i,o=e,a=null;return Gt(e)?o={ms:e._milliseconds,d:e._days,M:e._months}:l(e)||!isNaN(+e)?(o={},t?o[t]=+e:o.milliseconds=+e):(a=Zt.exec(e))?(n="-"===a[1]?-1:1,o={y:0,d:he(a[we])*n,h:he(a[Se])*n,m:he(a[_e])*n,s:he(a[Ie])*n,ms:he(Vt(1e3*a[xe]))*n}):(a=Xt.exec(e))?(n="-"===a[1]?-1:1,o={y:en(a[2],n),M:en(a[3],n),w:en(a[4],n),d:en(a[5],n),h:en(a[6],n),m:en(a[7],n),s:en(a[8],n)}):null==o?o={}:"object"==typeof o&&("from"in o||"to"in o)&&(i=function(e,t){var n;return e.isValid()&&t.isValid()?(t=qt(t,e),e.isBefore(t)?n=tn(e,t):((n=tn(t,e)).milliseconds=-n.milliseconds,n.months=-n.months),n):{milliseconds:0,months:0}}(jt(o.from),jt(o.to)),(o={}).ms=i.milliseconds,o.M=i.months),r=new Wt(o),Gt(e)&&s(e,"_locale")&&(r._locale=e._locale),Gt(e)&&s(e,"_isValid")&&(r._isValid=e._isValid),r}function en(e,t){var n=e&&parseFloat(e.replace(",","."));return(isNaN(n)?0:n)*t}function tn(e,t){var n={};return n.months=t.month()-e.month()+12*(t.year()-e.year()),e.clone().add(n.months,"M").isAfter(t)&&--n.months,n.milliseconds=+t-+e.clone().add(n.months,"M"),n}function nn(e,t){return function(n,r){var i;return null===r||isNaN(+r)||(E(t,"moment()."+t+"(period, number) is deprecated. Please use moment()."+t+"(number, period). See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info."),i=n,n=r,r=i),rn(this,Qt(n,r),e),this}}function rn(e,t,n,i){var o=t._milliseconds,s=Vt(t._days),a=Vt(t._months);e.isValid()&&(i=null==i||i,a&&Ue(e,Te(e,"Month")+a*n),s&&Ae(e,"Date",Te(e,"Date")+s*n),o&&e._d.setTime(e._d.valueOf()+o*n),i&&r.updateOffset(e,s||a))}Qt.fn=Wt.prototype,Qt.invalid=function(){return Qt(NaN)};var on=nn(1,"add"),sn=nn(-1,"subtract");function an(e){return"string"==typeof e||e instanceof String}function cn(e){return S(e)||u(e)||an(e)||l(e)||function(e){var t=i(e),n=!1;return t&&(n=0===e.filter((function(t){return!l(t)&&an(e)})).length),t&&n}(e)||function(e){var t,n,r=o(e)&&!a(e),i=!1,c=["years","year","y","months","month","M","days","day","d","dates","date","D","hours","hour","h","minutes","minute","m","seconds","second","s","milliseconds","millisecond","ms"],l=c.length;for(t=0;t<l;t+=1)n=c[t],i=i||s(e,n);return r&&i}(e)||null==e}function ln(e){var t,n=o(e)&&!a(e),r=!1,i=["sameDay","nextDay","lastDay","nextWeek","lastWeek","sameElse"];for(t=0;t<i.length;t+=1)r=r||s(e,i[t]);return n&&r}function un(e,t){if(e.date()<t.date())return-un(t,e);var n=12*(t.year()-e.year())+(t.month()-e.month()),r=e.clone().add(n,"months");return-(n+(t-r<0?(t-r)/(r-e.clone().add(n-1,"months")):(t-r)/(e.clone().add(n+1,"months")-r)))||0}function dn(e){var t;return void 0===e?this._locale._abbr:(null!=(t=yt(e))&&(this._locale=t),this)}r.defaultFormat="YYYY-MM-DDTHH:mm:ssZ",r.defaultFormatUtc="YYYY-MM-DDTHH:mm:ss[Z]";var hn=I("moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.",(function(e){return void 0===e?this.localeData():this.locale(e)}));function fn(){return this._locale}var pn=1e3,gn=6e4,mn=60*gn,yn=3506328*mn;function vn(e,t){return(e%t+t)%t}function bn(e,t,n){return e<100&&e>=0?new Date(e+400,t,n)-yn:new Date(e,t,n).valueOf()}function wn(e,t,n){return e<100&&e>=0?Date.UTC(e+400,t,n)-yn:Date.UTC(e,t,n)}function Sn(e,t){return t.erasAbbrRegex(e)}function _n(){var e,t,n,r,i,o=[],s=[],a=[],c=[],l=this.eras();for(e=0,t=l.length;e<t;++e)n=ue(l[e].name),r=ue(l[e].abbr),i=ue(l[e].narrow),s.push(n),o.push(r),a.push(i),c.push(n),c.push(r),c.push(i);this._erasRegex=new RegExp("^("+c.join("|")+")","i"),this._erasNameRegex=new RegExp("^("+s.join("|")+")","i"),this._erasAbbrRegex=new RegExp("^("+o.join("|")+")","i"),this._erasNarrowRegex=new RegExp("^("+a.join("|")+")","i")}function In(e,t){D(0,[e,e.length],0,t)}function xn(e,t,n,r,i){var o;return null==e?ze(this,r,i).year:(t>(o=qe(e,r,i))&&(t=o),kn.call(this,e,t,n,r,i))}function kn(e,t,n,r,i){var o=He(e,t,n,r,i),s=Ve(o.year,0,o.dayOfYear);return this.year(s.getUTCFullYear()),this.month(s.getUTCMonth()),this.date(s.getUTCDate()),this}D("N",0,0,"eraAbbr"),D("NN",0,0,"eraAbbr"),D("NNN",0,0,"eraAbbr"),D("NNNN",0,0,"eraName"),D("NNNNN",0,0,"eraNarrow"),D("y",["y",1],"yo","eraYear"),D("y",["yy",2],0,"eraYear"),D("y",["yyy",3],0,"eraYear"),D("y",["yyyy",4],0,"eraYear"),ce("N",Sn),ce("NN",Sn),ce("NNN",Sn),ce("NNNN",(function(e,t){return t.erasNameRegex(e)})),ce("NNNNN",(function(e,t){return t.erasNarrowRegex(e)})),pe(["N","NN","NNN","NNNN","NNNNN"],(function(e,t,n,r){var i=n._locale.erasParse(e,r,n._strict);i?p(n).era=i:p(n).invalidEra=e})),ce("y",te),ce("yy",te),ce("yyy",te),ce("yyyy",te),ce("yo",(function(e,t){return t._eraYearOrdinalRegex||te})),pe(["y","yy","yyy","yyyy"],ve),pe(["yo"],(function(e,t,n){var r;n._locale._eraYearOrdinalRegex&&(r=e.match(n._locale._eraYearOrdinalRegex)),n._locale.eraYearOrdinalParse?t[ve]=n._locale.eraYearOrdinalParse(e,r):t[ve]=parseInt(e,10)})),D(0,["gg",2],0,(function(){return this.weekYear()%100})),D(0,["GG",2],0,(function(){return this.isoWeekYear()%100})),In("gggg","weekYear"),In("ggggg","weekYear"),In("GGGG","isoWeekYear"),In("GGGGG","isoWeekYear"),ce("G",ne),ce("g",ne),ce("GG",K,Y),ce("gg",K,Y),ce("GGGG",Q,z),ce("gggg",Q,z),ce("GGGGG",ee,q),ce("ggggg",ee,q),ge(["gggg","ggggg","GGGG","GGGGG"],(function(e,t,n,r){t[r.substr(0,2)]=he(e)})),ge(["gg","GG"],(function(e,t,n,i){t[i]=r.parseTwoDigitYear(e)})),D("Q",0,"Qo","quarter"),ce("Q",V),pe("Q",(function(e,t){t[be]=3*(he(e)-1)})),D("D",["DD",2],"Do","date"),ce("D",K,se),ce("DD",K,Y),ce("Do",(function(e,t){return e?t._dayOfMonthOrdinalParse||t._ordinalParse:t._dayOfMonthOrdinalParseLenient})),pe(["D","DD"],we),pe("Do",(function(e,t){t[we]=he(e.match(K)[0])}));var En=Ne("Date",!0);D("DDD",["DDDD",3],"DDDo","dayOfYear"),ce("DDD",X),ce("DDDD",H),pe(["DDD","DDDD"],(function(e,t,n){n._dayOfYear=he(e)})),D("m",["mm",2],0,"minute"),ce("m",K,ae),ce("mm",K,Y),pe(["m","mm"],_e);var Cn=Ne("Minutes",!1);D("s",["ss",2],0,"second"),ce("s",K,ae),ce("ss",K,Y),pe(["s","ss"],Ie);var $n,On,Nn=Ne("Seconds",!1);for(D("S",0,0,(function(){return~~(this.millisecond()/100)})),D(0,["SS",2],0,(function(){return~~(this.millisecond()/10)})),D(0,["SSS",3],0,"millisecond"),D(0,["SSSS",4],0,(function(){return 10*this.millisecond()})),D(0,["SSSSS",5],0,(function(){return 100*this.millisecond()})),D(0,["SSSSSS",6],0,(function(){return 1e3*this.millisecond()})),D(0,["SSSSSSS",7],0,(function(){return 1e4*this.millisecond()})),D(0,["SSSSSSSS",8],0,(function(){return 1e5*this.millisecond()})),D(0,["SSSSSSSSS",9],0,(function(){return 1e6*this.millisecond()})),ce("S",X,V),ce("SS",X,Y),ce("SSS",X,H),$n="SSSS";$n.length<=9;$n+="S")ce($n,te);function Tn(e,t){t[xe]=he(1e3*("0."+e))}for($n="S";$n.length<=9;$n+="S")pe($n,Tn);On=Ne("Milliseconds",!1),D("z",0,0,"zoneAbbr"),D("zz",0,0,"zoneName");var An=w.prototype;function Mn(e){return e}An.add=on,An.calendar=function(e,t){1===arguments.length&&(arguments[0]?cn(arguments[0])?(e=arguments[0],t=void 0):ln(arguments[0])&&(t=arguments[0],e=void 0):(e=void 0,t=void 0));var n=e||jt(),i=qt(n,this).startOf("day"),o=r.calendarFormat(this,i)||"sameElse",s=t&&(C(t[o])?t[o].call(this,n):t[o]);return this.format(s||this.localeData().calendar(o,this,jt(n)))},An.clone=function(){return new w(this)},An.diff=function(e,t,n){var r,i,o;if(!this.isValid())return NaN;if(!(r=qt(e,this)).isValid())return NaN;switch(i=6e4*(r.utcOffset()-this.utcOffset()),t=U(t)){case"year":o=un(this,r)/12;break;case"month":o=un(this,r);break;case"quarter":o=un(this,r)/3;break;case"second":o=(this-r)/1e3;break;case"minute":o=(this-r)/6e4;break;case"hour":o=(this-r)/36e5;break;case"day":o=(this-r-i)/864e5;break;case"week":o=(this-r-i)/6048e5;break;default:o=this-r}return n?o:de(o)},An.endOf=function(e){var t,n;if(void 0===(e=U(e))||"millisecond"===e||!this.isValid())return this;switch(n=this._isUTC?wn:bn,e){case"year":t=n(this.year()+1,0,1)-1;break;case"quarter":t=n(this.year(),this.month()-this.month()%3+3,1)-1;break;case"month":t=n(this.year(),this.month()+1,1)-1;break;case"week":t=n(this.year(),this.month(),this.date()-this.weekday()+7)-1;break;case"isoWeek":t=n(this.year(),this.month(),this.date()-(this.isoWeekday()-1)+7)-1;break;case"day":case"date":t=n(this.year(),this.month(),this.date()+1)-1;break;case"hour":t=this._d.valueOf(),t+=mn-vn(t+(this._isUTC?0:this.utcOffset()*gn),mn)-1;break;case"minute":t=this._d.valueOf(),t+=gn-vn(t,gn)-1;break;case"second":t=this._d.valueOf(),t+=pn-vn(t,pn)-1}return this._d.setTime(t),r.updateOffset(this,!0),this},An.format=function(e){e||(e=this.isUtc()?r.defaultFormatUtc:r.defaultFormat);var t=R(this,e);return this.localeData().postformat(t)},An.from=function(e,t){return this.isValid()&&(S(e)&&e.isValid()||jt(e).isValid())?Qt({to:this,from:e}).locale(this.locale()).humanize(!t):this.localeData().invalidDate()},An.fromNow=function(e){return this.from(jt(),e)},An.to=function(e,t){return this.isValid()&&(S(e)&&e.isValid()||jt(e).isValid())?Qt({from:this,to:e}).locale(this.locale()).humanize(!t):this.localeData().invalidDate()},An.toNow=function(e){return this.to(jt(),e)},An.get=function(e){return C(this[e=U(e)])?this[e]():this},An.invalidAt=function(){return p(this).overflow},An.isAfter=function(e,t){var n=S(e)?e:jt(e);return!(!this.isValid()||!n.isValid())&&("millisecond"===(t=U(t)||"millisecond")?this.valueOf()>n.valueOf():n.valueOf()<this.clone().startOf(t).valueOf())},An.isBefore=function(e,t){var n=S(e)?e:jt(e);return!(!this.isValid()||!n.isValid())&&("millisecond"===(t=U(t)||"millisecond")?this.valueOf()<n.valueOf():this.clone().endOf(t).valueOf()<n.valueOf())},An.isBetween=function(e,t,n,r){var i=S(e)?e:jt(e),o=S(t)?t:jt(t);return!!(this.isValid()&&i.isValid()&&o.isValid())&&("("===(r=r||"()")[0]?this.isAfter(i,n):!this.isBefore(i,n))&&(")"===r[1]?this.isBefore(o,n):!this.isAfter(o,n))},An.isSame=function(e,t){var n,r=S(e)?e:jt(e);return!(!this.isValid()||!r.isValid())&&("millisecond"===(t=U(t)||"millisecond")?this.valueOf()===r.valueOf():(n=r.valueOf(),this.clone().startOf(t).valueOf()<=n&&n<=this.clone().endOf(t).valueOf()))},An.isSameOrAfter=function(e,t){return this.isSame(e,t)||this.isAfter(e,t)},An.isSameOrBefore=function(e,t){return this.isSame(e,t)||this.isBefore(e,t)},An.isValid=function(){return g(this)},An.lang=hn,An.locale=dn,An.localeData=fn,An.max=Lt,An.min=Rt,An.parsingFlags=function(){return h({},p(this))},An.set=function(e,t){if("object"==typeof e){var n,r=function(e){var t,n=[];for(t in e)s(e,t)&&n.push({unit:t,priority:W[t]});return n.sort((function(e,t){return e.priority-t.priority})),n}(e=B(e)),i=r.length;for(n=0;n<i;n++)this[r[n].unit](e[r[n].unit])}else if(C(this[e=U(e)]))return this[e](t);return this},An.startOf=function(e){var t,n;if(void 0===(e=U(e))||"millisecond"===e||!this.isValid())return this;switch(n=this._isUTC?wn:bn,e){case"year":t=n(this.year(),0,1);break;case"quarter":t=n(this.year(),this.month()-this.month()%3,1);break;case"month":t=n(this.year(),this.month(),1);break;case"week":t=n(this.year(),this.month(),this.date()-this.weekday());break;case"isoWeek":t=n(this.year(),this.month(),this.date()-(this.isoWeekday()-1));break;case"day":case"date":t=n(this.year(),this.month(),this.date());break;case"hour":t=this._d.valueOf(),t-=vn(t+(this._isUTC?0:this.utcOffset()*gn),mn);break;case"minute":t=this._d.valueOf(),t-=vn(t,gn);break;case"second":t=this._d.valueOf(),t-=vn(t,pn)}return this._d.setTime(t),r.updateOffset(this,!0),this},An.subtract=sn,An.toArray=function(){var e=this;return[e.year(),e.month(),e.date(),e.hour(),e.minute(),e.second(),e.millisecond()]},An.toObject=function(){var e=this;return{years:e.year(),months:e.month(),date:e.date(),hours:e.hours(),minutes:e.minutes(),seconds:e.seconds(),milliseconds:e.milliseconds()}},An.toDate=function(){return new Date(this.valueOf())},An.toISOString=function(e){if(!this.isValid())return null;var t=!0!==e,n=t?this.clone().utc():this;return n.year()<0||n.year()>9999?R(n,t?"YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]":"YYYYYY-MM-DD[T]HH:mm:ss.SSSZ"):C(Date.prototype.toISOString)?t?this.toDate().toISOString():new Date(this.valueOf()+60*this.utcOffset()*1e3).toISOString().replace("Z",R(n,"Z")):R(n,t?"YYYY-MM-DD[T]HH:mm:ss.SSS[Z]":"YYYY-MM-DD[T]HH:mm:ss.SSSZ")},An.inspect=function(){if(!this.isValid())return"moment.invalid(/* "+this._i+" */)";var e,t,n,r="moment",i="";return this.isLocal()||(r=0===this.utcOffset()?"moment.utc":"moment.parseZone",i="Z"),e="["+r+'("]',t=0<=this.year()&&this.year()<=9999?"YYYY":"YYYYYY",n=i+'[")]',this.format(e+t+"-MM-DD[T]HH:mm:ss.SSS"+n)},"undefined"!=typeof Symbol&&null!=Symbol.for&&(An[Symbol.for("nodejs.util.inspect.custom")]=function(){return"Moment<"+this.format()+">"}),An.toJSON=function(){return this.isValid()?this.toISOString():null},An.toString=function(){return this.clone().locale("en").format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ")},An.unix=function(){return Math.floor(this.valueOf()/1e3)},An.valueOf=function(){return this._d.valueOf()-6e4*(this._offset||0)},An.creationData=function(){return{input:this._i,format:this._f,locale:this._locale,isUTC:this._isUTC,strict:this._strict}},An.eraName=function(){var e,t,n,r=this.localeData().eras();for(e=0,t=r.length;e<t;++e){if(n=this.clone().startOf("day").valueOf(),r[e].since<=n&&n<=r[e].until)return r[e].name;if(r[e].until<=n&&n<=r[e].since)return r[e].name}return""},An.eraNarrow=function(){var e,t,n,r=this.localeData().eras();for(e=0,t=r.length;e<t;++e){if(n=this.clone().startOf("day").valueOf(),r[e].since<=n&&n<=r[e].until)return r[e].narrow;if(r[e].until<=n&&n<=r[e].since)return r[e].narrow}return""},An.eraAbbr=function(){var e,t,n,r=this.localeData().eras();for(e=0,t=r.length;e<t;++e){if(n=this.clone().startOf("day").valueOf(),r[e].since<=n&&n<=r[e].until)return r[e].abbr;if(r[e].until<=n&&n<=r[e].since)return r[e].abbr}return""},An.eraYear=function(){var e,t,n,i,o=this.localeData().eras();for(e=0,t=o.length;e<t;++e)if(n=o[e].since<=o[e].until?1:-1,i=this.clone().startOf("day").valueOf(),o[e].since<=i&&i<=o[e].until||o[e].until<=i&&i<=o[e].since)return(this.year()-r(o[e].since).year())*n+o[e].offset;return this.year()},An.year=Oe,An.isLeapYear=function(){return ye(this.year())},An.weekYear=function(e){return xn.call(this,e,this.week(),this.weekday()+this.localeData()._week.dow,this.localeData()._week.dow,this.localeData()._week.doy)},An.isoWeekYear=function(e){return xn.call(this,e,this.isoWeek(),this.isoWeekday(),1,4)},An.quarter=An.quarters=function(e){return null==e?Math.ceil((this.month()+1)/3):this.month(3*(e-1)+this.month()%3)},An.month=Be,An.daysInMonth=function(){return Me(this.year(),this.month())},An.week=An.weeks=function(e){var t=this.localeData().week(this);return null==e?t:this.add(7*(e-t),"d")},An.isoWeek=An.isoWeeks=function(e){var t=ze(this,1,4).week;return null==e?t:this.add(7*(e-t),"d")},An.weeksInYear=function(){var e=this.localeData()._week;return qe(this.year(),e.dow,e.doy)},An.weeksInWeekYear=function(){var e=this.localeData()._week;return qe(this.weekYear(),e.dow,e.doy)},An.isoWeeksInYear=function(){return qe(this.year(),1,4)},An.isoWeeksInISOWeekYear=function(){return qe(this.isoWeekYear(),1,4)},An.date=En,An.day=An.days=function(e){if(!this.isValid())return null!=e?this:NaN;var t=Te(this,"Day");return null!=e?(e=function(e,t){return"string"!=typeof e?e:isNaN(e)?"number"==typeof(e=t.weekdaysParse(e))?e:null:parseInt(e,10)}(e,this.localeData()),this.add(e-t,"d")):t},An.weekday=function(e){if(!this.isValid())return null!=e?this:NaN;var t=(this.day()+7-this.localeData()._week.dow)%7;return null==e?t:this.add(e-t,"d")},An.isoWeekday=function(e){if(!this.isValid())return null!=e?this:NaN;if(null!=e){var t=function(e,t){return"string"==typeof e?t.weekdaysParse(e)%7||7:isNaN(e)?null:e}(e,this.localeData());return this.day(this.day()%7?t:t-7)}return this.day()||7},An.dayOfYear=function(e){var t=Math.round((this.clone().startOf("day")-this.clone().startOf("year"))/864e5)+1;return null==e?t:this.add(e-t,"d")},An.hour=An.hours=at,An.minute=An.minutes=Cn,An.second=An.seconds=Nn,An.millisecond=An.milliseconds=On,An.utcOffset=function(e,t,n){var i,o=this._offset||0;if(!this.isValid())return null!=e?this:NaN;if(null!=e){if("string"==typeof e){if(null===(e=zt(ie,e)))return this}else Math.abs(e)<16&&!n&&(e*=60);return!this._isUTC&&t&&(i=Kt(this)),this._offset=e,this._isUTC=!0,null!=i&&this.add(i,"m"),o!==e&&(!t||this._changeInProgress?rn(this,Qt(e-o,"m"),1,!1):this._changeInProgress||(this._changeInProgress=!0,r.updateOffset(this,!0),this._changeInProgress=null)),this}return this._isUTC?o:Kt(this)},An.utc=function(e){return this.utcOffset(0,e)},An.local=function(e){return this._isUTC&&(this.utcOffset(0,e),this._isUTC=!1,e&&this.subtract(Kt(this),"m")),this},An.parseZone=function(){if(null!=this._tzm)this.utcOffset(this._tzm,!1,!0);else if("string"==typeof this._i){var e=zt(re,this._i);null!=e?this.utcOffset(e):this.utcOffset(0,!0)}return this},An.hasAlignedHourOffset=function(e){return!!this.isValid()&&(e=e?jt(e).utcOffset():0,(this.utcOffset()-e)%60==0)},An.isDST=function(){return this.utcOffset()>this.clone().month(0).utcOffset()||this.utcOffset()>this.clone().month(5).utcOffset()},An.isLocal=function(){return!!this.isValid()&&!this._isUTC},An.isUtcOffset=function(){return!!this.isValid()&&this._isUTC},An.isUtc=Jt,An.isUTC=Jt,An.zoneAbbr=function(){return this._isUTC?"UTC":""},An.zoneName=function(){return this._isUTC?"Coordinated Universal Time":""},An.dates=I("dates accessor is deprecated. Use date instead.",En),An.months=I("months accessor is deprecated. Use month instead",Be),An.years=I("years accessor is deprecated. Use year instead",Oe),An.zone=I("moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/",(function(e,t){return null!=e?("string"!=typeof e&&(e=-e),this.utcOffset(e,t),this):-this.utcOffset()})),An.isDSTShifted=I("isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information",(function(){if(!c(this._isDSTShifted))return this._isDSTShifted;var e,t={};return b(t,this),(t=Pt(t))._a?(e=t._isUTC?f(t._a):jt(t._a),this._isDSTShifted=this.isValid()&&function(e,t){var n,r=Math.min(e.length,t.length),i=Math.abs(e.length-t.length),o=0;for(n=0;n<r;n++)he(e[n])!==he(t[n])&&o++;return o+i}(t._a,e.toArray())>0):this._isDSTShifted=!1,this._isDSTShifted}));var Pn=O.prototype;function Dn(e,t,n,r){var i=yt(),o=f().set(r,t);return i[n](o,e)}function jn(e,t,n){if(l(e)&&(t=e,e=void 0),e=e||"",null!=t)return Dn(e,t,n,"month");var r,i=[];for(r=0;r<12;r++)i[r]=Dn(e,r,n,"month");return i}function Rn(e,t,n,r){"boolean"==typeof e?(l(t)&&(n=t,t=void 0),t=t||""):(n=t=e,e=!1,l(t)&&(n=t,t=void 0),t=t||"");var i,o=yt(),s=e?o._week.dow:0,a=[];if(null!=n)return Dn(t,(n+s)%7,r,"day");for(i=0;i<7;i++)a[i]=Dn(t,(i+s)%7,r,"day");return a}Pn.calendar=function(e,t,n){var r=this._calendar[e]||this._calendar.sameElse;return C(r)?r.call(t,n):r},Pn.longDateFormat=function(e){var t=this._longDateFormat[e],n=this._longDateFormat[e.toUpperCase()];return t||!n?t:(this._longDateFormat[e]=n.match(T).map((function(e){return"MMMM"===e||"MM"===e||"DD"===e||"dddd"===e?e.slice(1):e})).join(""),this._longDateFormat[e])},Pn.invalidDate=function(){return this._invalidDate},Pn.ordinal=function(e){return this._ordinal.replace("%d",e)},Pn.preparse=Mn,Pn.postformat=Mn,Pn.relativeTime=function(e,t,n,r){var i=this._relativeTime[n];return C(i)?i(e,t,n,r):i.replace(/%d/i,e)},Pn.pastFuture=function(e,t){var n=this._relativeTime[e>0?"future":"past"];return C(n)?n(t):n.replace(/%s/i,t)},Pn.set=function(e){var t,n;for(n in e)s(e,n)&&(C(t=e[n])?this[n]=t:this["_"+n]=t);this._config=e,this._dayOfMonthOrdinalParseLenient=new RegExp((this._dayOfMonthOrdinalParse.source||this._ordinalParse.source)+"|"+/\d{1,2}/.source)},Pn.eras=function(){var e,t,n,i=this._eras||yt("en")._eras;for(e=0,t=i.length;e<t;++e)switch("string"==typeof i[e].since&&(n=r(i[e].since).startOf("day"),i[e].since=n.valueOf()),typeof i[e].until){case"undefined":i[e].until=1/0;break;case"string":n=r(i[e].until).startOf("day").valueOf(),i[e].until=n.valueOf()}return i},Pn.erasParse=function(e,t,n){var r,i,o,s,a,c=this.eras();for(e=e.toUpperCase(),r=0,i=c.length;r<i;++r)if(o=c[r].name.toUpperCase(),s=c[r].abbr.toUpperCase(),a=c[r].narrow.toUpperCase(),n)switch(t){case"N":case"NN":case"NNN":if(s===e)return c[r];break;case"NNNN":if(o===e)return c[r];break;case"NNNNN":if(a===e)return c[r]}else if([o,s,a].indexOf(e)>=0)return c[r]},Pn.erasConvertYear=function(e,t){var n=e.since<=e.until?1:-1;return void 0===t?r(e.since).year():r(e.since).year()+(t-e.offset)*n},Pn.erasAbbrRegex=function(e){return s(this,"_erasAbbrRegex")||_n.call(this),e?this._erasAbbrRegex:this._erasRegex},Pn.erasNameRegex=function(e){return s(this,"_erasNameRegex")||_n.call(this),e?this._erasNameRegex:this._erasRegex},Pn.erasNarrowRegex=function(e){return s(this,"_erasNarrowRegex")||_n.call(this),e?this._erasNarrowRegex:this._erasRegex},Pn.months=function(e,t){return e?i(this._months)?this._months[e.month()]:this._months[(this._months.isFormat||je).test(t)?"format":"standalone"][e.month()]:i(this._months)?this._months:this._months.standalone},Pn.monthsShort=function(e,t){return e?i(this._monthsShort)?this._monthsShort[e.month()]:this._monthsShort[je.test(t)?"format":"standalone"][e.month()]:i(this._monthsShort)?this._monthsShort:this._monthsShort.standalone},Pn.monthsParse=function(e,t,n){var r,i,o;if(this._monthsParseExact)return Fe.call(this,e,t,n);for(this._monthsParse||(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[]),r=0;r<12;r++){if(i=f([2e3,r]),n&&!this._longMonthsParse[r]&&(this._longMonthsParse[r]=new RegExp("^"+this.months(i,"").replace(".","")+"$","i"),this._shortMonthsParse[r]=new RegExp("^"+this.monthsShort(i,"").replace(".","")+"$","i")),n||this._monthsParse[r]||(o="^"+this.months(i,"")+"|^"+this.monthsShort(i,""),this._monthsParse[r]=new RegExp(o.replace(".",""),"i")),n&&"MMMM"===t&&this._longMonthsParse[r].test(e))return r;if(n&&"MMM"===t&&this._shortMonthsParse[r].test(e))return r;if(!n&&this._monthsParse[r].test(e))return r}},Pn.monthsRegex=function(e){return this._monthsParseExact?(s(this,"_monthsRegex")||We.call(this),e?this._monthsStrictRegex:this._monthsRegex):(s(this,"_monthsRegex")||(this._monthsRegex=Le),this._monthsStrictRegex&&e?this._monthsStrictRegex:this._monthsRegex)},Pn.monthsShortRegex=function(e){return this._monthsParseExact?(s(this,"_monthsRegex")||We.call(this),e?this._monthsShortStrictRegex:this._monthsShortRegex):(s(this,"_monthsShortRegex")||(this._monthsShortRegex=Re),this._monthsShortStrictRegex&&e?this._monthsShortStrictRegex:this._monthsShortRegex)},Pn.week=function(e){return ze(e,this._week.dow,this._week.doy).week},Pn.firstDayOfYear=function(){return this._week.doy},Pn.firstDayOfWeek=function(){return this._week.dow},Pn.weekdays=function(e,t){var n=i(this._weekdays)?this._weekdays:this._weekdays[e&&!0!==e&&this._weekdays.isFormat.test(t)?"format":"standalone"];return!0===e?Ke(n,this._week.dow):e?n[e.day()]:n},Pn.weekdaysMin=function(e){return!0===e?Ke(this._weekdaysMin,this._week.dow):e?this._weekdaysMin[e.day()]:this._weekdaysMin},Pn.weekdaysShort=function(e){return!0===e?Ke(this._weekdaysShort,this._week.dow):e?this._weekdaysShort[e.day()]:this._weekdaysShort},Pn.weekdaysParse=function(e,t,n){var r,i,o;if(this._weekdaysParseExact)return nt.call(this,e,t,n);for(this._weekdaysParse||(this._weekdaysParse=[],this._minWeekdaysParse=[],this._shortWeekdaysParse=[],this._fullWeekdaysParse=[]),r=0;r<7;r++){if(i=f([2e3,1]).day(r),n&&!this._fullWeekdaysParse[r]&&(this._fullWeekdaysParse[r]=new RegExp("^"+this.weekdays(i,"").replace(".","\\.?")+"$","i"),this._shortWeekdaysParse[r]=new RegExp("^"+this.weekdaysShort(i,"").replace(".","\\.?")+"$","i"),this._minWeekdaysParse[r]=new RegExp("^"+this.weekdaysMin(i,"").replace(".","\\.?")+"$","i")),this._weekdaysParse[r]||(o="^"+this.weekdays(i,"")+"|^"+this.weekdaysShort(i,"")+"|^"+this.weekdaysMin(i,""),this._weekdaysParse[r]=new RegExp(o.replace(".",""),"i")),n&&"dddd"===t&&this._fullWeekdaysParse[r].test(e))return r;if(n&&"ddd"===t&&this._shortWeekdaysParse[r].test(e))return r;if(n&&"dd"===t&&this._minWeekdaysParse[r].test(e))return r;if(!n&&this._weekdaysParse[r].test(e))return r}},Pn.weekdaysRegex=function(e){return this._weekdaysParseExact?(s(this,"_weekdaysRegex")||rt.call(this),e?this._weekdaysStrictRegex:this._weekdaysRegex):(s(this,"_weekdaysRegex")||(this._weekdaysRegex=Qe),this._weekdaysStrictRegex&&e?this._weekdaysStrictRegex:this._weekdaysRegex)},Pn.weekdaysShortRegex=function(e){return this._weekdaysParseExact?(s(this,"_weekdaysRegex")||rt.call(this),e?this._weekdaysShortStrictRegex:this._weekdaysShortRegex):(s(this,"_weekdaysShortRegex")||(this._weekdaysShortRegex=et),this._weekdaysShortStrictRegex&&e?this._weekdaysShortStrictRegex:this._weekdaysShortRegex)},Pn.weekdaysMinRegex=function(e){return this._weekdaysParseExact?(s(this,"_weekdaysRegex")||rt.call(this),e?this._weekdaysMinStrictRegex:this._weekdaysMinRegex):(s(this,"_weekdaysMinRegex")||(this._weekdaysMinRegex=tt),this._weekdaysMinStrictRegex&&e?this._weekdaysMinStrictRegex:this._weekdaysMinRegex)},Pn.isPM=function(e){return"p"===(e+"").toLowerCase().charAt(0)},Pn.meridiem=function(e,t,n){return e>11?n?"pm":"PM":n?"am":"AM"},gt("en",{eras:[{since:"0001-01-01",until:1/0,offset:1,name:"Anno Domini",narrow:"AD",abbr:"AD"},{since:"0000-12-31",until:-1/0,offset:1,name:"Before Christ",narrow:"BC",abbr:"BC"}],dayOfMonthOrdinalParse:/\d{1,2}(th|st|nd|rd)/,ordinal:function(e){var t=e%10;return e+(1===he(e%100/10)?"th":1===t?"st":2===t?"nd":3===t?"rd":"th")}}),r.lang=I("moment.lang is deprecated. Use moment.locale instead.",gt),r.langData=I("moment.langData is deprecated. Use moment.localeData instead.",yt);var Ln=Math.abs;function Fn(e,t,n,r){var i=Qt(t,n);return e._milliseconds+=r*i._milliseconds,e._days+=r*i._days,e._months+=r*i._months,e._bubble()}function Un(e){return e<0?Math.floor(e):Math.ceil(e)}function Bn(e){return 4800*e/146097}function Wn(e){return 146097*e/4800}function Gn(e){return function(){return this.as(e)}}var Vn=Gn("ms"),Yn=Gn("s"),Hn=Gn("m"),zn=Gn("h"),qn=Gn("d"),Kn=Gn("w"),Jn=Gn("M"),Zn=Gn("Q"),Xn=Gn("y"),Qn=Vn;function er(e){return function(){return this.isValid()?this._data[e]:NaN}}var tr=er("milliseconds"),nr=er("seconds"),rr=er("minutes"),ir=er("hours"),or=er("days"),sr=er("months"),ar=er("years");var cr=Math.round,lr={ss:44,s:45,m:45,h:22,d:26,w:null,M:11};function ur(e,t,n,r,i){return i.relativeTime(t||1,!!n,e,r)}var dr=Math.abs;function hr(e){return(e>0)-(e<0)||+e}function fr(){if(!this.isValid())return this.localeData().invalidDate();var e,t,n,r,i,o,s,a,c=dr(this._milliseconds)/1e3,l=dr(this._days),u=dr(this._months),d=this.asSeconds();return d?(e=de(c/60),t=de(e/60),c%=60,e%=60,n=de(u/12),u%=12,r=c?c.toFixed(3).replace(/\.?0+$/,""):"",i=d<0?"-":"",o=hr(this._months)!==hr(d)?"-":"",s=hr(this._days)!==hr(d)?"-":"",a=hr(this._milliseconds)!==hr(d)?"-":"",i+"P"+(n?o+n+"Y":"")+(u?o+u+"M":"")+(l?s+l+"D":"")+(t||e||c?"T":"")+(t?a+t+"H":"")+(e?a+e+"M":"")+(c?a+r+"S":"")):"P0D"}var pr=Wt.prototype;return pr.isValid=function(){return this._isValid},pr.abs=function(){var e=this._data;return this._milliseconds=Ln(this._milliseconds),this._days=Ln(this._days),this._months=Ln(this._months),e.milliseconds=Ln(e.milliseconds),e.seconds=Ln(e.seconds),e.minutes=Ln(e.minutes),e.hours=Ln(e.hours),e.months=Ln(e.months),e.years=Ln(e.years),this},pr.add=function(e,t){return Fn(this,e,t,1)},pr.subtract=function(e,t){return Fn(this,e,t,-1)},pr.as=function(e){if(!this.isValid())return NaN;var t,n,r=this._milliseconds;if("month"===(e=U(e))||"quarter"===e||"year"===e)switch(t=this._days+r/864e5,n=this._months+Bn(t),e){case"month":return n;case"quarter":return n/3;case"year":return n/12}else switch(t=this._days+Math.round(Wn(this._months)),e){case"week":return t/7+r/6048e5;case"day":return t+r/864e5;case"hour":return 24*t+r/36e5;case"minute":return 1440*t+r/6e4;case"second":return 86400*t+r/1e3;case"millisecond":return Math.floor(864e5*t)+r;default:throw new Error("Unknown unit "+e)}},pr.asMilliseconds=Vn,pr.asSeconds=Yn,pr.asMinutes=Hn,pr.asHours=zn,pr.asDays=qn,pr.asWeeks=Kn,pr.asMonths=Jn,pr.asQuarters=Zn,pr.asYears=Xn,pr.valueOf=Qn,pr._bubble=function(){var e,t,n,r,i,o=this._milliseconds,s=this._days,a=this._months,c=this._data;return o>=0&&s>=0&&a>=0||o<=0&&s<=0&&a<=0||(o+=864e5*Un(Wn(a)+s),s=0,a=0),c.milliseconds=o%1e3,e=de(o/1e3),c.seconds=e%60,t=de(e/60),c.minutes=t%60,n=de(t/60),c.hours=n%24,s+=de(n/24),a+=i=de(Bn(s)),s-=Un(Wn(i)),r=de(a/12),a%=12,c.days=s,c.months=a,c.years=r,this},pr.clone=function(){return Qt(this)},pr.get=function(e){return e=U(e),this.isValid()?this[e+"s"]():NaN},pr.milliseconds=tr,pr.seconds=nr,pr.minutes=rr,pr.hours=ir,pr.days=or,pr.weeks=function(){return de(this.days()/7)},pr.months=sr,pr.years=ar,pr.humanize=function(e,t){if(!this.isValid())return this.localeData().invalidDate();var n,r,i=!1,o=lr;return"object"==typeof e&&(t=e,e=!1),"boolean"==typeof e&&(i=e),"object"==typeof t&&(o=Object.assign({},lr,t),null!=t.s&&null==t.ss&&(o.ss=t.s-1)),r=function(e,t,n,r){var i=Qt(e).abs(),o=cr(i.as("s")),s=cr(i.as("m")),a=cr(i.as("h")),c=cr(i.as("d")),l=cr(i.as("M")),u=cr(i.as("w")),d=cr(i.as("y")),h=o<=n.ss&&["s",o]||o<n.s&&["ss",o]||s<=1&&["m"]||s<n.m&&["mm",s]||a<=1&&["h"]||a<n.h&&["hh",a]||c<=1&&["d"]||c<n.d&&["dd",c];return null!=n.w&&(h=h||u<=1&&["w"]||u<n.w&&["ww",u]),(h=h||l<=1&&["M"]||l<n.M&&["MM",l]||d<=1&&["y"]||["yy",d])[2]=t,h[3]=+e>0,h[4]=r,ur.apply(null,h)}(this,!i,o,n=this.localeData()),i&&(r=n.pastFuture(+this,r)),n.postformat(r)},pr.toISOString=fr,pr.toString=fr,pr.toJSON=fr,pr.locale=dn,pr.localeData=fn,pr.toIsoString=I("toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)",fr),pr.lang=hn,D("X",0,0,"unix"),D("x",0,0,"valueOf"),ce("x",ne),ce("X",/[+-]?\d+(\.\d{1,3})?/),pe("X",(function(e,t,n){n._d=new Date(1e3*parseFloat(e))})),pe("x",(function(e,t,n){n._d=new Date(he(e))})),
1
+ import{config as e}from"dotenv";import{readFile as t,access as n}from"node:fs/promises";import{nanoid as r}from"nanoid";import i from"util";import o from"crypto-js";import{z as s}from"zod";import a from"emittery";import{Parser as c}from"expr-eval";import{satisfies as l}from"compare-versions";import u from"debug";import d,{mkdir as h,access as f,constants as p,readdir as g,rm as m,readFile as y}from"fs/promises";import v from"minimist";import b,{join as w,dirname as S,resolve as _}from"path";import"node-ipc";import*as I from"fs";import x from"fs";import k from"tty";import E,{homedir as C,platform as $}from"os";import O from"stream";import N from"buffer";import T from"events";import A from"zlib";import M from"string_decoder";import P from"http";import D from"https";import j,{createHash as R}from"crypto";import L from"net";import F from"tls";import U from"dgram";import B,{fileURLToPath as W}from"url";import G from"node:os";import{spawn as V}from"child_process";import{join as Y,resolve as H,dirname as z}from"node:path";import{ImageData as q,loadImage as K,createCanvas as J}from"@napi-rs/canvas";var Z;!function(e){e.STARTING="STARTING",e.PENDING="PENDING",e.RUNNING="RUNNING",e.PAUSED="PAUSED",e.DRAINING="DRAINING",e.STOPPED="STOPPED",e.ERROR="ERROR"}(Z||(Z={}));const X="undefined"!=typeof window&&void 0!==window.document&&void 0!==window.document.createElement,Q="object"==typeof self&&self.constructor&&"DedicatedWorkerGlobalScope"===self.constructor.name,ee="undefined"!=typeof process&&null!=process.versions&&null!=process.versions.node,te={};let ne=0,re="";const ie=e=>te[e]?te[e]:null,oe=(e,t)=>{const n=ie(e);if(!n)return n;return n.blocks[t]||null},se=e=>{const{recipeId:t,widgetId:n}=e,r=ie(t);if(!r)return null;for(const e in r.blocks){const t=r.blocks[e].gates[n];if(t)return t}return null},ae=(e,t,n)=>{const r=oe(e,t);if(!r)return r;return r.gates[n]},ce=(e,t)=>{let n=r(4);for(;te[n];)n=r(4);const i=(o=e,JSON.parse(JSON.stringify(o)));var o;return i.logs="",i.addLog=e=>{i.logs+=`${(()=>{const e=Date.now();if(e!==ne){const t=new Date;ne=e,re=t.toJSON()}return re})()}:: ${e}\n`},i.dbInfo={...t},te[n]=i,n},le=e=>{const t=ie(e);if(!t)throw new Error("Recipe not found. Cannot get recipe info.");return{poolId:e,uuid:t.uuid,name:t.name,type:t.dbInfo.recipeType,dbId:t.dbInfo.id,version:t.dbInfo.version,authorId:t.dbInfo.authorId}},ue="interrupt_port",de="UI:",he="default";var fe,pe,ge,me,ye,ve,be,we;let Se;!function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(fe||(fe={})),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"}(pe||(pe={})),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"}(ge||(ge={})),function(e){e.Javascript="js",e.Python="py",e.Executable="exe"}(me||(me={})),function(e){e.IpcAcknowledge="iack:",e.SocketAcknowledge="sack:",e.AcknowledgeResponse="ackr:",e.ServicesListChanged="update-services",e.SendManifest="send-manifest",e.BroadcastStart="broadcast-start",e.BroadcastEnd="broadcast-end",e.AssumeSession="assume:"}(ye||(ye={})),function(e){e.GetServices="getServices",e.SubscribeToService="subscribeToService",e.UnsubscribeFromService="unsubscribeFromService",e.GetServiceContents="getServiceContents",e.SocketAckResponse="socketAckResponse",e.ShowSecretsConfigScreen="showSecretsConfigScreen",e.GetMappedSecrets="getMappedSecrets",e.GetSecretContexts="getSecretContexts",e.AddServiceSecret="addServiceSecret",e.OnParentEvent="onParentEvent",e.GetDefaultState="getDefaultState",e.BroadcastEvent="broadcastEvent",e.HubBroadcastEvent="hubBroadcastEvent",e.ServiceManifest="serviceManifest",e.SendToRecipe="sendToRecipe",e.KemuComposerDisconnected="kemu-composer-disconnected",e.GetState="getState",e.SetState="setState",e.SetOutputs="setOutputs",e.UIEvent="uiEvent",e.GetSystemInfo="getSystemInfo",e.InitializeInstance="initializeInstance",e.TerminateInstance="terminateInstance",e.UninstallService="uninstallService",e.ChooseDirectoryDialog="chooseDirectoryDialog",e.ChooseFileDialog="chooseFileDialog",e.SaveRecipeToFile="saveRecipeToFile",e.RestartApp="restartApp",e.ShowHubScreen="showHubScreen",e.ExchangeSessionTokenForApiKey="exchangeSessionTokenForApiKey",e.GetUniqueId="getUniqueId",e.RebootToInstallUpdate="rebootToInstallUpdate",e.GetFileContentFromCacheId="getFileContentFromCacheId",e.GetDecryptedEdgeApiKey="getDecryptedEdgeApiKey",e.GetHubConfig="getHubConfig",e.GetRecipeDecryptedSecretsValues="getRecipeDecryptedSecretsValues",e.GetRecipeSecretMappings="getRecipeSecretMappings",e.AddRecipeSecretMapping="addRecipeSecretMapping",e.DeleteRecipeSecretMapping="deleteRecipeSecretMapping",e.GetHubSecrets="getHubSecrets",e.AddHubSecrets="addHubSecrets",e.DeleteHubSecret="deleteHubSecret"}(ve||(ve={})),function(e){e.SetDependencyPath="setDependencyPath",e.GetDependencyPath="getDependencyPath",e.ParseStringExpression="parseStringExpression",e.GetGlobalVariableNames="getGlobalVariableNames",e.GetGlobalVariableValues="getGlobalVariableValues",e.SetGlobalVariableValues="setGlobalVariableValues"}(be||(be={})),function(e){e.IPC="ipc",e.WS="ws"}(we||(we={}));const _e=()=>{if(!Se)throw new Error("CanvasManager not set");return Se},Ie=e=>{Se=e},xe=(e,t)=>_e().createCanvas(e,t),ke=e=>X?e.getContext("2d",{willReadFrequently:!0}):e.getContext("2d"),Ee=e=>_e().loadImage(e),Ce="-",$e=`inner${Ce}`,Oe=`outer${Ce}`,Ne=`${Oe}input${Ce}`,Te=`${Oe}output${Ce}`,Ae=`${$e}input${Ce}`,Me=`${$e}output${Ce}`,Pe=e=>e===ue,De=e=>e&&void 0!==e.width&&void 0!==e.height&&void 0!==e.data&&e.data.constructor&&"Uint8ClampedArray"===e.data.constructor.name,je=e=>e&&void 0!==e.width&&void 0!==e.height&&void 0!==e.top&&void 0!==e.left&&"number"==typeof e.width&&"number"==typeof e.height&&"number"==typeof e.top&&"number"==typeof e.left,Re=e=>e&&"number"==typeof e.x&&"number"==typeof e.y,Le=e=>e&&"string"==typeof e.format&&e.data&&e.data instanceof ArrayBuffer,Fe=e=>"number"==typeof e?pe.Number:"string"==typeof e?pe.String:"boolean"==typeof e?pe.Boolean:Array.isArray(e)?pe.Array:De(e)?pe.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?pe.AudioBuffer:e&&void 0!==e.byteLength?pe.ArrayBuffer:je(e)?pe.Rect:e&&void 0!==e.x&&void 0!==e.y&&"number"==typeof e.x&&"number"==typeof e.y?pe.Point:Le(e)?pe.BinaryFile:pe.JsonObj,Ue=e=>{const t={};let n;n=Array.isArray(e)?e[0]:e;for(const e in n){const r=Fe(n[e]);t[e]=r}return t},Be=(e,t,n)=>"inner"===e?"input"===t?`${Ae}${n}`:`${Me}${n}`:"input"===t?`${Ne}${n}`:`${Te}${n}`,We=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]}},Ge=async e=>{try{return new ImageData(e.data,e.width,e.height,{colorSpace:e.colorSpace})}catch(t){console.warn("Failed to create ImageData from info, assuming raw image data",t);return await Ee(e.data)}},Ve=e=>{const t=(e=>{const t=xe(e.width,e.height),n=ke(t);if(!n)throw new Error("Failed to get canvas context");n.putImageData(e,0,0);const r=t.toDataURL("image/png");if(!r)throw new Error("Failed to convert canvas to data URL");return r})(e);return t.split(",")[1]},Ye=async e=>{const{memoryCanvas:t,finalW:n,finalH:r}=e;let i=e.base64Str;i.startsWith("data:image/")||(i=`data:image/png;base64,${i}`);let o=await Ee(i);return o=(e=>{const{image:t,newWidth:n,newHeight:r}=e;let i=e.resizeCanvas;if(n===t.width&&r===t.height&&t instanceof ImageData)return t;i||(i=xe(n,r));const o=i.getContext("2d");if(!o)throw new Error("Failed to get canvas context");i.width=n,i.height=r;try{let e;if(t instanceof ImageData){e=xe(t.width,t.height);const n=e.getContext("2d");if(!n)throw new Error("Failed to get canvas context");n.putImageData(t,0,0)}o.drawImage(e||t,0,0,t.width,t.height,0,0,n,r)}catch(e){throw console.warn("Failed to resize image",e),e}return o.getImageData(0,0,n,r)})({image:o,newWidth:n??o.width,newHeight:r??o.height,resizeCanvas:t}),o};var He,ze;!function(e){e.Action="action",e.CustomInput="customInput"}(He||(He={})),function(e){e.input="input",e.counter="counter",e.play="play",e.elapsed="elapsed",e.ifGate="ifGate",e.skipEvent="skipEvent",e.between="between",e.map="map",e.parser="parser",e.slider="slider",e.suspend="suspend",e.display="display",e.json="json",e.arrayItem="arrayItem",e.extractImage="extractImage",e.imageConvolution="imageConvolution",e.firstEvent="firstEvent",e.pixelDraw="pixelDraw",e.randomBetween="randomBetween",e.arrayCombine="arrayCombine",e.clock="clock",e.delay="delay",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.sequence="sequence",e.variable="variable",e.hubService="hubService",e.imageFilter="imageFilter",e.recipeLoad="recipeLoad",e.note="note",e.stringify="stringify",e.templateString="templateString",e.expressionEval="expressionEval",e.rescue="rescue",e.objectCombine="objectCombine",e.loop="loop",e.status="status",e.secret="secret",e.output="output",e.globalVariable="globalVariable",e.switch="switch",e.edgeFunction="edgeFunction",e.fieldValue="fieldValue"}(ze||(ze={}));const qe={};let Ke,Je=()=>0;const Ze=async e=>{const t=qe[e],n={name:ue,type:pe.Boolean};if(t){const r={name:t.portName},i=t.data||{type:pe.Boolean,value:!0};if(!Je)throw new Error("consumeEventCounter is not set");const o=Je();Ke?(await Ke({interruptDriven:!0,childGateId:t.targetWidgetId,sourceWidgetId:t.sourceWidgetId,block:t.thingId,recipeId:t.recipePoolId,sourcePortName:n.name,targetPort:r,data:{...i,timestamp:Date.now()},sourceOutputNames:[n],currentPath:[],eventId:o}),"timeout"===t.type&&Xe(e)):console.warn("Interrupt service has not been initialized")}},Xe=e=>{const t=qe[e];return!!t&&(t.timerRef&&("interval"===t.type?clearInterval(t.timerRef):"timeout"===t.type&&clearTimeout(t.timerRef)),delete qe[e],!0)};var Qe={interruptHandler:Ze,createInterrupt:e=>{const{type:t,recipePoolId:n,thingId:i,targetWidgetId:o,sourceWidgetId:s,portName:a,config:c,data:l,customId:u}=e;if(u&&qe[u])throw new Error("The given interrupt id already exists");const d=u||r().replace(/_/g,"-");if("interval"===t&&!c.interval)throw new Error(`Invalid interval. Expected a number greater than 0, but got '${c.interval}'`);if("timeout"===t&&!c.timeout)throw new Error(`Invalid timeout. Expected a number greater than 0, but got '${c.timeout}'`);if(qe[d]={data:l,portName:a,recipePoolId:n,targetWidgetId:o,sourceWidgetId:s,thingId:i,type:t},"interval"===t)qe[d].timerRef=setInterval((async()=>await Ze(d)),c.interval);else{if("timeout"!==t)throw new Error(`Invalid interrupt type '${t}'`);qe[d].timerRef=setTimeout((async()=>await Ze(d)),c.timeout)}return d},destroyInterrupt:Xe,destroyAllInterrupts:()=>{Object.keys(qe).forEach(Xe)},setInvokeChildGateCb:e=>{Ke=e},setConsumeEventCounterCb:e=>{Je=e}};const et=[10001,"Invalid `sourcePort` parameter"],tt=[10002,"The gate [%s] does not exist. Have you called `loadWidgets` yet?"],nt=(e,...t)=>JSON.stringify({code:e[0],message:t[0]?i.format(e[1],...t):e[1].replace(/ \[%s\]/g,"")});let rt=0,it={};var ot=(e,t)=>{const n=`${e}-${++rt}`,r={event:t,eventKey:n,widgetId:e,resolve:()=>{},reject:()=>{}},i=new Promise(((e,t)=>{r.resolve=e,r.reject=t}));return r.promise=i,it[n]=r,r},st=(e,t)=>{const n=it[e];n&&(delete it[e],n.resolve(t))};const at=()=>({inputName:"",dataType:pe.Anything}),ct="output",lt={processEvent:async(e,t)=>{const n=t.getState(),r={...at(),...n};if(e.type!==r.dataType&&r.dataType!==pe.Anything)return void console.error(`Invalid data type: ${e.type} for input: ${r.inputName}. Expected: ${r.dataType}`);const i=t.waitForOutputChild,o=i?ot(t.id,e):void 0,s=i?{eventKey:o?.eventKey}:void 0;if(await t.nextWidget(ct,{type:e.type,value:e.value},s).catch((e=>{console.log("[INPUT] error resolving event: ",e),o?.reject(e)})),o){return await o.promise}},getOutputNames:e=>{const t={...at(),...e};return[{name:ct,type:t.dataType}]},getInputNames:()=>[]},ut=Object.freeze({in:"in",reset:"reset",increment:"increment"}),dt="output";var ht={onParentEvent:async(e,t,n,r)=>{if(!e)throw new Error(nt(et));const i={currentValue:0,increment:1,...r.getState()};let o=i.increment,s=i.currentValue;const a=await r.getParentAtPort(ut.increment);if(t.name===ut.increment)return void(n.data.type===pe.Number&&r.setState({...i,increment:Number(n.data.value)}));if(a){const e=a.getValue();null!==e&&(o=e)}if(t.name===ut.reset)return r.setState({...i,currentValue:0});s+=o,r.setState({currentValue:s,increment:o});const c={type:pe.Number,value:s};return r.nextGate(dt,c)},getInputNames:()=>[{name:ut.in,type:pe.Anything},{name:ut.reset,type:pe.Anything},{name:ut.increment,type:pe.Number}],getOutputNames:()=>[{name:dt,type:pe.Number}]};const ft=Object.freeze({in:"in",reset:"reset"}),pt="output";var gt={onParentEvent:async(e,t,n,r)=>{const i={updatedAt:0,elapsed:0,...r.getState()},o=Date.now(),s=o-(i.updatedAt||o);return t.name===ft.reset?r.setState({...i,updatedAt:o,elapsed:0}):(r.setState({updatedAt:o,elapsed:s}),r.nextGate(pt,{type:pe.Number,value:s}))},getInputNames:()=>[{name:ft.in,type:pe.Anything},{name:ft.reset,type:pe.Anything}],getOutputNames:()=>[{name:pt,type:pe.Number}]};const mt=Object.freeze({data:"data",evaluation:"evaluation"}),yt="then",vt="else";var bt={onParentEvent:async(e,t,n,r)=>{const i={value:5,condition:"Equal",useDataPort:!1,...r.getState()},o=n.data.value,s=!isNaN(Number(o)),a="string"==typeof o;if(!i.useDataPort&&(n.data.type===pe.Number||n.data.type===pe.String||n.data.type===pe.Boolean||n.data.type===pe.Anything&&s||n.data.type===pe.Anything&&a)){let e=!1;return("Equal"===i.condition&&(n.data.value==i.value||n.data.type===pe.Boolean&&n.data.value.toString()===i.value.toString())||"Not Equal"===i.condition&&(n.data.value!==i.value||n.data.type===pe.Boolean&&n.data.value!==i.value.toString())||"Greater"===i.condition&&n.data.type===pe.Number&&n.data.value>Number(i.value)||"Less"===i.condition&&n.data.type===pe.Number&&n.data.value<Number(i.value)||"Starts With"===i.condition&&String(n.data.value).startsWith(String(i.value))||"Ends With"===i.condition&&String(n.data.value).endsWith(String(i.value))||"Includes"===i.condition&&String(n.data.value).includes(String(i.value))||"Matches"===i.condition&&String(n.data.value).match(String(i.value)))&&(e=!0),e?r.nextGate(yt,n.data):r.nextGate(vt,n.data)}if(t.name===mt.evaluation&&(n.data.type===pe.Number||n.data.type===pe.String||n.data.type===pe.Boolean||n.data.type===pe.Anything&&(s||a))&&(i.$lastValue=n.data.value,i.$lastInputDataType=n.data.type,r.setState({...i})),t.name===mt.data){let e=!1;return("Equal"===i.condition&&(i.$lastValue==i.value||i.$lastInputDataType===pe.Boolean&&i.$lastValue?.toString()===i.value.toString())||"Not Equal"===i.condition&&(i.$lastValue!==i.value||i.$lastInputDataType===pe.Boolean&&i.$lastValue!==i.value.toString())||"Greater"===i.condition&&i.$lastInputDataType===pe.Number&&Number(i.$lastValue)>Number(i.value)||"Less"===i.condition&&i.$lastInputDataType===pe.Number&&Number(i.$lastValue)<Number(i.value)||"Starts With"===i.condition&&String(i.$lastValue).startsWith(String(i.value))||"Ends With"===i.condition&&String(i.$lastValue).endsWith(String(i.value))||"Includes"===i.condition&&String(i.$lastValue).includes(String(i.value))||"Matches"===i.condition&&String(i.$lastValue).match(String(i.value)))&&(e=!0),r.setState({...i,$lastValue:void 0,$lastInputDataType:void 0}),e?r.nextGate(yt,n.data):r.nextGate(vt,n.data)}},getInputNames:e=>e.useDataPort?[{name:mt.data,type:pe.Anything,triggerPort:!0},{name:mt.evaluation,type:[pe.Number,pe.String,pe.Boolean]}]:[{name:"in",type:[pe.Number,pe.String,pe.Boolean]}],getOutputNames:e=>e.$lastOutputDataType?[{name:yt,type:e.$lastOutputDataType},{name:vt,type:e.$lastOutputDataType}]:[{name:yt,type:[pe.Number,pe.String]},{name:vt,type:[pe.Number,pe.String]}]};const wt=Object.freeze({in:"in",reset:"reset"}),St="out",_t="skipped";var It={onParentEvent:async(e,t,n,r)=>{const i={totalCalls:0,callsLimit:1,...r.getState()};return t.name===wt.reset?r.setState({...i,totalCalls:0}):(i.totalCalls=i.totalCalls+1,i.totalCalls>i.callsLimit?(i.totalCalls=0,r.setState(i),r.nextWidget(St,n.data)):(n.data.type!==i.$$lastDetectedType&&(i.$$lastDetectedType=n.data.type),r.setState(i),r.nextWidget(_t,n.data)))},getInputNames:()=>[{name:wt.in,type:pe.Anything},{name:wt.reset,type:pe.Anything}],getOutputNames:e=>[{name:St,type:e.$$lastDetectedType??pe.Anything},{name:_t,type:e.$$lastDetectedType??pe.Anything}]};const xt=Object.freeze({in:"in"}),kt="then",Et="else";var Ct={onParentEvent:async(e,t,n,r)=>{const i={min:1,max:10,...r.getState()};if(n.data.type===pe.Number)return n.data.value>=i.min&&n.data.value<=i.max?r.nextGate(kt,n.data):r.nextGate(Et,n.data)},getInputNames:()=>[{name:xt.in,type:pe.Number}],getOutputNames:()=>[{name:kt,type:pe.Number},{name:Et,type:pe.Number}]};const $t=Object.freeze({in:"in"}),Ot="out";var Nt={onParentEvent:async(e,t,n,r)=>{const i={clamp:!0,...r.getState()},o=Number(n.data.value);if(void 0!==i.fromMax&&void 0!==i.fromMin&&void 0!==i.toMax&&void 0!==i.toMin&&""!==i.fromMax&&""!==i.fromMin&&""!==i.toMax&&""!==i.toMin&&(n.data.type===pe.Number||n.data.type===pe.Anything&&!isNaN(Number(o)))){let e=((e,t,n,r,i)=>(e-t)*(i-r)/(n-t)+r)(o,Number(i.fromMin),Number(i.fromMax),Number(i.toMin),Number(i.toMax));if(isNaN(e))return;return i.clamp&&(e<Number(i.toMin)&&(e=Number(i.toMin)),e>Number(i.toMax)&&(e=Number(i.toMax))),r.nextGate(Ot,{type:pe.Number,value:Number(e)})}},getInputNames:()=>[{name:$t.in,type:pe.Number}],getOutputNames:()=>[{name:Ot,type:pe.Number}]};const Tt=Object.freeze({in:"in"}),At="out",Mt=["image/png","image/jpeg","image/jpg","image/gif","image/webp","image/bmp","image/svg+xml"];var Pt={onParentEvent:async(e,t,n,r)=>{const i={convertTo:"Integer",floatPlaces:2,...r.getState()};let o=n.data.value;if("ImageData"===i.convertTo){if(!Le(n.data.value))throw new Error("Invalid data type, expected a BinaryFile type");const e=n.data.value;if(!Mt.includes(e.format))throw new Error(`Unsupported image format: ${e.format}. Supported formats are: ${Mt.join(", ")}.`);const t=await Ee(e);return r.nextGate(At,{type:pe.ImageData,value:t})}if(n.data.type===pe.Number||n.data.type===pe.Anything||n.data.type===pe.String){if((!isNaN(Number(o))||"string"==typeof o)&&!Array.isArray(o))return"Integer"===i.convertTo?o=parseInt(o):"Decimal"===i.convertTo?o=parseFloat(Number(o).toFixed(i.floatPlaces)):"String"===i.convertTo?o=String(o):"Abs"===i.convertTo?o=Math.abs(Number(o)):"Round"===i.convertTo&&(o=Math.round(Number(o))),r.nextGate(At,{type:"String"===i.convertTo?pe.String:pe.Number,value:o})}},getInputNames:()=>[{name:Tt.in,type:pe.Number}],getOutputNames:e=>{const t="String"===e?.convertTo?pe.String:"ImageData"===e?.convertTo?pe.ImageData:pe.Number;return[{name:At,type:t}]}};const Dt=Object.freeze({in:"in"}),jt="out";var Rt={onParentEvent:async(e,t,n,r)=>{const i={currentValue:50,min:0,max:100,...r.getState()};let o=!1;return i.currentValue<i.min&&(i.currentValue=i.min,o=!0),i.currentValue>i.max&&(i.currentValue=i.max,o=!0),o&&r.setState(i),r.nextWidget(jt,{type:pe.Number,value:i.currentValue})},getInputNames:()=>[{name:Dt.in,type:pe.Anything}],getOutputNames:()=>[{name:jt,type:pe.Number}]};const Lt=Object.freeze({in:"in",reset:"reset"}),Ft="out",Ut="skipped";var Bt={onParentEvent:async(e,t,n,r)=>{const i={lastCalledAt:0,delayMs:500},o={lastCalledAt:0,delayMs:500,...r.getState()};if(t.name===Lt.reset)return r.setState({...o,lastCalledAt:0});const s=Date.now(),a=s-o.lastCalledAt;return o.lastCalledAt===i.lastCalledAt||a>=o.delayMs&&o.delayMs>0?(o.lastCalledAt=s,r.setState(o),r.nextWidget(Ft,n.data)):(n.data.type!==o.$$lastDetectedType&&(o.$$lastDetectedType=n.data.type),r.setState(o),r.nextWidget(Ut,n.data))},getInputNames:()=>[{name:Lt.in,type:pe.Anything},{name:Lt.reset,type:pe.Anything}],getOutputNames:e=>[{name:Ft,type:e.$$lastDetectedType??pe.Anything},{name:Ut,type:e.$$lastDetectedType??pe.Anything}]};const Wt="in";var Gt={onParentEvent:async()=>{},getInputNames:()=>[{name:Wt,type:[pe.ImageData,pe.Number]}],getOutputNames:()=>[]};const Vt=()=>({properties:[{label:"property1",name:"property1"}],detectedProperties:{}}),Yt=(e,t)=>t.split(".").reduce(((e,t)=>null!=e?e[t]:e),e);var Ht={onParentEvent:async(e,t,n,r)=>{const i={properties:[{label:"property1",name:"property1"}],detectedProperties:{},...r.getState()},o=n?.data?.value,s=Array.isArray(o);if(n.data.type===pe.JsonObj||n.data.type===pe.Rect||n.data.type===pe.Point||n.data.type===pe.BinaryFile||n.data.type===pe.Anything||s){let e=!1;for(const t in o){const n=Fe(o[t]),r=!!i.detectedProperties[t],s=i.detectedProperties[t]?.type!==n;if(!r||s){const r=n===pe.JsonObj||n===pe.Rect||n===pe.Point||n===pe.Array;i.detectedProperties[t]={type:n,...r?{shape:Ue(o[t])}:void 0},e=!0}}if(s&&void 0===i.detectedProperties.length&&(i.detectedProperties.length={type:pe.Number}),e&&r.setState(i),o){const e=[];for(const t of i.properties||[]){const n=Yt(o,t.label),s=t.label.includes(".");if(void 0!==n){const o=s?Fe(n):void 0!==i.detectedProperties[t.label]?.type?i.detectedProperties[t.label].type:pe.Anything;e.push(r.nextGate(t.name,{type:o,value:n}))}}await Promise.allSettled(e)}}},getInputNames:()=>[{name:"in",type:pe.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:pe.Anything,r=t.detectedProperties[e.label]?.shape||void 0,i="string"==typeof e;return{name:i?e:e.name,label:i?e:e.label,type:n,jsonShape:r}}))},getDefaultState:Vt};const zt="output",qt="noItem";var Kt={onParentEvent:async(e,t,n,r)=>{const i={index:0,...r.getState()};let o=i.index;const s=n.data.value,a="string"==typeof n.data.value,c=Array.isArray(n.data.value);if(n.data.type===pe.Anything&&(c||a)||n.data.type===pe.String&&a||n.data.type===pe.Array&&c){o<0&&(o=s.length+o);const e=a?pe.String:Fe(s[o]);return e!==i.$$lastDetectedType&&r.setState({...i,$$lastDetectedType:e}),void 0!==s[o]?r.nextGate(zt,{value:s[o],type:e}):r.nextGate(qt,{value:!0,type:pe.Boolean})}},getInputNames:()=>[{name:"in",type:[pe.Array,pe.String]}],getOutputNames:e=>[{name:zt,type:e.$$lastDetectedType??pe.Anything},{name:qt,type:pe.Boolean}]};const Jt={},Zt=e=>(Jt[e]||(Jt[e]={canvasFrom:xe(320,240),canvasTo:xe(320,240)}),Jt[e]),Xt=Object.freeze({image:"image",rect:"rect"}),Qt="image";var en={onParentEvent:async(e,t,n,r)=>{const i=Zt(r.id),o={offset:{height:0,left:0,top:0,width:0},...r.getState()},s=[pe.Anything,pe.Rect,pe.JsonObj];if(t.name===Xt.rect&&je(n.data.value)&&s.includes(n.data.type)&&(o.rect=n.data.value,r.setState({...o})),t.name===Xt.image){if(!((n.data.type===pe.ImageData||n.data.type===pe.Anything)&&De(n.data.value)))throw new Error("Invalid image data. Expected a valid ImageData type");i.lastImage=n.data.value}if(i.lastImage&&o.rect){const e=((e,t,n,r,i)=>{if(r&&r.getContext){const o=r.getContext("2d"),s=n.getContext("2d");if(o&&s){n.width=e.width,n.height=e.height,s.putImageData(e,0,0);const a={...i};i&&(a.height=Number(i.height),a.width=Number(i.width),a.left=Number(i.left),a.top=Number(i.top));const c={top:0,width:0,left:0,height:0,...a};return i&&(Number.isInteger(c.width)||(c.width=t.width*c.width),Number.isInteger(c.height)||(c.height=t.height*c.height),Number.isInteger(c.left)||(c.left=t.left+t.width*c.left),Number.isInteger(c.top)||(c.top=t.top+t.height*c.top)),r.width=t.width+c.width,r.height=t.height+c.height,o.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),o.getImageData(0,0,r.width||1,r.height||1)}}return e})(i.lastImage,o.rect,i.canvasFrom,i.canvasTo,o.offset);r.setState({...o,rect:null}),i.lastImage=void 0,await r.nextWidget(Qt,{type:pe.ImageData,value:e})}},getInputNames:()=>[{name:Xt.image,type:pe.ImageData},{name:Xt.rect,type:[pe.Rect,pe.JsonObj]}],getOutputNames:()=>[{name:Qt,type:pe.ImageData}],initialize:async e=>{Zt(e.widgetId)},terminate:async e=>{delete Jt[e.widgetId]}};const tn=(e,t)=>{const n=Math.round(Math.sqrt(t.length)),r=Math.floor(n/2),i=e.data,o=e.width,s=e.height,a=o,c=s,l=((e,t,n)=>{if(X)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,h=4*(e*a+c);let f=0,p=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<s&&u>=0&&u<o){const r=4*(c*o+u),s=t[e*n+a];f+=i[r]*s,p+=i[r+1]*s,g+=i[r+2]*s,m+=i[r+3]*s}}u[h]=f,u[h+1]=p,u[h+2]=g,u[h+3]=m+1*(255-m)}return l},nn=[-1,0,1,-2,0,2,1,0,1],rn=Object.freeze({image:"image"}),on="image";var sn={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),o={matrix:[...nn],...i};if(n.data.type===pe.ImageData||n.data.type===pe.Anything&&De(n.data.value)){const e=tn(n.data.value,o.matrix);return r.nextGate(on,{type:pe.ImageData,value:e})}},getInputNames:()=>[{name:rn.image,type:pe.ImageData}],getOutputNames:()=>[{name:on,type:pe.ImageData}]};const an=Object.freeze({output:"output",aborted:"aborted"}),cn=()=>({inputs:2,matchingOutputs:!0,lastInputIndex:-1,delayMs:500,triggeredAt:0}),ln=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:pe.Anything})));return n.push({name:"reset",type:pe.Anything}),n};var un={onParentEvent:async(e,t,n,r)=>{const i={inputs:2,matchingOutputs:!0,lastInputIndex:-1,delayMs:500,triggeredAt:0,...r.getState()};if("reset"===t.name)return r.setState({...i,triggeredAt:0});const o=Date.now(),s=o-i.triggeredAt;if(i.triggeredAt&&!(s>=i.delayMs&&i.delayMs>0)&&i.delayMs)return r.nextGate(an.aborted,n.data);{i.triggeredAt=o;const e=ln(i,(r.recipePoolId,r.recipeType,r.thingRecipeId,r.id)).findIndex((e=>e.name===t.name));-1!==e&&(i.lastInputIndex=e),i.matchingOutputs?-1!==e&&await r.nextGate(`output${e+1}`,n.data):await r.nextGate(an.output,n.data),r.setState(i)}},getInputNames:ln,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:pe.Anything})));return e.push({name:an.aborted,type:pe.Anything}),e}return[{name:an.output,type:pe.Anything},{name:an.aborted,type:pe.Anything}]},getDefaultState:cn};const dn=(e,t,n,r,i,o)=>{if(i){const s=e.measureText(i),a=s.fontBoundingBoxAscent+s.fontBoundingBoxDescent;e.fillStyle=r,e.fillRect(t,n-o,1.1*s.width,a),e.font=`${o}px Arial`,e.fillStyle="black",e.fillText(i,t,n)}},hn=(e,t,n,r,i,o,s)=>{e.fillStyle=i,e.fillRect(t,n,r,r),dn(e,t,n,i,o,s)},fn=(e,t,n,r,i,o)=>{e.beginPath(),e.strokeStyle=r,e.lineWidth=n,e.rect(t.left,t.top,t.width,t.height),e.stroke();const s=n/2;dn(e,t.left-s,t.top-s,r,i,o)},pn={},gn=e=>(pn[e]||(pn[e]={memCanvas:xe(320,240),lastFrame:void 0,pixels:void 0}),pn[e]),mn=Object.freeze({image:"image",pixels:"pixels"}),yn="image";var vn={onParentEvent:async(e,t,n,r)=>{const i=gn(r.id),o={fontSize:12,color:"#00ff00",size:2,...r.getState()},s=(n.data.type===pe.ImageData||n.data.type===pe.Anything)&&De(n.data.value);if(t.name===mn.pixels){const e=(e=>Re(e)||je(e)||Array.isArray(e)&&e[0]&&(Re(e[0])||je(e[0])))(n.data.value);if(!e)return;i.pixels=n.data.value}if(t.name===mn.image&&s){const e=n.data.value;i.lastFrame=e}if(i.lastFrame&&i.pixels&&i.memCanvas){const e=(e=>{const{sourceImage:t,pixels:n,memCanvas:r,size:i,color:o,labelProp:s,fontSize:a}=e;if(r){const e=ke(r);if(e){r.width!==t.width&&(r.width=t.width),r.height!==t.height&&(r.height=t.height),e.putImageData(t,0,0);const c=Array.isArray(n)?n:[n];for(let t=0;t<c.length;t++){const n=c[t],r=s?n[s]:"";je(n)?fn(e,n,i,o,r,a):Re(n)&&hn(e,n.x,n.y,i,o,r,a)}return e.getImageData(0,0,r.width,r.height)}}return t})({sourceImage:i.lastFrame,pixels:i.pixels||[],memCanvas:i.memCanvas,size:o.size,color:o.color,labelProp:o.labelProp,fontSize:o.fontSize});return i.lastFrame=void 0,i.pixels=void 0,r.setState({...o}),r.nextWidget(yn,{type:pe.ImageData,value:e})}r.setState(o)},getInputNames:()=>[{name:mn.image,type:pe.ImageData},{name:mn.pixels,type:[pe.Rect,pe.Point,pe.Array,pe.JsonObj]}],getOutputNames:()=>[{name:yn,type:pe.ImageData}],initialize:async e=>{gn(e.widgetId)},terminate:async e=>{delete pn[e.widgetId]}};const bn=Object.freeze({in:"in"}),wn="output",Sn=e=>{const t=String(e).split(".");return t.length<2?0:t[1].length};var _n={onParentEvent:async(e,t,n,r)=>{const i={min:1,max:100,...r.getState()},o=!Number.isInteger(i.min),s=!Number.isInteger(i.max),a=o||s;let c=(l=i.min,u=i.max,Math.random()*(u-l)+l);var l,u;if(a){let e=0;if(o&&(e=Sn(i.min)),s){const t=Sn(i.max);t>e&&(e=t)}c=Number(c.toFixed(e))}else c=Math.floor(c);return r.nextGate(wn,{type:pe.Number,value:c})},getInputNames:()=>[{name:bn.in,type:pe.Anything}],getOutputNames:()=>[{name:wn,type:pe.Number}]};const In=Object.freeze({output:"output",totalItems:"totalItems"}),xn=Object.freeze({trigger:"trigger",clear:"clear"}),kn=()=>({$$$time:0,totalSentItems:-1,totalSentAt:0,$$list:[],$$outputShape:{},totalInputs:1}),En=async(e,t)=>t.nextGate(In.totalItems,{type:pe.Number,value:e});var Cn={onParentEvent:async(e,t,n,r)=>{const i={$$$time:0,totalSentItems:-1,totalSentAt:0,$$list:[],$$outputShape:{},totalInputs:1,...r.getState()};if(t.name===xn.clear)return i.$$list=[],i.properties?.autoFilled&&delete i.properties,r.setState(i),En(i.$$list.length,r);const o=t.name===xn.trigger;if(!o)if(Array.isArray(n.data.value))n.data.type!==pe.Array&&n.data.type!==pe.Anything||(i.$$outputShape={...i.$$outputShape,...e?.jsonShape},i.$$list=i.$$list.concat(n.data.value),r.setState({...i}),await En(i.$$list.length,r));else{const t=`$$primitive_${Object.keys(i.$$outputShape).length}`;n.data.type===pe.JsonObj?i.$$outputShape={...i.$$outputShape,...e?.jsonShape?e.jsonShape:void 0}:i.$$outputShape={...i.$$outputShape,[t]:n.data.type},i.$$list.push(n.data.value),r.setState({...i}),await En(i.$$list.length,r)}if(o){Object.keys(i.$$outputShape).length&&(i.properties={autoFilled:!0,jsonShape:{...i.$$outputShape}});const e=i.$$list.length,t=[...i.$$list];return i.$$list=[],r.setState({...i}),await En(e,r),r.nextGate(In.output,{type:pe.Array,value:t})}},getInputNames:e=>{const t={$$$time:0,totalSentItems:-1,totalSentAt:0,$$list:[],$$outputShape:{},totalInputs:1,...e},n=Array(t.totalInputs||1).fill(0).map(((e,t)=>({name:`input${t+1}`,type:pe.Anything})));return n.push({name:xn.clear,type:pe.Anything},{name:xn.trigger,type:pe.Anything}),n},getOutputNames:e=>[{name:In.output,type:pe.Array,...e.properties?{jsonShape:e.properties?.jsonShape}:void 0},{name:In.totalItems,label:"Total Items",type:pe.Number}],getDefaultState:kn};const $n=Object.freeze({start:"start",stop:"stop"}),On="output",Nn="clock_interrupt";var Tn={onParentEvent:async(e,t,n,r)=>{const i={enabled:!1,interval:1e3,intervalMode:"ms",...r.getState()};if(Pe(e?.name||"")&&t.name===Nn)return r.nextGate(On,{type:pe.Boolean,value:!0});if(t.name===$n.stop&&i.enabled&&i.$$interruptId){r.cancelInterrupt(i.$$interruptId)?(i.enabled=!1,i.$$interruptId=void 0,r.setState(i)):console.warn(`Failed to cancel interrupt [${i.$$interruptId}]`)}else t.name!==$n.start||i.enabled||i.$$interruptId||(i.$$interruptId=r.registerInterrupt({type:"interval",sourceWidgetId:r.id,customTargetPortName:Nn,config:{interval:i.interval}}),i.enabled=!0,r.setState(i))},getInputNames:()=>[{name:$n.start,type:pe.Anything},{name:$n.stop,type:pe.Anything}],getOutputNames:()=>[{name:On,type:pe.Boolean}],initialize:async e=>{const t=e.getState();if(t.enabled&&!t.$$interruptId){const n=e.registerInterrupt({type:"interval",sourceWidgetId:e.widgetId,customTargetPortName:Nn,config:{interval:t.interval}});e.setState({...t,$$interruptId:n})}}};const An=864e5;var Mn;!function(e){e.ABORTED="DELAY_ABORTED",e.CONTINUED="DELAY_CONTINUED",e.TERMINATED="WIDGET_TERMINATED"}(Mn||(Mn={}));const Pn={},Dn=Object.freeze({in:"in",abort:"abort",continue:"continue"}),jn="out",Rn=(e,t)=>{const n=e.getState();e.setState({...n,pendingDelaysCount:Math.max(0,n.pendingDelaysCount+t)})};var Ln={onParentEvent:async(e,t,n,i)=>{const o={enabled:!1,interval:1e3,intervalMode:"ms",pendingDelaysCount:0,...i.getState()},s=i.id;Pn[s]||(Pn[s]=new Map);const a=Pn[s];if(t.name!==Dn.abort)if(t.name!==Dn.continue){if(t.name===Dn.in){const e=o.interval;if(!((c=e)>=1&&c<=An))throw new Error(`Invalid interval: ${e}ms. Must be between 1ms and 86400000ms`);const t={...n.data},s=r();Rn(i,1);const l=new Promise(((n,r)=>{const o=setTimeout((()=>{n(t),a.delete(s),Rn(i,-1)}),e);a.set(s,{id:s,eventData:t,timeoutId:o,resolve:n,reject:r})}));try{const e=await l;return i.invokeNextWidget({port:jn,data:e})}catch{Rn(i,-1)}}var c}else{const e=Array.from(a.entries());for(const[t,n]of e)clearTimeout(n.timeoutId),n.reject(new Error(Mn.CONTINUED)),a.delete(t);for(const[,t]of e)await i.invokeNextWidget({port:jn,data:t.eventData});Rn(i,-i.getState().pendingDelaysCount)}else{for(const[e,t]of a)clearTimeout(t.timeoutId),t.reject(new Error(Mn.ABORTED)),a.delete(e);Rn(i,-i.getState().pendingDelaysCount)}},getInputNames:()=>[{name:Dn.in,type:pe.Anything},{name:Dn.abort,type:pe.Anything},{name:Dn.continue,type:pe.Anything}],getOutputNames:()=>[{name:jn,type:pe.Anything}],initialize:async e=>{const t=e.getState();0!==t.pendingDelaysCount&&e.setState({...t,pendingDelaysCount:0})},terminate:async e=>{const t=e.widgetId;if(Pn[t]){for(const[,e]of Pn[t])clearTimeout(e.timeoutId),e.reject(new Error(Mn.TERMINATED));delete Pn[t]}}};const Fn=Object.freeze({in:"in"}),Un="output",Bn=(e,t,n)=>"number"==typeof e?Number((e*t).toFixed(n)):e;var Wn={onParentEvent:async(e,t,n,r)=>{const i={userProperties:[],factor:2,decimalPoints:2,...r.getState()},o=n.data.type;let s=n.data.value,a=!1;return e?.jsonShape&&(i.detectedInputJson={...i.detectedInputJson,...e?.jsonShape},a=!0),i.detectedInputType||(i.detectedInputType=o,a=!0),n.data.type===pe.Array&&("number"==typeof n.data.value?.[0]?s=((e,t,n)=>{const r=(e||[]).map((e=>Bn(e,t,n)));return r})(n.data.value,i.factor,i.decimalPoints):"object"==typeof n.data.value?.[0]&&(s=((e,t,n,r)=>{const i=(e||[]).map((e=>{const i={...e};return Object.keys(i).forEach((e=>{r?.length&&!r?.includes(e)||(i[e]=Bn(i[e],t,n))})),i}));return i})(n.data.value,i.factor,i.decimalPoints,i.userProperties))),n.data.type===pe.Number&&(s=Bn(n.data.value,i.factor,i.decimalPoints)),a&&r.setState(i),r.nextGate(Un,{type:o,value:s})},getInputNames:()=>[{name:Fn.in,type:[pe.Array,pe.Number]}],getOutputNames:e=>[{name:Un,type:e.detectedInputType||pe.Number,jsonShape:e.detectedInputJson}]};const Gn={},Vn=Object.freeze({output:"output"}),Yn=Object.freeze({trigger:"trigger"}),Hn=()=>({useTriggerPort:!0,properties:[{name:"x",label:"x"},{name:"y",label:"y"}]}),zn=(e,t)=>{const n={};Gn[t]=Gn[t]||{};for(let r=0;r<e.properties.length;r++){const i=Gn[t][e.properties[r].name];n[e.properties[r].label]=i}return n};var qn={onParentEvent:async(e,t,n,r)=>{const i={useTriggerPort:!0,properties:[{name:"x",label:"x"},{name:"y",label:"y"}],...r.getState()};if(t.name===Yn.trigger){const e=zn(i,r.id);return r.nextWidget(Vn.output,{type:pe.JsonObj,value:e})}const o=i.properties.findIndex((e=>e.name===t.name));if(-1!==o){const e=i.properties[o];if(Gn[r.id]=Gn[r.id]||{},Gn[r.id][e.name]=n.data.value,!i.useTriggerPort){const e=zn(i,r.id);return r.nextWidget(Vn.output,{type:pe.JsonObj,value:e})}}},getInputNames:e=>{const t={useTriggerPort:!0,properties:[{name:"x",label:"x"},{name:"y",label:"y"}],...e},n=t.properties.map((e=>({name:e.name,label:e.label,type:pe.Anything})));return t.useTriggerPort&&n.push({name:Yn.trigger,label:Yn.trigger,type:pe.Anything,triggerPort:!0}),n},getOutputNames:()=>[{name:Vn.output,label:Vn.output,type:pe.JsonObj}],getDefaultState:Hn,initialize:async e=>{Gn[e.widgetId]={}},terminate:async e=>{delete Gn[e.widgetId]}};const Kn=async e=>{const t=(e,t)=>e.split(t)[1];if(e.startsWith(Ne)){const n=t(e,Ne);return Be("inner","input",n)}if(e.startsWith(Me)){const n=t(e,Me);return Be("outer","output",n)}return null},Jn=()=>({canvasPosition:{x:0,y:0},canvasZoom:1,inputs:[{name:"input",type:[pe.Anything],index:0}],outputs:[{name:"output",type:[pe.Anything],index:0}],name:"Custom Widget 1",description:"",type:"custom"}),Zn=e=>{const t={...Jn(),...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 Xn={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),o={...Jn(),...i},s=Zn(o,(r.recipePoolId,r.recipeType,r.thingRecipeId,r.id));for(let e=0;e<s.length;e++){const i=s[e];if(t.name===i.name&&(i.type.includes(pe.Anything)||i.type.includes(n.data.type))){const e=await Kn(t.name);e&&await r.nextWidget(e,{type:n.data.type,value:n.data.value})}}},getInputNames:Zn,getOutputNames:e=>{const t={...Jn(),...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:Jn};const Qn=(e,t,n,r,i)=>{const o=4*(t*n.width+e),s=n.data[o],a=n.data[o+1],c=n.data[o+2];return Math.abs(s-r.r)<=i&&Math.abs(a-r.g)<=i&&Math.abs(c-r.b)<=i};var er={image:{getPixelValueAtIndex:(e,t)=>{const n=e.data,r=n[t]||0,i=n[t+1]||0,o=n[t+2]||0;return{avr:(r+i+o)/3,r:r,g:i,b:o}},getBoundingBox:(e,t,n)=>{const r=e.width,i=e.height,o=new Set,s=Number(n.threshold||0),a=isNaN(s)?10:s,c=(n,s)=>{const c=[[n,s]];let l=n,u=n,d=s,h=s;for(;c.length>0;){const n=c.shift();if(!n)continue;const[s,f]=n;s<0||f<0||s>=r||f>=i||o.has(`${s},${f}`)||!Qn(s,f,e,t,a||0)||(o.add(`${s},${f}`),l=Math.min(l,s),u=Math.max(u,s),d=Math.min(d,f),h=Math.max(h,f),c.push([s+1,f],[s-1,f],[s,f+1],[s,f-1]))}return{minX:l,maxX:u,minY:d,maxY:h}},l=[];for(let s=0;s<i;s+=4)for(let i=0;i<r;i+=4)if(!o.has(`${i},${s}`)&&Qn(i,s,e,t,a)){const{minX:e,maxX:t,minY:r,maxY:o}=c(i,s),a=t-e,u=o-r;if(a>=(n.minWidth||1)&&u>=(n.minHeight||1)&&l.push({left:e,top:r,width:a,height:u}),n.maxBoxes&&l.length>=n.maxBoxes)return l}return l},copyImageData:e=>new ImageData(new Uint8ClampedArray(e.data),e.width,e.height),setPixelValueAtIndex:(e,t,n)=>{const r=e.data,i="object"==typeof n,o=i?n.r:n,s=i?n.g:n,a=i?n.b:n;r[t]=o,r[t+1]=s,r[t+2]=a,r[t+3]=255}}};const tr=e=>Fe(e),nr=s.enum(["Read","Modify","Comment"]),rr=s.object({email:s.email(),name:s.string(),accessMode:nr});var ir;!function(e){e.Seats="seats",e.RecipeInvocations="recipe_invocations",e.HubServices="hub_services",e.RecipeExports="recipe_exports",e.RecipeHistory="recipe_history",e.AssistedCodeGeneration="assisted_code_generation",e.CustomServices="custom_services",e.OnDeviceSecretManagement="on_device_secret_management",e.PrivateRecipes="private_recipes",e.InBrowserRecipeExecution="in_browser_recipe_execution",e.EventLoggerLogsRetention="event_logger_logs_retention",e.AgenticExecutions="agentic_executions",e.PrivateSnippets="private_snippets",e.SnippetHistory="snippet_history",e.LogHistoryRetentionDays="log_history_retention_days",e.LogHistoryMonthlyEvents="log_history_monthly_events",e.FileStorageRetentionHours="file_storage_retention_hours",e.FileStorageSizeMB="file_storage_size_mb",e.PrivateWidgets="private_widgets",e.WidgetHistory="widget_history"}(ir||(ir={}));const or=s.enum(["active","inactive"]),sr=s.enum(["CreateApiKeys","RevokeApiKeys"]),ar=s.enum(["organization"]),cr=s.object({[ar.enum.organization]:s.object({scopes:s.array(sr)}).optional()}).partial(),lr=s.enum(["Owner","Admin","Member"]);s.object({apiKey:s.string(),createdAt:s.string(),createdBy:s.string()}),s.object({id:s.string(),organizationId:s.string(),userId:s.string(),key:s.string(),comment:s.string().optional(),createdAt:s.string(),createdBy:s.string(),revokedAt:s.string().optional(),revokedBy:s.string().optional()});const ur=s.object({country:s.string(),city:s.string(),address1:s.string(),address2:s.string(),postCode:s.string()}),dr=s.object({id:s.string(),name:s.string(),groups:s.array(s.string()),logo:s.string().optional(),industry:s.string().optional(),accountOwner:s.string(),stripeCustomerId:s.string(),stripeSubscription:s.custom(),domain:s.string().optional(),createdAt:s.string(),updatedAt:s.string(),accountState:s.custom(),location:ur.optional()}),hr=s.object({id:s.string(),firstName:s.string(),lastName:s.string(),email:s.email().optional(),loginId:s.string().optional(),role:lr,groups:s.array(s.string()).optional().default([]),entityScopes:cr.optional(),status:or,lastSeenAt:s.string().optional(),createdAt:s.string()});var fr,pr,gr,mr;dr.pick({id:!0,name:!0,stripeSubscription:!0,stripeCustomerId:!0}),s.object({member:s.object({firstName:s.string().optional(),lastName:s.string().optional(),email:s.string().optional(),role:lr.optional(),groups:s.array(s.string()).optional(),status:or,entityScopes:cr.optional()})}),hr.omit({id:!0,createdAt:!0,lastSeenAt:!0}),s.object({name:s.string(),location:ur.optional()}),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"}(fr||(fr={})),function(e){e.Hardware="hardware",e.Virtual="virtual"}(pr||(pr={})),function(e){e.Cloud="cloud",e.Web="web"}(gr||(gr={})),function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(mr||(mr={}));const yr=s.object({name:s.string(),category:s.string(),id:s.string(),type:s.enum(gr),version:s.string()}),vr=s.object({version:s.number(),contents:s.string(),contentsLength:s.number(),createdAt:s.string(),comments:s.string().optional()}),br=s.object({id:s.string(),name:s.string(),uuid:s.string().optional(),version:s.number(),dataSources:s.array(s.object({host:s.string().optional(),stream:s.string(),blocks:s.array(s.string())})).optional(),protocolVersion:s.string(),linkedTutorial:s.string().optional(),blocks:s.array(yr),widgets:s.array(s.object({type:s.string(),name:s.string(),thingId:s.string()})).optional(),contents:s.string(),storage:s.string().optional(),history:s.array(vr).optional(),cloud:s.object({environment:s.enum(fr),enabled:s.boolean()}).optional()}),wr=s.object({recipeId:s.string(),version:s.number()});br.extend({userId:s.string(),author:s.object({name:s.string(),id:s.string()}),copiedFrom:wr.optional(),updatedAt:s.string(),createdAt:s.string(),preview:s.string(),isPublic:s.boolean(),isDefault:s.boolean(),meta:s.object({contentsLength:s.number(),storageLength:s.number(),storageChecksum:s.string().optional()}),sharedWith:s.array(rr),publicSharedId:s.string().optional(),marketplacePublication:s.string().optional()});const Sr=br.omit({id:!0,version:!0,contents:!0,storage:!0});var _r,Ir,xr,kr,Er,Cr,$r,Or;s.object({rawContents:s.string(),recipe:Sr.extend({contentLength:s.number(),copiedFrom:wr.optional()}),storageSize:s.number().optional(),storageChecksum:s.string().optional(),comments:s.string().optional(),currentVersion:s.number().optional()}),s.object({message:s.string(),recipeId:s.string(),version:s.number(),versionHistory:s.array(vr)}),function(e){e.Bundle="bundle",e.Group="group"}(_r||(_r={})),function(e){e.Gateway="gateway",e.Timer="timer"}(Ir||(Ir={})),function(e){e.InstallInProgress="installation-in-progress"}(xr||(xr={})),function(e){e.InstallDependencies="install-dependencies",e.GetInstalledDependencies="get-installed-dep"}(kr||(kr={})),function(e){e.Success="success",e.Error="error",e.Pending="pending"}(Er||(Er={})),function(e){e.NotFound="not-found",e.BadRequest="bad-request",e.Forbidden="forbidden",e.InternalError="internal-error"}(Cr||(Cr={})),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",e.IsCustomTier="is_custom_tier"}($r||($r={})),function(e){e.KeyCreated="key_created",e.ValidateKey="validate_key",e.ExecuteRecipe="execute_recipe",e.InstallHubService="install_hub_service",e.UninstallHubService="uninstall_hub_service",e.ExportRecipe="export_recipe"}(Or||(Or={}));const Nr=s.object({id:s.string(),name:s.string(),organizationId:s.string()}),Tr=s.object({version:s.number(),contents:s.string(),contentsLength:s.number(),createdAt:s.string(),title:s.string(),shortDescription:s.string(),comments:s.string().optional()}),Ar=s.object({id:s.string(),title:s.string(),author:Nr,shortDescription:s.string(),authorId:s.string(),category:s.string(),tags:s.array(s.string()),createdAt:s.string(),downloads:s.number().default(0),updatedAt:s.string(),iconSvg:s.string(),contents:s.string(),descriptionMarkdown:s.string(),githubUrl:s.string().optional(),visibility:s.enum(["public","private","organization"]),version:s.number(),history:s.array(Tr).default([]),deletedAt:s.string().optional()}),Mr=Ar.extend({rating:s.object({average:s.number(),total:s.number()}).optional()});s.object({id:s.string(),author:s.object({id:s.string(),name:s.string()}).optional(),description:s.string(),createdAt:s.string(),updatedAt:s.string(),snippetId:s.string(),deletedAt:s.string().optional(),isAbuseReport:s.boolean().optional(),reportReason:s.enum(["spam","inappropriate","not-working","security","other"]).optional()}),s.object({query:s.string().optional(),category:s.string().optional(),featured:s.boolean().optional(),recommended:s.boolean().optional(),sortBy:s.enum(["most_recent","most_liked","alphabetical"]).optional(),visibility:s.enum(["public","private","organization"]).optional(),page:s.number().optional(),limit:s.number().optional()}),s.object({snippets:s.array(Mr),total:s.number(),page:s.number(),limit:s.number(),hasMore:s.boolean()}),s.object({snippetId:s.string(),rating:s.number(),off:s.boolean().optional()}),s.object({average:s.number(),total:s.number()}),s.object({success:s.boolean(),error:s.string().optional()}),s.object({snippet:s.lazy((()=>s.object({title:s.string(),shortDescription:s.string(),category:s.string(),tags:s.array(s.string()),iconSvg:s.string(),contents:s.string(),descriptionMarkdown:s.string(),githubUrl:s.string().optional(),visibility:s.enum(["public","private","organization"]),deletedAt:s.string().optional()})))}),s.object({snippet:s.lazy((()=>s.object({title:s.string(),shortDescription:s.string(),category:s.string(),tags:s.array(s.string()),iconSvg:s.string(),contents:s.string(),descriptionMarkdown:s.string(),githubUrl:s.string().optional(),visibility:s.enum(["public","private","organization"])})))}),s.object({snippet:Ar}),s.object({snippet:Ar}),s.object({snippetId:s.string(),version:s.number()}),s.object({snippet:Ar});let Pr=null;var Dr=()=>{if(!Pr)throw new Error("Required function is not set");return Pr};class jr extends Error{targetWidgetId;targetPortName;sourcePortName;sourceWidgetId;targetWidgetType;sourceWidgetType;constructor(e,t){super(e),this.name="ChildWidgetError",t.stack&&(this.stack=t.stack),this.targetWidgetId=t.targetWidgetId,this.targetPortName=t.targetPortName,this.sourcePortName=t.sourcePortName,this.sourceWidgetId=t.sourceWidgetId,this.targetWidgetType=t.targetWidgetType,this.sourceWidgetType=t.sourceWidgetType}}class Rr extends Error{constructor(e,t){super(e),this.name="UserCodeError",t&&(this.stack=t)}}const Lr=(e,t)=>`\n\t\tfunction _user_code_(){\n\t\t\t${t===mr.Browser?"\n\t\t\tvar global = {\n\t\t\t\t__user_code: true\n\t\t\t};\n\t\t\tvar process = {};\n\t\t\tvar globalThis = global;\n\t\t\tvar require = this.___notSupportedMethod;\n\t\t\t":"\n\t\t\tvar require = this.require;\n\t\t\tvar process = this.kemuProcess;\n\t\t\t"}\n\t\t\t\n\t\t\tvar console = this.console;\n\t\t\tvar eval = () => {};\n\t\t\tvar document = {};\n\t\t\tvar navigator = {};\n\t\t\tvar window = this.window;\n\t\t\tvar alert = this.notify.info;\n\t\t\tvar DataType = this.dataTypesEnum;\n\t\t\tvar setInterval = this.setInterval;\n\t\t\tvar setTimeout = this.setTimeout;\n\t\t\tvar addEventListener = this.addEventListener;\n\t\t\tvar removeEventListener = this.removeEventListener;\n\t\t\tvar requestAnimationFrame = this.___notSupportedMethod;\n\t\t\tvar __delay = (ms) => new Promise((resolve, reject) => setTimeout(resolve, ms, reject));\n\t\t\tvar sendToPort;\n\t\t\t// Updated function to send data to the next widget using new object syntax\n\t\t\tvar setOutput;\n\n\t\t\tvar Kemu = {\n\t\t\t\timage: this.imageHelpers,\n\t\t\t\tvariable: this.variablesManager,\n\t\t\t\tstatus: this.statusManager,\n\t\t\t\tsecrets: this.secretsManager,\n\t\t\t\tglobalVars: this.globalVariablesManager,\n\t\t\t\thelpers: {\n\t\t\t\t\tdecodeDataType: this.decodeDataType,\n\t\t\t\t\tcryptoJS: this.CryptoJS,\n\t\t\t\t\thttp: this.http,\n\t\t\t\t\tdelay: __delay,\n\t\t\t\t}\n\t\t\t};\n\n\t\t\t\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\tlet userProcessEvent = typeof processEvent === 'undefined' ? undefined : processEvent;\n\t\t\t\tlet userOnParentEvent = typeof onParentEvent === 'undefined' ? undefined : onParentEvent;\n\t\t\t\t\n\n\t\t\t\tif(userProcessEvent || userOnParentEvent) {\n\t\t\t\t\ttry{\n\t\t\t\t\t\tif(userProcessEvent) {\n\t\t\t\t\t\t\treturn await userProcessEvent(targetPort, sourcePort, event);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\treturn await userOnParentEvent({ targetPort, sourcePort, event });\n\t\t\t\t\t\t}\n\t\t\t\t\t}catch(e){\n\t\t\t\t\t\tthis.__errorTracer(e);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/** invoked the very first time the recipe is initialized */\n\t\t\tconst asyncRecipeInit = async (context) => {\n\t\t\t\ttry {\n\t\t\t\t\tif(typeof recipeInit === 'function') {\n\t\t\t\t\t\treturn recipeInit(context);\n\t\t\t\t\t}\n\t\t\t\t}catch(e){\n\t\t\t\t\tthis.__errorTracer(e);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/** invoked every time the code is about to be replaced */\n\t\t\tconst asyncOnTerminate = async (context) => {\n\t\t\t\ttry {\n\t\t\t\t\tif(typeof onTerminate === 'function') {\n\t\t\t\t\t\treturn onTerminate(context);\n\t\t\t\t\t}\n\t\t\t\t}catch(e){\n\t\t\t\t\tthis.__errorTracer(e);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/** updates the function that allows widget contexts to send data to the next widget */\n\t\t\tconst setSendToPort = (sendNextFun) => {\n\t\t\t\tsendToPort = sendNextFun;\n\t\t\t}\n\n\t\t\t/** updates the function that allows widget contexts to send data to the next widget with the new object argument syntax */\n\t\t\tconst setSetOutputFn = (setOutputFn) => {\n\t\t\t\tsetOutput = setOutputFn;\n\t\t\t}\n\n\t\t\t/** invoked the every time the user code is compiled. */\n\t\t\tconst asyncMainEvent = async (sendNextFun) => {\n\t\t\t\ttry{\n\t\t\t\t\t// setSendToPort(sendNextFun);\n\t\t\t\t\tif(typeof main === 'function'){\n\t\t\t\t\t\treturn main();\n\t\t\t\t\t}\n\t\t\t\t}catch(e){\n\t\t\t\t\tthis.__errorTracer(e);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tasyncProcessEvent: asyncProcessEvent,\n\t\t\t\tmain: asyncMainEvent,\n\t\t\t\trecipeInit: asyncRecipeInit,\n\t\t\t\tsetSendToPortFun: setSendToPort,\n\t\t\t\tsetSetOutputFn: setSetOutputFn,\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`,Fr=(e,t,n,r)=>{const i=Lr(e,n),s={...t,document:{},__errorTracer:e=>{if(e instanceof jr)throw e;throw new Rr(e.message,e.stack)},__jest:void 0===globalThis.__jest?void 0:globalThis.__jest,___notSupportedMethod:()=>r?.error("This method is not supported."),console:{...t.logger},setInterval:()=>r?.error("'setInterval' is not supported. Please use a \"Timer\" widget instead."),setTimeout:t?.setTimeout,imageHelpers:er.image,...n===mr.Cloud?{require:Dr(),kemuProcess:process.env.KEMU_PROCESS?process.env.KEMU_PROCESS:{}}:{},CryptoJS:o,decodeDataType:tr,window:{addEventListener:t?.addEventListener,removeEventListener:t?.removeEventListener}};try{const e="browser"===(()=>{if(X)return"browser";if(ee)return"node";if(Q)return"worker";throw new Error("Unsupported environment")})()?(e=>e.replace(/[//]{2}[ ]*@kemu-cloud[ \t]*\{[\s\S]*?[//]{2}[ ]*@kemu-cloud[ \t]*\}/gim,""))(i):(e=>e.replace(/[//]{2}[ ]*@kemu-browser[ \t]*\{[\s\S]*?[//]{2}[ ]*@kemu-browser[ \t]*\}/gim,""))(i),t=new Function(e);return{compiledModule:t()(s)}}catch(e){return{error:{name:"CompileError",message:e.message,stack:e.stack}}}},Ur="main",Br="My Script",Wr="This is a test script.",Gr=`\n/**\n * Name: ${Br}\n * Description: ${Wr}\n */\n\nconst getWidgetInputs = () => [\n\t{ name: 'Input 1', type: DataType.Number }\n];\n\nconst getWidgetOutputs = () => [\n\t{ name: 'Output 1', type: DataType.Number }\n]\n\nlet counter = 0;\n\nconst onParentEvent = async ({ targetPort, sourceWidget, event }) => {\n\tif(targetPort.name === 'Input 1'){\n\t\treturn setOutput({\n\t\t\tport: 'Output 1',\n\t\t\tdata: {\n\t\t\t\ttype: DataType.Number,\n\t\t\t\tvalue: counter++,\n\t\t\t}\n\t\t});\n\t}\n}\n`.trim(),Vr=()=>({pauseExecution:!1,autoPauseOnError:!0,$$eventListeners:{},version:2,metadata:{name:Br,description:Wr},pages:{[Ur]:{code:Gr,language:"javascript",name:"My First Script"}}}),Yr=(e,t)=>{const n={message:"Unknown Error"};if(e?.stack){const r=e?.stack?.split(":")[0].trim();n.type=r;const i=(e=>{const t=/,[ ]?<anonymous>:([0-9]+:[0-9]+)\)/gm;let n;for(;null!==(n=t.exec(e));){n.index===t.lastIndex&&t.lastIndex++;const e=n[1].split(":");if(2===e.length)return{line:Number(e[0])||0,column:Number(e[1])||0}}return null})(e.stack);i&&(n.line=i.line-(e=>{const t="___user_code_section___";return Lr(t,e).split(t)[0].split("\n").length+2})(t),n.column=i.column)}return e.message&&(n.message=e.message),n},Hr=(e,t)=>{const n={...{...Vr(),...t.getState()},$$error:e||void 0};e&&console.error(e.message),t.setState(n)},zr=new a;let qr,Kr,Jr={},Zr={};const Xr=e=>{const t=ae(qr,Kr,e);if(!t)throw new Error(`Widget ${e} not found in thing ${Kr}`);return t},Qr=(e,t)=>`${e}:${t}`,ei=e=>`${Xr(e.createdByWidgetId).id}::${e.variableName}`,ti=e=>`${de}${e}`;var ni=e=>{const t=Xr(e.createdByWidgetId),n=ei({variableName:e.variableName,createdByWidgetId:e.createdByWidgetId});Zr[n]={type:e.type,subscriberWidgetId:t.id,subscriberWidgetType:t.type}},ri=e=>{const t=ei({variableName:e.variableName,createdByWidgetId:e.createdByWidgetId});delete Zr[t]},ii=async e=>{const t=Xr(e.setByWidgetId);if(!t)throw new Error(`Widget ${e.setByWidgetId} not found in thing ${Kr} in recipe ${qr}`);const n=e.variableName.startsWith(de)?ei({variableName:e.variableName,createdByWidgetId:e.setByWidgetId}):e.variableName;Jr[n]={value:e.value,type:e.type};const r={value:e.value,type:e.type,varName:e.variableName,isUIElement:e.variableName.startsWith(de),setByWidgetType:t.type,setByWidgetId:e.setByWidgetId};await zr.emit(Qr(e.variableName,e.type),r),e.type!==pe.Anything&&await zr.emit(Qr(e.variableName,pe.Anything),r)},oi=e=>{const{readerWidgetId:t,variableName:n}=e;if(!Xr(t))throw new Error(`Widget ${t} not found in thing ${Kr} in recipe ${qr}`);const r=n.startsWith(de)?ei({variableName:e.variableName,createdByWidgetId:e.readerWidgetId}):n,i=Jr[r];if(i)return{type:i.type,value:i.value}},si=e=>{const{widgetId:t,variableName:n,type:r}=e;if(!Xr(t))throw new Error(`Widget ${t} not found in thing ${Kr} in recipe ${qr}`);const i=Qr(n,r);let o;return o=zr.on(i,(async r=>{ae(qr,Kr,t)?await e.onValueChange(r):(console.warn(`Zombie widget ${t} detected, unsubscribing from variable events "${n}"`),o?.())})),o},ai=e=>{Zr={},Jr={},qr=e.recipePoolId,Kr=e.thingId};const ci="setTimeout",li="variableChanged",ui="globalVariableChanged",di=e=>{const{recipePoolId:t,thingId:n,scriptWidgetId:r}=e,i=ae(t,n,r);if(!i)throw new Error(`Widget "${r}" not found in recipe "${t}"`);const o=(e,t)=>{const n=oi({readerWidgetId:r,variableName:e});if(n||t)return void 0===n?{value:t?.value??t,type:t?.type??Fe(t)}:{value:n.value,type:n.type}},s=(t,n,o)=>{if(!e.setState)return void console.warn("Cannot subscribe to variable changes without a setState function");const s={...Vr(),...e.getState()},a=si({variableName:t,type:pe.Anything,widgetId:r,onValueChange:async e=>{n?e.setByWidgetType===ze.widgetGroup&&e.setByWidgetId===i.groupId&&await o(e):o(e)}});delete s.$$eventListeners[t],s.$$eventListeners[t]={handler:o,abort:async()=>{a()},name:li},e.setState(s)};return{get:o,set:async(e,t,n)=>{await ii({variableName:e,type:n||Fe(t),setByWidgetId:r,value:t})},onValueChange:(e,t)=>{s(e,!1,t)},onUIValueChange:(e,t)=>{const n=ti(e);s(n,!0,t)},getUIValue:e=>{const r=ti(e),s=o(r);if(s)return{value:s.value,type:s.type};const a=i.groupId;if(!a)throw new Error("You can only read UI variables from inside a widgetGroup");const c=ae(t,n,a);if(!c)throw new Error(`Widget "${a}" not found in recipe "${t}"`);const l=c.state,u=(l.settings||[]).find((t=>t.variableName===e));if(!u)throw new Error(`Field "${e}" not found in widgetGroup "${l.name}"`);const d=u.config,h=d.customValue??d.defaultValue;if(void 0===h)throw new Error(`Field "${e}" in widgetGroup "${l.name}" has no default value`);return{value:h,type:Fe(h)}}}};let hi;var fi=e=>{hi=e},pi=()=>{if(!hi)throw new Error("Hub Connector not set");return hi};const gi=new a,mi="invoked";let yi={},vi={},bi={},wi={};const Si=(e,t,n)=>`${e}-${t}${n?`-${n}`:""}`;var _i=e=>{const{data:t,thingId:n,widgetId:r,sourcePortName:i,recipeId:o,target:s,sourceOutputNames:a,currentPath:c,eventId:l}=e,u=Si(n,r,i),d=Si(n,r),h=Si(n,r,"produced"),f=bi[d],p=Date.now();wi[d]=p,yi[u]={data:t,recipeId:o,currentPath:c,eventId:l,source:{widgetId:r,portName:i},sourceOutputNames:a,...s?{target:{widgetId:s.widgetId,portName:s.portName}}:{}},gi.emit(h,{currentTime:p,prevTime:f,...s?{targetPort:s?.portName}:{}})},Ii=e=>{const{thingId:t,widgetId:n,targetPortName:r,data:i,source:o,originalEvent:s,recipeId:a,sourceOutputNames:c,currentPath:l,eventId:u}=e,d=Si(t,n,r),h=Si(t,n),f=Si(t,n,mi),p=bi[h],g=Date.now();bi[h]=g,vi[d]={data:i,recipeId:a,originalEvent:s,sourceOutputNames:c,currentPath:l,eventId:u,target:{widgetId:n,portName:r},...o?{source:{widgetId:o.widgetId,portName:o.portName}}:{}},gi.emit(f,{prevTime:p,currentTime:g,targetPort:r,sourceInfo:o})},xi=()=>{yi={},vi={},bi={},wi={},gi.clearListeners()};const ki=e=>{const{recipePoolId:t,widgetId:n,secrets:r,clearExistingSecrets:i}=e,o=se({recipeId:t,widgetId:n});if(!o)throw new Error(`Widget [${n}] not found in recipe [${t}]`);i&&(o.secrets={});for(const e of r)o.secrets={...o.secrets,[e.name]:e}},Ei=e=>{const{recipePoolId:t,widgetId:n}=e,r=se({recipeId:t,widgetId:n});if(!r)throw new Error(`Widget [${n}] not found in recipe [${t}]`);delete r.secrets},Ci={},$i="value",Oi=async e=>{const{recipeUuid:t,secretNames:n,serviceName:r}=e,i=pi(),o=[{recipeUuid:t,secretNames:n,serviceName:r}];let s={};try{const e=await i.executeHubFunction(ve.GetRecipeDecryptedSecretsValues,o);e&&(s=e[0].secrets)}catch(e){if("FNC_NOT_FOUND"===e.errCode)throw new Error("Your Hub does not support dynamic secrets. Please update your Hub to the latest version.");throw new Error(`Failed to read secret "${n.join(", ")}" from Hub: ${e.message}`)}return s},Ni=e=>{const t=ie(e);if(!t)throw new Error(`Recipe [${e}] does not exist]`);return{uuid:t.uuid,recipeType:t.dbInfo?.recipeType}};var Ti={onParentEvent:async(e,t,n,r)=>{const i={name:"",...r.getState()};if(!i.name||!e)return;const{uuid:o}=Ni(r.recipePoolId);if(!o)throw new Error(`Recipe [${o}] does not have a valid id]`);const s=r.recipeType===fe.Desktop,a=Ci[r.id]?.[i.name];let c=a;if(!a||a&&!s){const e=await Oi({recipeUuid:o,secretNames:[i.name]});c=e?.[i.name],null!=c&&s&&(Ci[r.id]||(Ci[r.id]={}),Ci[r.id][i.name]=c)}if(null==c)throw new Error(`Secret "${i.name}" not mapped to this recipe`);r.nextWidget($i,{type:pe.String,value:c})},getOutputNames:()=>[{name:$i,type:pe.String}],getInputNames:()=>[{name:"read",type:pe.Anything}],terminate:async e=>{Ci[e.widgetId]={},Ei({recipePoolId:e.recipePoolId,widgetId:e.widgetId})},initialize:async e=>{const t={name:"",...e.getState()};t.name&&(Ci[e.widgetId]={},ki({recipePoolId:e.recipePoolId,widgetId:e.widgetId,secrets:[{name:t.name}]}))}};const Ai={},Mi=e=>{const{recipePoolId:t,thingId:n,scriptWidgetId:r}=e,i=ie(t),o=i?.dbInfo.recipeType,s=Ni(t).uuid,a=ae(t,n,r);return{secretsManager:{requestAccess:e=>{a&&(a.secrets={...a.secrets,[e]:{name:e}})},read:async e=>{if(!a)return e.reduce(((e,t)=>(e[t]=null,e)),{});const t=o===fe.Desktop,n={};let i=[];for(const t of e){const e=Ai[r]?.[t];null==e&&i.push(t)}if(t||(i=e),i.length>0){const t=await Oi({recipeUuid:s,secretNames:i});for(const i of e){const e=t?.[i],o=Ai[r]?.[i];n[i]=void 0!==e?e:void 0!==o?o:null}Ai[r]={...Ai[r],...n}}else for(const t of e)n[t]=Ai[r]?.[t]||null;return n}},unregisteredSecrets:()=>{a&&(a.secrets={})}}},Pi=new a;let Di={};const ji="statusValueChanged",Ri="keyRemovedFromWidget",Li=()=>{Di={}},Fi=()=>{Pi.clearListeners()},Ui=e=>{Pi.emit(ji,e)};var Bi=e=>{const{name:t,value:n,sourceWidget:r,widgetId:i,widgetType:o}=e;Di[i]=Di[i]||[];const s=Di[i].find((e=>e.name===t&&e.widgetType===o&&e.widgetId===i));s?s.data=n:Di[i].push({name:t,data:n,sourceWidget:r,widgetId:i,widgetType:o});let a=n;null===n&&(a={type:pe.Anything,value:""}),Ui({name:t,value:a,sourceWidget:r,statusWidgetId:i,widgetType:o})},Wi=e=>Pi.on(ji,e),Gi=()=>{Li(),Fi()},Vi=e=>{const t=()=>{const e=[];for(const t in Di)for(const n of Di[t])e.push(n.name);return e},n=t();delete Di[e];(e=>{Pi.emit(Ri,e)})({before:n,after:t()})};const Yi=e=>{const{scriptWidgetId:t}=e;return{statusManager:{set:(e,n)=>{let r=null;r=n&&"object"==typeof n&&"value"in n&&"type"in n||null==n||void 0===n?n:{type:Fe(n),value:n},Bi({name:e,sourceWidget:t,widgetId:t,value:r,widgetType:ze.script})}},clearStatusValues:()=>{Vi(t)}}},Hi=new a,zi=e=>{if(e.includes("."))throw new Error("Variable and group names cannot contain dots")},qi=(e,t)=>{if(!t)throw new Error("name is required");return zi(t),e?`${e}.${t}`:t},Ki=e=>{if(!e)throw new Error("fullPath is required");const t=e.lastIndexOf(".");if(-1===t)return{group:null,name:e};return{group:e.substring(0,t),name:e.substring(t+1)}},Ji=e=>`globalVariableChange_${e}`,Zi=e=>`globalVariableGroupChange_${e}`,Xi=e=>`globalVariableParentGroupStateChange_${e}`,Qi=e=>`globalVariableRenamed_${e}`;let eo={};const to=e=>{const{name:t,notify:n=!0}=e,r=ro(t);if(!r)return;if("group"===r.controlType){const e=oo().filter((e=>!!e.group&&(e.group===t||e.group.startsWith(t+"."))));for(const t of e)to({name:t.name,notify:n})}n&&Hi.emit("globalVariableRemoved",r),delete eo[t]},no=()=>{for(const e in eo)to({name:e,notify:!0})},ro=e=>{let t;t="string"==typeof e?e:qi(e.group,e.name);return eo[t]??null},io=async e=>{const{value:t,lastDataType:n,controlType:r,widgetId:i,doNotOverrideExisting:o=!1,executionContext:s,helpText:a,order:c,forceValueChangeNotification:l=!1,disableChangeNotifications:u=!1,disableDefineNotifications:d=!1,group:h}=e;let{controlSettings:f,name:p}=e;if(!p)throw new Error("name is required");zi(p),p=p.replace(/-/g,"_");const g=qi(h??null,p);let m=ro(g);const y=!m,v=!!m;if(y)m={},f||(f=(e=>{switch(e){case"number":case"slider":return{min:0,max:100,step:1};case"dropdown":case"multiSelect":return{options:[]};case"binaryFile":return{allowedMimeTypes:[]};default:return{}}})(r??"anything"));else if(o)return;const b=n??(t?Fe(t):null),w=t!==m.lastValue,S=h!==m.group&&void 0!==h,_=c!==m.order&&void 0!==c;m.lastDataType=b,m.lastValue=t,m.controlType=r??m.controlType??"anything",m.lastChangedByWidgetId=i??null,m.lastExecutionContext=s??null,m.helpText=a??m.helpText,m.controlSettings=f??m.controlSettings,m.name=g,m.order=c??m.order,m.group=void 0!==h?h:m.group,eo[g]=m,u||null!==t&&(w||l)&&(await Hi.emit(Ji(g),m),await Hi.emit("globalVariableChange_any",m)),v&&(S||_)&&await Hi.emit(Zi(g),m),y&&!d&&await Hi.emit("globalVariableDefined",m)},oo=()=>Object.values(eo),so=e=>oo().filter((t=>!!t.group&&(t.group===e||t.group.startsWith(e+".")))),ao={resetAllGlobalVariables:no,getGlobalVariable:ro,setGlobalVariable:io,onGlobalVariableChange:(e,t)=>Hi.on(Ji(e),t),onGlobalVariableParentGroupChange:(e,t)=>Hi.on(Zi(e),t),onVarParentGroupStateChange:(e,t)=>Hi.on(Xi(e),t),notifyGroupMembersOfParentGroupChange:async e=>{const t=so(e),n=ro(e);if(n)for(const e of t)await Hi.emit(Xi(e.name),{variable:e,parentGroup:n})},deleteGlobalVariable:to,onGlobalVariableDefined:e=>Hi.on("globalVariableDefined",e),onGlobalVariableRemoved:e=>Hi.on("globalVariableRemoved",e),onGlobalVariableRenamed:(e,t)=>Hi.on(Qi(e),t),onAnyGlobalVariableChange:e=>Hi.on("globalVariableChange_any",e),getAllVariables:oo,renameVariable:e=>{const{oldName:t,newName:n}=e,r=ro(t);if(!r)throw new Error("Global variable not found");zi(n);const i="group"===r.controlType,{group:o}=Ki(t),s=qi(o,n);if(i){const e=oo().filter((e=>!!e.group&&(e.group===t||e.group.startsWith(t+"."))));for(const n of e){const{group:e,name:r}=Ki(n.name);let i=null;e&&(i=e===t?s:e.startsWith(t+".")?s+e.substring(t.length):e),io({name:r,value:n.lastValue,lastDataType:n.lastDataType??null,controlType:n.controlType,controlSettings:n.controlSettings,widgetId:n.lastChangedByWidgetId??void 0,executionContext:n.lastExecutionContext??void 0,helpText:n.helpText??void 0,order:n.order??void 0,group:i,disableChangeNotifications:!0,disableDefineNotifications:!0})}}to({name:t,notify:!1}),io({name:n,controlSettings:r.controlSettings,value:r.lastValue,lastDataType:r.lastDataType??null,controlType:r.controlType,widgetId:r.lastChangedByWidgetId??void 0,executionContext:r.lastExecutionContext??void 0,helpText:r.helpText??void 0,order:r.order??void 0,group:o}),Hi.emit(Qi(t),{oldName:t,newName:s})},registerGlobalVariables:e=>{no(),eo={};const t=e.map((e=>{if(!e.name.includes(".")){if(e.group){const t=qi(e.group,e.name);return{...e,name:t}}return e}const{name:t}=Ki(e.name);if(t.includes("."))throw new Error(`Invalid variable name: "${e.name}" - display names cannot contain dots`);return e}));for(const e of t)eo[e.name]=e},getVariablesInGroup:so,isGroupVariable:e=>"group"===e.controlType,buildFullPath:qi,parsePath:Ki,validateName:zi},co="kemu.io.scriptHttp",lo=e=>{const{recipePoolId:t,widgetId:n,httpConfig:r}=e,i=pi();let o;const s=(e=>e.find((e=>e.name===co&&e.internal))||null)(i.getCachedServices().available);if(!s)throw new Error("HTTP service not found");const a={listener:{recipeId:t},targetService:{serviceName:co,version:"1.0.0"}};i.subscribeToServiceEvents(a);const c=i.onBroadcastEvent(n,co,"1.0.0",(e=>{const t=e.outputs?.find((e=>"stream"===e.name));if(t){const e=t.value;o=e.requestId,r.onStream&&r.onStream(e)}})),l=le(t),u={currentState:{},recipe:l,recipeType:l.type,widgetId:n,recipeId:t},d=(e,t)=>i.callProcessorHandler(s.sessionId,u,e,t,{timeout:0});return{promise:d("send",r),abort:async()=>{c(),o&&await d("abort",{requestId:o})}}},uo="__command-compile__",ho={};let fo;const po=()=>{throw new Error("Method not implemented")},go=e=>{const{features:t,widgetContext:n,widgetEnvInfo:i}=e,o=(e,...t)=>{const r={...Vr(),...n.getState()}.$$eventListeners[e];r&&r.handler(t)},s={};Object.keys(pe).forEach((e=>{s[e]=pe[e]}));const a=Mi({recipePoolId:i.recipePoolId,thingId:i.thingId,scriptWidgetId:i.widgetId}),c=Yi({scriptWidgetId:i.widgetId}),l=(e=>{const{scriptWidgetId:t}=e,n=(t,n)=>{if(!e.setState)return void console.warn("Cannot subscribe to global variable changes without a setState function");const r={...Vr(),...e.getState()},i=async e=>{const t={name:e.name,value:e.lastValue,type:e.lastDataType,controlType:e.controlType};try{await n(t)}catch(e){console.error("Error in global variable change handler:",e)}},o=t?ao.onGlobalVariableChange(t,i):ao.onAnyGlobalVariableChange(i),s=t?`globalVar_${t}`:"anyGlobalVar";t&&r.$$eventListeners[s]&&delete r.$$eventListeners[s],r.$$eventListeners[s]={handler:n,abort:async()=>{o()},name:ui},e.setState(r)};return{get:e=>{const t=ao.getGlobalVariable(e);return t?{name:t.name,value:t.lastValue,type:t.lastDataType,controlType:t.controlType}:null},set:async e=>{const n=e.type?e.type:Fe(e.value);if(e.name.includes("."))throw new Error("Variable names cannot contain dots");if(e.group){const t=async(n,r)=>{if(ao.getGlobalVariable(n))return;const{group:i,name:o}=Ki(n);i&&await t(i,!1),await ao.setGlobalVariable({name:o,group:i,value:null,controlType:"group",controlSettings:{},helpText:r&&e.groupHelpText||void 0})};await t(e.group,!0)}await ao.setGlobalVariable({name:e.name,value:e.value,lastDataType:n,helpText:e.helpText,order:e.order,controlType:e.controlType??"anything",controlSettings:e.controlSettings,widgetId:t,disableChangeNotifications:!(e.emitChangeEvent??1),disableDefineNotifications:!(e.emitDefineEvent??1),group:e.group})},onValueChange:(e,t)=>{n(e,t)},onAnyValueChange:e=>{n(null,e)}}})({scriptWidgetId:i.widgetId,getState:n.getState,setState:n.setState});a.unregisteredSecrets(),c.clearStatusValues(),ho[i.widgetId]?.abortHttp?.().catch((e=>{console.warn("Error aborting old HTTP instance: ",e)}));return{logger:vo(),dataTypesEnum:s,recipePoolId:i.recipePoolId,widgetId:i.widgetId,http:e=>{const{promise:t,abort:n}=lo({httpConfig:e,recipePoolId:i.recipePoolId,widgetId:i.widgetId});ho[i.widgetId]={abortHttp:n};return t.abort=async()=>{delete ho[i.widgetId],await n()},t},notify:{success:e=>{n.getState()?.$$managedUI?.notify?.success(e)},error:e=>{n.getState()?.$$managedUI?.notify?.error(e)},info:e=>{n.getState()?.$$managedUI?.notify?.info(e)}},variablesManager:t.variablesManager?di({recipePoolId:i.recipePoolId,scriptWidgetId:i.widgetId,thingId:i.thingId,getState:n.getState,setState:n.setState}):{get:po,set:async()=>po(),onValueChange:po,onUIValueChange:po,getUIValue:po},statusManager:c.statusManager,secretsManager:a.secretsManager,globalVariablesManager:l,setTimeout:(e,o,s)=>{if(t.withTimers&&n&&n.setState&&n.registerInterrupt){const t=r(),a={...Vr(),...n.getState()};a.$$eventListeners[t]={handler:e,rejectHandler:s,name:ci},n.setState(a),n.registerInterrupt({type:"timeout",customTargetPortName:t,sourceWidgetId:i.widgetId,config:{timeout:o},customId:t})}},addEventListener:(e,t)=>{if(n.setState){const i=r(),s={...Vr(),...n.getState()};s.$$eventListeners[i]={handler:t,name:e},n.setState(s),window.addEventListener(e,o.bind(i))}else console.warn(`Cannot remove event listener '${e}' because the widget context is not available.`)},removeEventListener:(e,t)=>{if(n.setState){const r={...Vr(),...n.getState()},i=Object.keys(r.$$eventListeners).find((n=>r.$$eventListeners[n].name===e&&r.$$eventListeners[n].handler===t));n.setState(r),i&&removeEventListener(r.$$eventListeners[i].name,r.$$eventListeners[i].handler)}else console.warn(`Cannot remove event listener '${e}' because the widget context is not available.`)}}},mo=(e,t,n)=>{const r={...Vr(),...n.getState()},i=r.pages[Ur].$$compiledCode;if(i)return{compiledModule:i};{const i=go({features:e,widgetContext:n,widgetEnvInfo:t});return Fr(r.pages[Ur].code,i,n.recipeType)}},yo=e=>e.map((e=>({...e,name:e.name.replace("_","")}))),vo=()=>{const e=(e,...t)=>{if(fo)try{return fo[e](...t)}catch(e){return void console.log("Error in custom logger: ",e)}console[e](...t)};return{log:(...t)=>{e("log",...t)},error:(...t)=>{e("error",...t)},warn:(...t)=>{e("warn",...t)},info:(...t)=>{e("info",...t)}}},bo=async(e,t)=>{const n={...e};for(const r in e){if(e[r].name===ci){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},wo=async e=>{const t={...e};for(const r in e){if((n=e[r]).name===li||n.name===ui){const n=e[r]?.abort;if("function"==typeof n)try{await n()}catch(e){console.log("Error in abort interrupt handler: ",e)}delete t[r]}}var n;return t},So=async(e,t,n)=>{let r={...Vr(),...e.getState()};if(void 0!==n){r.pages[Ur]?.$$compiledCode?.onTerminate&&await(r.pages[Ur].$$compiledCode?.onTerminate());let t=await bo(r.$$eventListeners,e);t=await wo(t),r.$$eventListeners=t,r.pages[Ur].$$compiledCode=void 0,r.pages[Ur].code=n,e.setState({...r})}const i=!r.pages[Ur].$$compiledCode,{compiledModule:o,error:s}=mo({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(s){console.log("Failed to compile user code");const t=Yr(s,e.recipeType);return Hr(t,e),null}if(o){let n;r={...e.getState()},r.pages[Ur].$$compiledCode=o;const s=_o(r.pages[Ur].code);s?.name===r.metadata?.name&&s?.description===r.metadata?.description||(r.metadata=s||void 0);const a=e.nextWidget||e.nextGate;if(a&&o.setSendToPortFun(a),e.invokeNextWidget&&o.setSetOutputFn(e.invokeNextWidget),t)try{await o.recipeInit({setState:e.setState,getState:e.getState})}catch(t){n=Yr(t,e.recipeType)}if(a&&i)try{await o.main()}catch(t){n=Yr(t,e.recipeType)}r.$$lastInputs=o.getWidgetInputs?o.getWidgetInputs():[],r.$$lastOutputs=o.getWidgetOutputs?o.getWidgetOutputs():[],e.setState(r),Hr(n,e)}},_o=e=>{const t=e.trimStart().match(/^(?:\/\*\*(?:[^*]|\*(?!\/))*\*\/|\/\*(?:[^*]|\*(?!\/))*\*\/)/);if(!t)return null;const n=t[0].replace(/^\/\*\*?/,"").replace(/\*\/$/,"").split("\n").map((e=>e.replace(/^\s*\*?\s?/,"").trim())).join("\n"),r=n.match(/Name\s*:\s*([^]*?)(?=\n\s*[A-Za-z]+\s*:|$)/i),i=n.match(/Description\s*:\s*([^]*?)(?=\n\s*[A-Za-z]+\s*:|$)/i),o={};return r&&r[1]&&(o.name=r[1].trim()),i&&i[1]&&(o.description=i[1].trim()),Object.keys(o).length>0?o:null};var Io={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),o={...Vr(),...i};if(!o.pages[Ur])return console.warn("Missing default page");if(Pe(e?.name||""))return o.$$eventListeners[t.name]?(await o.$$eventListeners[t.name].handler(),o.$$eventListeners[t.name].name===ci&&delete o.$$eventListeners[t.name],void r.setState({...o})):void console.log(`Unknown interrupt id [${t.name}] `);const s=t.name===uo;await So(r,!1,s?n.data.value:void 0);const a=o.pages[Ur].$$compiledCode;if(e&&e.name!==uo&&a)try{await a.asyncProcessEvent(t,e,{...n,executionContext:{currentPath:r.currentPath,eventId:r.eventId}})}catch(e){if("UserCodeError"===e.name){const t=Yr(e,r.recipeType);throw Hr(t,r),t}throw e}},getInputNames:(e,t)=>{const n={...Vr(),...e},{compiledModule:r}=mo({},{recipePoolId:t.recipePoolId,thingId:t.thingRecipeId,widgetId:t.widgetId},{getState:()=>n,recipeType:t.recipeType});if(r?.getWidgetInputs){const e=r.getWidgetInputs();return yo(e)}return e.$$lastInputs||[]},getOutputNames:(e,t)=>{const n={...Vr(),...e},{compiledModule:r}=mo({},{recipePoolId:t.recipePoolId,thingId:t.thingRecipeId,widgetId:t.widgetId},{getState:()=>n,recipeType:t.recipeType});if(r?.getWidgetOutputs){const e=r.getWidgetOutputs();return yo(e)}return e.$$lastOutputs||[]},getDefaultState:Vr,initialize:async e=>{const t=e.getState(),n={...Vr(),...t};n.pages[Ur].code&&await So({getState:e.getState,id:e.widgetId,recipePoolId:e.recipePoolId,recipeType:e.recipeType,registerInterrupt:e.registerInterrupt,setState:e.setState,nextWidget:e.nextWidget,invokeNextWidget:e.invokeNextWidget,thingRecipeId:e.thingRecipeId,cancelInterrupt:()=>!0},!0,n.pages[Ur].code)},terminate:async e=>{try{const t=e.getState();t.pages[Ur].$$compiledCode?.onTerminate&&await t.pages[Ur].$$compiledCode.onTerminate();const n=e=>Qe.destroyInterrupt(e),r=await bo(t.$$eventListeners,{cancelInterrupt:n});await wo(r);const i=Yi({scriptWidgetId:e.widgetId});Mi({recipePoolId:e.recipePoolId,thingId:e.thingRecipeId,scriptWidgetId:e.widgetId}).unregisteredSecrets(),i.clearStatusValues();for(const e of Object.values(ho))e.abortHttp?.().catch((e=>{console.warn("Error aborting old HTTP instance: ",e)}))}catch(t){console.warn(`Error terminating script widget ${e.widgetId}: `,t)}}};const xo=new Map,ko=e=>(xo.has(e)||xo.set(e,xe(320,240)),xo.get(e)),Eo=Object.freeze({image:"image"}),Co=Object.freeze({base64:"base64"}),$o=()=>({});var Oo={onParentEvent:async(e,t,n,r)=>{const i={...r.getState()};if(t.name===Co.base64){if("string"!=typeof n.data.value)return;if(n.data.type!==pe.String&&n.data.type!==pe.Anything)return;const e=n.data.value,t=ko(r.id);try{const n=await Ye({base64Str:e,memoryCanvas:t,finalW:i.resize?.width,finalH:i.resize?.height});return r.setState(i),r.nextGate(Eo.image,{type:pe.ImageData,value:n})}catch(e){console.log("[base64ToImageData] Error: ",e)}}},getInputNames:()=>[{name:Co.base64,type:pe.String}],getOutputNames:()=>[{name:Eo.image,type:pe.ImageData}],getDefaultState:$o,initialize:async e=>{ko(e.widgetId)},terminate:async e=>{xo.delete(e.widgetId)}};const No=Object.freeze({object:"object",error:"error"}),To=Object.freeze({string:"string"}),Ao=()=>({outputIsArray:!1});var Mo={onParentEvent:async(e,t,n,r)=>{const i={outputIsArray:!1,...r.getState()};if((n.data.type===pe.String||n.data.type===pe.Anything)&&"string"==typeof n.data.value)try{const e=JSON.parse(n.data.value),t=Array.isArray(e);return t&&!i.outputIsArray?r.setState({...i,outputIsArray:!0}):!t&&i.outputIsArray&&r.setState({...i,outputIsArray:!1}),r.nextGate("object",{type:t?pe.Array:pe.JsonObj,value:e})}catch(e){return r.nextGate("error",{type:pe.Boolean,value:!0})}},getInputNames:()=>[{name:To.string,type:pe.String}],getOutputNames:e=>[{name:No.object,type:[pe.JsonObj,pe.Array],label:e.outputIsArray?"array":No.object},{name:No.error,type:pe.Boolean}],getDefaultState:Ao};const Po=Object.freeze({string:"string",length:"length"}),Do=Object.freeze({trigger:"trigger",setText:"setText"}),jo=()=>({text:"",dispatchOnSet:!1});var Ro={onParentEvent:async(e,t,n,r)=>{const i={text:"",dispatchOnSet:!1,...r.getState()};if(t.name===Do.setText){if(!((n.data.type===pe.String||n.data.type===pe.Anything)&&"string"==typeof n.data.value))return;if("string"==typeof n.data.value&&(i.text=n.data.value,r.setState(i)),!i.dispatchOnSet)return}const o=r.nextGate(Po.length,{type:pe.Number,value:i.text.length}),s=r.nextGate(Po.string,{type:pe.String,value:i.text});await Promise.all([o,s])},getInputNames:e=>{const t=[{name:Do.setText,type:pe.String}];return e.dispatchOnSet||t.push({name:Do.trigger,type:pe.Anything}),t},getOutputNames:()=>[{name:Po.string,type:pe.String},{name:Po.length,type:pe.Number}],getDefaultState:jo};const Lo=Object.freeze({image:"image"}),Fo=Object.freeze({image:"image",x:"x",y:"y",width:"width",height:"height"}),Uo=()=>({showInputPorts:!1});var Bo={onParentEvent:async(e,t,n,r)=>{const i={showInputPorts:!1,...r.getState()};if("number"==typeof n.data.value)return t.name===Fo.x&&(i.cropX=n.data.value),t.name===Fo.y&&(i.cropY=n.data.value),t.name===Fo.width&&(i.cropWidth=n.data.value),t.name===Fo.height&&(i.cropHeight=n.data.value),void r.setState(i);if(t.name===Fo.image){if(n.data.type!==pe.ImageData&&n.data.type!==pe.Anything)return;if(!De(n.data.value))return;const e=n.data.value;if(i.$$memCanvas&&i.$$memCanvas.getContext||(i.$$memCanvas=xe(320,240),i.$$memCanvasContext=ke(i.$$memCanvas),r.setState(i)),!i.$$memCanvas||!i.$$memCanvasContext)return void console.error("Failed to get canvas or context");let t=e;return i.$$memCanvas.width=e.width,i.$$memCanvas.height=e.height,(i.cropX||i.cropY||i.cropWidth||i.cropHeight)&&(t=((e,t,n,r)=>{if(!n)return e;const i=Math.max(r.x||0,0),o=Math.max(r.y||0,0),s=e.width,a=e.height,c=Math.min(Math.ceil(r.width||s),s),l=Math.min(Math.ceil(r.height||a),a);return t.width=e.width,t.height=e.height,n.putImageData(e,0,0),n.drawImage(t,i,o,c,l,0,0,c,l),n.getImageData(0,0,c,l)})(e,i.$$memCanvas,i.$$memCanvasContext,{x:i.cropX,y:i.cropY,width:i.cropWidth,height:i.cropHeight})),r.nextGate(Lo.image,{type:pe.ImageData,value:t})}},getInputNames:e=>{const t=[{name:Fo.image,type:[pe.ImageData]}];return e.showInputPorts&&(t.push({name:Fo.x,type:pe.Number}),t.push({name:Fo.y,type:pe.Number}),t.push({name:Fo.width,type:pe.Number}),t.push({name:Fo.height,type:pe.Number})),t},getOutputNames:()=>[{name:Lo.image,type:pe.ImageData}],getDefaultState:Uo};const Wo=Object.freeze({image:"image"}),Go=Object.freeze({image:"image",width:"width",height:"height"}),Vo=()=>({showInputPorts:!1});var Yo={onParentEvent:async(e,t,n,r)=>{const i={showInputPorts:!1,...r.getState()};if("number"==typeof n.data.value)return t.name===Go.width&&(i.width=n.data.value),t.name===Go.height&&(i.height=n.data.value),void r.setState(i);if(t.name===Go.image){if(n.data.type!==pe.ImageData&&n.data.type!==pe.Anything)return;if(!De(n.data.value))return;const e=n.data.value;if(i.$$memCanvas&&i.$$memCanvas.getContext||(i.$$memCanvas=xe(320,240),i.$$tempCanvas=xe(320,240),r.setState(i)),!i.$$memCanvas||!i.$$tempCanvas)return;let t=e;return(i.width||i.height)&&(t=((e,t,n,r,i)=>{if(!r&&!i)return e;r&&!i?i=r*(e.height/e.width):!r&&i&&(r=i*(e.width/e.height));const o=Math.max(1,r||e.width),s=Math.max(1,i||e.height);n.width===e.width&&n.height===e.height||(n.width=e.width,n.height=e.height),t.width=o,t.height=s;const a=ke(t),c=ke(n);if(!a||!c)throw new Error("Failed to get canvas context");return c.putImageData(e,0,0),a.drawImage(n,0,0,e.width,e.height,0,0,o,s),a.getImageData(0,0,o,s)})(e,i.$$memCanvas,i.$$tempCanvas,i.width,i.height)),r.nextGate(Wo.image,{type:pe.ImageData,value:t})}},getInputNames:e=>{const t=[{name:Go.image,type:pe.ImageData}];return e.showInputPorts&&(t.push({name:Go.width,type:pe.Number}),t.push({name:Go.height,type:pe.Number})),t},getOutputNames:()=>[{name:Wo.image,type:pe.ImageData}],getDefaultState:Vo};const Ho=Object.freeze({value:"value"}),zo=Object.freeze({trigger:"trigger",setValue:"setValue"}),qo=()=>({value:0,dispatchOnSet:!1});var Ko={onParentEvent:async(e,t,n,r)=>{const i={value:0,dispatchOnSet:!1,...r.getState()};if(t.name===zo.setValue){const e=n.data.type===pe.Number||n.data.type===pe.Anything||n.data.type===pe.String,t=!isNaN(Number(n.data.value))&&!Array.isArray(n.data.value);if(!e||!t)return;if(i.value=Number(n.data.value),r.setState(i),!i.dispatchOnSet)return}return r.nextGate(Ho.value,{type:pe.Number,value:i.value})},getInputNames:e=>{const t=[{name:zo.setValue,type:pe.Number}];return e.dispatchOnSet||t.push({name:zo.trigger,type:pe.Anything}),t},getOutputNames:()=>[{name:Ho.value,type:pe.Number}],getDefaultState:qo};const Jo=Object.freeze({image:"image"}),Zo=Object.freeze({image:"image"}),Xo=()=>({anchors:[],vertices:[],matrix:[]}),Qo={onParentEvent:async(e,t,n,r)=>{const i={anchors:[],vertices:[],matrix:[],...r.getState()},o=window,s=n.data.type===pe.ImageData;if(o.Speedy&&s){const e=o.Speedy,t=n.data.value;let s,u,d,h=i.$$private?.canvas,f=i.$$private?.context,p={...i};const g=4===i.anchors.length;if(i.$$private?.pipeline)s=i.$$private?.pipeline,u=i.$$private?.source;else{s=e.Pipeline(),u=e.Image.Source();const n=e.Image.Sink();d=e.Transform.PerspectiveWarp(),h?h.width===t.width&&h.height===t.height||(h.width=t.width,h.height=t.height,f=h.getContext("2d")):(c=t.width,l=t.height,h=xe(c,l),f=h.getContext("2d")),u.output().connectTo(d.input()),d.output().connectTo(n.input()),s.init(u,n,d);let r=e.Matrix(3,3,[1,0,0,0,1,0,0,0,1]);if(4===i.anchors.length){const t=e.Matrix(2,4,[(a=i.anchors)[0].x,a[0].y,a[1].x,a[1].y,a[2].x,a[2].y,a[3].x,a[3].y]),n=e.Matrix(2,4,i.vertices.reduce(((e,t)=>e.concat([t.x,t.y])),[])),o=e.Matrix.Zeros(3,3);await e.Matrix.perspective(o,t,n);const s=o.read();r=e.Matrix(3,3,s)}d.transform=r,p={...p,$$private:{...p.$$private,canvas:h,context:f,perspective:d,pipeline:s,source:u}}}let m=t;if(g){const e=await(async(e,t)=>{const n=window,r=e.$$private?.source,i=e.$$private?.pipeline;if(n.Speedy&&r&&i){const e=n.Speedy,o=await createImageBitmap(t),s=await e.load(o);return r.media=s,(await i.run()).image.source}return null})(p,m);e&&(h&&f&&(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,h,f)),p.$$private&&r.setState({...p,$$private:{...p.$$private,lastInputImage:t}}))}else p.$$private&&r.setState({...p,$$private:{...p.$$private,lastInputImage:t}});return r.nextGate(Jo.image,{type:pe.ImageData,value:m})}var a,c,l;console.log("Environment not supported")},getInputNames:()=>[{name:Zo.image,type:pe.ImageData}],getOutputNames:()=>[{name:Jo.image,type:pe.ImageData}],getDefaultState:Xo,terminate:async e=>{const t=e.getState();t.$$private?.pipeline.release()}},es=Object.freeze({event:"event"}),ts="1",ns="2",rs="3";var is={onParentEvent:async(e,t,n,r)=>{const i={...r.getState()};r.setState({...i,$$lastEventType:n.data.type}),await r.nextGate(ts,n.data),await r.nextGate(ns,n.data),await r.nextGate(rs,n.data)},getInputNames:()=>[{name:es.event,type:pe.Anything}],getOutputNames:e=>{const t={type:{...e}.$$lastEventType??pe.Anything};return[{name:ts,...t},{name:ns,...t},{name:rs,...t}]}};const os=()=>({name:"myVar",type:pe.Anything,reactive:!0,defaultValue:""}),ss=Object.freeze({set:"set",read:"read"}),as="value";var cs={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),o={...os(),...i};if(t.name!==ss.set){if(t.name===ss.read){const e=oi({variableName:o.name,readerWidgetId:r.id}),t=e?e.value:o.defaultValue;await r.nextWidget(as,{type:o.type,value:t})}}else{if(n.data.type!==o.type&&o.type!==pe.Anything)return;await ii({variableName:o.name,value:n.data.value,setByWidgetId:r.id,type:o.type})}},getInputNames:e=>{const t={...e};return[{name:ss.set,type:t.type||pe.Anything},{name:ss.read,type:pe.Anything}]},getOutputNames:e=>{const t={...e};return[{name:as,type:t.type||pe.Anything}]},initialize:async e=>{const t=e.getState(),n={...os(),...t};if(n.$$abortListener)try{n.$$abortListener()}catch(t){console.warn(`Error aborting variable listener for widget ${e.widgetId}: `,t)}ni({variableName:n.name,type:n.type,createdByWidgetId:e.widgetId});const r=si({variableName:n.name,type:n.type,widgetId:e.widgetId,onValueChange:async t=>{const n=e.getState();void 0!==t.value&&(n.type!==pe.Anything&&t.type!==n.type||n.reactive&&await e.nextWidget(as,{type:t.type,value:t.value}))}});e.setState({...n,$$abortListener:r})},terminate:async e=>{const t=e.getState(),n={...os(),...t};n.$$abortListener&&n.$$abortListener(),ri({variableName:n.name,createdByWidgetId:e.widgetId})}};const ls=async(e,t=!1)=>{const n=pi();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 us={onParentEvent:async(e,t,n,r)=>{const i={dynamicInputs:{},dynamicOutputs:{},customState:{},...r.getState()};if(!e)return;const o=ie(r.recipePoolId);if(!o)throw new Error(`Recipe [${r.recipePoolId}] not found`);const s=pi();let a=i.$$$serviceId;if(!a){const e=s.getCachedServices().available.find((e=>e.name===i.service?.name&&e.version===i.service?.version));if(!e)return;a=e.sessionId,i.$$$serviceId=a,r.setState(i)}const c=i.service?.variants?.find((e=>e.id===i.variantId)),l=c?i.dynamicInputs[c.id]||c?.inputs||[]:i.service?.inputs||[];if(!l?.length)return;if(!c&&i.service?.ignoreParentEvents)return;const u=i.service?.processingTimeoutSec,d=r.eventContext,h=o?.name||"";return s.onParentEvent({recipeId:r.recipePoolId,recipeName:h,data:n.data,targetServiceSessionId:a,currentState:i.customState,targetVariantId:i.variantId,currentPath:r.currentPath,eventId:r.eventId,recipe:{uuid:o.uuid,poolId:r.recipePoolId,name:h,type:r.recipeType,version:o.dbInfo.version,authorId:o.dbInfo.authorId},target:{portName:t.name,widgetId:r.id,widgetType:r.type},source:e,config:{timeout:u?1e3*u:0,async:i.service?.asyncParentEvents},eventContext:d})},getInputNames:async e=>{const t=e.variantId;if(t&&e.dynamicInputs?.[t])return[...e.dynamicInputs[t]||[]];if(!t)return e.service?.inputs||[];{const n=e.service?.variants?.find((e=>e.id===t));if(n)return n.inputs||[]}return[]},getOutputNames:async e=>{const t=e.variantId;if(t&&e.dynamicOutputs?.[t])return[...e.dynamicOutputs[t]||[]];if(!t)return e.service?.outputs||[];{const n=e.service?.variants?.find((e=>e.id===t));if(n)return n.outputs||[]}return[]},initialize:async e=>{const t={dynamicInputs:{},dynamicOutputs:{},customState:{},...e.getState()},n=ie(e.recipePoolId),r=n?.name||"",i=pi(),o=await ls(t);if(o)try{return await i.initializeServiceInstance({recipePoolId:e.recipePoolId,sessionId:o,recipeName:r,widgetId:e.widgetId,recipeType:e.recipeType,variantId:t.variantId})}catch(t){if("FNC_NOT_FOUND"!==t?.errCode){if(!!("string"!=typeof t||!t.match('^Function ".*" not found.$')))throw t;console.warn(`Widget [${e.widgetId}] does not have an init function.`)}}else console.log(`Aborting service initialization, "${t.service?.name}" was not found in the current Hub.`)},terminate:async e=>{const t={dynamicInputs:{},dynamicOutputs:{},customState:{},...e.getState()},n=pi(),r=await ls(t,!0);if(r)return n.terminateServiceInstance(r,e.widgetId,e.recipePoolId,t.variantId)}};const ds=Object.freeze({Image:"image"}),hs=Object.freeze({Image:"image"}),fs=()=>({filters:[{name:"grayscale",value:"0.5",id:"d-1"}]});var ps={onParentEvent:async(e,t,n,r)=>{const i={filters:[{name:"grayscale",value:"0.5",id:"d-1"}],...r.getState()};if(t.name===ds.Image&&(n.data.type===pe.ImageData||n.data.type===pe.Anything)){if(!De(n.data.value))return void console.log("ImageFilter: Invalid image data type, aborting process");const e=n.data.value;i.$$memCanvas?.getContext||(i.$$memCanvas=xe(e.width,e.height)),i.$$context?.drawImage||(i.$$context=i.$$memCanvas.getContext("2d")),i.$$memCanvas.width!==e.width&&(i.$$memCanvas.width=e.width),i.$$memCanvas.height!==e.height&&(i.$$memCanvas.height=e.height),r.setState(i),i.$$context.putImageData(e,0,0),i.filters.length?i.$$context.filter=i.filters.map((e=>{let t="";return"blur"===e.name?t="px":"hue-rotate"===e.name&&(t="deg"),`${e.name}(${parseFloat(e.value)}${t})`})).join(" "):i.$$context.filter="none",i.$$context.drawImage(i.$$memCanvas,0,0);const t=i.$$context.getImageData(0,0,e.width,e.height);return r.nextWidget(hs.Image,{type:pe.ImageData,value:t})}},getInputNames:()=>[{name:ds.Image,type:pe.ImageData}],getOutputNames:()=>[{name:hs.Image,type:pe.ImageData}],getDefaultState:fs};const gs="loaded";var ms={onParentEvent:async(e,t,n,r)=>r.nextWidget(gs,{value:!0,type:pe.Boolean}),getInputNames:()=>[],getOutputNames:()=>[{name:gs,type:pe.Boolean,description:"Triggered when the recipe is fully loaded"}]};var ys={onParentEvent:async()=>{},getInputNames:()=>[],getOutputNames:()=>[],getDefaultState:()=>({text:"",color:"#eac43e",size:{width:300,height:200}})};var vs={onParentEvent:async(e,t,n,r)=>{try{const e=((e,t)=>{switch(t){case pe.Number:case pe.Boolean:case pe.String:return String(e);case pe.Array:case pe.JsonObj:case pe.Rect:case pe.Point:return JSON.stringify(e,((e,t)=>"bigint"==typeof t?t.toString():t));case pe.ArrayBuffer:if(e instanceof ArrayBuffer){if(ee)return Buffer.from(e).toString("base64");{const t=new Uint8Array(e),n=t.length,r=new Array(n);for(let e=0;e<n;e++)r[e]=String.fromCharCode(t[e]);return btoa(r.join(""))}}throw new Error("Type is ArrayBuffer but value is not an ArrayBuffer");case pe.ImageData:if(!De(e))throw new Error("Expected ImageData");return Ve(e);default:return String(e)}})(n.data.value,n.data.type);return r.nextWidget("text",{type:pe.String,value:e})}catch(e){return r.nextWidget("error",{type:pe.String,value:e instanceof Error?e.message:"Failed to stringify object"})}},getInputNames:()=>[{name:"object",type:[pe.Number,pe.String,pe.ArrayBuffer,pe.Array,pe.Boolean,pe.JsonObj,pe.Rect,pe.Point,pe.ImageData]}],getOutputNames:()=>[{name:"text",type:pe.String},{name:"error",type:pe.String}],getDefaultState:()=>({})};const bs=(e,t)=>{if(!Array.isArray(e)||"number"!=typeof t||t<=0)return[e];const n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n},ws=e=>{const{code:t,enableFnTag:n=!1,context:r={},securityOptions:i={}}=e;if(!n)throw new Error("$fn helper is disabled by default for security reasons. Set enableFnTag: true in options to enable.");if("string"!=typeof t)throw new Error("$fn requires a string argument");const o=((e={})=>{const{restrictionLevel:t="strict",allowedGlobals:n=[],blockedGlobals:r=[]}=e,i={Math:"undefined"!=typeof Math?Math:void 0,Date:"undefined"!=typeof Date?Date:void 0,JSON:"undefined"!=typeof JSON?JSON:void 0,Array:"undefined"!=typeof Array?Array:void 0,Object:"undefined"!=typeof Object?Object:void 0,String:"undefined"!=typeof String?String:void 0,Number:"undefined"!=typeof Number?Number:void 0,Boolean:"undefined"!=typeof Boolean?Boolean:void 0,RegExp:"undefined"!=typeof RegExp?RegExp:void 0,Symbol:"undefined"!=typeof Symbol?Symbol:void 0,Map:"undefined"!=typeof Map?Map:void 0,Set:"undefined"!=typeof Set?Set:void 0,Promise:"undefined"!=typeof Promise?Promise:void 0},o={process:void 0,require:void 0,global:void 0,globalThis:void 0,window:void 0,document:void 0,navigator:void 0,console:void 0,eval:void 0,Function:void 0,setTimeout:void 0,setInterval:void 0,setImmediate:void 0,clearTimeout:void 0,clearInterval:void 0,clearImmediate:void 0,fetch:void 0,XMLHttpRequest:void 0,WebSocket:void 0,Worker:void 0,SharedWorker:void 0,ServiceWorker:void 0,localStorage:void 0,sessionStorage:void 0,indexedDB:void 0};let s={};switch(t){case"strict":case"moderate":s={...i,...o};break;case"permissive":s={...i,process:void 0,require:void 0,eval:void 0,Function:void 0}}if(n.length>0)for(const e of n)"undefined"!=typeof globalThis&&e in globalThis&&(s[e]=globalThis[e]);for(const e of r)s[e]=void 0;return s})(i);o.$vars=r.$vars,o.date=r.date,o.chunkArray=r.chunkArray;const s=new Set(["Math","Date","JSON","Array","Object","String","Number","Boolean","RegExp","Symbol","Map","Set","Promise","eval","Function","require","process","global","globalThis","window","document","navigator","console","$vars","date","chunkArray"]),a=Object.entries(r).filter((([e])=>!s.has(e))),c=a.map((([e])=>e)),l=a.map((([,e])=>e)),u=`\n // Get sandbox environment from the last argument\n const __sandbox = arguments[arguments.length - 1]; // Last argument is the sandbox\n \n // Shadow dangerous globals at the top level (these will be overridden by sandbox if allowed)\n var eval = undefined;\n var Function = undefined;\n var require = undefined;\n var process = undefined;\n var global = undefined;\n var globalThis = undefined;\n var console = __sandbox.console;\n var window = __sandbox.window;\n var document = __sandbox.document;\n var navigator = __sandbox.navigator;\n \n // Make context variables available in local scope\n ${c.map(((e,t)=>`var ${e} = arguments[${t}];`)).join("\n ")}\n \n // Shadow global references to use sandbox versions\n const Math = __sandbox.Math;\n const Date = __sandbox.Date;\n const JSON = __sandbox.JSON;\n const Array = __sandbox.Array;\n const Object = __sandbox.Object;\n const String = __sandbox.String;\n const Number = __sandbox.Number;\n const Boolean = __sandbox.Boolean;\n const RegExp = __sandbox.RegExp;\n const Symbol = __sandbox.Symbol;\n const Map = __sandbox.Map;\n const Set = __sandbox.Set;\n const Promise = __sandbox.Promise;\n \n // Make special context items available\n const $vars = __sandbox.$vars;\n const date = __sandbox.date;\n const chunkArray = __sandbox.chunkArray;\n \n // Execute the user code in strict mode for additional security\n // Use call(null) to ensure 'this' is null/undefined in strict mode\n return (() => {\n "use strict";\n return ${t};\n }).call(null);\n `;try{return new Function(...c,"sandbox",u).call({},...l,o)}catch(e){throw new Error(`Error executing $fn: ${e instanceof Error?e.message:String(e)}`)}},Ss=e=>{const t={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","/":"&#x2F;"};return e.replace(/[&<>"'/]/g,(e=>t[e]))},_s=()=>new Proxy({},{get(e,t){if("string"==typeof t){const e=ao.getGlobalVariable(t);return e?.lastValue??void 0}}}),Is=e=>{const t=new Set,n=e.match(/\$secrets\.([a-zA-Z_$][a-zA-Z0-9_$]*)/g);if(n)for(const e of n){const n=e.substring(9);n&&t.add(n)}const r=e.match(/\$secrets\[['"]([^'"]+)['"]\]/g);if(r)for(const e of r){const n=e.match(/['"]([^'"]+)['"]/);n&&n[1]&&t.add(n[1])}return t},xs=(e=new Date)=>({year:e.getFullYear(),month:e.getMonth()+1,day:e.getDate(),hours:e.getHours(),minutes:e.getMinutes(),seconds:e.getSeconds(),milliseconds:e.getMilliseconds(),time:e.getTime(),dayOfWeek:e.getDay(),dayName:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][e.getDay()],shortDayName:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"][e.getDay()],date:e.getDate(),fullYear:e.getFullYear(),timezoneOffset:e.getTimezoneOffset(),UTCDate:e.getUTCDate(),UTCDay:e.getUTCDay(),UTCFullYear:e.getUTCFullYear(),UTCHours:e.getUTCHours(),UTCMilliseconds:e.getUTCMilliseconds(),UTCMonth:e.getUTCMonth()+1,UTCMinutes:e.getUTCMinutes(),UTCSeconds:e.getUTCSeconds(),isoString:e.toISOString(),localeString:e.toLocaleString()}),ks={$capitalize:e=>"string"==typeof e&&e.length>0?e.charAt(0).toUpperCase()+e.slice(1):e,$uppercase:e=>"string"==typeof e?e.toUpperCase():e,$lowercase:e=>"string"==typeof e?e.toLowerCase():e,$json:e=>{if("string"==typeof e)try{return JSON.parse(e)}catch{return e}return e},$stringify:(e,t,n)=>{try{return void 0!==t||void 0!==n?JSON.stringify(e,t,n):JSON.stringify(e)}catch{return String(e)}},$length:e=>"string"==typeof e||Array.isArray(e)?e.length:0,$compact:e=>Array.isArray(e)?e.filter((e=>null!=e&&""!==e&&!1!==e)):e,$chunk:e=>{if(!Array.isArray(e))return e;const t=[];for(let n=0;n<e.length;n+=2)t.push(e.slice(n,n+2));return t},$isEmpty:e=>Array.isArray(e)||"string"==typeof e?0===e.length:null==e,$isNotEmpty:e=>Array.isArray(e)||"string"==typeof e?e.length>0:null!=e,$first:e=>Array.isArray(e)?e.length>0?e[0]:void 0:"string"==typeof e&&e.length>0?e.charAt(0):void 0,$last:e=>Array.isArray(e)?e.length>0?e[e.length-1]:void 0:"string"==typeof e&&e.length>0?e.charAt(e.length-1):void 0,$base64Decode:e=>{if("string"!=typeof e)return e;try{return X&&window.atob?window.atob(e):"undefined"!=typeof Buffer?Buffer.from(e,"base64").toString("utf-8"):e}catch{return e}},$base64Encode:e=>{if("string"!=typeof e)return e;try{return"undefined"!=typeof window&&window.btoa?window.btoa(e):"undefined"!=typeof Buffer?Buffer.from(e,"utf-8").toString("base64"):e}catch{return e}},$domain:e=>{if("string"==typeof e)try{const t=e.match(/https?:\/\/[^\s]+/i),n=t?t[0]:e;return new URL(n).hostname}catch{try{const t=new URL("http://"+e.trim());if(t.hostname.includes(".")&&!t.hostname.startsWith("http"))return t.hostname}catch{}return}},$email:e=>{if("string"==typeof e)try{const t=e.match(/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/);return t?t[0]:void 0}catch{return}},$url:e=>{if("string"==typeof e)try{const t=e.match(/https?:\/\/[^\s]+/i);if(t){return new URL(t[0]).toString()}return new URL(e.trim()).toString()}catch{return}},$urlPath:e=>{if("string"==typeof e)try{return new URL(e).pathname}catch{try{return new URL("http://"+e).pathname}catch{return}}},$urlEncode:e=>{if("string"!=typeof e)return e;try{return encodeURIComponent(e)}catch{return e}},$urlDecode:(e,t)=>{if("string"!=typeof e)return e;try{return!0===t?decodeURI(e):decodeURIComponent(e)}catch{return e}}},Es=e=>{const t=[];let n=0;for(;n<e.length;){const r=e.indexOf("{{",n);if(-1===r)break;const i="{{{"===e.slice(r,r+3),o=i?"{{{":"{{",s=i?"}}}":"}}";let a=1,c=!1,l="",u=r+o.length;for(;u<e.length&&a>0;){const t=e[u],n=e[u+1];c?t===l&&"\\"!==e[u-1]&&(c=!1,l=""):'"'===t||"'"===t?(c=!0,l=t):"{"===t&&"{"===n?i&&"{"===e[u+2]?(a++,u+=2):i||(a++,u++):"}"===t&&"}"===n&&(i&&"}"===e[u+2]?(a--,u+=2):i||(a--,u++)),u++}if(0===a){const a=e.slice(r,u),c=e.slice(r+o.length,u-s.length).trim();t.push({expression:c,start:r,end:u,fullMatch:a,escaped:!i}),n=u}else n=r+o.length}return t},Cs=e=>{const t=e.match(/\$\w+\(/);if(!t)return{hasFunctionPropertyAccess:!1};const n=((e,t)=>{let n=0,r=!1,i="",o=t;for(;o<e.length&&"("!==e[o];)o++;if(o>=e.length)return null;const s=t;for(o++,n=1;o<e.length&&n>0;){const t=e[o];r?t===i&&"\\"!==e[o-1]&&(r=!1,i=""):'"'===t||"'"===t?(r=!0,i=t):"("===t?n++:")"===t&&n--,o++}return 0===n?{functionCall:e.slice(s,o),endIndex:o}:null})(e,t.index);if(!n)return{hasFunctionPropertyAccess:!1};const{functionCall:r,endIndex:i}=n,o=e.slice(i).match(/^(\.[a-zA-Z_$][a-zA-Z0-9_$]*|\[\d+\]|\[['"'][^'"]*['"']\])(?:\.[a-zA-Z_$][a-zA-Z0-9_$]*|\[\d+\]|\[['"'][^'"]*['"']\])*/);return o?{hasFunctionPropertyAccess:!0,functionCall:r,propertyPath:o[0],fullMatch:r+o[0]}:{hasFunctionPropertyAccess:!1}},$s=(e,t,n,r)=>{const i=n.evaluate(e,r);if(null==i)return;let o=i;const s=t.match(/\.[a-zA-Z_$][a-zA-Z0-9_$]*|\[\d+\]|\[['"'][^'"]*['"']\]/g)||[];for(const e of s){if(null==o)return;if(e.startsWith(".")){o=o[e.slice(1)]}else if(e.startsWith("[")&&e.endsWith("]")){const t=e.slice(1,-1);if(/^\d+$/.test(t)){o=o[parseInt(t,10)]}else{o=o[t.replace(/^['"]|['"]$/g,"")]}}}return o},Os=e=>{const t=e.match(/^([a-zA-Z_$][a-zA-Z0-9_$]*)\[/);if(!t)return{hasObjectBracketAccess:!1};const n=t[1],r=t.index;if("vars"===n||e.startsWith("$vars["))return{hasObjectBracketAccess:!1};if("secrets"===n||e.startsWith("$secrets["))return{hasObjectBracketAccess:!1};const i=r+n.length,o=e.slice(i).match(/^(?:\[(?:['"'][^'"]*['"]|\d+|[^\]]+)\])+/);if(o){const e=o[0];return{hasObjectBracketAccess:!0,objectName:n,bracketPath:e,fullMatch:n+e}}return{hasObjectBracketAccess:!1}},Ns=(e,t,n,r)=>{const i=r[e];if(null==i)return;const o=t.match(/\[(?:['"'][^'"]*['"]|\d+|[^\]]+)\]/g)||[];if(0===o.length)return;let s=i;for(const e of o){if(null==s)return;const t=e.slice(1,-1);let i;if(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))i=t.slice(1,-1);else if(/^\d+$/.test(t))i=parseInt(t,10);else try{i=n.evaluate(t,r)}catch{return}if("number"==typeof i&&Array.isArray(s))s=s[i];else{if("string"!=typeof i||"object"!=typeof s||null===s)return;s=s[i]}}return s},Ts=e=>{const t=e.match(/\$(?:vars|secrets)\[/);if(!t)return{hasVarsBracketAccess:!1};const n=t.index,r="$secrets["===e.slice(n,n+9)?"$secrets":"$vars",i=n+r.length,o=e.slice(i).match(/^(?:\[(?:['"'][^'"]*['"]|\d+|[^\]]+)\])+/);if(o){const e=o[0];return{hasVarsBracketAccess:!0,bracketPath:e,fullMatch:r+e,objectName:r}}return{hasVarsBracketAccess:!1}},As=(e,t,n,r,i=!1)=>{const o=e.match(/\[(?:['"'][^'"]*['"]|\d+|[^\]]+)\]/g)||[];if(0===o.length)return;const s=o[0],a=s?.slice(1,-1);let c,l;if(a?.startsWith('"')&&a.endsWith('"')||a?.startsWith("'")&&a.endsWith("'"))c=a.slice(1,-1);else if(a&&/^\d+$/.test(a))c=parseInt(a,10);else if(a)try{c=n.evaluate(a,r)}catch{return}if("$vars"===t){if("string"!=typeof c)return;const e=ao.getGlobalVariable(c);l=e?.lastValue??void 0}else{if("$secrets"!==t)return;{if(!i)return;const e=r.$secrets;if(!e)return;if("string"!=typeof c)return;l=e[c]??void 0}}for(let e=1;e<o.length;e++){if(null==l)return;const t=o[e].slice(1,-1);let i;if(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))i=t.slice(1,-1);else if(/^\d+$/.test(t))i=parseInt(t,10);else try{i=n.evaluate(t,r)}catch{return}if("number"==typeof i&&Array.isArray(l))l=l[i];else{if("string"!=typeof i||"object"!=typeof l)return;l=l[i]}}return l},Ms=async e=>{const{template:t,context:n={},options:r={}}=e,{helpers:i={},enableFnTag:o=!1,securityOptions:s={},recipeUuid:a,serviceName:l,enableSecretsBracketNotation:u=!1}=r,d={...ks,...i},h=_s(),f=xs(),p={...n};var g;"input"in p&&(p.input="object"==typeof(g=p.input)&&null!==g?g:{value:g});let m,y={};if(a){const e=(e=>{const t=new Set,n=Es(e);for(const e of n)Is(e.expression).forEach((e=>t.add(e)));return t})(t),n=Array.from(e);if(n.length>0)try{y=await Oi({recipeUuid:a,secretNames:n,serviceName:l})}catch(e){console.error("Failed to fetch secrets for template:",e),y={}}m=y}const v={...p,$vars:h,date:f,chunkArray:bs};void 0!==m&&(v.$secrets=m);const b={...d};b.$fn=e=>ws({code:e,enableFnTag:o,context:v,securityOptions:s});const w=new c({operators:{add:!0,comparison:!0,concatenate:!0,conditional:!0,logical:!0,power:!1,assignment:!1}});for(const[e,t]of Object.entries(b))w.functions[e]=t;const S=Es(t);if(0===S.length)return t;let _="",I=0;for(const e of S){_+=t.slice(I,e.start);try{if(!o&&e.expression.includes("$fn"))throw new Error("$fn helper is disabled by default for security reasons. Set enableFnTag: true in options to enable.");let t;const n=Ts(e.expression);if(n.hasVarsBracketAccess&&n.bracketPath&&n.objectName)t=As(n.bracketPath,n.objectName,w,{...v,...b},u);else{const n=Os(e.expression);if(n.hasObjectBracketAccess&&n.objectName&&n.bracketPath)t=Ns(n.objectName,n.bracketPath,w,{...v,...b});else{const n=Cs(e.expression);t=n.hasFunctionPropertyAccess&&n.functionCall&&n.propertyPath?$s(n.functionCall,n.propertyPath,w,{...v,...b}):w.evaluate(e.expression,{...v,...b})}}null!==t&&"object"==typeof t&&"then"in t&&(t=await t);let r=null==t?"":String(t);e.escaped&&(r=Ss(r)),_+=r}catch(e){if(e instanceof Error&&e.message.includes("undefined variable"))_+="";else{const t=e instanceof Error?e.message:String(e);if(e instanceof Error&&e.message.includes("$fn helper is disabled"))throw e;_+=`[Error: ${t}]`}}I=e.end}return _+=t.slice(I),_},Ps=()=>({text:"",format:"Text"});var Ds={onParentEvent:async(e,t,n,r)=>{const i={text:"",format:"Text",...r.getState()},{uuid:o}=Ni(r.recipePoolId);if(!o)throw new Error(`Recipe [${o}] does not have a valid id]`);const s=await Ms({template:i.text,context:{input:n.data.value},options:{enableFnTag:!0,recipeUuid:o}});return r.nextWidget("text",{type:pe.String,value:s})},getInputNames:()=>[{name:"input",type:pe.Anything}],getOutputNames:()=>[{name:"text",type:pe.String}],getDefaultState:Ps};const js=()=>({expression:""}),Rs=async e=>{const{expression:t,recipeUuid:n,serviceName:r,enableFnTag:i=!0,customContext:o={}}=e,s=Symbol("abort");try{const e={restrictionLevel:"strict"},a=_s(),c=xs();let l;if(n&&t.includes("$secrets")){const e=Array.from(Is(t));if(e.length>0)try{l=await Oi({recipeUuid:n,secretNames:e,serviceName:r})}catch(e){console.error("Failed to fetch secrets for expression:",e),l={}}}const u={...o,abort:s,$vars:a,date:c,chunkArray:bs,...ks};void 0!==l&&(u.$secrets=l);const d=ws({code:t,enableFnTag:i,context:u,securityOptions:e});return d===s?{value:s,error:null}:{value:d,error:null}}catch(e){let t=e instanceof Error?e.message:String(e);return t.startsWith("Error executing $fn: ")&&(t=t.substring(21)),{error:"Error during expression execution: "+t,value:null}}};var Ls={onParentEvent:async(e,t,n,r)=>{const i={expression:"",...r.getState()},{uuid:o}=Ni(r.recipePoolId);if(!o)throw new Error(`Recipe [${o}] does not have a valid id]`);const s=await Rs({customContext:{data:n.data.value},expression:i.expression,recipeUuid:o,serviceName:void 0});if("symbol"==typeof s.value)return;if(s.error)throw new Error(s.error);if(Number.isNaN(s.value))throw new Error("Expression resulted in NaN");if(void 0===s.value||null===s.value)return;const a=Fe(s.value);return a!==i.$$lastResultType&&r.setState({...i,$$lastResultType:a}),r.nextWidget("result",{type:a,value:s.value})},getInputNames:()=>[{name:"data",type:pe.Anything}],getOutputNames:e=>[{name:"result",type:e.$$lastResultType||pe.Anything}],getDefaultState:js};const Fs={};let Us={};const Bs=new a;let Ws=!1,Gs=!1,Vs=!1,Ys=null,Hs=null;const zs="processing-state-change",qs="error-event",Ks={abortRequested:!1,isPaused:!1,pausePromise:null,pausePromiseResolve:null,lastPausedWidgetId:null},Js=e=>(Hs=e,Bs.emit(zs,e)),Zs=(e,t)=>`${e}-${t}`,Xs=(e,t)=>`state-change:${Zs(e,t)}`,Qs=e=>{const{thingId:t,widgetId:n}=e,r=Zs(t,n);return Fs[r]||{isProcessing:!1}},ea=e=>{const t=(e=>{let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t+e.charCodeAt(n);return Math.abs(t).toString(36)})(e.error);return`${e.targetWidgetId}-${e.targetPortName}-${e.sourcePortName}-${t}`};let ta=null;const na={},ra=()=>{Ks.abortRequested=!1,Ks.isPaused=!1},ia=e=>(Ks.pausePromise||(Ks.isPaused=!0,Ks.pausePromise=new Promise((e=>{Ks.pausePromiseResolve=e})),e&&(Ks.lastPausedWidgetId=e),Js({isProcessing:!0,isPaused:!0,...e?{pauseTrapWidgetId:e}:{}})),Ks.pausePromise);var oa=async e=>{const{thingId:t,widgetId:n}=e,r=Zs(t,n),i=Xs(t,n),o=Qs({thingId:t,widgetId:n});if(o.isProcessing)return;const s={isProcessing:!0,isPaused:!1,startTime:Date.now()};Fs[r]=s,Ws||(Ws=!0,Ys=null,await Js({isProcessing:!0,isPaused:!1})),await Bs.emit(i,{thingId:t,widgetId:n,prevState:o,newState:s})},sa=async e=>{const{thingId:t,widgetId:n,error:r}=e,i=Zs(t,n),o=Xs(t,n),s=Qs({thingId:t,widgetId:n}),a={isProcessing:!1,isPaused:!1,startTime:s.startTime,endTime:Date.now(),error:r};Fs[i]=a,await Bs.emit(o,{thingId:t,widgetId:n,prevState:s,newState:a}),r&&(Ys=r,(e=>{const{error:t,stateKey:n}=e,r=ea(t);na[r]={error:t,stateKey:n},ta&&clearTimeout(ta),ta=setTimeout((()=>{for(const e in na)Bs.emit(qs,na[e].error),delete na[e]}),250)})({error:r,stateKey:i})),Ws&&0===Object.values(Fs).filter((e=>e.isProcessing)).length&&(Ws=!1,Gs=!1,ra(),await Js({isProcessing:!1,isPaused:!1}))},aa=e=>Bs.on(zs,e),ca=()=>{Ws=!1;for(const e in Fs)delete Fs[e];Ks.abortRequested=!1,Ks.isPaused=!1,Ks.pausePromise=null,Ks.pausePromiseResolve=null,Ks.lastPausedWidgetId=null,Bs.clearListeners()},la=()=>Ks.abortRequested,ua=e=>{Ks.lastPausedWidgetId=e,Ks.isPaused=!0,Js({isProcessing:!0,isPaused:!0,pauseTrapWidgetId:e})},da=()=>Gs||Vs?null:Ks.pausePromise,ha=e=>Vs?null:Us[e]??null,fa=()=>Gs,pa=e=>ia(e),ga=e=>{const t=ea(e),n=na[t];if(r=Ys,i=n?.error,r?.targetWidgetId===i?.targetWidgetId&&r?.targetPortName===i?.targetPortName&&r?.sourcePortName===i?.sourcePortName&&r?.error===i?.error){if(n){const e=n.stateKey;Fs[e].error=null}Ys=null}var r,i;delete na[t]};var ma={onParentEvent:async(e,t,n,r)=>{const i={...r.getState()};r.setState({...i,$$lastEventType:n.data.type});try{await r.nextWidget("event",n.data)}catch(e){const t=e;t.targetWidgetId&&t.targetPortName&&t.sourcePortName&&ga({targetWidgetId:t.targetWidgetId,targetPortName:t.targetPortName,sourcePortName:t.sourcePortName,error:t.message}),await r.nextWidget("error",{type:pe.JsonObj,value:{error:{message:e.message,targetWidgetId:t.targetWidgetId,targetPortName:t.targetPortName,sourcePortName:t.sourcePortName,sourceWidgetId:t.sourceWidgetId,targetWidgetType:t.targetWidgetType,sourceWidgetType:t.sourceWidgetType,stack:e.stack},inputEvent:{type:n.data.type,data:n.data.value}}})}},getInputNames:()=>[{name:"event",type:pe.Anything}],getOutputNames:e=>[{name:"event",type:{...e}.$$lastEventType??pe.Anything},{name:"error",type:pe.JsonObj,jsonShape:{error:pe.JsonObj,inputEvent:pe.JsonObj}}]};const ya={},va=Object.freeze({output:"output"}),ba=Object.freeze({read:"read",clear:"clear"}),wa=()=>({$$$time:0,totalInputs:1});var Sa={onParentEvent:async(e,t,n,r)=>{const i={$$$time:0,totalInputs:1,...r.getState()};if(ya[r.id]||(ya[r.id]={}),t.name===ba.clear)return ya[r.id]={},void r.setState(i);const o=t.name===ba.read;if(!(o||n.data.type!==pe.JsonObj&&n.data.type!==pe.Anything&&n.data.type!==pe.Rect||"object"!=typeof n.data.value||null===n.data.value||Array.isArray(n.data.value))){const e=ya[r.id]||{};ya[r.id]={...e,...n.data.value}}if(o){const e={...ya[r.id]};return ya[r.id]={},r.setState({...i}),r.nextWidget(va.output,{type:pe.JsonObj,value:e})}},getInputNames:e=>{const t={$$$time:0,totalInputs:1,...e},n=Array(t.totalInputs||1).fill(0).map(((e,t)=>({name:`input${t+1}`,type:pe.Anything})));return n.push({name:ba.clear,type:pe.Anything},{name:ba.read,type:pe.Anything,triggerPort:!0}),n},getOutputNames:()=>[{name:va.output,type:pe.JsonObj}],getDefaultState:wa,initialize:async e=>{ya[e.widgetId]={}},terminate:async e=>{delete ya[e.widgetId]}};const _a={},Ia=Object.freeze({output:"output",index:"index",finish:"finish"}),xa=Object.freeze({array:"array",next:"next",clear:"clear"}),ka=()=>({autoLoop:!1,autoClear:!1,$$outputType:pe.Anything,totalItems:0,currentIndex:0});var Ea={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),o={...ka(),...i};if(t.name===xa.clear)return delete _a[r.id],void r.setState({...ka(),autoLoop:o.autoLoop,autoClear:o.autoClear});if(t.name!==xa.array)t.name===xa.next&&await(async e=>{const t=e.id,n=_a[t],r={...ka(),...e.getState()};if(n&&n.index<n.list.length){const i=n.index,o=n.list[i];await e.nextWidget(Ia.index,{type:pe.Number,value:i}),await e.nextWidget(Ia.output,{type:r.$$outputType,value:o}),n.index++,e.setState({...r,currentIndex:n.index}),n.index===n.list.length&&(await e.nextWidget(Ia.finish,{type:pe.Boolean,value:!0}),r.autoClear?(delete _a[t],e.setState({...ka()})):(n.index=0,e.setState({...r,currentIndex:0})))}})(r);else if((n.data.type===pe.Array||n.data.type===pe.Anything)&&Array.isArray(n.data.value)){const e=n.data.value,t=e[0],i=void 0!==t?Fe(t):pe.Anything,s={list:e,index:0};_a[r.id]=s;const a={...o,$$outputType:i,totalItems:e.length,currentIndex:0};if(r.setState(a),a.autoLoop&&e.length>0){for(const t of e){const e=s.index;r.setState({...a,currentIndex:e}),await r.nextWidget(Ia.index,{type:pe.Number,value:e}),await r.nextWidget(Ia.output,{type:a.$$outputType,value:t}),s.index++}await r.nextWidget(Ia.finish,{type:pe.Boolean,value:!0}),a.autoClear?(delete _a[r.id],r.setState({...a,$$outputType:pe.Anything,totalItems:0,currentIndex:0})):(s.index=0,r.setState({...a,currentIndex:0}))}}},getInputNames:()=>[{name:xa.array,type:pe.Array},{name:xa.next,type:pe.Anything},{name:xa.clear,type:pe.Anything}],getOutputNames:e=>{const t={...ka(),...e};return[{name:Ia.index,type:pe.Number},{name:Ia.output,type:t.$$outputType},{name:Ia.finish,type:pe.Anything}]},getDefaultState:ka,initialize:async e=>{const t={...ka(),...e.getState()};_a[e.widgetId]={list:[],index:0},e.setState({...t,currentIndex:0,totalItems:0})},terminate:async e=>{delete _a[e.widgetId]}};var Ca={onParentEvent:async(e,t,n,r)=>{const i={name:"",...r.getState()};i.name&&e&&Bi({name:i.name,sourceWidget:e?.sourceWidgetId,widgetId:r.id,widgetType:ze.status,value:{type:n.data.type,value:n.data.value}})},getOutputNames:()=>[],getInputNames:()=>[{name:"status",type:pe.Anything}],terminate:async e=>{Vi(e.widgetId)},initialize:async e=>{const t={name:"",...e.getState()};Bi({name:t.name||"",sourceWidget:"",widgetType:ze.status,widgetId:e.widgetId,value:null})}};const $a={onParentEvent:async(e,t,n,r)=>{if(!r.eventContext)return;const i=r.eventContext;if(i?.eventKey)return st(i.eventKey,n.data.value);console.error("No event key found in context event")},getOutputNames:()=>[],getInputNames:()=>[{name:"event",type:pe.Anything}]},Oa="read",Na="setValue",Ta=new Map,Aa=new Map,Ma=(e,t)=>{const n=`${e}_${t}`,r=Ta.get(n);r&&(r(),Ta.delete(n))},Pa=(e,t,n)=>{const r=`${e}_${t}`;n?Ta.set(r,n):Ta.delete(r)};var Da={onParentEvent:async(e,t,n,r)=>{const i={name:"",reactive:!1,lastConfiguration:null,...r.getState()};if(!i.name)return;const o=ao.getGlobalVariable(i.name);if(o)if(t.name===Oa)o&&null!==o.lastValue&&null!==o.lastDataType&&await r.invokeNextWidget({port:"value",data:{type:o.lastDataType,value:o.lastValue}});else if(t.name===Na){let e=n.data.value;if(("number"===o.controlType||"slider"===o.controlType)&&(e=Number(e),isNaN(e)))throw new Error("Expected event value to be a number");if("binaryFile"===o.controlType&&n.data.type!==pe.BinaryFile||"image"===o.controlType&&n.data.type!==pe.ImageData||("text"===o.controlType||"multilineText"===o.controlType)&&n.data.type!==pe.String||"checkbox"===o.controlType&&n.data.type!==pe.Boolean&&n.data.type!==pe.Number||"button"===o.controlType&&n.data.type!==pe.Boolean)throw new Error(`Invalid type, expected event value to be a ${(e=>{switch(e){case"number":case"slider":return"Number";case"text":case"dropdown":case"multilineText":return"String";case"image":return"ImageData";case"binaryFile":return"Binary File";case"checkbox":return"Boolean or Number";case"button":return"Boolean"}return"Anything"})(o.controlType)}`);i.lastConfiguration?.controlSettings===o.controlSettings&&i.lastConfiguration?.controlType===o.controlType&&i.lastConfiguration?.helpText===o.helpText&&i.lastConfiguration?.group===o.group||(i.lastConfiguration={controlType:o.controlType,controlSettings:o.controlSettings,helpText:o.helpText,group:o.group},r.setState({...i})),Aa.set(r.id,{eventId:r.eventId,varName:i.name,type:n.data.type});const{group:t,name:s}=Ki(i.name);await ao.setGlobalVariable({name:s,group:t,value:e,lastDataType:n.data.type,widgetId:r.id,executionContext:{eventId:r.eventId,currentPath:r.currentPath}}),i.reactive&&await r.invokeNextWidget({port:"value",executionContext:{currentPath:r.currentPath,eventId:r.eventId},data:{type:n.data.type,value:e}})}},getOutputNames:e=>{const t={name:"",reactive:!1,lastConfiguration:null,...e};let n=pe.Anything;if(t.name){const e=ao.getGlobalVariable(t.name);e?.lastDataType&&(n=e.lastDataType)}return[{name:"value",type:n}]},getInputNames:()=>[{name:Oa,type:pe.Anything},{name:Na,type:pe.Anything}],terminate:async e=>{Ma(e.widgetId,"variable"),Ma(e.widgetId,"group"),Ma(e.widgetId,"parentGroup"),Aa.delete(e.widgetId)},initialize:async e=>{const t={name:"",reactive:!1,lastConfiguration:null,...e.getState()};Ma(e.widgetId,"variable"),Ma(e.widgetId,"group"),Ma(e.widgetId,"parentGroup"),Aa.set(e.widgetId,null);let n=t.name;t.name&&!t.name.includes(".")&&t.lastConfiguration?.group&&(n=qi(t.lastConfiguration.group,t.name),e.setState({...t,name:n}));const r=ao.getGlobalVariable(n);if(!r&&t.lastConfiguration?.controlType){const{group:r,name:i}=Ki(n);if(r){if(!ao.getGlobalVariable(r)){const{name:e,group:n}=Ki(r);await ao.setGlobalVariable({name:e,group:n,helpText:t.lastConfiguration.groupHelpText??void 0,controlType:"group",value:null,disableChangeNotifications:!0,disableDefineNotifications:!1})}}await ao.setGlobalVariable({name:i,helpText:t.lastConfiguration.helpText,controlType:t.lastConfiguration.controlType,controlSettings:t.lastConfiguration.controlSettings,order:t.lastConfiguration.order,value:null,group:r,disableChangeNotifications:!0,disableDefineNotifications:!1});const o=qi(r,i);e.setState({...t,name:o})}else r&&e.setState({...t,name:n,lastConfiguration:{...t.lastConfiguration,controlType:r.controlType,controlSettings:r.controlSettings,helpText:r.helpText,group:r.group}});if(n){const t=ao.onGlobalVariableParentGroupChange(n,(async t=>{const n=e.getState();let r;if(t.group){const e=ao.getGlobalVariable(t.group);e&&(r=e.helpText??void 0)}const i=t.name;e.setState({...n,name:i,lastConfiguration:{controlType:t.controlType,controlSettings:t.controlSettings,helpText:t.helpText,group:t.group,groupHelpText:r,order:t.order}})}));Pa(e.widgetId,"group",t)}if(n){const t=ao.onVarParentGroupStateChange(n,(async t=>{const r=e.getState(),{name:i}=Ki(n),o=qi(t.parentGroup.name,i);e.setState({...r,name:o,lastConfiguration:{...r.lastConfiguration??{},group:t.parentGroup.name,groupHelpText:t.parentGroup.helpText??void 0}})}));Pa(e.widgetId,"parentGroup",t)}if(t.reactive&&n){const t=ao.onGlobalVariableChange(n,(async t=>{const n=e.getState();if(n.lastConfiguration?.controlType===t.controlType&&n.lastConfiguration?.controlSettings===t.controlSettings&&n.lastConfiguration?.helpText===t.helpText&&n.lastConfiguration?.group===t.group||e.setState({...n,lastConfiguration:{controlType:t.controlType,controlSettings:t.controlSettings,helpText:t.helpText,group:t.group}}),null!==t.lastValue&&null!==t.lastDataType){const n=Aa.get(e.widgetId);if(n?.varName===t.name&&n.type===t.lastDataType&&n.eventId===t.lastExecutionContext?.eventId)return void Aa.set(e.widgetId,null);await e.invokeNextWidget({port:"value",...t.lastExecutionContext?{executionContext:{...t.lastExecutionContext}}:void 0,data:{type:t.lastDataType,value:t.lastValue}})}}));Pa(e.widgetId,"variable",t)}}};const ja=Object.freeze({input:"input"}),Ra="out",La="else",Fa=()=>({conditions:[{expression:"",output:"input"},{expression:"",output:"input"}],multipleOutputs:!0}),Ua=e=>null!=e&&("number"==typeof e?0!==e&&!Number.isNaN(e):"string"==typeof e?e.length>0:Boolean(e));var Ba={onParentEvent:async(e,t,n,r)=>{const i={conditions:[{expression:"",output:"input"},{expression:"",output:"input"}],multipleOutputs:!0,...r.getState()};if(t.name!==ja.input)return;let o;try{o=Ni(r.recipePoolId).uuid}catch{o=void 0}const s=i.conditions||[];for(let e=0;e<s.length;e++){const t=s[e],a=await Rs({customContext:{input:n.data.value},expression:t.expression||"",recipeUuid:o,enableFnTag:!0});if("symbol"!=typeof a.value){if(a.error)throw new Error(a.error);if(Ua(a.value)){let a=n.data.value;if(t.output&&"input"!==t.output){const e=await Rs({customContext:{input:n.data.value},expression:t.output,recipeUuid:o,enableFnTag:!0});if(e.error)throw new Error(e.error);"symbol"!=typeof e.value&&(a=e.value)}else a=n.data.value;const c=Fe(a);if(i.multipleOutputs){const n=[...s];n[e]={...t,$lastOutputType:c},r.setState({...i,conditions:n})}const l=i.multipleOutputs?String(e+1):Ra;return i.multipleOutputs||i.$lastOutputType===c||r.setState({...i,$lastOutputType:c}),r.invokeNextWidget({port:l,data:{type:c,value:a}})}}}return r.invokeNextWidget({port:La,data:{type:n.data.type,value:n.data.value}})},getInputNames:()=>[{name:ja.input,type:pe.Anything}],getOutputNames:e=>{if(!e.multipleOutputs)return[{name:Ra,type:e.$lastOutputType||pe.Anything},{name:La,type:e.$lastElseOutputType||pe.Anything}];const t=Math.max(1,e.conditions?.length||0),n=[];for(let r=0;r<t;r++){const t=e.conditions?.[r]?.$lastOutputType||pe.Anything;n.push({name:String(r+1),type:t})}return n.push({name:La,type:e.$lastElseOutputType||pe.Anything}),n},getDefaultState:Fa};const Wa=new Map;var Ga={registerFunctionHandler:(e,t)=>{Wa.set(e,t)},invokeFunction:async e=>{const{eventId:t,functionName:n,functionParams:r}=e,i=Wa.get(n);if(i)try{const e=await i(r,t);if("function"==typeof e)throw new Error("Functions are not allowed as return types");return e}catch(e){throw console.error(`Error invoking edge function [${n}]:`,e),e}},unregisterFunctionHandler:e=>{Wa.delete(e)},clearAllHandlers:()=>{Wa.clear()}};const Va=()=>({functionName:""}),Ya="result";var Ha={onParentEvent:async(e,t,n,r)=>{const i={functionName:"",...r.getState()};if(!i.functionName||!e)return;const o=r.eventId,s=await Ga.invokeFunction({eventId:o,functionName:i.functionName,functionParams:n.data.value});if(null!=s){const e=Fe(s);await r.invokeNextWidget({port:Ya,data:{type:e,value:s}})}},getOutputNames:()=>[{name:Ya,type:pe.Anything}],getInputNames:()=>[{name:"params",type:pe.Anything}],getDefaultState:Va};const za=new Map,qa="read",Ka="setValue",Ja="value",Za=(e,t,n)=>{const r=se({recipeId:e,widgetId:n});if(!r)return null;const i=r.groupId;if(!i)return null;const o=se({recipeId:e,widgetId:i});return o&&o.type===ze.widgetGroup?{widget:o,thingRecipeId:t}:null};var Xa={onParentEvent:async(e,t,n,r)=>{const i={fieldName:"",reactive:!1,...r.getState()};if(!i.fieldName)return;const o=Za(r.recipePoolId,r.thingRecipeId,r.id);if(!o)return;const s=o.widget,a=s.state,c=a.settings||[],l=c.find((e=>e.variableName===i.fieldName));if(l)if(t.name===qa){const e=l.config,t=e.customValue??e.defaultValue;if(void 0!==t){const e=Fe(t);await r.invokeNextWidget({port:Ja,data:{type:e,value:t}})}}else if(t.name===Ka){const e=c.map((e=>{if(e.variableName===i.fieldName){const t={...e.config,customValue:n.data.value};return{...e,config:t}}return e}));s.state={...a,settings:e};const t=ti(i.fieldName);await ii({variableName:t,setByWidgetId:s.id,value:n.data.value,type:n.data.type})}},getOutputNames:()=>{const e=pe.Anything;return[{name:Ja,type:e}]},getInputNames:()=>[{name:qa,type:pe.Anything},{name:Ka,type:pe.Anything}],initialize:async e=>{const t={fieldName:"",reactive:!1,...e.getState()},n=za.get(e.widgetId);if(n&&(n(),za.delete(e.widgetId)),t.reactive&&t.fieldName){const n=Za(e.recipePoolId,e.thingRecipeId,e.widgetId);if(!n)return;const r=n.widget,i=ti(t.fieldName),o=si({variableName:i,type:pe.Anything,widgetId:e.widgetId,onValueChange:async t=>{if(t.setByWidgetType===ze.widgetGroup&&t.setByWidgetId===r.id){if(!{fieldName:"",reactive:!1,...e.getState()}.reactive)return;if(void 0===t.value)return;await e.invokeNextWidget({port:Ja,data:{type:t.type,value:t.value}})}}});za.set(e.widgetId,o)}},terminate:async e=>{const t=za.get(e.widgetId);t&&(t(),za.delete(e.widgetId))}};const Qa={input:lt,counter:ht,elapsed:gt,ifGate:bt,skipEvent:It,between:Ct,map:Nt,parser:Pt,slider:Rt,suspend:Bt,display:Gt,json:Ht,arrayItem:Kt,extractImage:en,imageConvolution:sn,firstEvent:un,pixelDraw:vn,randomBetween:_n,arrayCombine:Cn,clock:Tn,delay:Ln,multiplication:Wn,object:qn,widgetGroup:Xn,script:Io,base64ToImageData:Oo,jsonParse:Mo,text:Ro,imageCrop:Bo,imageResize:Yo,value:Ko,imageWarp:Qo,sequence:is,variable:cs,hubService:us,imageFilter:ps,recipeLoad:ms,note:ys,stringify:vs,templateString:Ds,expressionEval:Ls,rescue:ma,objectCombine:Sa,loop:Ea,status:Ca,secret:Ti,output:$a,globalVariable:Da,switch:Ba,edgeFunction:Ha,fieldValue:Xa,play:{getInputNames:()=>[],onParentEvent:()=>Promise.resolve(),getOutputNames:()=>[{name:"out",type:pe.Boolean}]}},ec={},tc=async()=>{if(!Object.keys(ec).length)for(const e in Qa){const t=Qa[e];ec[e]=Object.freeze({...t})}};var nc,rc,ic=e=>{if(ec[e])return ec[e];throw new Error(nt(tt,e))},oc=tc;!function(e){e.ServiceCreationLog="service-creation-log"}(nc||(nc={})),function(e){e.Service="service",e.ServiceUI="serviceUI"}(rc||(rc={}));let sc={},ac=0,cc=null;const lc=(e,t)=>{if(e.type===ze.hubService){if(t.type!==ze.hubService)return!1;const n=e.state,r=t.state,i=n.service?.name,o=r.service?.name;return!(!i||!o||i!==o)}return e.type===ze.output&&t.type===ze.input},uc=e=>{const{widgetId:t,widgets:n,currentPath:r}=e,i=n[t];if(!i)return[];const o=new Map;for(let e=0;e<r.length;e++){const t=r.slice(0,e+1),s=t.join("/"),a=sc[s];if(a){const c=n[a.widgetId];if(c){const n=a.path,l=r.join("/").startsWith(n);lc(i,c)&&l&&(o.has(s)||o.set(s,{path:s,data:a,pathSegments:t.length,pathIndex:e,invocationOrder:a.invocationOrder,timestamp:a.timestamp}))}}}const s=Array.from(o.values()).sort(((e,t)=>e.pathIndex-t.pathIndex));return s},dc=e=>{const{context:t,widgetId:n,currentPath:r,executionId:i="default"}=e;if(ac++,0===r.length)throw new Error("Current path cannot be empty");if(!r[r.length-1].includes(n))throw new Error("The widget id is expected to be part of the path");const o=r.join("/");sc[o]={path:o,eventContext:t,widgetId:n,invocationOrder:ac,timestamp:Date.now(),executionId:i}},hc=e=>{const t=uc(e);return t.length>0?t[t.length-1]:null},fc=()=>{sc={},ac=0},pc=e=>{cc=e},gc=()=>{sc={},ac=0};let mc,yc,vc,bc=!1,wc=0,Sc=0;const _c=async e=>{const{widgetId:t,thingId:n,recipeId:r,targetPortName:i,data:o}=e,s=oe(r,n);if(!s)return;const a=s.gates[t];if(!a||a.disabled)return;const c={...o,timestamp:Date.now()},l=ic(a.type);Sc+=1;const u=Cc({gateId:t,originalEvent:c,blockRecipeId:s.recipeId,blockDbId:s.id,blockVersion:s.version,recipeId:r,sourceWidgetId:void 0,currentPath:[],eventId:Sc});if(u&&l.onParentEvent){const e={name:i};return mc&&await mc({recipeId:r,blockId:s.recipeId,gateId:t,targetPort:e.name,data:o}),l.onParentEvent(null,e,{originalEvent:c,data:{...c}},u)}},Ic=async e=>{const{eventContext:t,interruptDriven:n,childGateId:r,recipeId:i,sourcePortName:o,targetPort:s,data:a,sourceOutputNames:c,sourceWidgetId:l,bypassHistoryRecording:u,eventId:d}=e;let{originalEvent:h,block:f}=e;if(!n&&!l)throw new Error("Missing parameter ['sourceGateId']");if(!n&&!h)throw new Error("Missing parameter ['originalEvent']");n&&(h={timestamp:Date.now(),type:pe.Boolean,value:!0});const p=h;if("string"==typeof f){const e=oe(i,f);if(!e)return;f=e}const g=f.gates[r];if(!g||g.disabled)return;const m=c.findIndex((e=>e.name===o)),y=ic(g.type),v=[...e.currentPath];if(l){0===v.length?v.push(`${l}:${d?.toString()}`):v.push(l)}if(t){const e=se({recipeId:i,widgetId:l});e?.type!==ze.hubService&&e?.type!==ze.input||dc({context:t,widgetId:l,currentPath:v,executionId:d?.toString()})}const b=Cc({gateId:r,originalEvent:p,blockRecipeId:f.recipeId,blockDbId:f.id,blockVersion:f.version,recipeId:i,sourceWidgetId:l,currentPath:v,eventId:d});if(b&&y.onParentEvent&&-1!==m){mc&&await mc({recipeId:i,blockId:f.recipeId,gateId:r,targetPort:s.name,data:a,sourceGate:n?"interrupt_widget":l,sourcePort:n?ue:o});const e={name:c[m].name,type:c[m].type,...c[m].jsonShape?{jsonShape:c[m].jsonShape}:void 0,sourceWidgetId:l};return u||Ii({thingId:f.recipeId,widgetId:r,sourceOutputNames:c,targetPortName:s.name,currentPath:v,eventId:d,data:a,originalEvent:p,recipeId:i,source:l?{widgetId:l,portName:o}:void 0}),y.onParentEvent(e,s,{originalEvent:p,data:a},b)}},xc=async e=>{const{portName:t,originalEvent:n,data:r,currentGateId:i,blockRecipeId:o,thingDbId:s,thingVersion:a,recipeId:c,eventContext:l,currentPath:u}=e;let{eventId:d}=e;const h=ie(c);if(!h)throw new Error(`Failed to find recipe "${c}" in cache`);const f=h.dbInfo.recipeType,p=ae(c,o,i);if(!p)return;const g={...r,timestamp:n.timestamp},m=ic(p.type);let y;y=p.type===ze.input?m.getOutputNames(p.state,{thingRecipeId:o,thingDbId:s,thingVersion:a,id:i,recipeId:c,recipeType:f,recipePoolId:c}):await m.getOutputNames(p.state,{recipePoolId:c,recipeType:f,thingRecipeId:o,widgetId:i});if(-1!==y.findIndex((e=>e.name===t))){const e=oe(c,o);if(!e)return;null===d&&(Sc+=1,d=Sc),_i({thingId:o,widgetId:i,sourceOutputNames:y,sourcePortName:t,currentPath:u,data:g,recipeId:c,eventId:d});let r=null;const s=p.children.length,a=u;try{for(let u=0;u<s;u++){const s=e.gates[p.children[u].childId];if(s?.disabled)continue;const h=We(p.children[u]?.sourcePort),m=We(p.children[u]?.targetPort);if(h.portName===t&&s&&!s.disabled){if(bc&&da()&&(ua(s.id),await da()),ha(s.id)&&!fa()&&"innerInput"!==m?.portType){const e=pa(s.id);await e}if(bc&&la())break;const u=ic(s.type);let h;const v={recipePoolId:c,recipeType:f,thingRecipeId:o,widgetId:i};h=s.type===ze.hubService?await u.getInputNames(s.state,v):u.getInputNames(s.state,v);const b=h.find((e=>e.name===m.portName));if(b){bc&&await oa({thingId:o,widgetId:s.id}),wc++;if(!await Ic({eventContext:l,interruptDriven:!1,childGateId:s.id,block:e,recipeId:c,sourcePortName:t,currentPath:a,eventId:d,targetPort:{name:b.name},data:p.returnOriginalEvent?n:g,sourceOutputNames:y,sourceWidgetId:p.id,originalEvent:n}).then((()=>!0)).catch((e=>{const n=s.type===ze.hubService&&"CHILD_WIDGET_ERROR"===e.errCode;if(e instanceof jr)throw e;if(n&&e.errData){const t=e.errData;throw new jr(e.error||e.message||("string"==typeof e?e:JSON.stringify(e)),{targetWidgetId:t.targetWidgetId,targetPortName:t.targetPortName,sourcePortName:t.sourcePortName,sourceWidgetId:t.sourceWidgetId,targetWidgetType:t.targetWidgetType,sourceWidgetType:t.sourceWidgetType})}if(!r){const n="string"==typeof e?e:e.message||JSON.stringify(e);r={targetWidgetId:s.id,targetPortName:b.name,sourcePortName:t,error:n}}throw new jr(e.message||("string"==typeof e?e:JSON.stringify(e)),{stack:e.stack,targetWidgetId:s.id,targetPortName:b.name,sourcePortName:t,sourceWidgetId:p.id,targetWidgetType:s.type,sourceWidgetType:p.type})})).finally((()=>{if(wc--,bc)return sa({thingId:o,widgetId:s.id,error:r})})))break}}}}catch(e){if(e instanceof jr)throw e;console.error(`Error processing next widget [${i}]: ${e}`)}finally{wc<0&&(console.warn("Active execution counter is negative, this should never happen"),wc=0),0===wc&&fc()}}},kc=async(e,t,n,r)=>{const i=ie(r);if(!i)return null;const o=oe(r,n);if(!o)return o;const s=o.gates,a=o.gates[t],c=ic(a.type),l=await c.getInputNames(a.state,{recipePoolId:r,recipeType:i.dbInfo.recipeType,thingRecipeId:n,widgetId:t}),u=l.findIndex((t=>t.name===e));if(-1!==u){const e=((e,t,n)=>{for(const r in n){const i=n[r],o=i.children.length;for(let n=0;n<o;n++){const r=i.children[n],o=We(r.targetPort);if(r.childId===e&&o.portName===t)return i}}return null})(t,l[u].name,s);if(e){const t=ic(e.type);return{getValue:()=>"function"==typeof t.getValue?t.getValue():null}}}return null},Ec=e=>{const{gateId:t,originalEvent:n,thingRecipeId:r,thingDbId:i,thingVersion:o,recipeId:s,currentPath:a,eventId:c}=e;if(!ie(s))throw new Error(`Failed to find recipe "${s}" in cache`);if(!ae(s,r,t))throw console.warn(`Gate ${t} not found in block ${r} for recipe ${s}`),new Error(`Gate ${t} not found in block ${r} for recipe ${s}`);return async e=>xc({portName:e.port,originalEvent:n||{timestamp:Date.now(),type:e.data.type,value:e.data.value},data:e.data,currentGateId:t,blockRecipeId:r,thingDbId:i,thingVersion:o,recipeId:s,eventContext:e.eventContext,currentPath:e.executionContext?.currentPath||a,eventId:e.executionContext?.eventId||c})},Cc=e=>{const{gateId:t,originalEvent:n,blockRecipeId:r,blockDbId:i,blockVersion:o,recipeId:s,currentPath:a,eventId:c}=e,l=ie(s);if(!l)throw new Error(`Failed to find recipe "${s}" in cache`);const u=ae(s,r,t);if(!u)return console.warn(`Gate ${t} not found in block ${r} for recipe ${s}`),null;const d=Ec({gateId:t,originalEvent:n,thingRecipeId:r,thingDbId:i,thingVersion:o,recipeId:s,currentPath:a,eventId:c}),h=hc({widgetId:t,widgets:l.blocks[r].gates,currentPath:e.currentPath}),f=(e,t,n,r)=>d({port:e,data:t,eventContext:n,executionContext:r}),p={id:t,type:u.type,recipePoolId:s,thingRecipeId:r,recipeType:l.dbInfo.recipeType,returnOriginalEvent:!!u.returnOriginalEvent,currentPath:e.currentPath,eventId:c,eventContext:h?.data.eventContext||void 0,registerInterrupt:e=>{const{type:n,customTargetPortName:i,config:o,sourceWidgetId:a,interruptData:c,customId:l}=e;return Qe.createInterrupt({type:n,recipePoolId:s,thingId:r,targetWidgetId:t,sourceWidgetId:a,portName:i,config:o,data:c,customId:l})},cancelInterrupt:e=>Qe.destroyInterrupt(e),invokeNextWidget:d,nextWidget:f,nextGate:f,getParentAtPort:e=>kc(e,t,r,s),getState:()=>Object.freeze({...u.state,...u.type===ze.input&&{customInputs:[]}}),setState:e=>{if("object"!=typeof e)return void console.warn(`Invalid state type [${typeof e}]. Expected an 'object'`);const n={...e,...u.type===ze.input&&!e.customInputs&&{customInputs:[]}},i={...u.state};u.state=n,yc&&yc({blockId:r,gateId:t,prevState:i,newState:{...n},recipeId:s})}};return p};Qe.setInvokeChildGateCb(Ic),Qe.setConsumeEventCounterCb((()=>++Sc));const $c=(e,t,n,r,i)=>{const o=ae(e,n,r);if(!o)return console.warn(`Gate ${r} not found in block ${n} for recipe ${e}`),null;const s=t=>{const{type:i,customTargetPortName:o,config:s,data:a}=t;return Qe.createInterrupt({type:i,recipePoolId:e,thingId:n,targetWidgetId:r,sourceWidgetId:r,portName:o,config:s,data:a})},a=()=>Object.freeze({...o.state,...o.type===ze.input&&{customInputs:[]}}),c=e=>{if("object"!=typeof e)return void console.warn(`Invalid state type [${typeof e}]. Expected an 'object'`);const t={...e,...o.type===ze.input&&!e.customInputs&&{customInputs:[]}};o.state=t},l=async t=>{const r=((e,t,n)=>{const r=ie(e);if(!r)throw new Error(`Recipe [${e} does not exist]`);if(!r.storage)return null;const i=oe(e,t);if(!i)throw new Error(`The Thing "${t}" does not exist in recipe ${e}`);if(!(i.storageUnits||[]).includes(n))throw new Error(`The Thing "${t}" has no access to storage unit "${n}"`);return r.storage[n]||null})(e,n,t);return r};if(i){const i=Ec({gateId:r,thingRecipeId:n,thingDbId:o.id,thingVersion:"default",recipeId:e,currentPath:[],eventId:null});return{getState:a,setState:c,registerInterrupt:s,getStorageData:l,nextWidget:(e,t,n)=>i({port:e,data:t,eventContext:n}),invokeNextWidget:i,recipePoolId:e,recipeType:t,thingRecipeId:n,widgetId:r}}return{getState:a,setState:c,recipePoolId:e,widgetId:r,thingRecipeId:n}},Oc=new a,Nc="invoked",Tc="state",Ac=()=>{Qe.destroyAllInterrupts()},Mc=async(e,t,n)=>{const r=ie(e),i=ae(e,t,n);if(i&&r){const o=ic(i.type);if(o&&"function"==typeof o.terminate){const i=((e,t,n,r)=>$c(e,t,n,r))(e,r.dbInfo.recipeType,t,n);if(i)try{await o.terminate(i)}catch(e){console.warn(`Error terminating widget "${n}" in thing "${t}". Failing silently: `,e)}}}},Pc=async e=>{const{recipePoolId:t,thingRecipeId:n,widgetRecipeId:r,options:i}=e,o=ie(t),s=ae(t,n,r);if(s&&o){const e=ic(s.type);if(e&&"function"==typeof e.initialize){const a=((e,t,n,r)=>$c(e,t,n,r,!0))(t,o.dbInfo.recipeType,n,r);if(a){const t=e.initialize;try{(e=>{if(e.type===ze.script){const t=e.state;if((t.version||0)<2){const n=Object.keys(e.variablesListener||{});for(const t of n)if(e.variablesListener){const n=ti(t);e.variablesListener[n]=e.variablesListener[t],delete e.variablesListener[t],delete e.variables}t.version=2}}})(s),await t(a,i||{})}catch(e){throw console.warn(`Error initializing widget "${r}" in thing "${n}": `,e),e}}}}},Dc=(e,t)=>{const n=ie(t);if(n)for(const t in n.blocks){const r=n.blocks[t];for(const t in r.gates)if(t===e)return{widget:r.gates[t],thing:r}}return null},jc=(e,t="",n="")=>`block:${t}:gate:${n||""}:${e}`,Rc=e=>{Oc.emit(jc(Tc),e),Oc.emit(jc(Tc,e.blockId,e.gateId),e)};mc=async e=>{await Oc.emit(jc(Nc),e),await Oc.emit(jc(Nc,e.blockId,e.gateId),e)},(e=>{yc=e})(Rc);var Lc=async(e,t,n,r,i)=>{const o=ce(e,{id:t,authorId:r,version:n,recipeType:i});xi(),gc(),pc(i),e.globalVariables&&ao.registerGlobalVariables(e.globalVariables);const s=ie(o);return s&&(s.startedAt=Date.now(),s.retryAttempts=0,s.execCounter=0,s.status=Z.STARTING,s.addLog("recipe registered")),o},Fc=async e=>{const t=ie(e);if(!t)return null;t.addLog("terminating recipe"),Ac(),ca();for(const n in t.blocks){const r=t.blocks[n];for(const t in r.gates)await Mc(e,n,t)}(e=>{!!te[e]&&delete te[e]})(e)},Uc=async(e,t)=>{const n=ie(e),r=[],i=[];if(n){Gi(),ai({recipePoolId:e,thingId:he});for(const o in n.blocks){const s=n.blocks[o];if(!t||!Array.isArray(t)||t.includes(o))for(const t in s.gates)try{if(n.dbInfo?.recipeType===mr.Desktop){const e=s.gates[t];if(e.type===ze.hubService){const r=e.state;if(r?.service?.webOnly){n?.addLog(`skipping initialization of web-only widget "${t}"`);continue}}e.type===ze.recipeLoad&&i.push(e)}await Pc({recipePoolId:e,thingRecipeId:o,widgetRecipeId:t,options:{keepCurrentState:!0}})}catch(e){r.push({widgetId:t,error:e.message})}}}return{failed:r,sendToInputWidget:t=>{const{inputName:n,data:r,thingId:i=he,waitForOutputChild:o=!0}=t;return(async e=>{const{inputName:t,data:n,recipePoolId:r,thingId:i,waitForOutputChild:o=!0}=e,s=ie(r),a=oe(r,i),c=Date.now();if(a&&s){Sc+=1;for(const e in a.gates){const s=a.gates[e];if(s.type===ze.input&&!s.disabled){const l=s.state.inputName||"";if(l===t){const t=ic(s.type),u={...n,timestamp:c},d=Cc({gateId:e,originalEvent:u,blockRecipeId:i,blockDbId:a.id,blockVersion:a.version,recipeId:r,sourceWidgetId:void 0,currentPath:[],eventId:Sc});if(d&&t.processEvent){const s={...d,getState:d.getState,waitForOutputChild:o};if(mc&&await mc({recipeId:r,blockId:i,gateId:e,targetPort:ct,data:n}),!vc)return await t.processEvent(u,s);await vc(i,r,l,n)}continue}}}}})({inputName:n,data:r,recipePoolId:e,thingId:i,waitForOutputChild:o})},invokeRecipeLoadedWidgets:async()=>{for(const t of i)await _c({widgetId:t.id,thingId:he,recipeId:e,targetPortName:gs,data:{type:pe.Boolean,value:!0}})}}},Bc=e=>{fi(e)},Wc=(e,t,n,r=!1)=>{const i=Dc(t,e);if(i){const{widget:o,thing:s}=i,a={...o.state};o.state=n,r&&Rc({blockId:s.recipeId,gateId:t,recipeId:e,newState:{...n},prevState:a})}},Gc=(e,t)=>{const n=Dc(t,e);return n?n.widget.state:null},Vc=async e=>{const{recipePoolId:t,currentGateId:n,sourcePortName:r,originalEvent:i,data:o,eventContext:s,currentPath:a,eventId:c}=e,l=Dc(n,t);if(l)return xc({portName:r,originalEvent:i,data:o,currentGateId:n,blockRecipeId:l.thing.recipeId,thingDbId:l.thing.id,thingVersion:l.thing.version,recipeId:t,eventContext:s,currentPath:a,eventId:c})},Yc=()=>{bc=!0},Hc=ki;const zc=async e=>{const t=async(e,n)=>{if(null==e)return null;switch(n){case"image":return await Ye({base64Str:e});case"binaryFile":{const t=e;let n;const r=((e,{minLength:t=4,maxChars:n=1e4,allowDataURI:r=!0,allowBase64Prefix:i=!0,sliceAndTest:o=!0}={})=>{if("string"!=typeof e)return!1;let s=e.trim();if(!s)return!1;if(r){const e=s.match(/^data:([^;,]+)?;base64,(.*)$/i);if(e){const t=e[2]??"";if(/[\r\n]/.test(t))return!1;s=t}}if(i&&s.startsWith("base64:")&&(s=s.substring(7)),s=s.replace(/\s+/g,""),!s)return!1;if(s.length>n){if(!o)return!1;s=s.slice(0,n)}const a=/[+/]/.test(s),c=/[-_]/.test(s);if(a&&c)return!1;if(c?!/^[A-Za-z0-9_-]*={0,2}$/.test(s):!/^[A-Za-z0-9+/]*={0,2}$/.test(s))return!1;const l=s.match(/=+$/)?.[0].length??0;if(l>2)return!1;if(/=/.test(s.slice(0,s.length-l)))return!1;if(s.length<Math.max(4,t))return!1;let u,d=c?s.replace(/-/g,"+").replace(/_/g,"/"):s;s.length%4&&(d=d.padEnd(d.length+(4-d.length%4),"="));try{if("undefined"!=typeof Buffer&&"function"==typeof Buffer.from)u=new Uint8Array(Buffer.from(d,"base64"));else{if("function"!=typeof atob)return!1;{const e=atob(d);u=new Uint8Array(e.length);for(let t=0;t<e.length;t++)u[t]=e.charCodeAt(t)}}}catch{return!1}if(0===u.length)return!1;let h=(e=>{if("undefined"!=typeof Buffer)return Buffer.from(e).toString("base64");let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)})(u);c&&(h=h.replace(/\+/g,"-").replace(/\//g,"_"));const f=e=>e.replace(/=+$/g,""),p=f(h)===f(s);if(!p)return!1;const g=String.fromCharCode(...u),m=/^[\x09\x0A\x0D\x20-\x7E]*$/.test(g);return!(s.length<=20&&!m||s.length<=20&&/^[A-Za-z0-9_-]+$/.test(s)&&m&&!p||s.length<=50&&/^[A-Za-z0-9][A-Za-z0-9._-]*\/[A-Za-z0-9._+-]+$/.test(s)&&m||s.length>20&&/^[A-Za-z0-9_-]+$/.test(s)&&!/=/.test(s)&&m&&!p||s.length>20&&/^[A-Za-z0-9_-]+$/.test(s)&&!/=/.test(s)&&!m)})(t.data);if(r)n=await(e=>{if(ee){const t=Buffer.from(e,"base64"),n=new ArrayBuffer(t.byteLength);return new Uint8Array(n).set(t),n}{if("function"==typeof Uint8Array.fromBase64){const t=Uint8Array.fromBase64(e),n=new ArrayBuffer(t.byteLength);return new Uint8Array(n).set(t),n}const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);const r=new ArrayBuffer(n.byteLength);return new Uint8Array(r).set(n),r}})(t.data);else{if("string"!=typeof t.data)return console.error("The BinaryFile variable value data is not a string. Unable to deserialize the variable."),null;try{n=(new TextEncoder).encode(t.data).buffer}catch(e){return console.error("Failed to convert the BinaryFile variable value data to an ArrayBuffer. Unable to deserialize the variable.",e),null}}return{...t,data:n}}case"anything":if(Array.isArray(e)){const r=e.map((e=>t(e,n)));return await Promise.all(r)}if("object"==typeof e){const r=e,i={};for(const e in r){const o=r[e];null!=o&&(i[e]=await t(o,n))}return i}return e;default:return e}},n=await Promise.all(e.map((async e=>({...e,lastValue:await t(e.lastValue,e.controlType).catch((e=>(console.error("Failed to deserialize the value of the global variable.",e),null)))}))));return n},qc=e=>{try{return JSON.parse(e)}catch(e){return null}},Kc="undefined"!=typeof window,Jc={protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8},Zc={protocolPrefix:4,txtLength:4},Xc=Object.values(Jc).reduce(((e,t)=>e+t),0),Qc=Object.values(Zc).reduce(((e,t)=>e+t),0),el=["width","height","colorSpace"],tl=(e,t)=>{const n={},r=[];let i=0,o=Array.isArray(e)?[]:{};const s=(e,o)=>{const a=(e=>{const t="undefined"!=typeof Buffer&&e instanceof Buffer,n=e instanceof ArrayBuffer,r=e instanceof Uint8ClampedArray,i=e instanceof Uint8Array,o=e instanceof Int8Array;return t?"Buffer":n?"ArrayBuffer":r?"Uint8ClampedArray":i?"Uint8Array":o?"Int8Array":null})(e);if(!a){if(Array.isArray(e)){const t=[];for(let n=0;n<e.length;n++)t[n]=s(e[n],`${o}[${n}]`);return t}if("object"==typeof e){const t={},n=(e=>{const t=e instanceof Int16Array,n=e instanceof Uint16Array,r=e instanceof Int32Array,i=e instanceof Uint32Array,o=e instanceof Float32Array,s=e instanceof Float64Array,a=e instanceof BigInt64Array,c=e instanceof BigUint64Array;return t?"Int16Array":n?"Uint16Array":r?"Int32Array":i?"Uint32Array":o?"Float32Array":s?"Float64Array":a?"BigInt64Array":c?"BigUint64Array":null})(e);if(n)throw new Error(`Unsupported binary type [${n}] at path "${o}"`);for(const n in e)Object.hasOwn(e,n)||el.includes(n)||console.warn(`Allowing inherited property: ${n} from path: ${o}`),t[n]=s(e[n],`${o.length?`${o}.`:""}${n}`);return t}return e}n[o]={index:i,length:e.byteLength,binaryType:a},"Buffer"===t?r.push(Buffer.from(e)):"ArrayBuffer"===a?r.push(e):r.push(e.buffer),i+=e.byteLength};o=s(e,"");let a=null;if(r.length>1)if("ArrayBuffer"===t){const e=r.reduce(((e,t)=>e+t.byteLength),0),t=new Uint8Array(e);let n=0;for(let e=0;e<r.length;e++)t.set(new Uint8Array(r[e]),n),n+=r[e].byteLength;a=t.buffer}else{a=Buffer.concat(r)}else 1===r.length&&(a=r[0]);return a?{map:n,combinedData:a,sourceCopy:o}:null},nl=(e,t,n)=>{const r=t.match(/(\[\d+\])|([^[\].]+)/g)||[];let i=e;for(let e=0;e<r.length;e++){let t=r[e];const o=t.startsWith("[")&&t.endsWith("]"),s=e===r.length-1;if(o){t=t.slice(1,-1);const o=parseInt(t,10);if(!Array.isArray(i))throw new Error(`Expected an array at key "${r.slice(0,e).join(".")}" but found an object.`);s?i[o]=n:(i[o]||(i[o]=r[e+1].startsWith("[")?[]:{}),i=i[o])}else s?i[t]=n:(i[t]||(i[t]=r[e+1].startsWith("[")?[]:{}),i=i[t])}return e},rl=(e,t,n)=>{const r="undefined"!=typeof Buffer,i=t instanceof Uint8Array;for(const o in n)if(Object.hasOwn(n,o)){const{index:s,length:a,binaryType:c}=n[o];let l=null;if(r&&t instanceof Buffer)switch(c){case"Buffer":l=t.subarray(s,s+a);break;case"ArrayBuffer":l=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(s,s+a);break;case"Uint8Array":l=new Uint8Array(t.subarray(s,s+a));break;case"Uint8ClampedArray":l=new Uint8ClampedArray(t.subarray(s,s+a));break;case"Int8Array":l=new Int8Array(t.subarray(s,s+a))}else if(t instanceof ArrayBuffer||t instanceof Uint8Array)switch(c){case"Buffer":if(r){l=Buffer.from(t.slice(s,s+a));break}case"ArrayBuffer":l=i?t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(s,s+a):t.slice(s,s+a);break;case"Uint8Array":l=i?t.slice(s,s+a):new Uint8Array(t.slice(s,s+a));break;case"Uint8ClampedArray":l=new Uint8ClampedArray(t.slice(s,s+a));break;case"Int8Array":l=new Int8Array(t.slice(s,s+a))}l&&nl(e,o,l)}return e},il=e=>u(e),ol="KMSG",sl="KCMD",al=il("klProtocol");var cl={encode:(e,t,n)=>{const r={json:e.json},i=tl(r.json,"Buffer"),o=i?.combinedData;i&&(r.jsonBinaryMap=i.map,r.json=i.sourceCopy);const s=o?o.byteLength:0,a=JSON.stringify(r),c=Buffer.from(a),l=c.byteLength,u=Jc.protocolPrefix+Jc.protocolVersion+Jc.jsonLength+Jc.binaryLength+Jc.fromServiceId+Jc.toServiceId+Jc.sentAt+l+s,d=Buffer.alloc(u),h=Date.now();let f=0;return d.write(ol,f),f+=Jc.protocolPrefix,d.writeUInt8(1,f),f+=Jc.protocolVersion,d.writeUInt32LE(l,f),f+=Jc.jsonLength,d.writeUInt32LE(s,f),f+=Jc.binaryLength,d.writeUInt32LE(t,f),f+=Jc.fromServiceId,d.writeUInt32LE(n,f),f+=Jc.toServiceId,d.writeBigInt64LE(BigInt(h),f),f+=Jc.sentAt,c.copy(d,f),f+=l,o&&s&&o.copy(d,f),d},decodeHeader:e=>{let t=0;const n=e.toString("utf-8",t,Jc.protocolPrefix);if(t+=Jc.protocolPrefix,n!==ol)return null;if(e.byteLength<Xc)return al(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const r=e.readUInt8(t);t+=Jc.protocolVersion;const i=e.readUInt32LE(t);t+=Jc.jsonLength;const o=e.readUInt32LE(t);t+=Jc.binaryLength;const s=e.readUInt32LE(t);t+=Jc.fromServiceId;const a=e.readUInt32LE(t);t+=Jc.toServiceId;const c=e.readBigInt64LE(t);t+=Jc.sentAt;const l=i+o,u=e.subarray(t,t+l),d=e.subarray(0,Xc);let h=null;return e.byteLength-Xc-i-o>0&&(h=e.subarray(Xc+i+o)),{header:{protocolVersion:r,jsonLength:i,binaryLength:o,fromServiceId:s,toServiceId:a,sentAt:new Date(Number(c)),packages:[u],headerPackage:d},remaining:h}},decodeFullKlMessage:e=>{const t=Buffer.concat(e.packages),n=t.subarray(0,e.jsonLength).toString(),r=t.subarray(e.jsonLength,e.jsonLength+e.binaryLength),i=qc(n);if(!i?.json)return al("Invalid JSON in KL message"),null;i.jsonBinaryMap&&r.byteLength&&rl(i.json,r,i.jsonBinaryMap);const o=Buffer.concat([e.headerPackage,t]);let s=o,a=null;const c=Xc+e.jsonLength+e.binaryLength;return o.byteLength>c&&(a=o.subarray(c),s=o.subarray(0,c)),{message:{json:i.json,rawMessage:s},remaining:a}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<Xc)return al("Invalid Header Size"),e;let n=0;return n+=Jc.protocolPrefix,n+=Jc.protocolVersion,n+=Jc.jsonLength,n+=Jc.binaryLength,void 0!==t.fromServiceId&&e.writeUInt32LE(t.fromServiceId,n),n+=Jc.fromServiceId,void 0!==t.toServiceId&&e.writeUInt32LE(t.toServiceId,n),e},encodeCommand:e=>{let t=0;const n=Buffer.from(e),r=n.byteLength,i=Qc+r,o=Buffer.alloc(i);return o.write(sl,t),t+=Zc.protocolPrefix,o.writeUint32LE(r,t),t+=Zc.txtLength,n.copy(o,t),o},decodeCommand:e=>{let t=0;if(e.byteLength<Qc)return{command:null};const n=e.toString("utf-8",t,Zc.protocolPrefix);if(t+=Zc.protocolPrefix,n!==sl)return{command:null};const r=e.readUInt32LE(t);t+=Zc.txtLength;const i=e.toString("utf-8",t,t+r),o=e.byteLength-Qc-r;let s=null;o>0&&(s=e.subarray(Qc+r));let a=0;return o<0&&(a=Math.abs(o)),{command:i,remainingData:s,missing:a}}};const ll="KMSG",ul="KCMD",dl=il("klProtocol"),hl=new TextEncoder;var fl={encode:(e,t,n)=>{const r={json:e.json},i=tl(e.json,"ArrayBuffer"),o=i?.combinedData;i&&(r.jsonBinaryMap=i.map,r.json=i.sourceCopy);const s=o?o.byteLength:0,a=JSON.stringify(r),c=hl.encode(a),l=c.byteLength,u=new ArrayBuffer(Jc.protocolPrefix+Jc.protocolVersion+Jc.jsonLength+Jc.binaryLength+Jc.fromServiceId+Jc.toServiceId+Jc.sentAt+l+s),d=new DataView(u),h=new Uint8Array(u),f=Date.now();let p=0;for(let e=0;e<4;++e)h[p++]=ll.charCodeAt(e);return d.setUint8(p,1),p+=Jc.protocolVersion,d.setUint32(p,l,!0),p+=Jc.jsonLength,d.setUint32(p,s,!0),p+=Jc.binaryLength,d.setUint32(p,t,!0),p+=Jc.fromServiceId,d.setUint32(p,n,!0),p+=Jc.toServiceId,d.setBigInt64(p,BigInt(f),!0),p+=Jc.sentAt,h.set(c,p),p+=l,o&&s&&h.set(new Uint8Array(o),p),u},decodeHeader:e=>{const t=new DataView(e);let n=0,r="";for(let e=0;e<Jc.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==ll)return null;if(e.byteLength<Xc)return dl.log(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const i=t.getUint8(n);n+=Jc.protocolVersion;const o=t.getUint32(n,!0);n+=Jc.jsonLength;const s=t.getUint32(n,!0);n+=Jc.binaryLength;const a=t.getUint32(n,!0);n+=Jc.fromServiceId;const c=t.getUint32(n,!0);n+=Jc.toServiceId;const l=t.getBigInt64(n,!0);n+=Jc.sentAt;const u=o+s,d=e.slice(n,n+u),h=new Uint8Array(e,0,Xc);let f=null;if(e.byteLength-Xc-o-s>0){f=new Uint8Array(e,Xc+o+s).slice().buffer}return{header:{protocolVersion:i,jsonLength:o,binaryLength:s,fromServiceId:a,toServiceId:c,sentAt:new Date(Number(l)),packages:[d],headerPackage:h.slice().buffer},remaining:f}},decodeFullKlMessage:e=>{const t=e.packages.reduce(((e,t)=>e+t.byteLength),0),n=new Uint8Array(t);let r,i=0;for(const t of e.packages)r=new Uint8Array(t),n.set(r,i),i+=r.byteLength;const o=(new TextDecoder).decode(n.subarray(0,e.jsonLength)),s=n.subarray(e.jsonLength,e.jsonLength+e.binaryLength),a=qc(o);if(!a?.json)return dl.log("Invalid JSON in KL message"),null;a.jsonBinaryMap&&s.byteLength&&rl(a.json,s,a.jsonBinaryMap);const c=new Uint8Array(e.headerPackage.byteLength+n.byteLength);c.set(new Uint8Array(e.headerPackage),0),c.set(n,e.headerPackage.byteLength);let l=c,u=null;const d=Xc+e.jsonLength+e.binaryLength;return c.byteLength>d&&(u=c.subarray(d),l=c.subarray(0,d)),{message:{json:a.json,...s.length?{binaryData:s.buffer}:{},rawMessage:l.buffer},remaining:u?.buffer??null}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<Xc)return dl("Invalid Header Size"),e;let n=0;n+=Jc.protocolPrefix,n+=Jc.protocolVersion,n+=Jc.jsonLength,n+=Jc.binaryLength;const r=new DataView(e);return void 0!==t.fromServiceId&&r.setUint32(n,t.fromServiceId,!0),n+=Jc.fromServiceId,void 0!==t.toServiceId&&r.setUint32(n,t.toServiceId,!0),e},encodeCommand:e=>{let t=0;const n=hl.encode(e),r=n.byteLength,i=new ArrayBuffer(Qc+r),o=new DataView(i),s=new Uint8Array(i);for(let e=0;e<4;++e)s[t++]=ul.charCodeAt(e);return o.setUint32(t,r,!0),t+=Zc.txtLength,s.set(n,t),i},decodeCommand:e=>{const t=new DataView(e);let n=0;if(e.byteLength<Qc)return{command:null};let r="";for(let e=0;e<Zc.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==ul)return{command:null};const i=t.getUint32(n,!0);n+=Zc.txtLength;const o=e.byteLength-Qc-i,s=new Uint8Array(e,n,Math.min(i,e.byteLength-Qc)),a=(new TextDecoder).decode(s);let c=null;o>0&&(c=e.slice(Qc+i));let l=0;return o<0&&(l=Math.abs(o)),{command:a,remainingData:c,missing:l}}};let pl=cl;Kc&&(pl=fl);var gl,ml=pl;!function(e){e.FunctionNotFound="FNC_NOT_FOUND",e.FunctionNotAllowed="FNC_NOT_ALLOWED",e.ParentEventCallbackError="PARENT_EVENT_CALLBACK_ERROR"}(gl||(gl={}));let yl=Math.ceil(Date.now()/1e3);let vl,bl,wl,Sl,_l,Il=!1;var xl=()=>{Il=!0},kl=()=>{Il=!1},El=(e,t)=>{if(!vl)throw new Error("Memory connection not set.");vl.sendBuf(e,t)},Cl=e=>bl=e,$l=e=>_l=e,Ol=e=>wl=e,Nl=e=>Sl=e;const Tl=async(e,t=2)=>{const n=async(e,r)=>{if(Array.isArray(e))for(let i=0;i<e.length;i++){const o=e[i];if(o&&"object"==typeof o)if(Array.isArray(o))await n(o,r+1);else{const s=o._kemuType;void 0!==s?s===pe.ImageData&&(e[i]=await Ge(o)):r<t&&await n(o,r+1)}}else if("object"==typeof e&&null!==e){const i=Object.keys(e);for(const o of i){const i=e[o];if(i&&"object"==typeof i){const s=i._kemuType;void 0!==s?s===pe.ImageData&&(e[o]=await Ge(i)):r<t&&await n(i,r+1)}}}};return await n(e,1),e};il("klTransmissionManager"),il("ipcClient"),il("kemuWidgetService"),v(process.argv.slice(2));const Al=e=>u(`runner:${e}`),Ml=Al("connectionManager"),Pl=Al("remoteInvoke"),Dl=new function(e){const t={};let n,r=console.log;const i={};let o=e||String(Date.now());const s={},a=e=>!s[e],c=(e,t,n,r,i,o)=>{let s=Kc?new ArrayBuffer(0):Buffer.alloc(0);const c={json:{functionName:e,args:o.success?o.success:[o],messageId:t,type:o.success?"response":"error"}};return a(r)&&(s=ml.encode(c,n,r)),i(s,{msg:c,sourceServiceId:n,targetServiceId:r})};return{setLogger:e=>{r=e},processMessage:(e,o,s,a)=>{if(!a)return!1;const l=a;if(t[l.messageId]){const e=t[l.messageId];return e&&(clearTimeout(e.timer),e.fulfilled||(e.fulfilled=!0,"response"===l.type?e.resolve(l.args):"error"===l.type&&e.reject(l.args[0])),delete t[l.messageId]),!0}if("execute"!==l.type&&r&&r(`No pending execution found for message id "${l.messageId}"`),"execute"===l.type){const t=i[l.functionName];if(t){const i=e=>{c(l.functionName,l.messageId,s.targetServiceId,s.sourceServiceId,o,e)};if(!(!n||n({args:l.args,functionName:l.functionName,transport:e,messageId:l.messageId,sourceServiceId:s.sourceServiceId,reply:i,send:o})))return r&&r(`Function "${l.functionName}" not allowed to be invoked by client [${s.sourceServiceId}]`),i({error:"Function not allowed",errCode:"FNC_NOT_ALLOWED"}),!0;t({transport:e,args:l.args,reply:i,messageId:l.messageId,sourceServiceId:s.sourceServiceId,send:o})}else{const e=`Function "${l.functionName}" not found.`;r&&r(e),c(l.functionName,l.messageId,s.targetServiceId,s.sourceServiceId,o,{error:e,errCode:"FNC_NOT_FOUND"})}return!0}return!1},execute:async(e,n,i,s,c,l)=>{if(!i){const e="No send buffer function provided.";throw r&&r(e),e}yl+=1;const u=`${o}-${yl}-exec-${e.substring(0,10)}`,d={messageId:u,functionName:e,send:i,sourceServiceId:s,targetServiceId:c,args:n||[],fulfilled:!1,resolve:()=>{},reject:()=>{}};d.promise=new Promise(((e,t)=>{d.resolve=e,d.reject=t}));let h=Kc?new ArrayBuffer(0):Buffer.alloc(0);const f={json:{functionName:e,args:n,messageId:u,type:"execute"}};a(c)&&(h=ml.encode(f,s,c)),t[u]=d,r&&r(`Calling remote function "${e}" with message id "${u}"`);const p="true"===process.env.NO_INVOKE_TIMEOUT;return l?.async?(d.fulfilled=!0,d.resolve([void 0]),delete t[u]):0===l?.timeout||p||(d.timer=setTimeout((()=>{r&&r(`Remote function ${u} timed out`);const n=t[u];n&&!n.fulfilled&&(n.fulfilled=!0,d.reject(`Function ${e} Timed out`)),delete t[u]}),l?.timeout||3e4)),i(h,{sourceServiceId:s,targetServiceId:c,msg:f}),d.promise},sendResponse:c,registerFunction:(e,t)=>{i[e]=t},registerFunctionsMiddleware:e=>{n=e},unregisterAllFunctions:()=>{Object.keys(i).forEach((e=>{delete i[e]}))},getTransportSendFunction:e=>{const n=t[e];return n?n.send:null},setServiceName:e=>{o=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,n,i)=>{yl+=1;const s=`${o}-${yl}-multicast-${e.substring(0,10)}`;let c=Kc?new ArrayBuffer(0):Buffer.alloc(0);const l={json:{functionName:e,args:t,messageId:s,type:"execute"}};let u=a(n[0].serviceId);u&&(c=ml.encode(l,i,n[0].serviceId));for(let t=0;t<n.length;t++)try{const o=n[t];r&&r(`Broadcasting function "${e}" with message id "${s}" to client [${o.serviceId}]`),0!==t&&(u=a(o.serviceId),u&&(c=ml.patchEncodedHeader(c,{toServiceId:o.serviceId}))),o.sendFn(c,{msg:l,sourceServiceId:i,targetServiceId:o.serviceId})}catch(e){r&&r(`Error broadcasting to client at index ${t}`)}},disableServiceEncoding:(e,t)=>{s[e]=t}}}("kweb");Dl.setLogger(Pl);const jl=new a,Rl=new a;let Ll,Fl=null,Ul=null,Bl=null,Wl=null;const Gl={},Vl=(e,t,n)=>{const r=`${e}_${t}`,i={contents:n,lastRequestedAt:Date.now(),contentsChecksum:""};return Gl[r]=i,i},Yl=(e,t)=>Gl[`${e}_${t}`]||null,Hl=async(e,t)=>{if(!Fl)return Ml("Hub Link has not been acknowledged. Cannot get services."),null;const n=[{serviceName:e,version:t}];return(await Dl.execute(ve.GetServiceContents,n,Kl,Fl,0))[0]},zl=new Map,ql=async(e,t,n=!1)=>{if(!e||!t)return null;const r=`${e}:${t}`;if(!n){const e=zl.get(r);if(e)return e}const i=Yl(e,t);if(!i||n){const n=i||Vl(e,t),o=(async()=>{try{const r=await Hl(e,t);return r&&(n.contents=r.uiContent,n.contentsChecksum=r.uiContentsChecksum||""),n.contents||null}catch(n){return Ml(`Failed to fetch service contents for ${e} v${t}`,n),null}finally{zl.delete(r)}})();return zl.set(r,o),o}return i?.contents||null},Kl=El,Jl=()=>{Ml("Disconnected from the server"),Fl=null,Bl=null,Dl.rejectAllPending("Disconnected from the server"),jl.emit("disconnected")},Zl=()=>{Ml("Connected to the server"),jl.emit("connected")},Xl=()=>Ul,Ql=(e,t,n,r)=>`${e}_${t}_${n}_${r}`,eu=async()=>{const e=Xl();if(e){const t=ie(e)?.blocks;if(t){const n={};for(const r in t){const i=t[r];for(const t in i.gates){const r=i.gates[t];if(r.type===ze.hubService){const t=r.state;if(t.service?.eventEmitter){const r=`${t.service.name}_${t.service.version}`;if(!n[r])try{Ml(`Re-issuing subscription for service ${t.service.name} (${t.service.version})`),n[r]=!0,await Iu({listener:{recipeId:e},targetService:{serviceName:t.service.name,version:t.service.version}})}catch(e){Ml(`Failed to re-issue subscription for service ${t.service.name} (${t.service.version})`,e)}}}}}}}},tu=async()=>{Ll=void 0;const e=await mu();jl.emit("services-changed",e)},nu=async()=>(Ml("Services list changed"),tu()),ru=async e=>{if(!e)return void Ml("Hub sent ACK request without service id");const t=Xl();if(!t)return void Ml("Hub sent ACK request without recipe pool id");if(!ie(t))throw new Error("Hub sent ACK request without recipe");const n=Wl?{...Wl}:null,r={recipe:le(t),user:n,ackSessionId:e};await Dl.execute(ve.SocketAckResponse,[r],Kl,e,0),Ml("Hub Link acknowledged"),Fl=e,jl.emit("acknowledged"),await Au(),eu()},iu=async()=>{await kl()},ou=async e=>{const t=e.args[0],{widgetId:n,recipePoolId:r,waitForResponse:i}=t;return e.reply({success:[`message received by recipe ok target widget "${n}", recipe pool id "${r}", waitForResponse "${i}"`]})},su=async e=>{const t=e.args[0],n=Ql("broadcast",`hub_${t.type}`,(0).toString(),"");await Rl.emit(n,t)},au=async e=>{const t=e.args[0],n=Xl(),r=t.targetRecipePoolId||t.targetRecipeId;if(!r||r===n){for(const e of t.outputs||[])e.type===pe.ImageData&&De(e.value)&&(e.value=await Ge(e.value));if(n){const r=ie(n);if(r){const i=async e=>{const n=Ql("broadcast",t.source.serviceName,t.source.serviceVersion,e);try{await Rl.emit(n,t)}catch(t){Ml(`Failed to emit broadcast event for target ${e}`,t)}};await i("app");for(const o in r.blocks){const s=r.blocks[o];for(const r in s.gates){const o=s.gates[r];if(o.disabled)continue;if(t.targetWidgetId&&t.targetWidgetId!==r)continue;const a=o.state;if(o.type!==ze.script){if(o.type===ze.hubService&&a.service?.name===t.source.serviceName&&a.service?.version===t.source.serviceVersion&&a.variantId===t.variantId){await i(r);for(const i of t.outputs||[])if(null!==i.value&&void 0!==i.value){const o={type:i.type,value:i.value,timestamp:Date.now()};Ml(`Sending data to output ${i.name} requested by messageId ${e.messageId}`),await Vc({recipePoolId:n,currentGateId:r,sourcePortName:i.name,originalEvent:o,data:o,eventContext:t.eventContext,currentPath:t.currentPath||[],eventId:t.eventId||null})}}}else await i(r)}}}}}},cu=async e=>{const t=e.args[0],{finalState:n,recipeId:r,widgetId:i}=t,o=Gc(r,i);let s=o;if(n&&s&&o&&(s={...o,customState:n},Wc(r,i,s,!0)),s?.service)try{const e=Ql("setOutputs",s.service.name,s.service.version,i);await Rl.emit(e,t.outputs)}catch(e){Ml(`Failed to emit setOutputs event for widget ${i}`,e)}let a=null;for(const n of t.outputs)if(null!==n.value&&void 0!==n.value){if(n.type===pe.ImageData){if(!De(n.value)){Ml(`Invalid ImageData value received for output ${n.name}. Expected an ImageData-like object`);continue}n.value=await Ge(n.value)}else n.type!==pe.JsonObj&&n.type!==pe.Array||await Tl(n.value);const o={type:n.type,value:n.value,timestamp:Date.now()};Ml(`Sending data to output ${n.name} requested by messageId ${e.messageId}`);try{await Vc({recipePoolId:r,currentGateId:i,sourcePortName:n.name,originalEvent:o,data:o,eventContext:t.eventContext,currentPath:t.currentPath||[],eventId:t.eventId||null})}catch(e){Ml(`Failed to trigger next global widget for output ${n.name}`,e),a=e;break}}if(a){const t=a instanceof jr,n=a;e.reply({error:a.message,errCode:t?"CHILD_WIDGET_ERROR":"INVOKING_ERROR",errData:{targetWidgetId:n.targetWidgetId,targetPortName:n.targetPortName,sourcePortName:n.sourcePortName,sourceWidgetId:n.sourceWidgetId,targetWidgetType:n.targetWidgetType,sourceWidgetType:n.sourceWidgetType}})}else e.reply({success:[]})},lu=async e=>{const t=e.args[0],{newState:n,recipeId:r,widgetId:i}=t,o=Gc(r,i);if(o){const t={...o,customState:{...o.customState,...n}};return Wc(r,i,t,!0),e.reply({success:[]})}},uu=async({args:e,reply:t})=>{const n=e[0],{recipeId:r,widgetId:i,path:o,key:s}=n;Ml(`Received request to set a dependency path for "${s}" on widget "${i}" in recipe "${r}"`);const a=Gc(r,i);if(a){const e={...a};e.dependencies=e.dependencies||{},e.dependencies[s]={path:o},Wc(r,i,e,!0)}return t({success:[]})},du=async({args:e,reply:t})=>{const n=e[0],{recipeId:r,widgetId:i,key:o}=n;Ml(`Received request to get a dependency path for "${o}" on widget "${i}" in recipe "${r}"`);const s=Gc(r,i);if(s){const e=s.dependencies?.[o]?.path;return Ml(`Returning dependency path for "${o}" on widget "${i}": "${e}"`),t({success:[e||null]})}return t({error:"Widget not found",errCode:"WIDGET_NOT_FOUND"})},hu=async({args:e,reply:t})=>{const n=e[0];if(!n.expressions)return t({error:"Expression is required",errCode:"EXPRESSION_REQUIRED"});const r=se({recipeId:n.recipePoolId,widgetId:n.widgetId});if(!r)return t({error:"Widget not found",errCode:"WIDGET_NOT_FOUND"});if(r.type!==ze.hubService)return t({error:"Widget is not a hub service",errCode:"WIDGET_NOT_A_HUB_SERVICE"});const i=r.state,{uuid:o}=(e=>{const t=ie(e);if(!t)throw new Error(`Recipe [${e} does not exist]`);return{uuid:t.uuid,recipeType:t.dbInfo?.recipeType}})(n.recipePoolId);return t({success:[{expressions:await Promise.all(n.expressions.map((async e=>await Ms({template:e.text,context:e.context||{},options:{enableFnTag:!1,recipeUuid:o,serviceName:i.service?.name,securityOptions:{restrictionLevel:"strict"}}}))))}]})},fu=async({args:e,reply:t})=>{const n=e[0],r=ao.getAllVariables().filter((e=>!n.filterTypes||n.filterTypes.includes(e.controlType))).map((e=>({name:e.name,type:e.controlType})));return t({success:[{variables:r}]})},pu=async({args:e,reply:t})=>{const n=e[0];if(!n.names||0===n.names.length)return t({error:"Variable names are required",errCode:"VARIABLE_NAMES_REQUIRED"});const r=ao.getAllVariables().filter((e=>n.names.includes(e.name))).map((e=>({name:e.name,value:e.lastValue})));return t({success:[{values:r}]})},gu=async({args:e,reply:t})=>{const n=e[0];if(!n.values||0===n.values.length)return t({error:"Variable values are required",errCode:"VARIABLE_VALUES_REQUIRED"});try{const{values:e}=n;for(const t of e)await ao.setGlobalVariable({name:t.name,value:t.value});return t({success:[]})}catch(e){return Ml(`Failed to set global variable values: ${e}`),t({error:"Failed to set some of the global variable values",errCode:"FAILED_TO_SET_GLOBAL_VARIABLE_VALUES",errData:e.message})}},mu=async()=>{if(Ml(`Requesting services on ${(new Date).toISOString()}`),!Fl)return Ml("Hub Link has not been acknowledged. Cannot get services."),{available:[],installed:[],failed:[]};const[e]=await Dl.execute(ve.GetServices,[],Kl,Fl,0);Ll=e;for(const t of e.available){if(t.internal)continue;const e=Yl(t.name,t.version);if(!e||e?.contentsChecksum!==t.uiContentChecksum)try{const n=e||Vl(t.name,t.version);Ml(`Service ${t.name} v${t.version} contents have changed, fetching new contents`);const r=await Hl(t.name,t.version);r&&(n.contents=r.uiContent,n.contentsChecksum=t.uiContentChecksum||"")}catch(e){Ml(`Failed to update service contents for ${t.name} v${t.version}`,e)}}return e},yu=()=>Ll||{available:[],installed:[],failed:[]},vu=()=>!!Ll,bu=async e=>{const{targetServiceSessionId:t}=e;if(!Fl)return void Ml("No target service session id provided");Ml(`Forwarding "onParentEvent" to service ${t}`);const n=await Dl.execute(ve.OnParentEvent,[e],Kl,Fl,t,e.config).catch((e=>{throw Ml(`Error invoking onParentEvent callback: ${e}`),e.errCode===gl.ParentEventCallbackError?e.error:e}));return n},wu=async e=>{if(!Fl)return Ml("Hub Link has not been acknowledged. Cannot get services."),{};const[t]=await Dl.execute(ve.GetDefaultState,[],Kl,Fl,e);return t},Su=async(e,t,n,r,i)=>{if(!Fl)return Ml("Hub Link has not been acknowledged. Cannot get services."),null;const[o]=await Dl.execute(ve.UIEvent,[t,n,r],Kl,Fl,e,i);return o},_u=(e,t)=>{const n=(...e)=>{t(...e)};return jl.on(e,n),()=>jl.off(e,n)},Iu=async e=>{if(Fl)return Dl.execute(ve.SubscribeToService,[e],Kl,Fl,0);Ml("Hub Link has not been acknowledged. Cannot subscribe to services.")},xu=async e=>{if(Fl)return Dl.execute(ve.UnsubscribeFromService,[e],Kl,Fl,0);Ml("Hub Link has not been acknowledged. Cannot subscribe to services.")},ku=(e,t,n,r)=>{const i=Ql("broadcast",t,n,e);return Rl.on(i,r)},Eu=(e,t,n,r)=>{const i=Ql("setOutputs",t,n,e);return Rl.on(i,r)},Cu=async(e,t,n)=>Fl?Dl.execute(e,t,Kl,Fl,0,n):(Ml("Hub Link has not been acknowledged. Cannot execute function."),null),$u=async e=>{if(!Fl)return void Ml("Hub Link has not been acknowledged. Cannot execute function.");const t=Gc(e.recipePoolId,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)),{});if(!ie(e.recipePoolId))throw new Error("Recipe not found. Cannot initialize service instance.");const r=[{currentState:t.customState,recipeId:e.recipePoolId,recipe:le(e.recipePoolId),widgetId:e.widgetId,variantId:e.variantId,recipeType:e.recipeType,recipeName:e.recipeName,currentDependencies:n}],[i,o,s]=await Dl.execute(ve.InitializeInstance,r,Kl,Fl,e.sessionId);if(o&&o.length>0){const n=o.filter((e=>e.name&&e.name.length>0)).map((e=>({...e,hubServiceName:t.service?.name})));Hc({clearExistingSecrets:!0,recipePoolId:e.recipePoolId,widgetId:e.widgetId,secrets:n})}if(s&&s.length>0&&await Promise.all(s.map((async t=>{await ao.setGlobalVariable({name:t.name,value:t.value,controlType:t.controlType,controlSettings:t.controlSettings,helpText:t.helpText,order:t.order,disableChangeNotifications:!1===t.emitChangeEvent,disableDefineNotifications:!1===t.emitDefineEvent,doNotOverrideExisting:t.doNotOverrideExisting??!1,widgetId:e.widgetId})}))),i){const t=Gc(e.recipePoolId,e.widgetId);if(t){const n={...t,customState:i};Wc(e.recipePoolId,e.widgetId,n,!0)}}},Ou=async(e,t,n,r)=>{if(!Fl)return void Ml("Hub Link has not been acknowledged. Cannot execute function.");const i=Gc(n,t);if(!i)throw new Error("Widget or recipe pool not found. Cannot initialize service instance.");const o=ie(n);if(!o)throw new Error("Recipe not found. Cannot terminate service instance.");const s=[{currentState:i.customState,recipeId:n,recipe:{poolId:n,uuid:o.uuid,name:o.name,type:o.dbInfo.recipeType,dbId:o.dbInfo.id,version:o.dbInfo.version,authorId:o.dbInfo.authorId},widgetId:t,variantId:r}];await Dl.execute(ve.TerminateInstance,s,Kl,Fl,e)},Nu=async(e,t,n="^",r)=>{const i=["^","~",">=",">","<=","<","="];if(!i.includes(n))throw new Error(`Invalid compare mode "${n}". Must be one of ${i.join(", ")}`);const o=vu(),s=r||!o?await mu():yu();for(const r of s.available)if(r.name===e){if(r.version===t)return r;if(l(r.version,`${n}${t}`))return r}return null},Tu=async(e=!1)=>{if(!Fl)return Ml("Hub Link has not been acknowledged. Cannot get services."),null;if(Bl&&!e)return Bl;const[t]=await Dl.execute(ve.GetSystemInfo,[],Kl,Fl,0).catch((e=>(Ml("Failed to get system info",e),[null])));return Bl=t,t},Au=async()=>{Bl=await Tu()};var Mu,Pu,Du,ju,Ru,Lu,Fu,Uu,Bu=async e=>{Wl=e,Ol(Zl),Nl(Jl),$l((({json:e,transmission:t})=>{Dl.processMessage("websocket",Kl,t,e)})),await iu(),Dl.unregisterAllFunctions(),Dl.registerFunction(ve.SetState,lu),Dl.registerFunction(ve.SetOutputs,cu),Dl.registerFunction(ve.BroadcastEvent,au),Dl.registerFunction(ve.HubBroadcastEvent,su),Dl.registerFunction(ve.SendToRecipe,ou),Dl.registerFunction(be.SetDependencyPath,uu),Dl.registerFunction(be.GetDependencyPath,du),Dl.registerFunction(be.ParseStringExpression,hu),Dl.registerFunction(be.GetGlobalVariableNames,fu),Dl.registerFunction(be.GetGlobalVariableValues,pu),Dl.registerFunction(be.SetGlobalVariableValues,gu),Cl((e=>{((e,t)=>{const n=ye.SocketAcknowledge,r=ye.IpcAcknowledge,i=e.startsWith(n);if(e===r)return t&&t(),0;if(i){const o=e.split(i?n:r),s=parseInt(o[1]);return t&&t(s),s}})(e,ru),((e,t)=>{e===ye.ServicesListChanged&&(t&&t())})(e,nu)})),await xl()},Wu=(e,t)=>{jl.on(e,t)},Gu=()=>({getServices:mu,getServiceContents:ql,onParentEvent:bu,onCommand:_u,getDefaultState:wu,getCachedServices:yu,areServicesCached:vu,subscribeToServiceEvents:Iu,unsubscribeFromServiceEvents:xu,callProcessorHandler:Su,onBroadcastEvent:ku,onSetOutputsEvent:Eu,executeHubFunction:Cu,initializeServiceInstance:$u,terminateServiceInstance:Ou,getCompatibleService:Nu,getHubSystemInfo:Tu}),Vu=e=>{Ul=e},Yu=()=>Dl;!function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(Mu||(Mu={})),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"}(Pu||(Pu={})),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"}(Du||(Du={})),function(e){e.Javascript="js",e.Python="py",e.Executable="exe"}(ju||(ju={})),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:"}(Ru||(Ru={})),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.AddServiceSecret="addServiceSecret",e.OnParentEvent="onParentEvent",e.GetDefaultState="getDefaultState",e.BroadcastEvent="broadcastEvent",e.HubBroadcastEvent="hubBroadcastEvent",e.ServiceManifest="serviceManifest",e.SendToRecipe="sendToRecipe",e.KemuComposerDisconnected="kemu-composer-disconnected",e.GetState="getState",e.SetState="setState",e.SetOutputs="setOutputs",e.UIEvent="uiEvent",e.GetSystemInfo="getSystemInfo",e.InitializeInstance="initializeInstance",e.TerminateInstance="terminateInstance",e.UninstallService="uninstallService",e.ChooseDirectoryDialog="chooseDirectoryDialog",e.ChooseFileDialog="chooseFileDialog",e.SaveRecipeToFile="saveRecipeToFile",e.GetUniqueId="getUniqueId",e.RebootToInstallUpdate="rebootToInstallUpdate",e.GetFileContentFromCacheId="getFileContentFromCacheId",e.GetDecryptedEdgeApiKey="getDecryptedEdgeApiKey",e.GetHubConfig="getHubConfig",e.GetRecipeDecryptedSecretsValues="getRecipeDecryptedSecretsValues",e.GetRecipeSecretMappings="getRecipeSecretMappings",e.AddRecipeSecretMapping="addRecipeSecretMapping",e.DeleteRecipeSecretMapping="deleteRecipeSecretMapping",e.GetHubSecrets="getHubSecrets",e.AddHubSecrets="addHubSecrets",e.DeleteHubSecret="deleteHubSecret"}(Lu||(Lu={})),function(e){e.SetDependencyPath="setDependencyPath",e.GetDependencyPath="getDependencyPath"}(Fu||(Fu={})),function(e){e.IPC="ipc",e.WS="ws"}(Uu||(Uu={}));const Hu=e=>{try{return JSON.parse(e)}catch(e){return null}},zu=()=>{const e=(()=>{switch(process.arch){case"x64":return"x64";case"ia32":return"x86";case"arm":return"arm";case"arm64":return"arm64";default:return""}})();if(!e)throw new Error(`Unsupported architecture: ${process.arch}`);switch(process.platform){case"win32":return`win-${e}`;case"darwin":return`osx-${e}`;case"linux":{let t="generic";try{const e=I.readFileSync("/etc/os-release","utf-8").split("\n").reduce(((e,t)=>{const[n,...r]=t.split("=");if(n&&r.length>0){let t=r.join("=").trim();t.startsWith('"')&&t.endsWith('"')&&(t=t.substring(1,t.length-1)),e[n.trim()]=t}return e}),{}),n=e.ID,r=e.ID_LIKE?.split(/\s+/)||[];"debian"===n||r.includes("debian")?t="debian":"rhel"===n||"fedora"===n||"centos"===n||r.includes("rhel")||r.includes("fedora")?t="rhel":("arch"===n||r.includes("arch"))&&(t="arch")}catch(e){}return`linux-${t}-${e}`}default:throw new Error(`Unsupported platform: ${process.platform}`)}},qu=/^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i,Ku=e=>{if("string"!=typeof e)throw new TypeError("Invalid argument expected string");const t=e.match(qu);if(!t)throw new Error(`Invalid argument not valid semver ('${e}' received)`);return t.shift(),t},Ju=e=>"*"===e||"x"===e||"X"===e,Zu=e=>{const t=parseInt(e,10);return isNaN(t)?e:t},Xu=(e,t)=>{if(Ju(e)||Ju(t))return 0;const[n,r]=((e,t)=>typeof e!=typeof t?[String(e),String(t)]:[e,t])(Zu(e),Zu(t));return n>r?1:n<r?-1:0},Qu=(e,t)=>{for(let n=0;n<Math.max(e.length,t.length);n++){const r=Xu(e[n]||"0",t[n]||"0");if(0!==r)return r}return 0},ed=(e,t,n)=>{rd(n);const r=((e,t)=>{const n=Ku(e),r=Ku(t),i=n.pop(),o=r.pop(),s=Qu(n,r);return 0!==s?s:i&&o?Qu(i.split("."),o.split(".")):i||o?i?-1:1:0})(e,t);return td[n].includes(r)},td={">":[1],">=":[0,1],"=":[0],"<=":[-1,0],"<":[-1],"!=":[-1,1]},nd=Object.keys(td),rd=e=>{if(-1===nd.indexOf(e))throw new Error(`Invalid operator, expected one of ${nd.join("|")}`)};var id="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function od(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var sd,ad,cd,ld,ud,dd={exports:{}},hd={exports:{}};function fd(){if(ad)return sd;ad=1;var e=1e3,t=60*e,n=60*t,r=24*n,i=7*r;function o(e,t,n,r){var i=t>=1.5*n;return Math.round(e/n)+" "+r+(i?"s":"")}return sd=function(s,a){a=a||{};var c=typeof s;if("string"===c&&s.length>0)return function(o){if(!((o=String(o)).length>100)){var s=/^(-?(?:\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(s){var a=parseFloat(s[1]);switch((s[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*a;case"weeks":case"week":case"w":return a*i;case"days":case"day":case"d":return a*r;case"hours":case"hour":case"hrs":case"hr":case"h":return a*n;case"minutes":case"minute":case"mins":case"min":case"m":return a*t;case"seconds":case"second":case"secs":case"sec":case"s":return a*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return a;default:return}}}}(s);if("number"===c&&isFinite(s))return a.long?function(i){var s=Math.abs(i);return s>=r?o(i,s,r,"day"):s>=n?o(i,s,n,"hour"):s>=t?o(i,s,t,"minute"):s>=e?o(i,s,e,"second"):i+" ms"}(s):function(i){var o=Math.abs(i);return o>=r?Math.round(i/r)+"d":o>=n?Math.round(i/n)+"h":o>=t?Math.round(i/t)+"m":o>=e?Math.round(i/e)+"s":i+"ms"}(s);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(s))}}function pd(){return ld||(ld=1,cd=function(e){function t(e){let r,i,o,s=null;function a(...e){if(!a.enabled)return;const n=a,i=Number(new Date),o=i-(r||i);n.diff=o,n.prev=r,n.curr=i,r=i,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let s=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((r,i)=>{if("%%"===r)return"%";s++;const o=t.formatters[i];if("function"==typeof o){const t=e[s];r=o.call(n,t),e.splice(s,1),s--}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!==s?s:(i!==t.namespaces&&(i=t.namespaces,o=t.enabled(e)),o),set:e=>{s=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){return e instanceof Error?e.stack||e.message:e},t.disable=function(){const e=[...t.names.map(r),...t.skips.map(r).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let n;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const r=("string"==typeof e?e:"").split(/[\s,]+/),i=r.length;for(n=0;n<i;n++)r[n]&&("-"===(e=r[n].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.slice(1)+"$")):t.names.push(new RegExp("^"+e+"$")))},t.enabled=function(e){if("*"===e[e.length-1])return!0;let n,r;for(n=0,r=t.skips.length;n<r;n++)if(t.skips[n].test(e))return!1;for(n=0,r=t.names.length;n<r;n++)if(t.names[n].test(e))return!0;return!1},t.humanize=fd(),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}),cd}var gd,md,yd,vd,bd,wd={exports:{}};"undefined"==typeof process||"renderer"===process.type||!0===process.browser||process.__nwjs?dd.exports=(ud||(ud=1,function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const n="color: "+this.color;t.splice(1,0,n,"color: inherit");let r=0,i=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(r++,"%c"===e&&(i=r))})),t.splice(i,0,n)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")}catch(e){}return!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG),e},t.useColors=function(){return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type&&!window.process.__nwjs)||("undefined"==typeof navigator||!navigator.userAgent||!navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=pd()(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(hd,hd.exports)),hd.exports):dd.exports=(bd||(bd=1,function(e,t){const n=k,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:i}=this;if(i){const t=this.color,i="[3"+(t<8?t:"8;5;"+t),o=` ${i};1m${r} `;n[0]=o+n[0].split("\n").join("\n"+o),n.push(i+"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(vd)return yd;vd=1;const e=E,t=k,n=md?gd:(md=1,gd=(e,t=process.argv)=>{const n=e.startsWith("-")?"":1===e.length?"-":"--",r=t.indexOf(n+e),i=t.indexOf("--");return-1!==r&&(-1===i||r<i)}),{env:r}=process;let i;function o(e){return 0!==e&&{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function s(t,o){if(0===i)return 0;if(n("color=16m")||n("color=full")||n("color=truecolor"))return 3;if(n("color=256"))return 2;if(t&&!o&&void 0===i)return 0;const s=i||0;if("dumb"===r.TERM)return s;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:s;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:s}return n("no-color")||n("no-colors")||n("color=false")||n("color=never")?i=0:(n("color")||n("colors")||n("color=true")||n("color=always"))&&(i=1),"FORCE_COLOR"in r&&(i="true"===r.FORCE_COLOR?1:"false"===r.FORCE_COLOR?0:0===r.FORCE_COLOR.length?1:Math.min(parseInt(r.FORCE_COLOR,10),3)),yd={supportsColor:function(e){return o(s(e,e&&e.isTTY))},stdout:o(s(!0,t.isatty(1))),stderr:o(s(!0,t.isatty(2)))},yd}();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=pd()(t);const{formatters:o}=e.exports;o.o=function(e){return this.inspectOpts.colors=this.useColors,r.inspect(e,this.inspectOpts).split("\n").map((e=>e.trim())).join(" ")},o.O=function(e){return this.inspectOpts.colors=this.useColors,r.inspect(e,this.inspectOpts)}}(wd,wd.exports)),wd.exports);var Sd=od(dd.exports);const _d=e=>Sd(e);var Id={},xd={};class kd extends Error{constructor(e){super(`Format functions must be synchronous taking a two arguments: (info, opts)\nFound: ${e.toString().split("\n")[0]}\n`),Error.captureStackTrace(this,kd)}}var Ed,Cd,$d,Od,Nd,Td=e=>{if(e.length>2)throw new kd(e);function t(e={}){this.options=e}function n(e){return new t(e)}return t.prototype.transform=e,n.Format=t,n},Ad={exports:{}},Md={exports:{}},Pd={exports:{}},Dd={exports:{}};function jd(){if(Nd)return Od;Nd=1;var e=E,t=$d?Cd:($d=1,Cd=function(e,t){var n=(t=t||process.argv||[]).indexOf("--"),r=/^-{1,2}/.test(e)?"":"--",i=t.indexOf(r+e);return-1!==i&&(-1===n||i<n)}),n=process.env,r=void 0;function i(i){var o=function(i){if(!1===r)return 0;if(t("color=16m")||t("color=full")||t("color=truecolor"))return 3;if(t("color=256"))return 2;if(i&&!i.isTTY&&!0!==r)return 0;var o=r?1:0;if("win32"===process.platform){var s=e.release().split(".");return Number(process.versions.node.split(".")[0])>=8&&Number(s[0])>=10&&Number(s[2])>=10586?Number(s[2])>=14931?3:2:1}if("CI"in n)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI"].some((function(e){return e in n}))||"codeship"===n.CI_NAME?1:o;if("TEAMCITY_VERSION"in n)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(n.TEAMCITY_VERSION)?1:0;if("TERM_PROGRAM"in n){var a=parseInt((n.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(n.TERM_PROGRAM){case"iTerm.app":return a>=3?3:2;case"Hyper":return 3;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(n.TERM)?2:/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(n.TERM)||"COLORTERM"in n?1:(n.TERM,o)}(i);return function(e){return 0!==e&&{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}(o)}return t("no-color")||t("no-colors")||t("color=false")?r=!1:(t("color")||t("colors")||t("color=true")||t("color=always"))&&(r=!0),"FORCE_COLOR"in n&&(r=0===n.FORCE_COLOR.length||0!==parseInt(n.FORCE_COLOR,10)),Od={supportsColor:i,stdout:i(process.stdout),stderr:i(process.stderr)}}var Rd,Ld,Fd,Ud,Bd,Wd,Gd,Vd,Yd={exports:{}},Hd={exports:{}},zd={exports:{}},qd={exports:{}},Kd={exports:{}},Jd={exports:{}};function Zd(){return Gd||(Gd=1,function(){var e={};Pd.exports=e,e.themes={};var t=i,n=e.styles=(Ed||(Ed=1,function(){var e={};Dd.exports=e;var t={reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29],black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],gray:[90,39],grey:[90,39],brightRed:[91,39],brightGreen:[92,39],brightYellow:[93,39],brightBlue:[94,39],brightMagenta:[95,39],brightCyan:[96,39],brightWhite:[97,39],bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgGray:[100,49],bgGrey:[100,49],bgBrightRed:[101,49],bgBrightGreen:[102,49],bgBrightYellow:[103,49],bgBrightBlue:[104,49],bgBrightMagenta:[105,49],bgBrightCyan:[106,49],bgBrightWhite:[107,49],blackBG:[40,49],redBG:[41,49],greenBG:[42,49],yellowBG:[43,49],blueBG:[44,49],magentaBG:[45,49],cyanBG:[46,49],whiteBG:[47,49]};Object.keys(t).forEach((function(n){var r=t[n],i=e[n]=[];i.open="["+r[0]+"m",i.close="["+r[1]+"m"}))}()),Dd.exports),r=Object.defineProperties,o=new RegExp(/[\r\n]+/g);e.supportsColor=jd().supportsColor,void 0===e.enabled&&(e.enabled=!1!==e.supportsColor()),e.enable=function(){e.enabled=!0},e.disable=function(){e.enabled=!1},e.stripColors=e.strip=function(e){return(""+e).replace(/\x1B\[\d+m/g,"")},e.stylize=function(t,r){if(!e.enabled)return t+"";var i=n[r];return!i&&r in e?e[r](t):i.open+t+i.close};var s=/[|\\{}()[\]^$+*?.]/g;function a(e){var t=function e(){return d.apply(e,arguments)};return t._styles=e,t.__proto__=u,t}var c,l=(c={},n.grey=n.gray,Object.keys(n).forEach((function(e){n[e].closeRe=new RegExp(function(e){if("string"!=typeof e)throw new TypeError("Expected a string");return e.replace(s,"\\$&")}(n[e].close),"g"),c[e]={get:function(){return a(this._styles.concat(e))}}})),c),u=r((function(){}),l);function d(){var r=Array.prototype.slice.call(arguments).map((function(e){return null!=e&&e.constructor===String?e:t.inspect(e)})).join(" ");if(!e.enabled||!r)return r;for(var i=-1!=r.indexOf("\n"),s=this._styles,a=s.length;a--;){var c=n[s[a]];r=c.open+r.replace(c.closeRe,c.open)+c.close,i&&(r=r.replace(o,(function(e){return c.close+e+c.open})))}return r}e.setTheme=function(t){if("string"!=typeof t)for(var n in t)!function(n){e[n]=function(r){if("object"==typeof t[n]){var i=r;for(var o in t[n])i=e[t[n][o]](i);return i}return e[t[n]](r)}}(n);else console.log("colors.setTheme now only accepts an object, not a string. If you are trying to set a theme from a file, it is now your (the caller's) responsibility to require the file. The old syntax looked like colors.setTheme(__dirname + '/../themes/generic-logging.js'); The new syntax looks like colors.setTheme(require(__dirname + '/../themes/generic-logging.js'));")};var h=function(e,t){var n=t.split("");return(n=n.map(e)).join("")};for(var f in e.trap=(Rd||(Rd=1,Yd.exports=function(e){var t="";e=(e=e||"Run the trap, drop the bass").split("");var n={a:["@","Ą","Ⱥ","Ʌ","Δ","Λ","Д"],b:["ß","Ɓ","Ƀ","ɮ","β","฿"],c:["©","Ȼ","Ͼ"],d:["Ð","Ɗ","Ԁ","ԁ","Ԃ","ԃ"],e:["Ë","ĕ","Ǝ","ɘ","Σ","ξ","Ҽ","੬"],f:["Ӻ"],g:["ɢ"],h:["Ħ","ƕ","Ң","Һ","Ӈ","Ԋ"],i:["༏"],j:["Ĵ"],k:["ĸ","Ҡ","Ӄ","Ԟ"],l:["Ĺ"],m:["ʍ","Ӎ","ӎ","Ԡ","ԡ","൩"],n:["Ñ","ŋ","Ɲ","Ͷ","Π","Ҋ"],o:["Ø","õ","ø","Ǿ","ʘ","Ѻ","ם","۝","๏"],p:["Ƿ","Ҏ"],q:["্"],r:["®","Ʀ","Ȑ","Ɍ","ʀ","Я"],s:["§","Ϟ","ϟ","Ϩ"],t:["Ł","Ŧ","ͳ"],u:["Ʊ","Ս"],v:["ט"],w:["Ш","Ѡ","Ѽ","൰"],x:["Ҳ","Ӿ","Ӽ","ӽ"],y:["¥","Ұ","Ӌ"],z:["Ƶ","ɀ"]};return e.forEach((function(e){e=e.toLowerCase();var r=n[e]||[" "],i=Math.floor(Math.random()*r.length);t+=void 0!==n[e]?n[e][i]:e})),t}),Yd.exports),e.zalgo=(Ld||(Ld=1,Hd.exports=function(e,t){e=e||" he is here ";var n={up:["̍","̎","̄","̅","̿","̑","̆","̐","͒","͗","͑","̇","̈","̊","͂","̓","̈","͊","͋","͌","̃","̂","̌","͐","̀","́","̋","̏","̒","̓","̔","̽","̉","ͣ","ͤ","ͥ","ͦ","ͧ","ͨ","ͩ","ͪ","ͫ","ͬ","ͭ","ͮ","ͯ","̾","͛","͆","̚"],down:["̖","̗","̘","̙","̜","̝","̞","̟","̠","̤","̥","̦","̩","̪","̫","̬","̭","̮","̯","̰","̱","̲","̳","̹","̺","̻","̼","ͅ","͇","͈","͉","͍","͎","͓","͔","͕","͖","͙","͚","̣"],mid:["̕","̛","̀","́","͘","̡","̢","̧","̨","̴","̵","̶","͜","͝","͞","͟","͠","͢","̸","̷","͡"," ҉"]},r=[].concat(n.up,n.down,n.mid);function i(e){return Math.floor(Math.random()*e)}function o(e){var t=!1;return r.filter((function(n){t=n===e})),t}return function(e,t){var r,s,a="";for(s in(t=t||{}).up=void 0===t.up||t.up,t.mid=void 0===t.mid||t.mid,t.down=void 0===t.down||t.down,t.size=void 0!==t.size?t.size:"maxi",e=e.split(""))if(!o(s)){switch(a+=e[s],r={up:0,down:0,mid:0},t.size){case"mini":r.up=i(8),r.mid=i(2),r.down=i(8);break;case"maxi":r.up=i(16)+3,r.mid=i(4)+1,r.down=i(64)+3;break;default:r.up=i(8)+1,r.mid=i(6)/2,r.down=i(8)+1}var c=["up","mid","down"];for(var l in c)for(var u=c[l],d=0;d<=r[u];d++)t[u]&&(a+=n[u][i(n[u].length)])}return a}(e,t)}),Hd.exports),e.maps={},e.maps.america=(Fd||(Fd=1,zd.exports=function(e){return function(t,n){if(" "===t)return t;switch(n%3){case 0:return e.red(t);case 1:return e.white(t);case 2:return e.blue(t)}}}),zd.exports)(e),e.maps.zebra=(Ud||(Ud=1,qd.exports=function(e){return function(t,n){return n%2==0?t:e.inverse(t)}}),qd.exports)(e),e.maps.rainbow=(Bd||(Bd=1,Kd.exports=function(e){var t=["red","yellow","green","blue","magenta"];return function(n,r){return" "===n?n:e[t[r++%t.length]](n)}}),Kd.exports)(e),e.maps.random=(Wd||(Wd=1,Jd.exports=function(e){var t=["underline","inverse","grey","yellow","red","green","blue","white","cyan","magenta","brightYellow","brightRed","brightGreen","brightBlue","brightWhite","brightCyan","brightMagenta"];return function(n){return" "===n?n:e[t[Math.round(Math.random()*(t.length-2))]](n)}}),Jd.exports)(e),e.maps)!function(t){e[t]=function(n){return h(e.maps[t],n)}}(f);r(e,function(){var e={};return Object.keys(l).forEach((function(t){e[t]={get:function(){return a([t])}}})),e}())}()),Pd.exports}function Xd(){return Vd||(Vd=1,function(e){var t=Zd();e.exports=t}(Md)),Md.exports}var Qd,eh,th={},nh={},rh={};function ih(){if(eh)return Ad.exports;eh=1;const e=Xd(),{LEVEL:t,MESSAGE:n}=th;e.enabled=!0;const r=/\s+/;class i{constructor(e={}){e.colors&&this.addColors(e.colors),this.options=e}static addColors(e){const t=Object.keys(e).reduce(((t,n)=>(t[n]=r.test(e[n])?e[n].split(r):e[n],t)),{});return i.allColors=Object.assign({},i.allColors||{},t),i.allColors}addColors(e){return i.addColors(e)}colorize(t,n,r){if(void 0===r&&(r=n),!Array.isArray(i.allColors[t]))return e[i.allColors[t]](r);for(let n=0,o=i.allColors[t].length;n<o;n++)r=e[i.allColors[t][n]](r);return r}transform(e,r){return r.all&&"string"==typeof e[n]&&(e[n]=this.colorize(e[t],e.level,e[n])),(r.level||r.all||!r.message)&&(e.level=this.colorize(e[t],e.level)),(r.all||r.message)&&(e.message=this.colorize(e[t],e.level,e.message)),e}}return Ad.exports=e=>new i(e),Ad.exports.Colorizer=Ad.exports.Format=i,Ad.exports}rh.levels={emerg:0,alert:1,crit:2,error:3,warning:4,notice:5,info:6,debug:7},rh.colors={emerg:"red",alert:"yellow",crit:"red",error:"red",warning:"red",notice:"yellow",info:"green",debug:"blue"},Qd=nh,Object.defineProperty(Qd,"cli",{value:{levels:{error:0,warn:1,help:2,data:3,info:4,debug:5,prompt:6,verbose:7,input:8,silly:9},colors:{error:"red",warn:"yellow",help:"cyan",data:"grey",info:"green",debug:"blue",prompt:"grey",verbose:"cyan",input:"grey",silly:"magenta"}}}),Object.defineProperty(Qd,"npm",{value:{levels:{error:0,warn:1,info:2,http:3,verbose:4,debug:5,silly:6},colors:{error:"red",warn:"yellow",info:"green",http:"green",verbose:"cyan",debug:"blue",silly:"magenta"}}}),Object.defineProperty(Qd,"syslog",{value:rh}),function(e){Object.defineProperty(e,"LEVEL",{value:Symbol.for("level")}),Object.defineProperty(e,"MESSAGE",{value:Symbol.for("message")}),Object.defineProperty(e,"SPLAT",{value:Symbol.for("splat")}),Object.defineProperty(e,"configs",{value:nh})}(th);const{Colorizer:oh}=ih();var sh,ah,ch,lh,uh,dh,hh={exports:{}},fh={exports:{}};function ph(){if(uh)return fh.exports;uh=1;const{configs:e,LEVEL:t,MESSAGE:n}=th;class r{constructor(t={levels:e.npm.levels}){this.paddings=r.paddingForLevels(t.levels,t.filler),this.options=t}static getLongestLevel(e){const t=Object.keys(e).map((e=>e.length));return Math.max(...t)}static paddingForLevel(e,t,n){const r=n+1-e.length,i=Math.floor(r/t.length);return`${t}${t.repeat(i)}`.slice(0,r)}static paddingForLevels(e,t=" "){const n=r.getLongestLevel(e);return Object.keys(e).reduce(((e,i)=>(e[i]=r.paddingForLevel(i,t,n),e)),{})}transform(e,r){return e.message=`${this.paddings[e[t]]}${e.message}`,e[n]&&(e[n]=`${this.paddings[e[t]]}${e[n]}`),e}}return fh.exports=e=>new r(e),fh.exports.Padder=fh.exports.Format=r,fh.exports}var gh,mh,yh,vh,bh,wh,Sh,_h,Ih,xh,kh,Eh,Ch,$h,Oh={exports:{}},Nh={exports:{}};function Th(){return mh||(mh=1,function(e,t){const{hasOwnProperty:n}=Object.prototype,r=h();r.configure=h,r.stringify=r,r.default=r,t.stringify=r,t.configure=h,e.exports=r;const i=/[\u0000-\u001f\u0022\u005c\ud800-\udfff]/;function o(e){return e.length<5e3&&!i.test(e)?`"${e}"`:JSON.stringify(e)}function s(e,t){if(e.length>200||t)return e.sort(t);for(let t=1;t<e.length;t++){const n=e[t];let r=t;for(;0!==r&&e[r-1]>n;)e[r]=e[r-1],r--;e[r]=n}return e}const a=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Object.getPrototypeOf(new Int8Array)),Symbol.toStringTag).get;function c(e){return void 0!==a.call(e)&&0!==e.length}function l(e,t,n){e.length<n&&(n=e.length);const r=","===t?"":" ";let i=`"0":${r}${e[0]}`;for(let o=1;o<n;o++)i+=`${t}"${o}":${r}${e[o]}`;return i}function u(e,t){let r;if(n.call(e,t)){if(r=e[t],"number"!=typeof r)throw new TypeError(`The "${t}" argument must be of type number`);if(!Number.isInteger(r))throw new TypeError(`The "${t}" argument must be an integer`);if(r<1)throw new RangeError(`The "${t}" argument must be >= 1`)}return void 0===r?1/0:r}function d(e){return 1===e?"1 item":`${e} items`}function h(e){const t=function(e){if(n.call(e,"strict")){const t=e.strict;if("boolean"!=typeof t)throw new TypeError('The "strict" argument must be of type boolean');if(t)return e=>{let t="Object can not safely be stringified. Received type "+typeof e;throw"function"!=typeof e&&(t+=` (${e.toString()})`),new Error(t)}}}(e={...e});t&&(void 0===e.bigint&&(e.bigint=!1),"circularValue"in e||(e.circularValue=Error));const r=function(e){if(n.call(e,"circularValue")){const t=e.circularValue;if("string"==typeof t)return`"${t}"`;if(null==t)return t;if(t===Error||t===TypeError)return{toString(){throw new TypeError("Converting circular structure to JSON")}};throw new TypeError('The "circularValue" argument must be of type string or the value null or undefined')}return'"[Circular]"'}(e),i=function(e,t){let r;if(n.call(e,t)&&(r=e[t],"boolean"!=typeof r))throw new TypeError(`The "${t}" argument must be of type boolean`);return void 0===r||r}(e,"bigint"),a=function(e){let t;if(n.call(e,"deterministic")&&(t=e.deterministic,"boolean"!=typeof t&&"function"!=typeof t))throw new TypeError('The "deterministic" argument must be of type boolean or comparator function');return void 0===t||t}(e),h="function"==typeof a?a:void 0,f=u(e,"maximumDepth"),p=u(e,"maximumBreadth");function g(e,n,l,u,m,y){let v=n[e];switch("object"==typeof v&&null!==v&&"function"==typeof v.toJSON&&(v=v.toJSON(e)),v=u.call(n,e,v),typeof v){case"string":return o(v);case"object":{if(null===v)return"null";if(-1!==l.indexOf(v))return r;let e="",t=",";const n=y;if(Array.isArray(v)){if(0===v.length)return"[]";if(f<l.length+1)return'"[Array]"';l.push(v),""!==m&&(e+=`\n${y+=m}`,t=`,\n${y}`);const r=Math.min(v.length,p);let i=0;for(;i<r-1;i++){const n=g(String(i),v,l,u,m,y);e+=void 0!==n?n:"null",e+=t}const o=g(String(i),v,l,u,m,y);return e+=void 0!==o?o:"null",v.length-1>p&&(e+=`${t}"... ${d(v.length-p-1)} not stringified"`),""!==m&&(e+=`\n${n}`),l.pop(),`[${e}]`}let i=Object.keys(v);const b=i.length;if(0===b)return"{}";if(f<l.length+1)return'"[Object]"';let w="",S="";""!==m&&(t=`,\n${y+=m}`,w=" ");const _=Math.min(b,p);a&&!c(v)&&(i=s(i,h)),l.push(v);for(let n=0;n<_;n++){const r=i[n],s=g(r,v,l,u,m,y);void 0!==s&&(e+=`${S}${o(r)}:${w}${s}`,S=t)}return b>p&&(e+=`${S}"...":${w}"${d(b-p)} not stringified"`,S=t),""!==m&&S.length>1&&(e=`\n${y}${e}\n${n}`),l.pop(),`{${e}}`}case"number":return isFinite(v)?String(v):t?t(v):"null";case"boolean":return!0===v?"true":"false";case"undefined":return;case"bigint":if(i)return String(v);default:return t?t(v):void 0}}function m(e,n,s,a,c,l){switch("object"==typeof n&&null!==n&&"function"==typeof n.toJSON&&(n=n.toJSON(e)),typeof n){case"string":return o(n);case"object":{if(null===n)return"null";if(-1!==s.indexOf(n))return r;const e=l;let t="",i=",";if(Array.isArray(n)){if(0===n.length)return"[]";if(f<s.length+1)return'"[Array]"';s.push(n),""!==c&&(t+=`\n${l+=c}`,i=`,\n${l}`);const r=Math.min(n.length,p);let o=0;for(;o<r-1;o++){const e=m(String(o),n[o],s,a,c,l);t+=void 0!==e?e:"null",t+=i}const u=m(String(o),n[o],s,a,c,l);return t+=void 0!==u?u:"null",n.length-1>p&&(t+=`${i}"... ${d(n.length-p-1)} not stringified"`),""!==c&&(t+=`\n${e}`),s.pop(),`[${t}]`}s.push(n);let u="";""!==c&&(i=`,\n${l+=c}`,u=" ");let h="";for(const e of a){const r=m(e,n[e],s,a,c,l);void 0!==r&&(t+=`${h}${o(e)}:${u}${r}`,h=i)}return""!==c&&h.length>1&&(t=`\n${l}${t}\n${e}`),s.pop(),`{${t}}`}case"number":return isFinite(n)?String(n):t?t(n):"null";case"boolean":return!0===n?"true":"false";case"undefined":return;case"bigint":if(i)return String(n);default:return t?t(n):void 0}}function y(e,n,u,g,m){switch(typeof n){case"string":return o(n);case"object":{if(null===n)return"null";if("function"==typeof n.toJSON){if("object"!=typeof(n=n.toJSON(e)))return y(e,n,u,g,m);if(null===n)return"null"}if(-1!==u.indexOf(n))return r;const t=m;if(Array.isArray(n)){if(0===n.length)return"[]";if(f<u.length+1)return'"[Array]"';u.push(n);let e=`\n${m+=g}`;const r=`,\n${m}`,i=Math.min(n.length,p);let o=0;for(;o<i-1;o++){const t=y(String(o),n[o],u,g,m);e+=void 0!==t?t:"null",e+=r}const s=y(String(o),n[o],u,g,m);return e+=void 0!==s?s:"null",n.length-1>p&&(e+=`${r}"... ${d(n.length-p-1)} not stringified"`),e+=`\n${t}`,u.pop(),`[${e}]`}let i=Object.keys(n);const v=i.length;if(0===v)return"{}";if(f<u.length+1)return'"[Object]"';const b=`,\n${m+=g}`;let w="",S="",_=Math.min(v,p);c(n)&&(w+=l(n,b,p),i=i.slice(n.length),_-=n.length,S=b),a&&(i=s(i,h)),u.push(n);for(let e=0;e<_;e++){const t=i[e],r=y(t,n[t],u,g,m);void 0!==r&&(w+=`${S}${o(t)}: ${r}`,S=b)}return v>p&&(w+=`${S}"...": "${d(v-p)} not stringified"`,S=b),""!==S&&(w=`\n${m}${w}\n${t}`),u.pop(),`{${w}}`}case"number":return isFinite(n)?String(n):t?t(n):"null";case"boolean":return!0===n?"true":"false";case"undefined":return;case"bigint":if(i)return String(n);default:return t?t(n):void 0}}function v(e,n,u){switch(typeof n){case"string":return o(n);case"object":{if(null===n)return"null";if("function"==typeof n.toJSON){if("object"!=typeof(n=n.toJSON(e)))return v(e,n,u);if(null===n)return"null"}if(-1!==u.indexOf(n))return r;let t="";const i=void 0!==n.length;if(i&&Array.isArray(n)){if(0===n.length)return"[]";if(f<u.length+1)return'"[Array]"';u.push(n);const e=Math.min(n.length,p);let r=0;for(;r<e-1;r++){const e=v(String(r),n[r],u);t+=void 0!==e?e:"null",t+=","}const i=v(String(r),n[r],u);return t+=void 0!==i?i:"null",n.length-1>p&&(t+=`,"... ${d(n.length-p-1)} not stringified"`),u.pop(),`[${t}]`}let g=Object.keys(n);const m=g.length;if(0===m)return"{}";if(f<u.length+1)return'"[Object]"';let y="",b=Math.min(m,p);i&&c(n)&&(t+=l(n,",",p),g=g.slice(n.length),b-=n.length,y=","),a&&(g=s(g,h)),u.push(n);for(let e=0;e<b;e++){const r=g[e],i=v(r,n[r],u);void 0!==i&&(t+=`${y}${o(r)}:${i}`,y=",")}return m>p&&(t+=`${y}"...":"${d(m-p)} not stringified"`),u.pop(),`{${t}}`}case"number":return isFinite(n)?String(n):t?t(n):"null";case"boolean":return!0===n?"true":"false";case"undefined":return;case"bigint":if(i)return String(n);default:return t?t(n):void 0}}return function(e,t,n){if(arguments.length>1){let r="";if("number"==typeof n?r=" ".repeat(Math.min(n,10)):"string"==typeof n&&(r=n.slice(0,10)),null!=t){if("function"==typeof t)return g("",{"":e},[],t,r,"");if(Array.isArray(t))return m("",e,[],function(e){const t=new Set;for(const n of e)"string"!=typeof n&&"number"!=typeof n||t.add(String(n));return t}(t),r,"")}if(0!==r.length)return y("",e,[],r,"")}return v("",e,[])}}}(Nh,Nh.exports)),Nh.exports}function Ah(){if(vh)return yh;vh=1;const e=Td,{MESSAGE:t}=th,n=Th();function r(e,t){return"bigint"==typeof t?t.toString():t}return yh=e(((e,i)=>{const o=n.configure(i);return e[t]=o(e,i.replacer||r,i.space),e}))}var Mh,Ph,Dh,jh,Rh,Lh={exports:{}},Fh=/d{1,4}|M{1,4}|YY(?:YY)?|S{1,3}|Do|ZZ|Z|([HhMsDm])\1?|[aA]|"[^"]*"|'[^']*'/g,Uh="\\d\\d?",Bh="\\d\\d",Wh="[^\\s]+",Gh=/\[([^]*?)\]/gm;function Vh(e,t){for(var n=[],r=0,i=e.length;r<i;r++)n.push(e[r].substr(0,t));return n}var Yh=function(e){return function(t,n){var r=n[e].map((function(e){return e.toLowerCase()})),i=r.indexOf(t.toLowerCase());return i>-1?i:null}};function Hh(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];for(var r=0,i=t;r<i.length;r++){var o=i[r];for(var s in o)e[s]=o[s]}return e}var zh=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],qh=["January","February","March","April","May","June","July","August","September","October","November","December"],Kh=Vh(qh,3),Jh={dayNamesShort:Vh(zh,3),dayNames:zh,monthNamesShort:Kh,monthNames:qh,amPm:["am","pm"],DoFn:function(e){return e+["th","st","nd","rd"][e%10>3?0:(e-e%10!=10?1:0)*e%10]}},Zh=Hh({},Jh),Xh=function(e){return Zh=Hh(Zh,e)},Qh=function(e){return e.replace(/[|\\{()[^$+*?.-]/g,"\\$&")},ef=function(e,t){for(void 0===t&&(t=2),e=String(e);e.length<t;)e="0"+e;return e},tf={D:function(e){return String(e.getDate())},DD:function(e){return ef(e.getDate())},Do:function(e,t){return t.DoFn(e.getDate())},d:function(e){return String(e.getDay())},dd:function(e){return ef(e.getDay())},ddd:function(e,t){return t.dayNamesShort[e.getDay()]},dddd:function(e,t){return t.dayNames[e.getDay()]},M:function(e){return String(e.getMonth()+1)},MM:function(e){return ef(e.getMonth()+1)},MMM:function(e,t){return t.monthNamesShort[e.getMonth()]},MMMM:function(e,t){return t.monthNames[e.getMonth()]},YY:function(e){return ef(String(e.getFullYear()),4).substr(2)},YYYY:function(e){return ef(e.getFullYear(),4)},h:function(e){return String(e.getHours()%12||12)},hh:function(e){return ef(e.getHours()%12||12)},H:function(e){return String(e.getHours())},HH:function(e){return ef(e.getHours())},m:function(e){return String(e.getMinutes())},mm:function(e){return ef(e.getMinutes())},s:function(e){return String(e.getSeconds())},ss:function(e){return ef(e.getSeconds())},S:function(e){return String(Math.round(e.getMilliseconds()/100))},SS:function(e){return ef(Math.round(e.getMilliseconds()/10),2)},SSS:function(e){return ef(e.getMilliseconds(),3)},a:function(e,t){return e.getHours()<12?t.amPm[0]:t.amPm[1]},A:function(e,t){return e.getHours()<12?t.amPm[0].toUpperCase():t.amPm[1].toUpperCase()},ZZ:function(e){var t=e.getTimezoneOffset();return(t>0?"-":"+")+ef(100*Math.floor(Math.abs(t)/60)+Math.abs(t)%60,4)},Z:function(e){var t=e.getTimezoneOffset();return(t>0?"-":"+")+ef(Math.floor(Math.abs(t)/60),2)+":"+ef(Math.abs(t)%60,2)}},nf=function(e){return+e-1},rf=[null,Uh],of=[null,Wh],sf=["isPm",Wh,function(e,t){var n=e.toLowerCase();return n===t.amPm[0]?0:n===t.amPm[1]?1:null}],af=["timezoneOffset","[^\\s]*?[\\+\\-]\\d\\d:?\\d\\d|[^\\s]*?Z?",function(e){var t=(e+"").match(/([+-]|\d\d)/gi);if(t){var n=60*+t[1]+parseInt(t[2],10);return"+"===t[0]?n:-n}return 0}],cf={D:["day",Uh],DD:["day",Bh],Do:["day",Uh+Wh,function(e){return parseInt(e,10)}],M:["month",Uh,nf],MM:["month",Bh,nf],YY:["year",Bh,function(e){var t=+(""+(new Date).getFullYear()).substr(0,2);return+(""+(+e>68?t-1:t)+e)}],h:["hour",Uh,void 0,"isPm"],hh:["hour",Bh,void 0,"isPm"],H:["hour",Uh],HH:["hour",Bh],m:["minute",Uh],mm:["minute",Bh],s:["second",Uh],ss:["second",Bh],YYYY:["year","\\d{4}"],S:["millisecond","\\d",function(e){return 100*+e}],SS:["millisecond",Bh,function(e){return 10*+e}],SSS:["millisecond","\\d{3}"],d:rf,dd:rf,ddd:of,dddd:of,MMM:["month",Wh,Yh("monthNamesShort")],MMMM:["month",Wh,Yh("monthNames")],a:sf,A:sf,ZZ:af,Z:af},lf={default:"ddd MMM DD YYYY HH:mm:ss",shortDate:"M/D/YY",mediumDate:"MMM D, YYYY",longDate:"MMMM D, YYYY",fullDate:"dddd, MMMM D, YYYY",isoDate:"YYYY-MM-DD",isoDateTime:"YYYY-MM-DDTHH:mm:ssZ",shortTime:"HH:mm",mediumTime:"HH:mm:ss",longTime:"HH:mm:ss.SSS"},uf=function(e){return Hh(lf,e)},df=function(e,t,n){if(void 0===t&&(t=lf.default),void 0===n&&(n={}),"number"==typeof e&&(e=new Date(e)),"[object Date]"!==Object.prototype.toString.call(e)||isNaN(e.getTime()))throw new Error("Invalid Date pass to format");var r=[];t=(t=lf[t]||t).replace(Gh,(function(e,t){return r.push(t),"@@@"}));var i=Hh(Hh({},Zh),n);return(t=t.replace(Fh,(function(t){return tf[t](e,i)}))).replace(/@@@/g,(function(){return r.shift()}))};function hf(e,t,n){if(void 0===n&&(n={}),"string"!=typeof t)throw new Error("Invalid format in fecha parse");if(t=lf[t]||t,e.length>1e3)return null;var r={year:(new Date).getFullYear(),month:0,day:1,hour:0,minute:0,second:0,millisecond:0,isPm:null,timezoneOffset:null},i=[],o=[],s=t.replace(Gh,(function(e,t){return o.push(Qh(t)),"@@@"})),a={},c={};s=Qh(s).replace(Fh,(function(e){var t=cf[e],n=t[0],r=t[1],o=t[3];if(a[n])throw new Error("Invalid format. "+n+" specified twice in format");return a[n]=!0,o&&(c[o]=!0),i.push(t),"("+r+")"})),Object.keys(c).forEach((function(e){if(!a[e])throw new Error("Invalid format. "+e+" is required in specified format")})),s=s.replace(/@@@/g,(function(){return o.shift()}));var l=e.match(new RegExp(s,"i"));if(!l)return null;for(var u,d=Hh(Hh({},Zh),n),h=1;h<l.length;h++){var f=i[h-1],p=f[0],g=f[2],m=g?g(l[h],d):+l[h];if(null==m)return null;r[p]=m}if(1===r.isPm&&null!=r.hour&&12!=+r.hour?r.hour=+r.hour+12:0===r.isPm&&12==+r.hour&&(r.hour=0),null==r.timezoneOffset){u=new Date(r.year,r.month,r.day,r.hour,r.minute,r.second,r.millisecond);for(var y=[["month","getMonth"],["day","getDate"],["hour","getHours"],["minute","getMinutes"],["second","getSeconds"]],v=(h=0,y.length);h<v;h++)if(a[y[h][0]]&&r[y[h][0]]!==u[y[h][1]]())return null}else if(u=new Date(Date.UTC(r.year,r.month,r.day,r.hour,r.minute-r.timezoneOffset,r.second,r.millisecond)),r.month>11||r.month<0||r.day>31||r.day<1||r.hour>23||r.hour<0||r.minute>59||r.minute<0||r.second>59||r.second<0)return null;return u}var ff,pf,gf,mf,yf={format:df,parse:hf,defaultI18n:Jh,setGlobalDateI18n:Xh,setGlobalDateMasks:uf},vf=function(e){if(e.__esModule)return e;var t=e.default;if("function"==typeof t){var n=function e(){return this instanceof e?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach((function(t){var r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(n,t,r.get?r:{enumerable:!0,get:function(){return e[t]}})})),n}(Object.freeze({__proto__:null,assign:Hh,default:yf,defaultI18n:Jh,format:df,parse:hf,setGlobalDateI18n:Xh,setGlobalDateMasks:uf}));const bf=xd.format=Td;function wf(e,t){Object.defineProperty(bf,e,{get:()=>t(),configurable:!0})}xd.levels=e=>(oh.addColors(e.colors||e),e),wf("align",(function(){return ah?sh:(ah=1,sh=Td((e=>(e.message=`\t${e.message}`,e))))})),wf("errors",(function(){return function(){if(lh)return ch;lh=1;const e=Td,{LEVEL:t,MESSAGE:n}=th;return ch=e(((e,{stack:r,cause:i})=>{if(e instanceof Error){const o=Object.assign({},e,{level:e.level,[t]:e[t]||e.level,message:e.message,[n]:e[n]||e.message});return r&&(o.stack=e.stack),i&&(o.cause=e.cause),o}if(!(e.message instanceof Error))return e;const o=e.message;return Object.assign(e,o),e.message=o.message,e[n]=o.message,r&&(e.stack=o.stack),i&&(e.cause=o.cause),e}))}()})),wf("cli",(function(){return function(){if(dh)return hh.exports;dh=1;const{Colorizer:e}=ih(),{Padder:t}=ph(),{configs:n,MESSAGE:r}=th;class i{constructor(r={}){r.levels||(r.levels=n.cli.levels),this.colorizer=new e(r),this.padder=new t(r),this.options=r}transform(e,t){return this.colorizer.transform(this.padder.transform(e,t),t),e[r]=`${e.level}:${e.message}`,e}}return hh.exports=e=>new i(e),hh.exports.Format=i,hh.exports}()})),wf("combine",(function(){return function(){if(gh)return Oh.exports;gh=1;const e=Td;function t(e){if(e.every(n))return t=>{let n=t;for(let t=0;t<e.length;t++)if(n=e[t].transform(n,e[t].options),!n)return!1;return n}}function n(e){if("function"!=typeof e.transform)throw new Error(["No transform function found on format. Did you create a format instance?","const myFormat = format(formatFn);","const instance = myFormat();"].join("\n"));return!0}return Oh.exports=(...n)=>{const r=e(t(n)),i=r();return i.Format=r.Format,i},Oh.exports.cascade=t,Oh.exports}()})),wf("colorize",(function(){return ih()})),wf("json",(function(){return Ah()})),wf("label",(function(){return wh?bh:(wh=1,bh=Td(((e,t)=>t.message?(e.message=`[${t.label}] ${e.message}`,e):(e.label=t.label,e))))})),wf("logstash",(function(){return function(){if(_h)return Sh;_h=1;const e=Td,{MESSAGE:t}=th,n=Th();return Sh=e((e=>{const r={};return e.message&&(r["@message"]=e.message,delete e.message),e.timestamp&&(r["@timestamp"]=e.timestamp,delete e.timestamp),r["@fields"]=e,e[t]=n(r),e}))}()})),wf("metadata",(function(){return xh?Ih:(xh=1,Ih=Td(((e,t={})=>{let n="metadata";t.key&&(n=t.key);let r=[];return t.fillExcept||t.fillWith||(r.push("level"),r.push("message")),t.fillExcept&&(r=t.fillExcept),r.length>0?function(e,t,n){const r=t.reduce(((t,n)=>(t[n]=e[n],delete e[n],t)),{}),i=Object.keys(e).reduce(((t,n)=>(t[n]=e[n],delete e[n],t)),{});return Object.assign(e,r,{[n]:i}),e}(e,r,n):t.fillWith?function(e,t,n){return e[n]=t.reduce(((t,n)=>(t[n]=e[n],delete e[n],t)),{}),e}(e,t.fillWith,n):e})))})),wf("ms",(function(){return function(){if(Eh)return kh;Eh=1;const e=Td,t=fd();return kh=e((e=>{const n=+new Date;return this.diff=n-(this.prevTime||n),this.prevTime=n,e.ms=`+${t(this.diff)}`,e}))}()})),wf("padLevels",(function(){return ph()})),wf("prettyPrint",(function(){return function(){if($h)return Ch;$h=1;const e=i.inspect,t=Td,{LEVEL:n,MESSAGE:r,SPLAT:o}=th;return Ch=t(((t,i={})=>{const s=Object.assign({},t);return delete s[n],delete s[r],delete s[o],t[r]=e(s,!1,i.depth||null,i.colorize),t}))}()})),wf("printf",(function(){return function(){if(Mh)return Lh.exports;Mh=1;const{MESSAGE:e}=th;class t{constructor(e){this.template=e}transform(t){return t[e]=this.template(t),t}}return Lh.exports=e=>new t(e),Lh.exports.Printf=Lh.exports.Format=t,Lh.exports}()})),wf("simple",(function(){return function(){if(Dh)return Ph;Dh=1;const e=Td,{MESSAGE:t}=th,n=Th();return Ph=e((e=>{const r=n(Object.assign({},e,{level:void 0,message:void 0,splat:void 0})),i=e.padding&&e.padding[e.level]||"";return e[t]="{}"!==r?`${e.level}:${i} ${e.message} ${r}`:`${e.level}:${i} ${e.message}`,e}))}()})),wf("splat",(function(){return function(){if(Rh)return jh;Rh=1;const e=i,{SPLAT:t}=th,n=/%[scdjifoO%]/g,r=/%%/g;class o{constructor(e){this.options=e}_splat(n,i){const o=n.message,s=n[t]||n.splat||[],a=o.match(r),c=a&&a.length||0,l=i.length-c-s.length,u=l<0?s.splice(l,-1*l):[],d=u.length;if(d)for(let e=0;e<d;e++)Object.assign(n,u[e]);return n.message=e.format(o,...s),n}transform(e){const r=e.message,i=e[t]||e.splat;if(!i||!i.length)return e;const o=r&&r.match&&r.match(n);if(!o&&(i||i.length)){const t=i.length>1?i.splice(0):i,n=t.length;if(n)for(let r=0;r<n;r++)Object.assign(e,t[r]);return e}return o?this._splat(e,o):e}}return jh=e=>new o(e)}()})),wf("timestamp",(function(){return function(){if(pf)return ff;pf=1;const e=vf;return ff=Td(((t,n={})=>(n.format&&(t.timestamp="function"==typeof n.format?n.format():e.format(new Date,n.format)),t.timestamp||(t.timestamp=(new Date).toISOString()),n.alias&&(t[n.alias]=t.timestamp),t)))}()})),wf("uncolorize",(function(){return function(){if(mf)return gf;mf=1;const e=Xd(),t=Td,{MESSAGE:n}=th;return gf=t(((t,r)=>(!1!==r.level&&(t.level=e.strip(t.level)),!1!==r.message&&(t.message=e.strip(String(t.message))),!1!==r.raw&&t[n]&&(t[n]=e.strip(String(t[n]))),t)))}()}));var Sf={};!function(e){const{format:t}=i;e.warn={deprecated:e=>()=>{throw new Error(t("{ %s } was removed in winston@3.0.0.",e))},useFormat:e=>()=>{throw new Error([t("{ %s } was removed in winston@3.0.0.",e),"Use a custom winston.format = winston.format(function) instead."].join("\n"))},forFunctions(t,n,r){r.forEach((r=>{t[r]=e.warn[n](r)}))},forProperties(t,n,r){r.forEach((r=>{const i=e.warn[n](r);Object.defineProperty(t,r,{get:i,set:i})}))}}}(Sf);var _f,If,xf,kf,Ef,Cf,$f={},Of={exports:{}},Nf={exports:{}};function Tf(){return kf?xf:(kf=1,xf=O)}function Af(){if(Cf)return Ef;function e(e,r){n(e,r),t(e)}function t(e){e._writableState&&!e._writableState.emitClose||e._readableState&&!e._readableState.emitClose||e.emit("close")}function n(e,t){e.emit("error",t)}return Cf=1,Ef={destroy:function(r,i){var o=this,s=this._readableState&&this._readableState.destroyed,a=this._writableState&&this._writableState.destroyed;return s||a?(i?i(r):r&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,process.nextTick(n,this,r)):process.nextTick(n,this,r)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(r||null,(function(n){!i&&n?o._writableState?o._writableState.errorEmitted?process.nextTick(t,o):(o._writableState.errorEmitted=!0,process.nextTick(e,o,n)):process.nextTick(e,o,n):i?(process.nextTick(t,o),i(n)):process.nextTick(t,o)})),this)},undestroy:function(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)},errorOrDestroy:function(e,t){var n=e._readableState,r=e._writableState;n&&n.autoDestroy||r&&r.autoDestroy?e.destroy(t):e.emit("error",t)}},Ef}var Mf,Pf,Df,jf={};function Rf(){if(Mf)return jf;Mf=1;const e={};function t(t,n,r){r||(r=Error);class i extends r{constructor(e,t,r){super(function(e,t,r){return"string"==typeof n?n:n(e,t,r)}(e,t,r))}}i.prototype.name=r.name,i.prototype.code=t,e[t]=i}function n(e,t){if(Array.isArray(e)){const n=e.length;return e=e.map((e=>String(e))),n>2?`one of ${t} ${e.slice(0,n-1).join(", ")}, or `+e[n-1]:2===n?`one of ${t} ${e[0]} or ${e[1]}`:`of ${t} ${e[0]}`}return`of ${t} ${String(e)}`}return t("ERR_INVALID_OPT_VALUE",(function(e,t){return'The value "'+t+'" is invalid for option "'+e+'"'}),TypeError),t("ERR_INVALID_ARG_TYPE",(function(e,t,r){let i;var o;let s;if("string"==typeof t&&(o="not ",t.substr(0,4)===o)?(i="must not be",t=t.replace(/^not /,"")):i="must be",function(e,t,n){return(void 0===n||n>e.length)&&(n=e.length),e.substring(n-9,n)===t}(e," argument"))s=`The ${e} ${i} ${n(t,"type")}`;else{const r=function(e,t,n){return"number"!=typeof n&&(n=0),!(n+1>e.length)&&-1!==e.indexOf(".",n)}(e)?"property":"argument";s=`The "${e}" ${r} ${i} ${n(t,"type")}`}return s+=". Received type "+typeof r,s}),TypeError),t("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),t("ERR_METHOD_NOT_IMPLEMENTED",(function(e){return"The "+e+" method is not implemented"})),t("ERR_STREAM_PREMATURE_CLOSE","Premature close"),t("ERR_STREAM_DESTROYED",(function(e){return"Cannot call "+e+" after a stream was destroyed"})),t("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),t("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),t("ERR_STREAM_WRITE_AFTER_END","write after end"),t("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),t("ERR_UNKNOWN_ENCODING",(function(e){return"Unknown encoding: "+e}),TypeError),t("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),jf.codes=e,jf}function Lf(){if(Df)return Pf;Df=1;var e=Rf().codes.ERR_INVALID_OPT_VALUE;return Pf={getHighWaterMark:function(t,n,r,i){var o=function(e,t,n){return null!=e.highWaterMark?e.highWaterMark:t?e[n]:null}(n,i,r);if(null!=o){if(!isFinite(o)||Math.floor(o)!==o||o<0)throw new e(i?r:"highWaterMark",o);return Math.floor(o)}return t.objectMode?16:16384}}}var Ff,Uf,Bf,Wf,Gf={exports:{}},Vf={exports:{}};function Yf(){if(Uf)return Gf.exports;Uf=1;try{var e=require("util");if("function"!=typeof e.inherits)throw"";Gf.exports=e.inherits}catch(e){Gf.exports=(Ff||(Ff=1,"function"==typeof Object.create?Vf.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:Vf.exports=function(e,t){if(t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}}),Vf.exports)}return Gf.exports}function Hf(){if(Wf)return Bf;function e(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function t(t){for(var r=1;r<arguments.length;r++){var i=null!=arguments[r]?arguments[r]:{};r%2?e(Object(i),!0).forEach((function(e){n(t,e,i[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):e(Object(i)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(i,e))}))}return t}function n(e,t,n){return(t=r(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function r(e){var t=function(e){if("object"!=typeof e||null===e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:String(t)}Wf=1;var o=N.Buffer,s=i.inspect,a=s&&s.custom||"inspect";function c(e,t,n){o.prototype.copy.call(e,t,n)}return Bf=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.head=null,this.tail=null,this.length=0}return function(e,t){t&&function(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,r(i.key),i)}}(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1})}(e,[{key:"push",value:function(e){var t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length}},{key:"unshift",value:function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length}},{key:"shift",value:function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(e){if(0===this.length)return"";for(var t=this.head,n=""+t.data;t=t.next;)n+=e+t.data;return n}},{key:"concat",value:function(e){if(0===this.length)return o.alloc(0);for(var t=o.allocUnsafe(e>>>0),n=this.head,r=0;n;)c(n.data,t,r),r+=n.data.length,n=n.next;return t}},{key:"consume",value:function(e,t){var n;return e<this.head.data.length?(n=this.head.data.slice(0,e),this.head.data=this.head.data.slice(e)):n=e===this.head.data.length?this.shift():t?this._getString(e):this._getBuffer(e),n}},{key:"first",value:function(){return this.head.data}},{key:"_getString",value:function(e){var t=this.head,n=1,r=t.data;for(e-=r.length;t=t.next;){var i=t.data,o=e>i.length?i.length:e;if(o===i.length?r+=i:r+=i.slice(0,e),0==(e-=o)){o===i.length?(++n,t.next?this.head=t.next:this.head=this.tail=null):(this.head=t,t.data=i.slice(o));break}++n}return this.length-=n,r}},{key:"_getBuffer",value:function(e){var t=o.allocUnsafe(e),n=this.head,r=1;for(n.data.copy(t),e-=n.data.length;n=n.next;){var i=n.data,s=e>i.length?i.length:e;if(i.copy(t,t.length-e,0,s),0==(e-=s)){s===i.length?(++r,n.next?this.head=n.next:this.head=this.tail=null):(this.head=n,n.data=i.slice(s));break}++r}return this.length-=r,t}},{key:a,value:function(e,n){return s(this,t(t({},n),{},{depth:0,customInspect:!1}))}}]),e}()}var zf,qf,Kf,Jf,Zf,Xf,Qf,ep,tp,np,rp,ip,op,sp,ap={},cp={exports:{}};function lp(){if(qf)return ap;qf=1;var e=(zf||(zf=1,function(e,t){var n=N,r=n.Buffer;function i(e,t){for(var n in e)t[n]=e[n]}function o(e,t,n){return r(e,t,n)}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?e.exports=n:(i(n,t),t.Buffer=o),o.prototype=Object.create(r.prototype),i(r,o),o.from=function(e,t,n){if("number"==typeof e)throw new TypeError("Argument must not be a number");return r(e,t,n)},o.alloc=function(e,t,n){if("number"!=typeof e)throw new TypeError("Argument must be a number");var i=r(e);return void 0!==t?"string"==typeof n?i.fill(t,n):i.fill(t):i.fill(0),i},o.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return r(e)},o.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n.SlowBuffer(e)}}(cp,cp.exports)),cp.exports).Buffer,t=e.isEncoding||function(e){switch((e=""+e)&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function n(n){var r;switch(this.encoding=function(n){var r=function(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}(n);if("string"!=typeof r&&(e.isEncoding===t||!t(n)))throw new Error("Unknown encoding: "+n);return r||n}(n),this.encoding){case"utf16le":this.text=o,this.end=s,r=4;break;case"utf8":this.fillLast=i,r=4;break;case"base64":this.text=a,this.end=c,r=3;break;default:return this.write=l,void(this.end=u)}this.lastNeed=0,this.lastTotal=0,this.lastChar=e.allocUnsafe(r)}function r(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function i(e){var t=this.lastTotal-this.lastNeed,n=function(e,t){if(128!=(192&t[0]))return e.lastNeed=0,"�";if(e.lastNeed>1&&t.length>1){if(128!=(192&t[1]))return e.lastNeed=1,"�";if(e.lastNeed>2&&t.length>2&&128!=(192&t[2]))return e.lastNeed=2,"�"}}(this,e);return void 0!==n?n:this.lastNeed<=e.length?(e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,t,0,e.length),void(this.lastNeed-=e.length))}function o(e,t){if((e.length-t)%2==0){var n=e.toString("utf16le",t);if(n){var r=n.charCodeAt(n.length-1);if(r>=55296&&r<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],n.slice(0,-1)}return n}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function s(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var n=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,n)}return t}function a(e,t){var n=(e.length-t)%3;return 0===n?e.toString("base64",t):(this.lastNeed=3-n,this.lastTotal=3,1===n?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-n))}function c(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function l(e){return e.toString(this.encoding)}function u(e){return e&&e.length?this.write(e):""}return ap.StringDecoder=n,n.prototype.write=function(e){if(0===e.length)return"";var t,n;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";n=this.lastNeed,this.lastNeed=0}else n=0;return n<e.length?t?t+this.text(e,n):this.text(e,n):t||""},n.prototype.end=function(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+"�":t},n.prototype.text=function(e,t){var n=function(e,t,n){var i=t.length-1;if(i<n)return 0;var o=r(t[i]);return o>=0?(o>0&&(e.lastNeed=o-1),o):--i<n||-2===o?0:(o=r(t[i]))>=0?(o>0&&(e.lastNeed=o-2),o):--i<n||-2===o?0:(o=r(t[i]))>=0?(o>0&&(2===o?o=0:e.lastNeed=o-3),o):0}(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=n;var i=e.length-(n-this.lastNeed);return e.copy(this.lastChar,0,i),e.toString("utf8",t,i)},n.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length},ap}function up(){if(Jf)return Kf;Jf=1;var e=Rf().codes.ERR_STREAM_PREMATURE_CLOSE;function t(){}return Kf=function n(r,i,o){if("function"==typeof i)return n(r,null,i);i||(i={}),o=function(e){var t=!1;return function(){if(!t){t=!0;for(var n=arguments.length,r=new Array(n),i=0;i<n;i++)r[i]=arguments[i];e.apply(this,r)}}}(o||t);var s=i.readable||!1!==i.readable&&r.readable,a=i.writable||!1!==i.writable&&r.writable,c=function(){r.writable||u()},l=r._writableState&&r._writableState.finished,u=function(){a=!1,l=!0,s||o.call(r)},d=r._readableState&&r._readableState.endEmitted,h=function(){s=!1,d=!0,a||o.call(r)},f=function(e){o.call(r,e)},p=function(){var t;return s&&!d?(r._readableState&&r._readableState.ended||(t=new e),o.call(r,t)):a&&!l?(r._writableState&&r._writableState.ended||(t=new e),o.call(r,t)):void 0},g=function(){r.req.on("finish",u)};return function(e){return e.setHeader&&"function"==typeof e.abort}(r)?(r.on("complete",u),r.on("abort",p),r.req?g():r.on("request",g)):a&&!r._writableState&&(r.on("end",c),r.on("close",c)),r.on("end",h),r.on("finish",u),!1!==i.error&&r.on("error",f),r.on("close",p),function(){r.removeListener("complete",u),r.removeListener("abort",p),r.removeListener("request",g),r.req&&r.req.removeListener("finish",u),r.removeListener("end",c),r.removeListener("close",c),r.removeListener("finish",u),r.removeListener("end",h),r.removeListener("error",f),r.removeListener("close",p)}},Kf}function dp(){if(np)return tp;var e;np=1,tp=_,_.ReadableState=S,T.EventEmitter;var t,n=function(e,t){return e.listeners(t).length},r=Tf(),o=N.Buffer,s=(void 0!==id?id:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{}).Uint8Array||function(){},a=i;t=a&&a.debuglog?a.debuglog("stream"):function(){};var c,l,u,d=Hf(),h=Af(),f=Lf().getHighWaterMark,p=Rf().codes,g=p.ERR_INVALID_ARG_TYPE,m=p.ERR_STREAM_PUSH_AFTER_EOF,y=p.ERR_METHOD_NOT_IMPLEMENTED,v=p.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;Yf()(_,r);var b=h.errorOrDestroy,w=["error","close","destroy","pause","resume"];function S(t,n,r){e=e||hp(),t=t||{},"boolean"!=typeof r&&(r=n instanceof e),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.readableObjectMode),this.highWaterMark=f(this,t,"readableHighWaterMark",r),this.buffer=new d,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=!1!==t.emitClose,this.autoDestroy=!!t.autoDestroy,this.destroyed=!1,this.defaultEncoding=t.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,t.encoding&&(c||(c=lp().StringDecoder),this.decoder=new c(t.encoding),this.encoding=t.encoding)}function _(t){if(e=e||hp(),!(this instanceof _))return new _(t);var n=this instanceof e;this._readableState=new S(t,this,n),this.readable=!0,t&&("function"==typeof t.read&&(this._read=t.read),"function"==typeof t.destroy&&(this._destroy=t.destroy)),r.call(this)}function I(e,n,r,i,a){t("readableAddChunk",n);var c,l=e._readableState;if(null===n)l.reading=!1,function(e,n){if(t("onEofChunk"),!n.ended){if(n.decoder){var r=n.decoder.end();r&&r.length&&(n.buffer.push(r),n.length+=n.objectMode?1:r.length)}n.ended=!0,n.sync?C(e):(n.needReadable=!1,n.emittedReadable||(n.emittedReadable=!0,$(e)))}}(e,l);else if(a||(c=function(e,t){var n,r;return r=t,o.isBuffer(r)||r instanceof s||"string"==typeof t||void 0===t||e.objectMode||(n=new g("chunk",["string","Buffer","Uint8Array"],t)),n}(l,n)),c)b(e,c);else if(l.objectMode||n&&n.length>0)if("string"==typeof n||l.objectMode||Object.getPrototypeOf(n)===o.prototype||(n=function(e){return o.from(e)}(n)),i)l.endEmitted?b(e,new v):x(e,l,n,!0);else if(l.ended)b(e,new m);else{if(l.destroyed)return!1;l.reading=!1,l.decoder&&!r?(n=l.decoder.write(n),l.objectMode||0!==n.length?x(e,l,n,!1):O(e,l)):x(e,l,n,!1)}else i||(l.reading=!1,O(e,l));return!l.ended&&(l.length<l.highWaterMark||0===l.length)}function x(e,t,n,r){t.flowing&&0===t.length&&!t.sync?(t.awaitDrain=0,e.emit("data",n)):(t.length+=t.objectMode?1:n.length,r?t.buffer.unshift(n):t.buffer.push(n),t.needReadable&&C(e)),O(e,t)}Object.defineProperty(_.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._readableState&&this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}}),_.prototype.destroy=h.destroy,_.prototype._undestroy=h.undestroy,_.prototype._destroy=function(e,t){t(e)},_.prototype.push=function(e,t){var n,r=this._readableState;return r.objectMode?n=!0:"string"==typeof e&&((t=t||r.defaultEncoding)!==r.encoding&&(e=o.from(e,t),t=""),n=!0),I(this,e,t,!1,n)},_.prototype.unshift=function(e){return I(this,e,null,!0,!1)},_.prototype.isPaused=function(){return!1===this._readableState.flowing},_.prototype.setEncoding=function(e){c||(c=lp().StringDecoder);var t=new c(e);this._readableState.decoder=t,this._readableState.encoding=this._readableState.decoder.encoding;for(var n=this._readableState.buffer.head,r="";null!==n;)r+=t.write(n.data),n=n.next;return this._readableState.buffer.clear(),""!==r&&this._readableState.buffer.push(r),this._readableState.length=r.length,this};var k=1073741824;function E(e,t){return e<=0||0===t.length&&t.ended?0:t.objectMode?1:e!=e?t.flowing&&t.length?t.buffer.head.data.length:t.length:(e>t.highWaterMark&&(t.highWaterMark=function(e){return e>=k?e=k:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function C(e){var n=e._readableState;t("emitReadable",n.needReadable,n.emittedReadable),n.needReadable=!1,n.emittedReadable||(t("emitReadable",n.flowing),n.emittedReadable=!0,process.nextTick($,e))}function $(e){var n=e._readableState;t("emitReadable_",n.destroyed,n.length,n.ended),n.destroyed||!n.length&&!n.ended||(e.emit("readable"),n.emittedReadable=!1),n.needReadable=!n.flowing&&!n.ended&&n.length<=n.highWaterMark,j(e)}function O(e,t){t.readingMore||(t.readingMore=!0,process.nextTick(A,e,t))}function A(e,n){for(;!n.reading&&!n.ended&&(n.length<n.highWaterMark||n.flowing&&0===n.length);){var r=n.length;if(t("maybeReadMore read 0"),e.read(0),r===n.length)break}n.readingMore=!1}function M(e){var t=e._readableState;t.readableListening=e.listenerCount("readable")>0,t.resumeScheduled&&!t.paused?t.flowing=!0:e.listenerCount("data")>0&&e.resume()}function P(e){t("readable nexttick read 0"),e.read(0)}function D(e,n){t("resume",n.reading),n.reading||e.read(0),n.resumeScheduled=!1,e.emit("resume"),j(e),n.flowing&&!n.reading&&e.read(0)}function j(e){var n=e._readableState;for(t("flow",n.flowing);n.flowing&&null!==e.read(););}function R(e,t){return 0===t.length?null:(t.objectMode?n=t.buffer.shift():!e||e>=t.length?(n=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):n=t.buffer.consume(e,t.decoder),n);var n}function L(e){var n=e._readableState;t("endReadable",n.endEmitted),n.endEmitted||(n.ended=!0,process.nextTick(F,n,e))}function F(e,n){if(t("endReadableNT",e.endEmitted,e.length),!e.endEmitted&&0===e.length&&(e.endEmitted=!0,n.readable=!1,n.emit("end"),e.autoDestroy)){var r=n._writableState;(!r||r.autoDestroy&&r.finished)&&n.destroy()}}function U(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1}return _.prototype.read=function(e){t("read",e),e=parseInt(e,10);var n=this._readableState,r=e;if(0!==e&&(n.emittedReadable=!1),0===e&&n.needReadable&&((0!==n.highWaterMark?n.length>=n.highWaterMark:n.length>0)||n.ended))return t("read: emitReadable",n.length,n.ended),0===n.length&&n.ended?L(this):C(this),null;if(0===(e=E(e,n))&&n.ended)return 0===n.length&&L(this),null;var i,o=n.needReadable;return t("need readable",o),(0===n.length||n.length-e<n.highWaterMark)&&t("length less than watermark",o=!0),n.ended||n.reading?t("reading or ended",o=!1):o&&(t("do read"),n.reading=!0,n.sync=!0,0===n.length&&(n.needReadable=!0),this._read(n.highWaterMark),n.sync=!1,n.reading||(e=E(r,n))),null===(i=e>0?R(e,n):null)?(n.needReadable=n.length<=n.highWaterMark,e=0):(n.length-=e,n.awaitDrain=0),0===n.length&&(n.ended||(n.needReadable=!0),r!==e&&n.ended&&L(this)),null!==i&&this.emit("data",i),i},_.prototype._read=function(){b(this,new y("_read()"))},_.prototype.pipe=function(e,r){var i=this,o=this._readableState;switch(o.pipesCount){case 0:o.pipes=e;break;case 1:o.pipes=[o.pipes,e];break;default:o.pipes.push(e)}o.pipesCount+=1,t("pipe count=%d opts=%j",o.pipesCount,r);var s=r&&!1===r.end||e===process.stdout||e===process.stderr?p:a;function a(){t("onend"),e.end()}o.endEmitted?process.nextTick(s):i.once("end",s),e.on("unpipe",(function n(r,s){t("onunpipe"),r===i&&s&&!1===s.hasUnpiped&&(s.hasUnpiped=!0,t("cleanup"),e.removeListener("close",h),e.removeListener("finish",f),e.removeListener("drain",c),e.removeListener("error",d),e.removeListener("unpipe",n),i.removeListener("end",a),i.removeListener("end",p),i.removeListener("data",u),l=!0,!o.awaitDrain||e._writableState&&!e._writableState.needDrain||c())}));var c=function(e){return function(){var r=e._readableState;t("pipeOnDrain",r.awaitDrain),r.awaitDrain&&r.awaitDrain--,0===r.awaitDrain&&n(e,"data")&&(r.flowing=!0,j(e))}}(i);e.on("drain",c);var l=!1;function u(n){t("ondata");var r=e.write(n);t("dest.write",r),!1===r&&((1===o.pipesCount&&o.pipes===e||o.pipesCount>1&&-1!==U(o.pipes,e))&&!l&&(t("false write response, pause",o.awaitDrain),o.awaitDrain++),i.pause())}function d(r){t("onerror",r),p(),e.removeListener("error",d),0===n(e,"error")&&b(e,r)}function h(){e.removeListener("finish",f),p()}function f(){t("onfinish"),e.removeListener("close",h),p()}function p(){t("unpipe"),i.unpipe(e)}return i.on("data",u),function(e,t,n){if("function"==typeof e.prependListener)return e.prependListener(t,n);e._events&&e._events[t]?Array.isArray(e._events[t])?e._events[t].unshift(n):e._events[t]=[n,e._events[t]]:e.on(t,n)}(e,"error",d),e.once("close",h),e.once("finish",f),e.emit("pipe",i),o.flowing||(t("pipe resume"),i.resume()),e},_.prototype.unpipe=function(e){var t=this._readableState,n={hasUnpiped:!1};if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes||(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,n)),this;if(!e){var r=t.pipes,i=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var o=0;o<i;o++)r[o].emit("unpipe",this,{hasUnpiped:!1});return this}var s=U(t.pipes,e);return-1===s||(t.pipes.splice(s,1),t.pipesCount-=1,1===t.pipesCount&&(t.pipes=t.pipes[0]),e.emit("unpipe",this,n)),this},_.prototype.on=function(e,n){var i=r.prototype.on.call(this,e,n),o=this._readableState;return"data"===e?(o.readableListening=this.listenerCount("readable")>0,!1!==o.flowing&&this.resume()):"readable"===e&&(o.endEmitted||o.readableListening||(o.readableListening=o.needReadable=!0,o.flowing=!1,o.emittedReadable=!1,t("on readable",o.length,o.reading),o.length?C(this):o.reading||process.nextTick(P,this))),i},_.prototype.addListener=_.prototype.on,_.prototype.removeListener=function(e,t){var n=r.prototype.removeListener.call(this,e,t);return"readable"===e&&process.nextTick(M,this),n},_.prototype.removeAllListeners=function(e){var t=r.prototype.removeAllListeners.apply(this,arguments);return"readable"!==e&&void 0!==e||process.nextTick(M,this),t},_.prototype.resume=function(){var e=this._readableState;return e.flowing||(t("resume"),e.flowing=!e.readableListening,function(e,t){t.resumeScheduled||(t.resumeScheduled=!0,process.nextTick(D,e,t))}(this,e)),e.paused=!1,this},_.prototype.pause=function(){return t("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(t("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},_.prototype.wrap=function(e){var n=this,r=this._readableState,i=!1;for(var o in e.on("end",(function(){if(t("wrapped end"),r.decoder&&!r.ended){var e=r.decoder.end();e&&e.length&&n.push(e)}n.push(null)})),e.on("data",(function(o){t("wrapped data"),r.decoder&&(o=r.decoder.write(o)),r.objectMode&&null==o||(r.objectMode||o&&o.length)&&(n.push(o)||(i=!0,e.pause()))})),e)void 0===this[o]&&"function"==typeof e[o]&&(this[o]=function(t){return function(){return e[t].apply(e,arguments)}}(o));for(var s=0;s<w.length;s++)e.on(w[s],this.emit.bind(this,w[s]));return this._read=function(n){t("wrapped _read",n),i&&(i=!1,e.resume())},this},"function"==typeof Symbol&&(_.prototype[Symbol.asyncIterator]=function(){return void 0===l&&(l=function(){if(Xf)return Zf;var e;function t(e,t,n){return(t=function(e){var t=function(e){if("object"!=typeof e||null===e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:String(t)}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}Xf=1;var n=up(),r=Symbol("lastResolve"),i=Symbol("lastReject"),o=Symbol("error"),s=Symbol("ended"),a=Symbol("lastPromise"),c=Symbol("handlePromise"),l=Symbol("stream");function u(e,t){return{value:e,done:t}}function d(e){var t=e[r];if(null!==t){var n=e[l].read();null!==n&&(e[a]=null,e[r]=null,e[i]=null,t(u(n,!1)))}}function h(e){process.nextTick(d,e)}var f=Object.getPrototypeOf((function(){})),p=Object.setPrototypeOf((e={get stream(){return this[l]},next:function(){var e=this,t=this[o];if(null!==t)return Promise.reject(t);if(this[s])return Promise.resolve(u(void 0,!0));if(this[l].destroyed)return new Promise((function(t,n){process.nextTick((function(){e[o]?n(e[o]):t(u(void 0,!0))}))}));var n,r=this[a];if(r)n=new Promise(function(e,t){return function(n,r){e.then((function(){t[s]?n(u(void 0,!0)):t[c](n,r)}),r)}}(r,this));else{var i=this[l].read();if(null!==i)return Promise.resolve(u(i,!1));n=new Promise(this[c])}return this[a]=n,n}},t(e,Symbol.asyncIterator,(function(){return this})),t(e,"return",(function(){var e=this;return new Promise((function(t,n){e[l].destroy(null,(function(e){e?n(e):t(u(void 0,!0))}))}))})),e),f);return Zf=function(e){var d,f=Object.create(p,(t(d={},l,{value:e,writable:!0}),t(d,r,{value:null,writable:!0}),t(d,i,{value:null,writable:!0}),t(d,o,{value:null,writable:!0}),t(d,s,{value:e._readableState.endEmitted,writable:!0}),t(d,c,{value:function(e,t){var n=f[l].read();n?(f[a]=null,f[r]=null,f[i]=null,e(u(n,!1))):(f[r]=e,f[i]=t)},writable:!0}),d));return f[a]=null,n(e,(function(e){if(e&&"ERR_STREAM_PREMATURE_CLOSE"!==e.code){var t=f[i];return null!==t&&(f[a]=null,f[r]=null,f[i]=null,t(e)),void(f[o]=e)}var n=f[r];null!==n&&(f[a]=null,f[r]=null,f[i]=null,n(u(void 0,!0))),f[s]=!0})),e.on("readable",h.bind(null,f)),f},Zf}()),l(this)}),Object.defineProperty(_.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(_.prototype,"readableBuffer",{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(_.prototype,"readableFlowing",{enumerable:!1,get:function(){return this._readableState.flowing},set:function(e){this._readableState&&(this._readableState.flowing=e)}}),_._fromList=R,Object.defineProperty(_.prototype,"readableLength",{enumerable:!1,get:function(){return this._readableState.length}}),"function"==typeof Symbol&&(_.from=function(e,t){return void 0===u&&(u=function(){if(ep)return Qf;function e(e,t,n,r,i,o,s){try{var a=e[o](s),c=a.value}catch(e){return void n(e)}a.done?t(c):Promise.resolve(c).then(r,i)}function t(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function n(e,t,n){return(t=function(e){var t=function(e){if("object"!=typeof e||null===e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:String(t)}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}ep=1;var r=Rf().codes.ERR_INVALID_ARG_TYPE;return Qf=function(i,o,s){var a;if(o&&"function"==typeof o.next)a=o;else if(o&&o[Symbol.asyncIterator])a=o[Symbol.asyncIterator]();else{if(!o||!o[Symbol.iterator])throw new r("iterable",["Iterable"],o);a=o[Symbol.iterator]()}var c=new i(function(e){for(var r=1;r<arguments.length;r++){var i=null!=arguments[r]?arguments[r]:{};r%2?t(Object(i),!0).forEach((function(t){n(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):t(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}({objectMode:!0},s)),l=!1;function u(){return d.apply(this,arguments)}function d(){var t;return t=function*(){try{var e=yield a.next(),t=e.value;e.done?c.push(null):c.push(yield t)?u():l=!1}catch(e){c.destroy(e)}},d=function(){var n=this,r=arguments;return new Promise((function(i,o){var s=t.apply(n,r);function a(t){e(s,i,o,a,c,"next",t)}function c(t){e(s,i,o,a,c,"throw",t)}a(void 0)}))},d.apply(this,arguments)}return c._read=function(){l||(l=!0,u())},c},Qf}()),u(_,e,t)}),tp}function hp(){if(ip)return rp;ip=1;var e=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t};rp=s;var t=dp(),n=fp();Yf()(s,t);for(var r=e(n.prototype),i=0;i<r.length;i++){var o=r[i];s.prototype[o]||(s.prototype[o]=n.prototype[o])}function s(e){if(!(this instanceof s))return new s(e);t.call(this,e),n.call(this,e),this.allowHalfOpen=!0,e&&(!1===e.readable&&(this.readable=!1),!1===e.writable&&(this.writable=!1),!1===e.allowHalfOpen&&(this.allowHalfOpen=!1,this.once("end",a)))}function a(){this._writableState.ended||process.nextTick(c,this)}function c(e){e.end()}return Object.defineProperty(s.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(s.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(s.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(s.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._readableState&&void 0!==this._writableState&&this._readableState.destroyed&&this._writableState.destroyed},set:function(e){void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed=e,this._writableState.destroyed=e)}}),rp}function fp(){if(sp)return op;function e(e){var t=this;this.next=null,this.entry=null,this.finish=function(){!function(e,t){var n=e.entry;for(e.entry=null;n;){var r=n.callback;t.pendingcb--,r(undefined),n=n.next}t.corkedRequestsFree.next=e}(t,e)}}var t;sp=1,op=_,_.WritableState=S;var n,r={deprecate:If?_f:(If=1,_f=i.deprecate)},o=Tf(),s=N.Buffer,a=(void 0!==id?id:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{}).Uint8Array||function(){},c=Af(),l=Lf().getHighWaterMark,u=Rf().codes,d=u.ERR_INVALID_ARG_TYPE,h=u.ERR_METHOD_NOT_IMPLEMENTED,f=u.ERR_MULTIPLE_CALLBACK,p=u.ERR_STREAM_CANNOT_PIPE,g=u.ERR_STREAM_DESTROYED,m=u.ERR_STREAM_NULL_VALUES,y=u.ERR_STREAM_WRITE_AFTER_END,v=u.ERR_UNKNOWN_ENCODING,b=c.errorOrDestroy;function w(){}function S(n,r,i){t=t||hp(),n=n||{},"boolean"!=typeof i&&(i=r instanceof t),this.objectMode=!!n.objectMode,i&&(this.objectMode=this.objectMode||!!n.writableObjectMode),this.highWaterMark=l(this,n,"writableHighWaterMark",i),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var o=!1===n.decodeStrings;this.decodeStrings=!o,this.defaultEncoding=n.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){!function(e,t){var n=e._writableState,r=n.sync,i=n.writecb;if("function"!=typeof i)throw new f;if(function(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}(n),t)!function(e,t,n,r,i){--t.pendingcb,n?(process.nextTick(i,r),process.nextTick($,e,t),e._writableState.errorEmitted=!0,b(e,r)):(i(r),e._writableState.errorEmitted=!0,b(e,r),$(e,t))}(e,n,r,t,i);else{var o=E(n)||e.destroyed;o||n.corked||n.bufferProcessing||!n.bufferedRequest||k(e,n),r?process.nextTick(x,e,n,o,i):x(e,n,o,i)}}(r,e)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!1!==n.emitClose,this.autoDestroy=!!n.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new e(this)}function _(e){var r=this instanceof(t=t||hp());if(!r&&!n.call(_,this))return new _(e);this._writableState=new S(e,this,r),this.writable=!0,e&&("function"==typeof e.write&&(this._write=e.write),"function"==typeof e.writev&&(this._writev=e.writev),"function"==typeof e.destroy&&(this._destroy=e.destroy),"function"==typeof e.final&&(this._final=e.final)),o.call(this)}function I(e,t,n,r,i,o,s){t.writelen=r,t.writecb=s,t.writing=!0,t.sync=!0,t.destroyed?t.onwrite(new g("write")):n?e._writev(i,t.onwrite):e._write(i,o,t.onwrite),t.sync=!1}function x(e,t,n,r){n||function(e,t){0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}(e,t),t.pendingcb--,r(),$(e,t)}function k(t,n){n.bufferProcessing=!0;var r=n.bufferedRequest;if(t._writev&&r&&r.next){var i=n.bufferedRequestCount,o=new Array(i),s=n.corkedRequestsFree;s.entry=r;for(var a=0,c=!0;r;)o[a]=r,r.isBuf||(c=!1),r=r.next,a+=1;o.allBuffers=c,I(t,n,!0,n.length,o,"",s.finish),n.pendingcb++,n.lastBufferedRequest=null,s.next?(n.corkedRequestsFree=s.next,s.next=null):n.corkedRequestsFree=new e(n),n.bufferedRequestCount=0}else{for(;r;){var l=r.chunk,u=r.encoding,d=r.callback;if(I(t,n,!1,n.objectMode?1:l.length,l,u,d),r=r.next,n.bufferedRequestCount--,n.writing)break}null===r&&(n.lastBufferedRequest=null)}n.bufferedRequest=r,n.bufferProcessing=!1}function E(e){return e.ending&&0===e.length&&null===e.bufferedRequest&&!e.finished&&!e.writing}function C(e,t){e._final((function(n){t.pendingcb--,n&&b(e,n),t.prefinished=!0,e.emit("prefinish"),$(e,t)}))}function $(e,t){var n=E(t);if(n&&(function(e,t){t.prefinished||t.finalCalled||("function"!=typeof e._final||t.destroyed?(t.prefinished=!0,e.emit("prefinish")):(t.pendingcb++,t.finalCalled=!0,process.nextTick(C,e,t)))}(e,t),0===t.pendingcb&&(t.finished=!0,e.emit("finish"),t.autoDestroy))){var r=e._readableState;(!r||r.autoDestroy&&r.endEmitted)&&e.destroy()}return n}return Yf()(_,o),S.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(S.prototype,"buffer",{get:r.deprecate((function(){return this.getBuffer()}),"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(e){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(n=Function.prototype[Symbol.hasInstance],Object.defineProperty(_,Symbol.hasInstance,{value:function(e){return!!n.call(this,e)||this===_&&e&&e._writableState instanceof S}})):n=function(e){return e instanceof this},_.prototype.pipe=function(){b(this,new p)},_.prototype.write=function(e,t,n){var r,i=this._writableState,o=!1,c=!i.objectMode&&(r=e,s.isBuffer(r)||r instanceof a);return c&&!s.isBuffer(e)&&(e=function(e){return s.from(e)}(e)),"function"==typeof t&&(n=t,t=null),c?t="buffer":t||(t=i.defaultEncoding),"function"!=typeof n&&(n=w),i.ending?function(e,t){var n=new y;b(e,n),process.nextTick(t,n)}(this,n):(c||function(e,t,n,r){var i;return null===n?i=new m:"string"==typeof n||t.objectMode||(i=new d("chunk",["string","Buffer"],n)),!i||(b(e,i),process.nextTick(r,i),!1)}(this,i,e,n))&&(i.pendingcb++,o=function(e,t,n,r,i,o){if(!n){var a=function(e,t,n){return e.objectMode||!1===e.decodeStrings||"string"!=typeof t||(t=s.from(t,n)),t}(t,r,i);r!==a&&(n=!0,i="buffer",r=a)}var c=t.objectMode?1:r.length;t.length+=c;var l=t.length<t.highWaterMark;if(l||(t.needDrain=!0),t.writing||t.corked){var u=t.lastBufferedRequest;t.lastBufferedRequest={chunk:r,encoding:i,isBuf:n,callback:o,next:null},u?u.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1}else I(e,t,!1,c,r,i,o);return l}(this,i,c,e,t,n)),o},_.prototype.cork=function(){this._writableState.corked++},_.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,e.writing||e.corked||e.bufferProcessing||!e.bufferedRequest||k(this,e))},_.prototype.setDefaultEncoding=function(e){if("string"==typeof e&&(e=e.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new v(e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(_.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(_.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),_.prototype._write=function(e,t,n){n(new h("_write()"))},_.prototype._writev=null,_.prototype.end=function(e,t,n){var r=this._writableState;return"function"==typeof e?(n=e,e=null,t=null):"function"==typeof t&&(n=t,t=null),null!=e&&this.write(e,t),r.corked&&(r.corked=1,this.uncork()),r.ending||function(e,t,n){t.ending=!0,$(e,t),n&&(t.finished?process.nextTick(n):e.once("finish",n)),t.ended=!0,e.writable=!1}(this,r,n),this},Object.defineProperty(_.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(_.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),_.prototype.destroy=c.destroy,_.prototype._undestroy=c.undestroy,_.prototype._destroy=function(e,t){t(e)},op}const pp=i,gp=fp(),{LEVEL:mp}=th,yp=Nf.exports=function(e={}){gp.call(this,{objectMode:!0,highWaterMark:e.highWaterMark}),this.format=e.format,this.level=e.level,this.handleExceptions=e.handleExceptions,this.handleRejections=e.handleRejections,this.silent=e.silent,e.log&&(this.log=e.log),e.logv&&(this.logv=e.logv),e.close&&(this.close=e.close),this.once("pipe",(e=>{this.levels=e.levels,this.parent=e})),this.once("unpipe",(e=>{e===this.parent&&(this.parent=null,this.close&&this.close())}))};pp.inherits(yp,gp),yp.prototype._write=function(e,t,n){if(this.silent||!0===e.exception&&!this.handleExceptions)return n(null);const r=this.level||this.parent&&this.parent.level;if(!r||this.levels[r]>=this.levels[e[mp]]){if(e&&!this.format)return this.log(e,n);let t,r;try{r=this.format.transform(Object.assign({},e),this.format.options)}catch(e){t=e}if(t||!r){if(n(),t)throw t;return}return this.log(r,n)}return this._writableState.sync=!1,n(null)},yp.prototype._writev=function(e,t){if(this.logv){const n=e.filter(this._accept,this);return n.length?this.logv(n,t):t(null)}for(let n=0;n<e.length;n++){if(!this._accept(e[n]))continue;if(e[n].chunk&&!this.format){this.log(e[n].chunk,e[n].callback);continue}let r,i;try{i=this.format.transform(Object.assign({},e[n].chunk),this.format.options)}catch(e){r=e}if(r||!i){if(e[n].callback(),r)throw t(null),r}else this.log(i,e[n].callback)}return t(null)},yp.prototype._accept=function(e){const t=e.chunk;if(this.silent)return!1;const n=this.level||this.parent&&this.parent.level;return!(!0!==t.exception&&n&&!(this.levels[n]>=this.levels[t[mp]])||!this.handleExceptions&&!0===t.exception)},yp.prototype._nop=function(){};var vp=Nf.exports,bp={exports:{}};const wp=i,{LEVEL:Sp}=th,_p=vp,Ip=bp.exports=function(e={}){if(_p.call(this,e),!e.transport||"function"!=typeof e.transport.log)throw new Error("Invalid transport, must be an object with a log method.");this.transport=e.transport,this.level=this.level||e.transport.level,this.handleExceptions=this.handleExceptions||e.transport.handleExceptions,this._deprecated(),this.transport.__winstonError||(this.transport.__winstonError=function(e){this.emit("error",e,this.transport)}.bind(this),this.transport.on("error",this.transport.__winstonError))};wp.inherits(Ip,_p),Ip.prototype._write=function(e,t,n){if(this.silent||!0===e.exception&&!this.handleExceptions)return n(null);(!this.level||this.levels[this.level]>=this.levels[e[Sp]])&&this.transport.log(e[Sp],e.message,e,this._nop),n(null)},Ip.prototype._writev=function(e,t){for(let t=0;t<e.length;t++)this._accept(e[t])&&(this.transport.log(e[t].chunk[Sp],e[t].chunk.message,e[t].chunk,this._nop),e[t].callback());return t(null)},Ip.prototype._deprecated=function(){console.error([`${this.transport.name} is a legacy winston transport. Consider upgrading: `,"- Upgrade docs: https://github.com/winstonjs/winston/blob/master/UPGRADE-3.0.md"].join("\n"))},Ip.prototype.close=function(){this.transport.close&&this.transport.close(),this.transport.__winstonError&&(this.transport.removeListener("error",this.transport.__winstonError),this.transport.__winstonError=null)};var xp=bp.exports;Of.exports=vp,Of.exports.LegacyTransportStream=xp;var kp,Ep,Cp=Of.exports,$p={exports:{}},Op={exports:{}},Np={exports:{}};!function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return e&&"number"==typeof e.length&&e.length>=0&&e.length%1==0},e.exports=t.default}(Np,Np.exports);var Tp=Np.exports,Ap={},Mp={exports:{}},Pp={exports:{}};!function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return function(...t){var n=t.pop();return e.call(this,t,n)}},e.exports=t.default}(Pp,Pp.exports);var Dp=Pp.exports,jp={};Object.defineProperty(jp,"__esModule",{value:!0}),jp.fallback=Gp,jp.wrap=Vp;var Rp,Lp,Fp,Up=jp.hasQueueMicrotask="function"==typeof queueMicrotask&&queueMicrotask,Bp=jp.hasSetImmediate="function"==typeof setImmediate&&setImmediate,Wp=jp.hasNextTick="object"==typeof process&&"function"==typeof process.nextTick;function Gp(e){setTimeout(e,0)}function Vp(e){return(t,...n)=>e((()=>t(...n)))}function Yp(){if(Fp)return Ap;Fp=1,Object.defineProperty(Ap,"__esModule",{value:!0}),Ap.isAsyncIterable=Ap.isAsyncGenerator=Ap.isAsync=void 0;var e,t=(Lp||(Lp=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return(0,i.isAsync)(e)?function(...t){const n=t.pop();return s(e.apply(this,t),n)}:(0,n.default)((function(t,n){var r;try{r=e.apply(this,t)}catch(e){return n(e)}if(r&&"function"==typeof r.then)return s(r,n);n(null,r)}))};var n=o(Dp),r=o(jp),i=Yp();function o(e){return e&&e.__esModule?e:{default:e}}function s(e,t){return e.then((e=>{a(t,null,e)}),(e=>{a(t,e&&(e instanceof Error||e.message)?e:new Error(e))}))}function a(e,t,n){try{e(t,n)}catch(e){(0,r.default)((e=>{throw e}),e)}}e.exports=t.default}(Mp,Mp.exports)),Mp.exports),n=(e=t)&&e.__esModule?e:{default:e};function r(e){return"AsyncFunction"===e[Symbol.toStringTag]}return Ap.default=function(e){if("function"!=typeof e)throw new Error("expected a function");return r(e)?(0,n.default)(e):e},Ap.isAsync=r,Ap.isAsyncGenerator=function(e){return"AsyncGenerator"===e[Symbol.toStringTag]},Ap.isAsyncIterable=function(e){return"function"==typeof e[Symbol.asyncIterator]},Ap}Rp=Up?queueMicrotask:Bp?setImmediate:Wp?process.nextTick:Gp,jp.default=Vp(Rp);var Hp={exports:{}};!function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t){if(t||(t=e.length),!t)throw new Error("arity is undefined");return function(...n){return"function"==typeof n[t-1]?e.apply(this,n):new Promise(((r,i)=>{n[t-1]=(e,...t)=>{if(e)return i(e);r(t.length>1?t:t[0])},e.apply(this,n)}))}},e.exports=t.default}(Hp,Hp.exports);var zp,qp=Hp.exports,Kp={exports:{}},Jp={exports:{}},Zp={exports:{}},Xp={exports:{}};!function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){function t(...t){if(null!==e){var n=e;e=null,n.apply(this,t)}}return Object.assign(t,e),t},e.exports=t.default}(Xp,Xp.exports);var Qp=Xp.exports,eg={exports:{}},tg={exports:{}};!function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return e[Symbol.iterator]&&e[Symbol.iterator]()},e.exports=t.default}(tg,tg.exports);var ng=tg.exports;!function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){if((0,n.default)(e))return function(e){var t=-1,n=e.length;return function(){return++t<n?{value:e[t],key:t}:null}}(e);var t,i,o,s,a=(0,r.default)(e);return a?function(e){var t=-1;return function(){var n=e.next();return n.done?null:(t++,{value:n.value,key:t})}}(a):(i=(t=e)?Object.keys(t):[],o=-1,s=i.length,function e(){var n=i[++o];return"__proto__"===n?e():o<s?{value:t[n],key:n}:null})};var n=i(Tp),r=i(ng);function i(e){return e&&e.__esModule?e:{default:e}}e.exports=t.default}(eg,eg.exports);var rg=eg.exports,ig={exports:{}};!function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return function(...t){if(null===e)throw new Error("Callback was already called.");var n=e;e=null,n.apply(this,t)}},e.exports=t.default}(ig,ig.exports);var og=ig.exports,sg={exports:{}},ag={exports:{}};!function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default={},e.exports=t.default}(ag,ag.exports);var cg=ag.exports;!function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t,n,i){let o=!1,s=!1,a=!1,c=0,l=0;function u(){c>=t||a||o||(a=!0,e.next().then((({value:e,done:t})=>{if(!s&&!o){if(a=!1,t)return o=!0,void(c<=0&&i(null));c++,n(e,l,d),l++,u()}})).catch(h))}function d(e,t){if(c-=1,!s)return e?h(e):!1===e?(o=!0,void(s=!0)):t===r.default||o&&c<=0?(o=!0,i(null)):void u()}function h(e){s||(a=!1,o=!0,i(e))}u()};var n,r=(n=cg)&&n.__esModule?n:{default:n};e.exports=t.default}(sg,sg.exports);var lg=sg.exports;!function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var n=c(Qp),r=c(rg),i=c(og),o=Yp(),s=c(lg),a=c(cg);function c(e){return e&&e.__esModule?e:{default:e}}t.default=e=>(t,c,l)=>{if(l=(0,n.default)(l),e<=0)throw new RangeError("concurrency limit cannot be less than 1");if(!t)return l(null);if((0,o.isAsyncGenerator)(t))return(0,s.default)(t,e,c,l);if((0,o.isAsyncIterable)(t))return(0,s.default)(t[Symbol.asyncIterator](),e,c,l);var u=(0,r.default)(t),d=!1,h=!1,f=0,p=!1;function g(e,t){if(!h)if(f-=1,e)d=!0,l(e);else if(!1===e)d=!0,h=!0;else{if(t===a.default||d&&f<=0)return d=!0,l(null);p||m()}}function m(){for(p=!0;f<e&&!d;){var t=u();if(null===t)return d=!0,void(f<=0&&l(null));f+=1,c(t.value,t.key,(0,i.default)(g))}p=!1}m()},e.exports=t.default}(Zp,Zp.exports);var ug=Zp.exports;!function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var n=o(ug),r=o(Yp()),i=o(qp);function o(e){return e&&e.__esModule?e:{default:e}}t.default=(0,i.default)((function(e,t,i,o){return(0,n.default)(t)(e,(0,r.default)(i),o)}),4),e.exports=t.default}(Jp,Jp.exports);var dg,hg,fg=Jp.exports;var pg,gg,mg,yg,vg,bg,wg={exports:{}};function Sg(){if(gg)return pg;gg=1,pg=a;var e=Rf().codes,t=e.ERR_METHOD_NOT_IMPLEMENTED,n=e.ERR_MULTIPLE_CALLBACK,r=e.ERR_TRANSFORM_ALREADY_TRANSFORMING,i=e.ERR_TRANSFORM_WITH_LENGTH_0,o=hp();function s(e,t){var r=this._transformState;r.transforming=!1;var i=r.writecb;if(null===i)return this.emit("error",new n);r.writechunk=null,r.writecb=null,null!=t&&this.push(t),i(e);var o=this._readableState;o.reading=!1,(o.needReadable||o.length<o.highWaterMark)&&this._read(o.highWaterMark)}function a(e){if(!(this instanceof a))return new a(e);o.call(this,e),this._transformState={afterTransform:s.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,e&&("function"==typeof e.transform&&(this._transform=e.transform),"function"==typeof e.flush&&(this._flush=e.flush)),this.on("prefinish",c)}function c(){var e=this;"function"!=typeof this._flush||this._readableState.destroyed?l(this,null,null):this._flush((function(t,n){l(e,t,n)}))}function l(e,t,n){if(t)return e.emit("error",t);if(null!=n&&e.push(n),e._writableState.length)throw new i;if(e._transformState.transforming)throw new r;return e.push(null)}return Yf()(a,o),a.prototype.push=function(e,t){return this._transformState.needTransform=!1,o.prototype.push.call(this,e,t)},a.prototype._transform=function(e,n,r){r(new t("_transform()"))},a.prototype._write=function(e,t,n){var r=this._transformState;if(r.writecb=n,r.writechunk=e,r.writeencoding=t,!r.transforming){var i=this._readableState;(r.needTransform||i.needReadable||i.length<i.highWaterMark)&&this._read(i.highWaterMark)}},a.prototype._read=function(){var e=this._transformState;null===e.writechunk||e.transforming?e.needTransform=!0:(e.transforming=!0,this._transform(e.writechunk,e.writeencoding,e.afterTransform))},a.prototype._destroy=function(e,t){o.prototype._destroy.call(this,e,(function(e){t(e)}))},pg}!function(e,t){var n=O;"disable"===process.env.READABLE_STREAM&&n?(e.exports=n.Readable,Object.assign(e.exports,n),e.exports.Stream=n):((t=e.exports=dp()).Stream=n||t,t.Readable=t,t.Writable=fp(),t.Duplex=hp(),t.Transform=Sg(),t.PassThrough=function(){if(yg)return mg;yg=1,mg=t;var e=Sg();function t(n){if(!(this instanceof t))return new t(n);e.call(this,n)}return Yf()(t,e),t.prototype._transform=function(e,t,n){n(null,e)},mg}(),t.finished=up(),t.pipeline=function(){if(bg)return vg;var e;bg=1;var t=Rf().codes,n=t.ERR_MISSING_ARGS,r=t.ERR_STREAM_DESTROYED;function i(e){if(e)throw e}function o(e){e()}function s(e,t){return e.pipe(t)}return vg=function(){for(var t=arguments.length,a=new Array(t),c=0;c<t;c++)a[c]=arguments[c];var l,u=function(e){return e.length?"function"!=typeof e[e.length-1]?i:e.pop():i}(a);if(Array.isArray(a[0])&&(a=a[0]),a.length<2)throw new n("streams");var d=a.map((function(t,n){var i=n<a.length-1;return function(t,n,i,o){o=function(e){var t=!1;return function(){t||(t=!0,e.apply(void 0,arguments))}}(o);var s=!1;t.on("close",(function(){s=!0})),void 0===e&&(e=up()),e(t,{readable:n,writable:i},(function(e){if(e)return o(e);s=!0,o()}));var a=!1;return function(e){if(!s&&!a)return a=!0,function(e){return e.setHeader&&"function"==typeof e.abort}(t)?t.abort():"function"==typeof t.destroy?t.destroy():void o(e||new r("pipe"))}}(t,i,n>0,(function(e){l||(l=e),e&&d.forEach(o),i||(d.forEach(o),u(l))}))}));return a.reduce(s)},vg}())}(wg,wg.exports);var _g,Ig,xg,kg,Eg=wg.exports,Cg={exports:{}};function $g(){if(Ig)return _g;Ig=1;var e=[],t=[],n=function(){};function r(t){return!~e.indexOf(t)&&(e.push(t),!0)}function i(e){n=e}function o(t){for(var n=[],r=0;r<e.length;r++)if(e[r].async)n.push(e[r]);else if(e[r](t))return!0;return!!n.length&&new Promise((function(e){Promise.all(n.map((function(e){return e(t)}))).then((function(t){e(t.some(Boolean))}))}))}function s(e){return!~t.indexOf(e)&&(t.push(e),!0)}function a(){n.apply(n,arguments)}function c(e){for(var n=0;n<t.length;n++)e=t[n].apply(t[n],arguments);return e}function l(e,t){var n=Object.prototype.hasOwnProperty;for(var r in t)n.call(t,r)&&(e[r]=t[r]);return e}function u(e){return e.enabled=!1,e.modify=s,e.set=i,e.use=r,l((function(){return!1}),e)}function d(e){return e.enabled=!0,e.modify=s,e.set=i,e.use=r,l((function(){var t=Array.prototype.slice.call(arguments,0);return a.call(a,e,c(t,e)),!0}),e)}return _g=function(e){return e.introduce=l,e.enabled=o,e.process=c,e.modify=s,e.write=a,e.nope=u,e.yep=d,e.set=i,e.use=r,e}}var Og,Ng,Tg,Ag,Mg,Pg,Dg={exports:{}},jg={exports:{}};function Rg(){if(Pg)return Dg.exports;Pg=1;var e=Ng?Og:(Ng=1,Og={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]}),t=function(){if(Mg)return jg.exports;Mg=1;var e=Ag?Tg:(Ag=1,Tg=function(e){return!(!e||"string"==typeof e)&&(e instanceof Array||Array.isArray(e)||e.length>=0&&(e.splice instanceof Function||Object.getOwnPropertyDescriptor(e,e.length-1)&&"String"!==e.constructor.name))}),t=Array.prototype.concat,n=Array.prototype.slice,r=jg.exports=function(r){for(var i=[],o=0,s=r.length;o<s;o++){var a=r[o];e(a)?i=t.call(i,n.call(a)):i.push(a)}return i};return r.wrap=function(e){return function(){return e(r(arguments))}},jg.exports}(),n=Object.hasOwnProperty,r=Object.create(null);for(var i in e)n.call(e,i)&&(r[e[i]]=i);var o=Dg.exports={to:{},get:{}};function s(e,t,n){return Math.min(Math.max(t,e),n)}function a(e){var t=Math.round(e).toString(16).toUpperCase();return t.length<2?"0"+t:t}return o.get=function(e){var t,n;switch(e.substring(0,3).toLowerCase()){case"hsl":t=o.get.hsl(e),n="hsl";break;case"hwb":t=o.get.hwb(e),n="hwb";break;default:t=o.get.rgb(e),n="rgb"}return t?{model:n,value:t}:null},o.get.rgb=function(t){if(!t)return null;var r,i,o,a=[0,0,0,1];if(r=t.match(/^#([a-f0-9]{6})([a-f0-9]{2})?$/i)){for(o=r[2],r=r[1],i=0;i<3;i++){var c=2*i;a[i]=parseInt(r.slice(c,c+2),16)}o&&(a[3]=parseInt(o,16)/255)}else if(r=t.match(/^#([a-f0-9]{3,4})$/i)){for(o=(r=r[1])[3],i=0;i<3;i++)a[i]=parseInt(r[i]+r[i],16);o&&(a[3]=parseInt(o+o,16)/255)}else if(r=t.match(/^rgba?\(\s*([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)\s*(?:[,|\/]\s*([+-]?[\d\.]+)(%?)\s*)?\)$/)){for(i=0;i<3;i++)a[i]=parseInt(r[i+1],0);r[4]&&(r[5]?a[3]=.01*parseFloat(r[4]):a[3]=parseFloat(r[4]))}else{if(!(r=t.match(/^rgba?\(\s*([+-]?[\d\.]+)\%\s*,?\s*([+-]?[\d\.]+)\%\s*,?\s*([+-]?[\d\.]+)\%\s*(?:[,|\/]\s*([+-]?[\d\.]+)(%?)\s*)?\)$/)))return(r=t.match(/^(\w+)$/))?"transparent"===r[1]?[0,0,0,0]:n.call(e,r[1])?((a=e[r[1]])[3]=1,a):null:null;for(i=0;i<3;i++)a[i]=Math.round(2.55*parseFloat(r[i+1]));r[4]&&(r[5]?a[3]=.01*parseFloat(r[4]):a[3]=parseFloat(r[4]))}for(i=0;i<3;i++)a[i]=s(a[i],0,255);return a[3]=s(a[3],0,1),a},o.get.hsl=function(e){if(!e)return null;var t=e.match(/^hsla?\(\s*([+-]?(?:\d{0,3}\.)?\d+)(?:deg)?\s*,?\s*([+-]?[\d\.]+)%\s*,?\s*([+-]?[\d\.]+)%\s*(?:[,|\/]\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/);if(t){var n=parseFloat(t[4]);return[(parseFloat(t[1])%360+360)%360,s(parseFloat(t[2]),0,100),s(parseFloat(t[3]),0,100),s(isNaN(n)?1:n,0,1)]}return null},o.get.hwb=function(e){if(!e)return null;var t=e.match(/^hwb\(\s*([+-]?\d{0,3}(?:\.\d+)?)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/);if(t){var n=parseFloat(t[4]);return[(parseFloat(t[1])%360+360)%360,s(parseFloat(t[2]),0,100),s(parseFloat(t[3]),0,100),s(isNaN(n)?1:n,0,1)]}return null},o.to.hex=function(){var e=t(arguments);return"#"+a(e[0])+a(e[1])+a(e[2])+(e[3]<1?a(Math.round(255*e[3])):"")},o.to.rgb=function(){var e=t(arguments);return e.length<4||1===e[3]?"rgb("+Math.round(e[0])+", "+Math.round(e[1])+", "+Math.round(e[2])+")":"rgba("+Math.round(e[0])+", "+Math.round(e[1])+", "+Math.round(e[2])+", "+e[3]+")"},o.to.rgb.percent=function(){var e=t(arguments),n=Math.round(e[0]/255*100),r=Math.round(e[1]/255*100),i=Math.round(e[2]/255*100);return e.length<4||1===e[3]?"rgb("+n+"%, "+r+"%, "+i+"%)":"rgba("+n+"%, "+r+"%, "+i+"%, "+e[3]+")"},o.to.hsl=function(){var e=t(arguments);return e.length<4||1===e[3]?"hsl("+e[0]+", "+e[1]+"%, "+e[2]+"%)":"hsla("+e[0]+", "+e[1]+"%, "+e[2]+"%, "+e[3]+")"},o.to.hwb=function(){var e=t(arguments),n="";return e.length>=4&&1!==e[3]&&(n=", "+e[3]),"hwb("+e[0]+", "+e[1]+"%, "+e[2]+"%"+n+")"},o.to.keyword=function(e){return r[e.slice(0,3)]},Dg.exports}var Lg,Fg,Ug,Bg,Wg,Gg,Vg,Yg,Hg,zg,qg,Kg,Jg,Zg,Xg,Qg,em,tm,nm,rm,im,om,sm,am,cm,lm,um,dm={exports:{}};function hm(){if(Ug)return dm.exports;Ug=1;var e=Fg?Lg:(Fg=1,Lg={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]}),t={};for(var n in e)e.hasOwnProperty(n)&&(t[e[n]]=n);var r=dm.exports={rgb:{channels:3,labels:"rgb"},hsl:{channels:3,labels:"hsl"},hsv:{channels:3,labels:"hsv"},hwb:{channels:3,labels:"hwb"},cmyk:{channels:4,labels:"cmyk"},xyz:{channels:3,labels:"xyz"},lab:{channels:3,labels:"lab"},lch:{channels:3,labels:"lch"},hex:{channels:1,labels:["hex"]},keyword:{channels:1,labels:["keyword"]},ansi16:{channels:1,labels:["ansi16"]},ansi256:{channels:1,labels:["ansi256"]},hcg:{channels:3,labels:["h","c","g"]},apple:{channels:3,labels:["r16","g16","b16"]},gray:{channels:1,labels:["gray"]}};for(var i in r)if(r.hasOwnProperty(i)){if(!("channels"in r[i]))throw new Error("missing channels property: "+i);if(!("labels"in r[i]))throw new Error("missing channel labels property: "+i);if(r[i].labels.length!==r[i].channels)throw new Error("channel and label counts mismatch: "+i);var o=r[i].channels,s=r[i].labels;delete r[i].channels,delete r[i].labels,Object.defineProperty(r[i],"channels",{value:o}),Object.defineProperty(r[i],"labels",{value:s})}return r.rgb.hsl=function(e){var t,n,r=e[0]/255,i=e[1]/255,o=e[2]/255,s=Math.min(r,i,o),a=Math.max(r,i,o),c=a-s;return a===s?t=0:r===a?t=(i-o)/c:i===a?t=2+(o-r)/c:o===a&&(t=4+(r-i)/c),(t=Math.min(60*t,360))<0&&(t+=360),n=(s+a)/2,[t,100*(a===s?0:n<=.5?c/(a+s):c/(2-a-s)),100*n]},r.rgb.hsv=function(e){var t,n,r,i,o,s=e[0]/255,a=e[1]/255,c=e[2]/255,l=Math.max(s,a,c),u=l-Math.min(s,a,c),d=function(e){return(l-e)/6/u+.5};return 0===u?i=o=0:(o=u/l,t=d(s),n=d(a),r=d(c),s===l?i=r-n:a===l?i=1/3+t-r:c===l&&(i=2/3+n-t),i<0?i+=1:i>1&&(i-=1)),[360*i,100*o,100*l]},r.rgb.hwb=function(e){var t=e[0],n=e[1],i=e[2];return[r.rgb.hsl(e)[0],1/255*Math.min(t,Math.min(n,i))*100,100*(i=1-1/255*Math.max(t,Math.max(n,i)))]},r.rgb.cmyk=function(e){var t,n=e[0]/255,r=e[1]/255,i=e[2]/255;return[100*((1-n-(t=Math.min(1-n,1-r,1-i)))/(1-t)||0),100*((1-r-t)/(1-t)||0),100*((1-i-t)/(1-t)||0),100*t]},r.rgb.keyword=function(n){var r=t[n];if(r)return r;var i,o,s,a=1/0;for(var c in e)if(e.hasOwnProperty(c)){var l=(o=n,s=e[c],Math.pow(o[0]-s[0],2)+Math.pow(o[1]-s[1],2)+Math.pow(o[2]-s[2],2));l<a&&(a=l,i=c)}return i},r.keyword.rgb=function(t){return e[t]},r.rgb.xyz=function(e){var t=e[0]/255,n=e[1]/255,r=e[2]/255;return[100*(.4124*(t=t>.04045?Math.pow((t+.055)/1.055,2.4):t/12.92)+.3576*(n=n>.04045?Math.pow((n+.055)/1.055,2.4):n/12.92)+.1805*(r=r>.04045?Math.pow((r+.055)/1.055,2.4):r/12.92)),100*(.2126*t+.7152*n+.0722*r),100*(.0193*t+.1192*n+.9505*r)]},r.rgb.lab=function(e){var t=r.rgb.xyz(e),n=t[0],i=t[1],o=t[2];return i/=100,o/=108.883,n=(n/=95.047)>.008856?Math.pow(n,1/3):7.787*n+16/116,[116*(i=i>.008856?Math.pow(i,1/3):7.787*i+16/116)-16,500*(n-i),200*(i-(o=o>.008856?Math.pow(o,1/3):7.787*o+16/116))]},r.hsl.rgb=function(e){var t,n,r,i,o,s=e[0]/360,a=e[1]/100,c=e[2]/100;if(0===a)return[o=255*c,o,o];t=2*c-(n=c<.5?c*(1+a):c+a-c*a),i=[0,0,0];for(var l=0;l<3;l++)(r=s+1/3*-(l-1))<0&&r++,r>1&&r--,o=6*r<1?t+6*(n-t)*r:2*r<1?n:3*r<2?t+(n-t)*(2/3-r)*6:t,i[l]=255*o;return i},r.hsl.hsv=function(e){var t=e[0],n=e[1]/100,r=e[2]/100,i=n,o=Math.max(r,.01);return n*=(r*=2)<=1?r:2-r,i*=o<=1?o:2-o,[t,100*(0===r?2*i/(o+i):2*n/(r+n)),(r+n)/2*100]},r.hsv.rgb=function(e){var t=e[0]/60,n=e[1]/100,r=e[2]/100,i=Math.floor(t)%6,o=t-Math.floor(t),s=255*r*(1-n),a=255*r*(1-n*o),c=255*r*(1-n*(1-o));switch(r*=255,i){case 0:return[r,c,s];case 1:return[a,r,s];case 2:return[s,r,c];case 3:return[s,a,r];case 4:return[c,s,r];case 5:return[r,s,a]}},r.hsv.hsl=function(e){var t,n,r,i=e[0],o=e[1]/100,s=e[2]/100,a=Math.max(s,.01);return r=(2-o)*s,n=o*a,[i,100*(n=(n/=(t=(2-o)*a)<=1?t:2-t)||0),100*(r/=2)]},r.hwb.rgb=function(e){var t,n,r,i,o,s,a,c=e[0]/360,l=e[1]/100,u=e[2]/100,d=l+u;switch(d>1&&(l/=d,u/=d),r=6*c-(t=Math.floor(6*c)),1&t&&(r=1-r),i=l+r*((n=1-u)-l),t){default:case 6:case 0:o=n,s=i,a=l;break;case 1:o=i,s=n,a=l;break;case 2:o=l,s=n,a=i;break;case 3:o=l,s=i,a=n;break;case 4:o=i,s=l,a=n;break;case 5:o=n,s=l,a=i}return[255*o,255*s,255*a]},r.cmyk.rgb=function(e){var t=e[0]/100,n=e[1]/100,r=e[2]/100,i=e[3]/100;return[255*(1-Math.min(1,t*(1-i)+i)),255*(1-Math.min(1,n*(1-i)+i)),255*(1-Math.min(1,r*(1-i)+i))]},r.xyz.rgb=function(e){var t,n,r,i=e[0]/100,o=e[1]/100,s=e[2]/100;return n=-.9689*i+1.8758*o+.0415*s,r=.0557*i+-.204*o+1.057*s,t=(t=3.2406*i+-1.5372*o+-.4986*s)>.0031308?1.055*Math.pow(t,1/2.4)-.055:12.92*t,n=n>.0031308?1.055*Math.pow(n,1/2.4)-.055:12.92*n,r=r>.0031308?1.055*Math.pow(r,1/2.4)-.055:12.92*r,[255*(t=Math.min(Math.max(0,t),1)),255*(n=Math.min(Math.max(0,n),1)),255*(r=Math.min(Math.max(0,r),1))]},r.xyz.lab=function(e){var t=e[0],n=e[1],r=e[2];return n/=100,r/=108.883,t=(t/=95.047)>.008856?Math.pow(t,1/3):7.787*t+16/116,[116*(n=n>.008856?Math.pow(n,1/3):7.787*n+16/116)-16,500*(t-n),200*(n-(r=r>.008856?Math.pow(r,1/3):7.787*r+16/116))]},r.lab.xyz=function(e){var t,n,r,i=e[0];t=e[1]/500+(n=(i+16)/116),r=n-e[2]/200;var o=Math.pow(n,3),s=Math.pow(t,3),a=Math.pow(r,3);return n=o>.008856?o:(n-16/116)/7.787,t=s>.008856?s:(t-16/116)/7.787,r=a>.008856?a:(r-16/116)/7.787,[t*=95.047,n*=100,r*=108.883]},r.lab.lch=function(e){var t,n=e[0],r=e[1],i=e[2];return(t=360*Math.atan2(i,r)/2/Math.PI)<0&&(t+=360),[n,Math.sqrt(r*r+i*i),t]},r.lch.lab=function(e){var t,n=e[0],r=e[1];return t=e[2]/360*2*Math.PI,[n,r*Math.cos(t),r*Math.sin(t)]},r.rgb.ansi16=function(e){var t=e[0],n=e[1],i=e[2],o=1 in arguments?arguments[1]:r.rgb.hsv(e)[2];if(0===(o=Math.round(o/50)))return 30;var s=30+(Math.round(i/255)<<2|Math.round(n/255)<<1|Math.round(t/255));return 2===o&&(s+=60),s},r.hsv.ansi16=function(e){return r.rgb.ansi16(r.hsv.rgb(e),e[2])},r.rgb.ansi256=function(e){var t=e[0],n=e[1],r=e[2];return t===n&&n===r?t<8?16:t>248?231:Math.round((t-8)/247*24)+232:16+36*Math.round(t/255*5)+6*Math.round(n/255*5)+Math.round(r/255*5)},r.ansi16.rgb=function(e){var t=e%10;if(0===t||7===t)return e>50&&(t+=3.5),[t=t/10.5*255,t,t];var n=.5*(1+~~(e>50));return[(1&t)*n*255,(t>>1&1)*n*255,(t>>2&1)*n*255]},r.ansi256.rgb=function(e){if(e>=232){var t=10*(e-232)+8;return[t,t,t]}var n;return e-=16,[Math.floor(e/36)/5*255,Math.floor((n=e%36)/6)/5*255,n%6/5*255]},r.rgb.hex=function(e){var t=(((255&Math.round(e[0]))<<16)+((255&Math.round(e[1]))<<8)+(255&Math.round(e[2]))).toString(16).toUpperCase();return"000000".substring(t.length)+t},r.hex.rgb=function(e){var t=e.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);if(!t)return[0,0,0];var n=t[0];3===t[0].length&&(n=n.split("").map((function(e){return e+e})).join(""));var r=parseInt(n,16);return[r>>16&255,r>>8&255,255&r]},r.rgb.hcg=function(e){var t,n=e[0]/255,r=e[1]/255,i=e[2]/255,o=Math.max(Math.max(n,r),i),s=Math.min(Math.min(n,r),i),a=o-s;return t=a<=0?0:o===n?(r-i)/a%6:o===r?2+(i-n)/a:4+(n-r)/a+4,t/=6,[360*(t%=1),100*a,100*(a<1?s/(1-a):0)]},r.hsl.hcg=function(e){var t,n=e[1]/100,r=e[2]/100,i=0;return(t=r<.5?2*n*r:2*n*(1-r))<1&&(i=(r-.5*t)/(1-t)),[e[0],100*t,100*i]},r.hsv.hcg=function(e){var t=e[1]/100,n=e[2]/100,r=t*n,i=0;return r<1&&(i=(n-r)/(1-r)),[e[0],100*r,100*i]},r.hcg.rgb=function(e){var t=e[0]/360,n=e[1]/100,r=e[2]/100;if(0===n)return[255*r,255*r,255*r];var i,o=[0,0,0],s=t%1*6,a=s%1,c=1-a;switch(Math.floor(s)){case 0:o[0]=1,o[1]=a,o[2]=0;break;case 1:o[0]=c,o[1]=1,o[2]=0;break;case 2:o[0]=0,o[1]=1,o[2]=a;break;case 3:o[0]=0,o[1]=c,o[2]=1;break;case 4:o[0]=a,o[1]=0,o[2]=1;break;default:o[0]=1,o[1]=0,o[2]=c}return i=(1-n)*r,[255*(n*o[0]+i),255*(n*o[1]+i),255*(n*o[2]+i)]},r.hcg.hsv=function(e){var t=e[1]/100,n=t+e[2]/100*(1-t),r=0;return n>0&&(r=t/n),[e[0],100*r,100*n]},r.hcg.hsl=function(e){var t=e[1]/100,n=e[2]/100*(1-t)+.5*t,r=0;return n>0&&n<.5?r=t/(2*n):n>=.5&&n<1&&(r=t/(2*(1-n))),[e[0],100*r,100*n]},r.hcg.hwb=function(e){var t=e[1]/100,n=t+e[2]/100*(1-t);return[e[0],100*(n-t),100*(1-n)]},r.hwb.hcg=function(e){var t=e[1]/100,n=1-e[2]/100,r=n-t,i=0;return r<1&&(i=(n-r)/(1-r)),[e[0],100*r,100*i]},r.apple.rgb=function(e){return[e[0]/65535*255,e[1]/65535*255,e[2]/65535*255]},r.rgb.apple=function(e){return[e[0]/255*65535,e[1]/255*65535,e[2]/255*65535]},r.gray.rgb=function(e){return[e[0]/100*255,e[0]/100*255,e[0]/100*255]},r.gray.hsl=r.gray.hsv=function(e){return[0,0,e[0]]},r.gray.hwb=function(e){return[0,100,e[0]]},r.gray.cmyk=function(e){return[0,0,0,e[0]]},r.gray.lab=function(e){return[e[0],0,0]},r.gray.hex=function(e){var t=255&Math.round(e[0]/100*255),n=((t<<16)+(t<<8)+t).toString(16).toUpperCase();return"000000".substring(n.length)+n},r.rgb.gray=function(e){return[(e[0]+e[1]+e[2])/3/255*100]},dm.exports}function fm(){if(Vg)return Gg;Vg=1;var e=hm(),t=function(){if(Wg)return Bg;Wg=1;var e=hm();function t(t){var n=function(){for(var t={},n=Object.keys(e),r=n.length,i=0;i<r;i++)t[n[i]]={distance:-1,parent:null};return t}(),r=[t];for(n[t].distance=0;r.length;)for(var i=r.pop(),o=Object.keys(e[i]),s=o.length,a=0;a<s;a++){var c=o[a],l=n[c];-1===l.distance&&(l.distance=n[i].distance+1,l.parent=i,r.unshift(c))}return n}function n(e,t){return function(n){return t(e(n))}}function r(t,r){for(var i=[r[t].parent,t],o=e[r[t].parent][t],s=r[t].parent;r[s].parent;)i.unshift(r[s].parent),o=n(e[r[s].parent][s],o),s=r[s].parent;return o.conversion=i,o}return Bg=function(e){for(var n=t(e),i={},o=Object.keys(n),s=o.length,a=0;a<s;a++){var c=o[a];null!==n[c].parent&&(i[c]=r(c,n))}return i}}(),n={};return Object.keys(e).forEach((function(r){n[r]={},Object.defineProperty(n[r],"channels",{value:e[r].channels}),Object.defineProperty(n[r],"labels",{value:e[r].labels});var i=t(r);Object.keys(i).forEach((function(e){var t=i[e];n[r][e]=function(e){var t=function(t){if(null==t)return t;arguments.length>1&&(t=Array.prototype.slice.call(arguments));var n=e(t);if("object"==typeof n)for(var r=n.length,i=0;i<r;i++)n[i]=Math.round(n[i]);return n};return"conversion"in e&&(t.conversion=e.conversion),t}(t),n[r][e].raw=function(e){var t=function(t){return null==t?t:(arguments.length>1&&(t=Array.prototype.slice.call(arguments)),e(t))};return"conversion"in e&&(t.conversion=e.conversion),t}(t)}))})),Gg=n}function pm(){if(Jg)return Kg;Jg=1;var e=function(){if(Hg)return Yg;Hg=1;var e=Rg(),t=fm(),n=[].slice,r=["keyword","gray","hex"],i={};Object.keys(t).forEach((function(e){i[n.call(t[e].labels).sort().join("")]=e}));var o={};function s(a,c){if(!(this instanceof s))return new s(a,c);if(c&&c in r&&(c=null),c&&!(c in t))throw new Error("Unknown model: "+c);var u,d;if(null==a)this.model="rgb",this.color=[0,0,0],this.valpha=1;else if(a instanceof s)this.model=a.model,this.color=a.color.slice(),this.valpha=a.valpha;else if("string"==typeof a){var h=e.get(a);if(null===h)throw new Error("Unable to parse color from string: "+a);this.model=h.model,d=t[this.model].channels,this.color=h.value.slice(0,d),this.valpha="number"==typeof h.value[d]?h.value[d]:1}else if(a.length){this.model=c||"rgb",d=t[this.model].channels;var f=n.call(a,0,d);this.color=l(f,d),this.valpha="number"==typeof a[d]?a[d]:1}else if("number"==typeof a)a&=16777215,this.model="rgb",this.color=[a>>16&255,a>>8&255,255&a],this.valpha=1;else{this.valpha=1;var p=Object.keys(a);"alpha"in a&&(p.splice(p.indexOf("alpha"),1),this.valpha="number"==typeof a.alpha?a.alpha:0);var g=p.sort().join("");if(!(g in i))throw new Error("Unable to parse color from object: "+JSON.stringify(a));this.model=i[g];var m=t[this.model].labels,y=[];for(u=0;u<m.length;u++)y.push(a[m[u]]);this.color=l(y)}if(o[this.model])for(d=t[this.model].channels,u=0;u<d;u++){var v=o[this.model][u];v&&(this.color[u]=v(this.color[u]))}this.valpha=Math.max(0,Math.min(1,this.valpha)),Object.freeze&&Object.freeze(this)}function a(e,t,n){return(e=Array.isArray(e)?e:[e]).forEach((function(e){(o[e]||(o[e]=[]))[t]=n})),e=e[0],function(r){var i;return arguments.length?(n&&(r=n(r)),(i=this[e]()).color[t]=r,i):(i=this[e]().color[t],n&&(i=n(i)),i)}}function c(e){return function(t){return Math.max(0,Math.min(e,t))}}function l(e,t){for(var n=0;n<t;n++)"number"!=typeof e[n]&&(e[n]=0);return e}return s.prototype={toString:function(){return this.string()},toJSON:function(){return this[this.model]()},string:function(t){var n=this.model in e.to?this:this.rgb(),r=1===(n=n.round("number"==typeof t?t:1)).valpha?n.color:n.color.concat(this.valpha);return e.to[n.model](r)},percentString:function(t){var n=this.rgb().round("number"==typeof t?t:1),r=1===n.valpha?n.color:n.color.concat(this.valpha);return e.to.rgb.percent(r)},array:function(){return 1===this.valpha?this.color.slice():this.color.concat(this.valpha)},object:function(){for(var e={},n=t[this.model].channels,r=t[this.model].labels,i=0;i<n;i++)e[r[i]]=this.color[i];return 1!==this.valpha&&(e.alpha=this.valpha),e},unitArray:function(){var e=this.rgb().color;return e[0]/=255,e[1]/=255,e[2]/=255,1!==this.valpha&&e.push(this.valpha),e},unitObject:function(){var e=this.rgb().object();return e.r/=255,e.g/=255,e.b/=255,1!==this.valpha&&(e.alpha=this.valpha),e},round:function(e){return e=Math.max(e||0,0),new s(this.color.map(function(e){return function(t){return function(e,t){return Number(e.toFixed(t))}(t,e)}}(e)).concat(this.valpha),this.model)},alpha:function(e){return arguments.length?new s(this.color.concat(Math.max(0,Math.min(1,e))),this.model):this.valpha},red:a("rgb",0,c(255)),green:a("rgb",1,c(255)),blue:a("rgb",2,c(255)),hue:a(["hsl","hsv","hsl","hwb","hcg"],0,(function(e){return(e%360+360)%360})),saturationl:a("hsl",1,c(100)),lightness:a("hsl",2,c(100)),saturationv:a("hsv",1,c(100)),value:a("hsv",2,c(100)),chroma:a("hcg",1,c(100)),gray:a("hcg",2,c(100)),white:a("hwb",1,c(100)),wblack:a("hwb",2,c(100)),cyan:a("cmyk",0,c(100)),magenta:a("cmyk",1,c(100)),yellow:a("cmyk",2,c(100)),black:a("cmyk",3,c(100)),x:a("xyz",0,c(100)),y:a("xyz",1,c(100)),z:a("xyz",2,c(100)),l:a("lab",0,c(100)),a:a("lab",1),b:a("lab",2),keyword:function(e){return arguments.length?new s(e):t[this.model].keyword(this.color)},hex:function(t){return arguments.length?new s(t):e.to.hex(this.rgb().round().color)},rgbNumber:function(){var e=this.rgb().color;return(255&e[0])<<16|(255&e[1])<<8|255&e[2]},luminosity:function(){for(var e=this.rgb().color,t=[],n=0;n<e.length;n++){var r=e[n]/255;t[n]=r<=.03928?r/12.92:Math.pow((r+.055)/1.055,2.4)}return.2126*t[0]+.7152*t[1]+.0722*t[2]},contrast:function(e){var t=this.luminosity(),n=e.luminosity();return t>n?(t+.05)/(n+.05):(n+.05)/(t+.05)},level:function(e){var t=this.contrast(e);return t>=7.1?"AAA":t>=4.5?"AA":""},isDark:function(){var e=this.rgb().color;return(299*e[0]+587*e[1]+114*e[2])/1e3<128},isLight:function(){return!this.isDark()},negate:function(){for(var e=this.rgb(),t=0;t<3;t++)e.color[t]=255-e.color[t];return e},lighten:function(e){var t=this.hsl();return t.color[2]+=t.color[2]*e,t},darken:function(e){var t=this.hsl();return t.color[2]-=t.color[2]*e,t},saturate:function(e){var t=this.hsl();return t.color[1]+=t.color[1]*e,t},desaturate:function(e){var t=this.hsl();return t.color[1]-=t.color[1]*e,t},whiten:function(e){var t=this.hwb();return t.color[1]+=t.color[1]*e,t},blacken:function(e){var t=this.hwb();return t.color[2]+=t.color[2]*e,t},grayscale:function(){var e=this.rgb().color,t=.3*e[0]+.59*e[1]+.11*e[2];return s.rgb(t,t,t)},fade:function(e){return this.alpha(this.valpha-this.valpha*e)},opaquer:function(e){return this.alpha(this.valpha+this.valpha*e)},rotate:function(e){var t=this.hsl(),n=t.color[0];return n=(n=(n+e)%360)<0?360+n:n,t.color[0]=n,t},mix:function(e,t){if(!e||!e.rgb)throw new Error('Argument to "mix" was not a Color instance, but rather an instance of '+typeof e);var n=e.rgb(),r=this.rgb(),i=void 0===t?.5:t,o=2*i-1,a=n.alpha()-r.alpha(),c=((o*a==-1?o:(o+a)/(1+o*a))+1)/2,l=1-c;return s.rgb(c*n.red()+l*r.red(),c*n.green()+l*r.green(),c*n.blue()+l*r.blue(),n.alpha()*i+r.alpha()*(1-i))}},Object.keys(t).forEach((function(e){if(-1===r.indexOf(e)){var i=t[e].channels;s.prototype[e]=function(){if(this.model===e)return new s(this);if(arguments.length)return new s(arguments,e);var n,r="number"==typeof arguments[i]?i:this.valpha;return new s((n=t[this.model][e].raw(this.color),Array.isArray(n)?n:[n]).concat(r),e)},s[e]=function(t){return"number"==typeof t&&(t=l(n.call(arguments),i)),new s(t,e)}}})),Yg=s}(),t=(qg||(qg=1,zg=function(e){for(var t=0,n=0;t<e.length;n=e.charCodeAt(t++)+((n<<5)-n));var r=Math.floor(Math.abs(1e4*Math.sin(n)%1*16777216)).toString(16);return"#"+Array(6-r.length+1).join("0")+r}),zg);return Kg=function(n,r){var i=n.split(r||":"),o=t(i[0]);if(!i.length)return o;for(var s=0,a=i.length-1;s<a;s++)o=e(o).mix(e(t(i[s+1]))).saturate(1).hex();return o},Kg}function gm(){if(sm)return om;sm=1;var e=function(){if(im)return rm;im=1;var e=(nm||(nm=1,tm=function(e,t){if(!t)return!1;for(var n=t.split(/[\s,]+/),r=0;r<n.length;r++)if("-"!==(t=n[r].replace("*",".*?")).charAt(0)){if(new RegExp("^"+t+"$").test(e))return!0}else if(new RegExp("^"+t.substr(1)+"$").test(e))return!1;return!1}),tm);return rm=function(t){return function(n){try{return e(n,t())}catch(e){}return!1}}}();return om=e((function(){return process.env.DEBUG||process.env.DIAGNOSTICS}))}"production"===process.env.NODE_ENV?Cg.exports=function(){if(kg)return xg;kg=1;var e=$g()((function e(t,n){return(n=n||{}).namespace=t,n.prod=!0,n.dev=!1,n.force||e.force?e.yep(n):e.nope(n)}));return xg=e}():Cg.exports=function(){if(um)return lm;um=1;var e=$g(),t=k.isatty(1),n=e((function e(n,r){return(r=r||{}).colors="colors"in r?r.colors:t,r.namespace=n,r.prod=!1,r.dev=!0,e.enabled(n)||r.force||e.force?e.yep(r):e.nope(r)}));return n.modify(function(){if(em)return Qg;em=1;var e=pm(),t=function(){if(Xg)return Zg;function e(t,n){return n?new e(t).style(n):this instanceof e?void(this.text=t):new e(t)}return Xg=1,e.prototype.prefix="[",e.prototype.suffix="m",e.prototype.hex=function(e){3===(e="#"===e[0]?e.substring(1):e).length&&((e=e.split(""))[5]=e[2],e[4]=e[2],e[3]=e[1],e[2]=e[1],e[1]=e[0],e=e.join(""));var t=e.substring(0,2),n=e.substring(2,4),r=e.substring(4,6);return[parseInt(t,16),parseInt(n,16),parseInt(r,16)]},e.prototype.rgb=function(e,t,n){var r=e/255*5,i=t/255*5,o=n/255*5;return this.ansi(r,i,o)},e.prototype.ansi=function(e,t,n){return 16+36*Math.round(e)+6*Math.round(t)+Math.round(n)},e.prototype.reset=function(){return this.prefix+"39;49"+this.suffix},e.prototype.style=function(e){return this.prefix+"38;5;"+this.rgb.apply(this,this.hex(e))+this.suffix+this.text+this.reset()},Zg=e}();return Qg=function(n,r){var i=r.namespace,o=!1!==r.colors?t(i+":",e(i)):i+":";return n[0]=o+" "+n[0],n}}()),n.use(gm()),n.set(cm?am:(cm=1,am=function(e,t){try{Function.prototype.apply.call(console.log,console,t)}catch(e){}})),lm=n}();var mm,ym,vm,bm,wm,Sm,_m=Cg.exports;function Im(){if(bm)return vm;bm=1;const e=x,t=b,n=(hg||(hg=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t){return(0,r.default)(o.default,e,t)};var n=(zp||(zp=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var n=o(Tp),r=o(Yp()),i=o(qp);function o(e){return e&&e.__esModule?e:{default:e}}t.default=(0,i.default)(((e,t,i)=>{var o=(0,n.default)(t)?[]:{};e(t,((e,t,n)=>{(0,r.default)(e)(((e,...r)=>{r.length<2&&([r]=r),o[t]=r,n(e)}))}),(e=>i(e,o)))}),3),e.exports=t.default}(Op,Op.exports)),Op.exports),r=s(n),i=(dg||(dg=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var n=i(fg),r=i(qp);function i(e){return e&&e.__esModule?e:{default:e}}t.default=(0,r.default)((function(e,t,r){return(0,n.default)(e,1,t,r)}),3),e.exports=t.default}(Kp,Kp.exports)),Kp.exports),o=s(i);function s(e){return e&&e.__esModule?e:{default:e}}e.exports=t.default}($p,$p.exports)),$p.exports),r=A,{MESSAGE:i}=th,{Stream:o,PassThrough:s}=Eg,a=Cp,c=_m("winston:file"),l=E,u=function(){if(ym)return mm;ym=1;const e=x,{StringDecoder:t}=M,{Stream:n}=Eg;function r(){}return mm=(i,o)=>{const s=Buffer.alloc(65536),a=new t("utf8"),c=new n;let l="",u=0,d=0;return-1===i.start&&delete i.start,c.readable=!0,c.destroy=()=>{c.destroyed=!0,c.emit("end"),c.emit("close")},e.open(i.file,"a+","0644",((t,n)=>{if(t)return o?o(t):c.emit("error",t),void c.destroy();!function t(){if(!c.destroyed)return e.read(n,s,0,s.length,u,((e,n)=>{if(e)return o?o(e):c.emit("error",e),void c.destroy();if(!n)return l&&((null==i.start||d>i.start)&&(o?o(null,l):c.emit("line",l)),d++,l=""),setTimeout(t,1e3);let r=a.write(s.slice(0,n));o||c.emit("data",r),r=(l+r).split(/\n+/);const h=r.length-1;let f=0;for(;f<h;f++)(null==i.start||d>i.start)&&(o?o(null,r[f]):c.emit("line",r[f])),d++;return l=r[h],u+=n,t()}));e.close(n,r)}()})),o?c.destroy:c},mm}();return vm=class extends a{constructor(e={}){function n(t,...n){n.slice(1).forEach((n=>{if(e[n])throw new Error(`Cannot set ${n} and ${t} together`)}))}if(super(e),this.name=e.name||"file",this._stream=new s,this._stream.setMaxListeners(30),this._onError=this._onError.bind(this),e.filename||e.dirname)n("filename or dirname","stream"),this._basename=this.filename=e.filename?t.basename(e.filename):"winston.log",this.dirname=e.dirname||t.dirname(e.filename),this.options=e.options||{flags:"a"};else{if(!e.stream)throw new Error("Cannot log to file without filename or stream.");console.warn("options.stream will be removed in winston@4. Use winston.transports.Stream"),n("stream","filename","maxsize"),this._dest=this._stream.pipe(this._setupStream(e.stream)),this.dirname=t.dirname(this._dest.path)}this.maxsize=e.maxsize||null,this.rotationFormat=e.rotationFormat||!1,this.zippedArchive=e.zippedArchive||!1,this.maxFiles=e.maxFiles||null,this.eol="string"==typeof e.eol?e.eol:l.EOL,this.tailable=e.tailable||!1,this.lazy=e.lazy||!1,this._size=0,this._pendingSize=0,this._created=0,this._drain=!1,this._opening=!1,this._ending=!1,this._fileExist=!1,this.dirname&&this._createLogDirIfNotExist(this.dirname),this.lazy||this.open()}finishIfEnding(){this._ending&&(this._opening?this.once("open",(()=>{this._stream.once("finish",(()=>this.emit("finish"))),setImmediate((()=>this._stream.end()))})):(this._stream.once("finish",(()=>this.emit("finish"))),setImmediate((()=>this._stream.end()))))}log(e,t=()=>{}){if(this.silent)return t(),!0;if(this._drain)return void this._stream.once("drain",(()=>{this._drain=!1,this.log(e,t)}));if(this._rotate)return void this._stream.once("rotate",(()=>{this._rotate=!1,this.log(e,t)}));if(this.lazy){if(!this._fileExist)return this._opening||this.open(),void this.once("open",(()=>{this._fileExist=!0,this.log(e,t)}));if(this._needsNewFile(this._pendingSize))return void this._dest.once("close",(()=>{this._opening||this.open(),this.once("open",(()=>{this.log(e,t)}))}))}const n=`${e[i]}${this.eol}`,r=Buffer.byteLength(n);this._pendingSize+=r,this._opening&&!this.rotatedWhileOpening&&this._needsNewFile(this._size+this._pendingSize)&&(this.rotatedWhileOpening=!0);const o=this._stream.write(n,function(){this._size+=r,this._pendingSize-=r,c("logged %s %s",this._size,n),this.emit("logged",e),this._rotate||this._opening||this._needsNewFile()&&(this.lazy?this._endStream((()=>{this.emit("fileclosed")})):(this._rotate=!0,this._endStream((()=>this._rotateFile()))))}.bind(this));return o?t():(this._drain=!0,this._stream.once("drain",(()=>{this._drain=!1,t()}))),c("written",o,this._drain),this.finishIfEnding(),o}query(n,r){"function"==typeof n&&(r=n,n={}),n=function(e){return(e=e||{}).rows=e.rows||e.limit||10,e.start=e.start||0,e.until=e.until||new Date,"object"!=typeof e.until&&(e.until=new Date(e.until)),e.from=e.from||e.until-864e5,"object"!=typeof e.from&&(e.from=new Date(e.from)),e.order=e.order||"desc",e}(n);const i=t.join(this.dirname,this.filename);let o="",s=[],a=0;const c=e.createReadStream(i,{encoding:"utf8"});function l(e,t){try{const t=JSON.parse(e);(function(e){if(!e)return;if("object"!=typeof e)return;const t=new Date(e.timestamp);return!(n.from&&t<n.from||n.until&&t>n.until||n.level&&n.level!==e.level)||void 0})(t)&&function(e){n.rows&&s.length>=n.rows&&"desc"!==n.order?c.readable&&c.destroy():(n.fields&&(e=n.fields.reduce(((t,n)=>(t[n]=e[n],t)),{})),"desc"===n.order&&s.length>=n.rows&&s.shift(),s.push(e))}(t)}catch(e){t||c.emit("error",e)}}c.on("error",(e=>{if(c.readable&&c.destroy(),r)return"ENOENT"!==e.code?r(e):r(null,s)})),c.on("data",(e=>{const t=(e=(o+e).split(/\n+/)).length-1;let r=0;for(;r<t;r++)(!n.start||a>=n.start)&&l(e[r]),a++;o=e[t]})),c.on("close",(()=>{o&&l(o,!0),"desc"===n.order&&(s=s.reverse()),r&&r(null,s)}))}stream(e={}){const n=t.join(this.dirname,this.filename),r=new o,i={file:n,start:e.start};return r.destroy=u(i,((e,t)=>{if(e)return r.emit("error",e);try{r.emit("data",t),t=JSON.parse(t),r.emit("log",t)}catch(e){r.emit("error",e)}})),r}open(){this.filename&&(this._opening||(this._opening=!0,this.stat(((e,t)=>{if(e)return this.emit("error",e);c("stat done: %s { size: %s }",this.filename,t),this._size=t,this._dest=this._createStream(this._stream),this._opening=!1,this.once("open",(()=>{this._stream.emit("rotate")||(this._rotate=!1)}))}))))}stat(n){const r=this._getFile(),i=t.join(this.dirname,r);e.stat(i,((e,t)=>e&&"ENOENT"===e.code?(c("ENOENT ok",i),this.filename=r,n(null,0)):e?(c(`err ${e.code} ${i}`),n(e)):!t||this._needsNewFile(t.size)?this._incFile((()=>this.stat(n))):(this.filename=r,void n(null,t.size))))}close(e){this._stream&&this._stream.end((()=>{e&&e(),this.emit("flush"),this.emit("closed")}))}_needsNewFile(e){return e=e||this._size,this.maxsize&&e>=this.maxsize}_onError(e){this.emit("error",e)}_setupStream(e){return e.on("error",this._onError),e}_cleanupStream(e){return e.removeListener("error",this._onError),e.destroy(),e}_rotateFile(){this._incFile((()=>this.open()))}_endStream(e=()=>{}){this._dest?(this._stream.unpipe(this._dest),this._dest.end((()=>{this._cleanupStream(this._dest),e()}))):e()}_createStream(n){const r=t.join(this.dirname,this.filename);c("create stream start",r,this.options);const i=e.createWriteStream(r,this.options).on("error",(e=>c(e))).on("close",(()=>c("close",i.path,i.bytesWritten))).on("open",(()=>{c("file open ok",r),this.emit("open",r),n.pipe(i),this.rotatedWhileOpening&&(this._stream=new s,this._stream.setMaxListeners(30),this._rotateFile(),this.rotatedWhileOpening=!1,this._cleanupStream(i),n.end())}));return c("create stream ok",r),i}_incFile(e){c("_incFile",this.filename);const r=t.extname(this._basename),i=t.basename(this._basename,r),o=[];this.zippedArchive&&o.push(function(e){const n=this._created>0&&!this.tailable?this._created:"";this._compressFile(t.join(this.dirname,`${i}${n}${r}`),t.join(this.dirname,`${i}${n}${r}.gz`),e)}.bind(this)),o.push(function(e){this.tailable?this._checkMaxFilesTailable(r,i,e):(this._created+=1,this._checkMaxFilesIncrementing(r,i,e))}.bind(this)),n(o,e)}_getFile(){const e=t.extname(this._basename),n=t.basename(this._basename,e),r=this.rotationFormat?this.rotationFormat():this._created;return!this.tailable&&this._created?`${n}${r}${e}`:`${n}${e}`}_checkMaxFilesIncrementing(n,r,i){if(!this.maxFiles||this._created<this.maxFiles)return setImmediate(i);const o=this._created-this.maxFiles,s=`${r}${0!==o?o:""}${n}${this.zippedArchive?".gz":""}`,a=t.join(this.dirname,s);e.unlink(a,i)}_checkMaxFilesTailable(r,i,o){const s=[];if(!this.maxFiles)return;const a=this.zippedArchive?".gz":"";for(let n=this.maxFiles-1;n>1;n--)s.push(function(n,o){let s=`${i}${n-1}${r}${a}`;const c=t.join(this.dirname,s);e.exists(c,(l=>{if(!l)return o(null);s=`${i}${n}${r}${a}`,e.rename(c,t.join(this.dirname,s),o)}))}.bind(this,n));n(s,(()=>{e.rename(t.join(this.dirname,`${i}${r}${a}`),t.join(this.dirname,`${i}1${r}${a}`),o)}))}_compressFile(t,n,i){e.access(t,e.F_OK,(o=>{if(o)return i();var s=r.createGzip(),a=e.createReadStream(t),c=e.createWriteStream(n);c.on("finish",(()=>{e.unlink(t,i)})),a.pipe(s).pipe(c)}))}_createLogDirIfNotExist(t){e.existsSync(t)||e.mkdirSync(t,{recursive:!0})}},vm}const xm=e=>null!==e&&"object"==typeof e&&"function"==typeof e.pipe;xm.writable=e=>xm(e)&&!1!==e.writable&&"function"==typeof e._write&&"object"==typeof e._writableState,xm.readable=e=>xm(e)&&!1!==e.readable&&"function"==typeof e._read&&"object"==typeof e._readableState,xm.duplex=e=>xm.writable(e)&&xm.readable(e),xm.transform=e=>xm.duplex(e)&&"function"==typeof e._transform;var km,Em,Cm=xm;!function(e){Object.defineProperty(e,"Console",{configurable:!0,enumerable:!0,get:()=>function(){if(Ep)return kp;Ep=1;const e=E,{LEVEL:t,MESSAGE:n}=th,r=Cp;return kp=class extends r{constructor(t={}){super(t),this.name=t.name||"console",this.stderrLevels=this._stringArrayToSet(t.stderrLevels),this.consoleWarnLevels=this._stringArrayToSet(t.consoleWarnLevels),this.eol="string"==typeof t.eol?t.eol:e.EOL,this.forceConsole=t.forceConsole||!1,this._consoleLog=console.log.bind(console),this._consoleWarn=console.warn.bind(console),this._consoleError=console.error.bind(console),this.setMaxListeners(30)}log(e,r){return setImmediate((()=>this.emit("logged",e))),this.stderrLevels[e[t]]?(console._stderr&&!this.forceConsole?console._stderr.write(`${e[n]}${this.eol}`):this._consoleError(e[n]),void(r&&r())):this.consoleWarnLevels[e[t]]?(console._stderr&&!this.forceConsole?console._stderr.write(`${e[n]}${this.eol}`):this._consoleWarn(e[n]),void(r&&r())):(console._stdout&&!this.forceConsole?console._stdout.write(`${e[n]}${this.eol}`):this._consoleLog(e[n]),void(r&&r()))}_stringArrayToSet(e,t){if(!e)return{};if(t=t||"Cannot make set from type other than Array of string elements",!Array.isArray(e))throw new Error(t);return e.reduce(((e,n)=>{if("string"!=typeof n)throw new Error(t);return e[n]=!0,e}),{})}}}()}),Object.defineProperty(e,"File",{configurable:!0,enumerable:!0,get:()=>Im()}),Object.defineProperty(e,"Http",{configurable:!0,enumerable:!0,get:()=>function(){if(Sm)return wm;Sm=1;const e=P,t=D,{Stream:n}=Eg,r=Cp,{configure:i}=Th();return wm=class extends r{constructor(e={}){super(e),this.options=e,this.name=e.name||"http",this.ssl=!!e.ssl,this.host=e.host||"localhost",this.port=e.port,this.auth=e.auth,this.path=e.path||"",this.maximumDepth=e.maximumDepth,this.agent=e.agent,this.headers=e.headers||{},this.headers["content-type"]="application/json",this.batch=e.batch||!1,this.batchInterval=e.batchInterval||5e3,this.batchCount=e.batchCount||10,this.batchOptions=[],this.batchTimeoutID=-1,this.batchCallback={},this.port||(this.port=this.ssl?443:80)}log(e,t){this._request(e,null,null,((t,n)=>{n&&200!==n.statusCode&&(t=new Error(`Invalid HTTP Status Code: ${n.statusCode}`)),t?this.emit("warn",t):this.emit("logged",e)})),t&&setImmediate(t)}query(e,t){"function"==typeof e&&(t=e,e={});const n=(e={method:"query",params:this.normalizeQuery(e)}).params.auth||null;delete e.params.auth;const r=e.params.path||null;delete e.params.path,this._request(e,n,r,((e,n,r)=>{if(n&&200!==n.statusCode&&(e=new Error(`Invalid HTTP Status Code: ${n.statusCode}`)),e)return t(e);if("string"==typeof r)try{r=JSON.parse(r)}catch(e){return t(e)}t(null,r)}))}stream(e={}){const t=new n,r=(e={method:"stream",params:e}).params.path||null;delete e.params.path;const i=e.params.auth||null;delete e.params.auth;let o="";const s=this._request(e,i,r);return t.destroy=()=>s.destroy(),s.on("data",(e=>{const n=(e=(o+e).split(/\n+/)).length-1;let r=0;for(;r<n;r++)try{t.emit("log",JSON.parse(e[r]))}catch(e){t.emit("error",e)}o=e[n]})),s.on("error",(e=>t.emit("error",e))),t}_request(e,t,n,r){e=e||{},t=t||this.auth,n=n||this.path||"",this.batch?this._doBatch(e,r,t,n):this._doRequest(e,r,t,n)}_doBatch(e,t,n,r){if(this.batchOptions.push(e),1===this.batchOptions.length){const e=this;this.batchCallback=t,this.batchTimeoutID=setTimeout((function(){e.batchTimeoutID=-1,e._doBatchRequest(e.batchCallback,n,r)}),this.batchInterval)}this.batchOptions.length===this.batchCount&&this._doBatchRequest(this.batchCallback,n,r)}_doBatchRequest(e,t,n){this.batchTimeoutID>0&&(clearTimeout(this.batchTimeoutID),this.batchTimeoutID=-1);const r=this.batchOptions.slice();this.batchOptions=[],this._doRequest(r,e,t,n)}_doRequest(n,r,o,s){const a=Object.assign({},this.headers);o&&o.bearer&&(a.Authorization=`Bearer ${o.bearer}`);const c=(this.ssl?t:e).request({...this.options,method:"POST",host:this.host,port:this.port,path:`/${s.replace(/^\//,"")}`,headers:a,auth:o&&o.username&&o.password?`${o.username}:${o.password}`:"",agent:this.agent});c.on("error",r),c.on("response",(e=>e.on("end",(()=>r(null,e))).resume()));const l=i({...this.maximumDepth&&{maximumDepth:this.maximumDepth}});c.end(Buffer.from(l(n,this.options.replacer),"utf8"))}},wm}()}),Object.defineProperty(e,"Stream",{configurable:!0,enumerable:!0,get:()=>function(){if(Em)return km;Em=1;const e=Cm,{MESSAGE:t}=th,n=E,r=Cp;return km=class extends r{constructor(t={}){if(super(t),!t.stream||!e(t.stream))throw new Error("options.stream is required.");this._stream=t.stream,this._stream.setMaxListeners(1/0),this.isObjectMode=t.stream._writableState.objectMode,this.eol="string"==typeof t.eol?t.eol:n.EOL}log(e,n){if(setImmediate((()=>this.emit("logged",e))),this.isObjectMode)return this._stream.write(e),void(n&&n());this._stream.write(`${e[t]}${this.eol}`),n&&n()}}}()})}($f);var $m={};const Om=xd,{configs:Nm}=th;$m.cli=Om.levels(Nm.cli),$m.npm=Om.levels(Nm.npm),$m.syslog=Om.levels(Nm.syslog),$m.addColors=Om.levels;var Tm={exports:{}},Am={exports:{}};!function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var n=l(Tp),r=l(cg),i=l(fg),o=l(Qp),s=l(og),a=l(Yp()),c=l(qp);function l(e){return e&&e.__esModule?e:{default:e}}function u(e,t,n){n=(0,o.default)(n);var i=0,a=0,{length:c}=e,l=!1;function u(e,t){!1===e&&(l=!0),!0!==l&&(e?n(e):++a!==c&&t!==r.default||n(null))}for(0===c&&n(null);i<c;i++)t(e[i],i,(0,s.default)(u))}function d(e,t,n){return(0,i.default)(e,1/0,t,n)}t.default=(0,c.default)((function(e,t,r){return((0,n.default)(e)?u:d)(e,(0,a.default)(t),r)}),3),e.exports=t.default}(Am,Am.exports);var Mm=Am.exports,Pm={exports:{}};!function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return(t,n,r)=>e(t,r)},e.exports=t.default}(Pm,Pm.exports);var Dm=Pm.exports;!function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var n=s(Mm),r=s(Dm),i=s(Yp()),o=s(qp);function s(e){return e&&e.__esModule?e:{default:e}}t.default=(0,o.default)((function(e,t,o){return(0,n.default)(e,(0,r.default)((0,i.default)(t)),o)}),3),e.exports=t.default}(Tm,Tm.exports);var jm=Tm.exports,Rm=Object.prototype.toString,Lm=function(e){var t,n=0;function r(){return n||(n=1,t=e.apply(this,arguments),e=null),t}return r.displayName=function(e){if("string"==typeof e.displayName&&e.constructor.name)return e.displayName;if("string"==typeof e.name&&e.name)return e.name;if("object"==typeof e&&e.constructor&&"string"==typeof e.constructor.name)return e.constructor.name;var t=e.toString(),n=Rm.call(e).slice(8,-1);return(t="Function"===n?t.substring(t.indexOf("(")+1,t.indexOf(")")):n)||"anonymous"}(e),r},Fm={};!function(e){function t(e){for(var t in e)this[t]=e[t]}e.get=function(t){var n=Error.stackTraceLimit;Error.stackTraceLimit=1/0;var r={},i=Error.prepareStackTrace;Error.prepareStackTrace=function(e,t){return t},Error.captureStackTrace(r,t||e.get);var o=r.stack;return Error.prepareStackTrace=i,Error.stackTraceLimit=n,o},e.parse=function(e){if(!e.stack)return[];var t=this;return e.stack.split("\n").slice(1).map((function(e){if(e.match(/^\s*[-]{4,}$/))return t._createParsedCallSite({fileName:e,lineNumber:null,functionName:null,typeName:null,methodName:null,columnNumber:null,native:null});var n=e.match(/at (?:(.+)\s+\()?(?:(.+?):(\d+)(?::(\d+))?|([^)]+))\)?/);if(n){var r=null,i=null,o=null,s=null,a=null,c="native"===n[5];if(n[1]){var l=(o=n[1]).lastIndexOf(".");if("."==o[l-1]&&l--,l>0){r=o.substr(0,l),i=o.substr(l+1);var u=r.indexOf(".Module");u>0&&(o=o.substr(u+1),r=r.substr(0,u))}s=null}i&&(s=r,a=i),"<anonymous>"===i&&(a=null,o=null);var d={fileName:n[2]||null,lineNumber:parseInt(n[3],10)||null,functionName:o,typeName:s,methodName:a,columnNumber:parseInt(n[4],10)||null,native:c};return t._createParsedCallSite(d)}})).filter((function(e){return!!e}))},["this","typeName","functionName","methodName","fileName","lineNumber","columnNumber","function","evalOrigin"].forEach((function(e){t.prototype[e]=null,t.prototype["get"+e[0].toUpperCase()+e.substr(1)]=function(){return this[e]}})),["topLevel","eval","native","constructor"].forEach((function(e){t.prototype[e]=!1,t.prototype["is"+e[0].toUpperCase()+e.substr(1)]=function(){return this[e]}})),e._createParsedCallSite=function(e){return new t(e)}}(Fm);const{Writable:Um}=Eg,Bm=E,Wm=jm,Gm=_m("winston:exception"),Vm=Lm,Ym=Fm,Hm=class extends Um{constructor(e){if(super({objectMode:!0}),!e)throw new Error("ExceptionStream requires a TransportStream instance.");this.handleExceptions=!0,this.transport=e}_write(e,t,n){return e.exception?this.transport.log(e,n):(n(),!0)}};var zm=class{constructor(e){if(!e)throw new Error("Logger is required to handle exceptions");this.logger=e,this.handlers=new Map}handle(...e){e.forEach((e=>{if(Array.isArray(e))return e.forEach((e=>this._addHandler(e)));this._addHandler(e)})),this.catcher||(this.catcher=this._uncaughtException.bind(this),process.on("uncaughtException",this.catcher))}unhandle(){this.catcher&&(process.removeListener("uncaughtException",this.catcher),this.catcher=!1,Array.from(this.handlers.values()).forEach((e=>this.logger.unpipe(e))))}getAllInfo(e){let t=null;return e&&(t="string"==typeof e?e:e.message),{error:e,level:"error",message:[`uncaughtException: ${t||"(no error message)"}`,e&&e.stack||" No stack trace"].join("\n"),stack:e&&e.stack,exception:!0,date:(new Date).toString(),process:this.getProcessInfo(),os:this.getOsInfo(),trace:this.getTrace(e)}}getProcessInfo(){return{pid:process.pid,uid:process.getuid?process.getuid():null,gid:process.getgid?process.getgid():null,cwd:process.cwd(),execPath:process.execPath,version:process.version,argv:process.argv,memoryUsage:process.memoryUsage()}}getOsInfo(){return{loadavg:Bm.loadavg(),uptime:Bm.uptime()}}getTrace(e){return(e?Ym.parse(e):Ym.get()).map((e=>({column:e.getColumnNumber(),file:e.getFileName(),function:e.getFunctionName(),line:e.getLineNumber(),method:e.getMethodName(),native:e.isNative()})))}_addHandler(e){if(!this.handlers.has(e)){e.handleExceptions=!0;const t=new Hm(e);this.handlers.set(e,t),this.logger.pipe(t)}}_uncaughtException(e){const t=this.getAllInfo(e),n=this._getExceptionHandlers();let r,i="function"==typeof this.logger.exitOnError?this.logger.exitOnError(e):this.logger.exitOnError;function o(){Gm("doExit",i),Gm("process._exiting",process._exiting),i&&!process._exiting&&(r&&clearTimeout(r),process.exit(1))}if(!n.length&&i&&(console.warn("winston: exitOnError cannot be true with no exception handlers."),console.warn("winston: not exiting process."),i=!1),!n||0===n.length)return process.nextTick(o);Wm(n,((e,t)=>{const n=Vm(t),r=e.transport||e;function i(e){return()=>{Gm(e),n()}}r._ending=!0,r.once("finish",i("finished")),r.once("error",i("error"))}),(()=>i&&o())),this.logger.log(t),i&&(r=setTimeout(o,3e3))}_getExceptionHandlers(){return this.logger.transports.filter((e=>(e.transport||e).handleExceptions))}};const{Writable:qm}=Eg,Km=E,Jm=jm,Zm=_m("winston:rejection"),Xm=Lm,Qm=Fm,ey=class extends qm{constructor(e){if(super({objectMode:!0}),!e)throw new Error("RejectionStream requires a TransportStream instance.");this.handleRejections=!0,this.transport=e}_write(e,t,n){return e.rejection?this.transport.log(e,n):(n(),!0)}};var ty,ny,ry,iy,oy=class{constructor(e){if(!e)throw new Error("Logger is required to handle rejections");this.logger=e,this.handlers=new Map}handle(...e){e.forEach((e=>{if(Array.isArray(e))return e.forEach((e=>this._addHandler(e)));this._addHandler(e)})),this.catcher||(this.catcher=this._unhandledRejection.bind(this),process.on("unhandledRejection",this.catcher))}unhandle(){this.catcher&&(process.removeListener("unhandledRejection",this.catcher),this.catcher=!1,Array.from(this.handlers.values()).forEach((e=>this.logger.unpipe(e))))}getAllInfo(e){let t=null;return e&&(t="string"==typeof e?e:e.message),{error:e,level:"error",message:[`unhandledRejection: ${t||"(no error message)"}`,e&&e.stack||" No stack trace"].join("\n"),stack:e&&e.stack,rejection:!0,date:(new Date).toString(),process:this.getProcessInfo(),os:this.getOsInfo(),trace:this.getTrace(e)}}getProcessInfo(){return{pid:process.pid,uid:process.getuid?process.getuid():null,gid:process.getgid?process.getgid():null,cwd:process.cwd(),execPath:process.execPath,version:process.version,argv:process.argv,memoryUsage:process.memoryUsage()}}getOsInfo(){return{loadavg:Km.loadavg(),uptime:Km.uptime()}}getTrace(e){return(e?Qm.parse(e):Qm.get()).map((e=>({column:e.getColumnNumber(),file:e.getFileName(),function:e.getFunctionName(),line:e.getLineNumber(),method:e.getMethodName(),native:e.isNative()})))}_addHandler(e){if(!this.handlers.has(e)){e.handleRejections=!0;const t=new ey(e);this.handlers.set(e,t),this.logger.pipe(t)}}_unhandledRejection(e){const t=this.getAllInfo(e),n=this._getRejectionHandlers();let r,i="function"==typeof this.logger.exitOnError?this.logger.exitOnError(e):this.logger.exitOnError;function o(){Zm("doExit",i),Zm("process._exiting",process._exiting),i&&!process._exiting&&(r&&clearTimeout(r),process.exit(1))}if(!n.length&&i&&(console.warn("winston: exitOnError cannot be true with no rejection handlers."),console.warn("winston: not exiting process."),i=!1),!n||0===n.length)return process.nextTick(o);Jm(n,((e,t)=>{const n=Xm(t),r=e.transport||e;function i(e){return()=>{Zm(e),n()}}r._ending=!0,r.once("finish",i("finished")),r.once("error",i("error"))}),(()=>i&&o())),this.logger.log(t),i&&(r=setTimeout(o,3e3))}_getRejectionHandlers(){return this.logger.transports.filter((e=>(e.transport||e).handleRejections))}};function sy(){if(iy)return ry;iy=1;const{Stream:e,Transform:t}=Eg,n=jm,{LEVEL:r,SPLAT:i}=th,o=Cm,s=zm,a=oy,c=xp,l=(ny||(ny=1,ty=class{constructor(e){const t=sy();if("object"!=typeof e||Array.isArray(e)||!(e instanceof t))throw new Error("Logger is required for profiling");this.logger=e,this.start=Date.now()}done(...e){"function"==typeof e[e.length-1]&&(console.warn("Callback function no longer supported as of winston@3.0.0"),e.pop());const t="object"==typeof e[e.length-1]?e.pop():{};return t.level=t.level||"info",t.durationMs=Date.now()-this.start,this.logger.write(t)}}),ty),{warn:u}=Sf,d=$m,h=/%[scdjifoO%]/g;class f extends t{constructor(e){super({objectMode:!0}),this.configure(e)}child(e){const t=this;return Object.create(t,{write:{value:function(n){const r=Object.assign({},e,n);n instanceof Error&&(r.stack=n.stack,r.message=n.message),t.write(r)}}})}configure({silent:e,format:t,defaultMeta:n,levels:r,level:i="info",exitOnError:o=!0,transports:c,colors:l,emitErrs:u,formatters:h,padLevels:f,rewriters:p,stripColors:g,exceptionHandlers:m,rejectionHandlers:y}={}){if(this.transports.length&&this.clear(),this.silent=e,this.format=t||this.format||Ah()(),this.defaultMeta=n||null,this.levels=r||this.levels||d.npm.levels,this.level=i,this.exceptions&&this.exceptions.unhandle(),this.rejections&&this.rejections.unhandle(),this.exceptions=new s(this),this.rejections=new a(this),this.profilers={},this.exitOnError=o,c&&(c=Array.isArray(c)?c:[c]).forEach((e=>this.add(e))),l||u||h||f||p||g)throw new Error(["{ colors, emitErrs, formatters, padLevels, rewriters, stripColors } were removed in winston@3.0.0.","Use a custom winston.format(function) instead.","See: https://github.com/winstonjs/winston/tree/master/UPGRADE-3.0.md"].join("\n"));m&&this.exceptions.handle(m),y&&this.rejections.handle(y)}isLevelEnabled(e){const t=p(this.levels,e);if(null===t)return!1;const n=p(this.levels,this.level);return null!==n&&(this.transports&&0!==this.transports.length?-1!==this.transports.findIndex((e=>{let r=p(this.levels,e.level);return null===r&&(r=n),r>=t})):n>=t)}log(e,t,...n){if(1===arguments.length)return e[r]=e.level,this._addDefaultMeta(e),this.write(e),this;if(2===arguments.length)return t&&"object"==typeof t?(t[r]=t.level=e,this._addDefaultMeta(t),this.write(t),this):(t={[r]:e,level:e,message:t},this._addDefaultMeta(t),this.write(t),this);const[o]=n;if("object"==typeof o&&null!==o&&!(t&&t.match&&t.match(h))){const s=Object.assign({},this.defaultMeta,o,{[r]:e,[i]:n,level:e,message:t});return o.message&&(s.message=`${s.message} ${o.message}`),o.stack&&(s.stack=o.stack),o.cause&&(s.cause=o.cause),this.write(s),this}return this.write(Object.assign({},this.defaultMeta,{[r]:e,[i]:n,level:e,message:t})),this}_transform(e,t,n){if(this.silent)return n();e[r]||(e[r]=e.level),this.levels[e[r]]||0===this.levels[e[r]]||console.error("[winston] Unknown logger level: %s",e[r]),this._readableState.pipes||console.error("[winston] Attempt to write logs with no transports, which can increase memory usage: %j",e);try{this.push(this.format.transform(e,this.format.options))}finally{this._writableState.sync=!1,n()}}_final(e){const t=this.transports.slice();n(t,((e,t)=>{if(!e||e.finished)return setImmediate(t);e.once("finish",t),e.end()}),e)}add(e){const t=!o(e)||e.log.length>2?new c({transport:e}):e;if(!t._writableState||!t._writableState.objectMode)throw new Error("Transports must WritableStreams in objectMode. Set { objectMode: true }.");return this._onEvent("error",t),this._onEvent("warn",t),this.pipe(t),e.handleExceptions&&this.exceptions.handle(),e.handleRejections&&this.rejections.handle(),this}remove(e){if(!e)return this;let t=e;return(!o(e)||e.log.length>2)&&(t=this.transports.filter((t=>t.transport===e))[0]),t&&this.unpipe(t),this}clear(){return this.unpipe(),this}close(){return this.exceptions.unhandle(),this.rejections.unhandle(),this.clear(),this.emit("close"),this}setLevels(){u.deprecated("setLevels")}query(e,t){"function"==typeof e&&(t=e,e={}),e=e||{};const r={},i=Object.assign({},e.query||{});n(this.transports.filter((e=>!!e.query)),(function(t,n){!function(t,n){e.query&&"function"==typeof t.formatQuery&&(e.query=t.formatQuery(i)),t.query(e,((r,i)=>{if(r)return n(r);"function"==typeof t.formatResults&&(i=t.formatResults(i,e.format)),n(null,i)}))}(t,((e,i)=>{n&&((i=e||i)&&(r[t.name]=i),n()),n=null}))}),(()=>t(null,r)))}stream(t={}){const n=new e,r=[];return n._streams=r,n.destroy=()=>{let e=r.length;for(;e--;)r[e].destroy()},this.transports.filter((e=>!!e.stream)).forEach((e=>{const i=e.stream(t);i&&(r.push(i),i.on("log",(t=>{t.transport=t.transport||[],t.transport.push(e.name),n.emit("log",t)})),i.on("error",(t=>{t.transport=t.transport||[],t.transport.push(e.name),n.emit("error",t)})))})),n}startTimer(){return new l(this)}profile(e,...t){const n=Date.now();if(this.profilers[e]){const r=this.profilers[e];delete this.profilers[e],"function"==typeof t[t.length-2]&&(console.warn("Callback function no longer supported as of winston@3.0.0"),t.pop());const i="object"==typeof t[t.length-1]?t.pop():{};return i.level=i.level||"info",i.durationMs=n-r,i.message=i.message||e,this.write(i)}return this.profilers[e]=n,this}handleExceptions(...e){console.warn("Deprecated: .handleExceptions() will be removed in winston@4. Use .exceptions.handle()"),this.exceptions.handle(...e)}unhandleExceptions(...e){console.warn("Deprecated: .unhandleExceptions() will be removed in winston@4. Use .exceptions.unhandle()"),this.exceptions.unhandle(...e)}cli(){throw new Error(["Logger.cli() was removed in winston@3.0.0","Use a custom winston.formats.cli() instead.","See: https://github.com/winstonjs/winston/tree/master/UPGRADE-3.0.md"].join("\n"))}_onEvent(e,t){t["__winston"+e]||(t["__winston"+e]=function(n){"error"!==e||this.transports.includes(t)||this.add(t),this.emit(e,n,t)}.bind(this),t.on(e,t["__winston"+e]))}_addDefaultMeta(e){this.defaultMeta&&Object.assign(e,this.defaultMeta)}}function p(e,t){const n=e[t];return n||0===n?n:null}return Object.defineProperty(f.prototype,"transports",{configurable:!1,enumerable:!0,get(){const{pipes:e}=this._readableState;return Array.isArray(e)?e:[e].filter(Boolean)}}),ry=f}const{LEVEL:ay}=th,cy=$m,ly=sy(),uy=_m("winston:create-logger");var dy=function(e={}){e.levels=e.levels||cy.npm.levels;class t extends ly{constructor(e){super(e)}}const n=new t(e);return Object.keys(e.levels).forEach((function(e){uy('Define prototype method for "%s"',e),"log"!==e?(t.prototype[e]=function(...t){const r=this||n;if(1===t.length){const[i]=t,o=i&&i.message&&i||{message:i};return o.level=o[ay]=e,r._addDefaultMeta(o),r.write(o),this||n}return 0===t.length?(r.log(e,""),r):r.log(e,...t)},t.prototype[function(e){return"is"+e.charAt(0).toUpperCase()+e.slice(1)+"Enabled"}(e)]=function(){return(this||n).isLevelEnabled(e)}):console.warn('Level "log" not defined: conflicts with the method "log". Use a different level name.')})),n};const hy=dy;var fy=class{constructor(e={}){this.loggers=new Map,this.options=e}add(e,t){if(!this.loggers.has(e)){const n=(t=Object.assign({},t||this.options)).transports||this.options.transports;t.transports=n?Array.isArray(n)?n.slice():[n]:[];const r=hy(t);r.on("close",(()=>this._delete(e))),this.loggers.set(e,r)}return this.loggers.get(e)}get(e,t){return this.add(e,t)}has(e){return!!this.loggers.has(e)}close(e){if(e)return this._removeLogger(e);this.loggers.forEach(((e,t)=>this._removeLogger(t)))}_removeLogger(e){this.loggers.has(e)&&(this.loggers.get(e).close(),this._delete(e))}_delete(e){this.loggers.delete(e)}};!function(e){const t=xd,{warn:n}=Sf;e.version="3.17.0",e.transports=$f,e.config=$m,e.addColors=t.levels,e.format=t.format,e.createLogger=dy,e.Logger=sy(),e.ExceptionHandler=zm,e.RejectionHandler=oy,e.Container=fy,e.Transport=Cp,e.loggers=new e.Container;const r=e.createLogger();Object.keys(e.config.npm.levels).concat(["log","query","stream","add","remove","clear","profile","startTimer","handleExceptions","unhandleExceptions","handleRejections","unhandleRejections","configure","child"]).forEach((t=>e[t]=(...e)=>r[t](...e))),Object.defineProperty(e,"level",{get:()=>r.level,set(e){r.level=e}}),Object.defineProperty(e,"exceptions",{get:()=>r.exceptions}),Object.defineProperty(e,"rejections",{get:()=>r.rejections}),["exitOnError"].forEach((t=>{Object.defineProperty(e,t,{get:()=>r[t],set(e){r[t]=e}})})),Object.defineProperty(e,"default",{get:()=>({exceptionHandlers:r.exceptionHandlers,rejectionHandlers:r.rejectionHandlers,transports:r.transports})}),n.deprecated(e,"setLevels"),n.forFunctions(e,"useFormat",["cli"]),n.forProperties(e,"useFormat",["padLevels","stripColors"]),n.forFunctions(e,"deprecated",["addRewriter","addFilter","clone","extend"]),n.forProperties(e,"deprecated",["emitErrs","levelLength"])}(Id);var py=od(Id),gy={exports:{}};!function(e,t){var n=j;function r(e,t){return function(e,t){var r;if(void 0===(r="passthrough"!==t.algorithm?n.createHash(t.algorithm):new l).write&&(r.write=r.update,r.end=r.update),c(t,r).dispatch(e),r.update||r.end(""),r.digest)return r.digest("buffer"===t.encoding?void 0:t.encoding);var i=r.read();return"buffer"===t.encoding?i:i.toString(t.encoding)}(e,t=s(e,t))}(t=gy.exports=r).sha1=function(e){return r(e)},t.keys=function(e){return r(e,{excludeValues:!0,algorithm:"sha1",encoding:"hex"})},t.MD5=function(e){return r(e,{algorithm:"md5",encoding:"hex"})},t.keysMD5=function(e){return r(e,{algorithm:"md5",encoding:"hex",excludeValues:!0})};var i=n.getHashes?n.getHashes().slice():["sha1","md5"];i.push("passthrough");var o=["buffer","hex","binary","base64"];function s(e,t){t=t||{};var n={};if(n.algorithm=t.algorithm||"sha1",n.encoding=t.encoding||"hex",n.excludeValues=!!t.excludeValues,n.algorithm=n.algorithm.toLowerCase(),n.encoding=n.encoding.toLowerCase(),n.ignoreUnknown=!0===t.ignoreUnknown,n.respectType=!1!==t.respectType,n.respectFunctionNames=!1!==t.respectFunctionNames,n.respectFunctionProperties=!1!==t.respectFunctionProperties,n.unorderedArrays=!0===t.unorderedArrays,n.unorderedSets=!1!==t.unorderedSets,n.unorderedObjects=!1!==t.unorderedObjects,n.replacer=t.replacer||void 0,n.excludeKeys=t.excludeKeys||void 0,void 0===e)throw new Error("Object argument required.");for(var r=0;r<i.length;++r)i[r].toLowerCase()===n.algorithm.toLowerCase()&&(n.algorithm=i[r]);if(-1===i.indexOf(n.algorithm))throw new Error('Algorithm "'+n.algorithm+'" not supported. supported values: '+i.join(", "));if(-1===o.indexOf(n.encoding)&&"passthrough"!==n.algorithm)throw new Error('Encoding "'+n.encoding+'" not supported. supported values: '+o.join(", "));return n}function a(e){return"function"==typeof e&&null!=/^function\s+\w*\s*\(\s*\)\s*{\s+\[native code\]\s+}$/i.exec(Function.prototype.toString.call(e))}function c(e,t,n){n=n||[];var r=function(e){return t.update?t.update(e,"utf8"):t.write(e,"utf8")};return{dispatch:function(t){e.replacer&&(t=e.replacer(t));var n=typeof t;return null===t&&(n="null"),this["_"+n](t)},_object:function(t){var i,o=Object.prototype.toString.call(t),s=/\[object (.*)\]/i.exec(o);if(s=(s=s?s[1]:"unknown:["+o+"]").toLowerCase(),(i=n.indexOf(t))>=0)return this.dispatch("[CIRCULAR:"+i+"]");if(n.push(t),"undefined"!=typeof Buffer&&Buffer.isBuffer&&Buffer.isBuffer(t))return r("buffer:"),r(t);if("object"===s||"function"===s||"asyncfunction"===s){var c=Object.keys(t);e.unorderedObjects&&(c=c.sort()),!1===e.respectType||a(t)||c.splice(0,0,"prototype","__proto__","constructor"),e.excludeKeys&&(c=c.filter((function(t){return!e.excludeKeys(t)}))),r("object:"+c.length+":");var l=this;return c.forEach((function(n){l.dispatch(n),r(":"),e.excludeValues||l.dispatch(t[n]),r(",")}))}if(!this["_"+s]){if(e.ignoreUnknown)return r("["+s+"]");throw new Error('Unknown object type "'+s+'"')}this["_"+s](t)},_array:function(t,i){i=void 0!==i?i:!1!==e.unorderedArrays;var o=this;if(r("array:"+t.length+":"),!i||t.length<=1)return t.forEach((function(e){return o.dispatch(e)}));var s=[],a=t.map((function(t){var r=new l,i=n.slice();return c(e,r,i).dispatch(t),s=s.concat(i.slice(n.length)),r.read().toString()}));return n=n.concat(s),a.sort(),this._array(a,!1)},_date:function(e){return r("date:"+e.toJSON())},_symbol:function(e){return r("symbol:"+e.toString())},_error:function(e){return r("error:"+e.toString())},_boolean:function(e){return r("bool:"+e.toString())},_string:function(e){r("string:"+e.length+":"),r(e.toString())},_function:function(t){r("fn:"),a(t)?this.dispatch("[native]"):this.dispatch(t.toString()),!1!==e.respectFunctionNames&&this.dispatch("function-name:"+String(t.name)),e.respectFunctionProperties&&this._object(t)},_number:function(e){return r("number:"+e.toString())},_xml:function(e){return r("xml:"+e.toString())},_null:function(){return r("Null")},_undefined:function(){return r("Undefined")},_regexp:function(e){return r("regex:"+e.toString())},_uint8array:function(e){return r("uint8array:"),this.dispatch(Array.prototype.slice.call(e))},_uint8clampedarray:function(e){return r("uint8clampedarray:"),this.dispatch(Array.prototype.slice.call(e))},_int8array:function(e){return r("int8array:"),this.dispatch(Array.prototype.slice.call(e))},_uint16array:function(e){return r("uint16array:"),this.dispatch(Array.prototype.slice.call(e))},_int16array:function(e){return r("int16array:"),this.dispatch(Array.prototype.slice.call(e))},_uint32array:function(e){return r("uint32array:"),this.dispatch(Array.prototype.slice.call(e))},_int32array:function(e){return r("int32array:"),this.dispatch(Array.prototype.slice.call(e))},_float32array:function(e){return r("float32array:"),this.dispatch(Array.prototype.slice.call(e))},_float64array:function(e){return r("float64array:"),this.dispatch(Array.prototype.slice.call(e))},_arraybuffer:function(e){return r("arraybuffer:"),this.dispatch(new Uint8Array(e))},_url:function(e){return r("url:"+e.toString())},_map:function(t){r("map:");var n=Array.from(t);return this._array(n,!1!==e.unorderedSets)},_set:function(t){r("set:");var n=Array.from(t);return this._array(n,!1!==e.unorderedSets)},_file:function(e){return r("file:"),this.dispatch([e.name,e.size,e.type,e.lastModfied])},_blob:function(){if(e.ignoreUnknown)return r("[blob]");throw Error('Hashing Blob objects is currently not supported\n(see https://github.com/puleos/object-hash/issues/26)\nUse "options.replacer" or "options.ignoreUnknown"\n')},_domwindow:function(){return r("domwindow")},_bigint:function(e){return r("bigint:"+e.toString())},_process:function(){return r("process")},_timer:function(){return r("timer")},_pipe:function(){return r("pipe")},_tcp:function(){return r("tcp")},_udp:function(){return r("udp")},_tty:function(){return r("tty")},_statwatcher:function(){return r("statwatcher")},_securecontext:function(){return r("securecontext")},_connection:function(){return r("connection")},_zlib:function(){return r("zlib")},_context:function(){return r("context")},_nodescript:function(){return r("nodescript")},_httpparser:function(){return r("httpparser")},_dataview:function(){return r("dataview")},_signal:function(){return r("signal")},_fsevent:function(){return r("fsevent")},_tlswrap:function(){return r("tlswrap")}}}function l(){return{buf:"",write:function(e){this.buf+=e},end:function(e){this.buf+=e},read:function(){return this.buf}}}t.writeToStream=function(e,t,n){return void 0===n&&(n=t,t={}),c(t=s(e,t),n).dispatch(e)}}(0,gy.exports);var my,yy,vy,by={exports:{}};function wy(){return my||(my=1,(e=by).exports=function(){var t,n;function r(){return t.apply(null,arguments)}function i(e){return e instanceof Array||"[object Array]"===Object.prototype.toString.call(e)}function o(e){return null!=e&&"[object Object]"===Object.prototype.toString.call(e)}function s(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function a(e){if(Object.getOwnPropertyNames)return 0===Object.getOwnPropertyNames(e).length;var t;for(t in e)if(s(e,t))return!1;return!0}function c(e){return void 0===e}function l(e){return"number"==typeof e||"[object Number]"===Object.prototype.toString.call(e)}function u(e){return e instanceof Date||"[object Date]"===Object.prototype.toString.call(e)}function d(e,t){var n,r=[],i=e.length;for(n=0;n<i;++n)r.push(t(e[n],n));return r}function h(e,t){for(var n in t)s(t,n)&&(e[n]=t[n]);return s(t,"toString")&&(e.toString=t.toString),s(t,"valueOf")&&(e.valueOf=t.valueOf),e}function f(e,t,n,r){return Dt(e,t,n,r,!0).utc()}function p(e){return null==e._pf&&(e._pf={empty:!1,unusedTokens:[],unusedInput:[],overflow:-2,charsLeftOver:0,nullInput:!1,invalidEra:null,invalidMonth:null,invalidFormat:!1,userInvalidated:!1,iso:!1,parsedDateParts:[],era:null,meridiem:null,rfc2822:!1,weekdayMismatch:!1}),e._pf}function g(e){var t=null,r=!1,i=e._d&&!isNaN(e._d.getTime());return i&&(t=p(e),r=n.call(t.parsedDateParts,(function(e){return null!=e})),i=t.overflow<0&&!t.empty&&!t.invalidEra&&!t.invalidMonth&&!t.invalidWeekday&&!t.weekdayMismatch&&!t.nullInput&&!t.invalidFormat&&!t.userInvalidated&&(!t.meridiem||t.meridiem&&r),e._strict&&(i=i&&0===t.charsLeftOver&&0===t.unusedTokens.length&&void 0===t.bigHour)),null!=Object.isFrozen&&Object.isFrozen(e)?i:(e._isValid=i,e._isValid)}function m(e){var t=f(NaN);return null!=e?h(p(t),e):p(t).userInvalidated=!0,t}n=Array.prototype.some?Array.prototype.some:function(e){var t,n=Object(this),r=n.length>>>0;for(t=0;t<r;t++)if(t in n&&e.call(this,n[t],t,n))return!0;return!1};var y=r.momentProperties=[],v=!1;function b(e,t){var n,r,i,o=y.length;if(c(t._isAMomentObject)||(e._isAMomentObject=t._isAMomentObject),c(t._i)||(e._i=t._i),c(t._f)||(e._f=t._f),c(t._l)||(e._l=t._l),c(t._strict)||(e._strict=t._strict),c(t._tzm)||(e._tzm=t._tzm),c(t._isUTC)||(e._isUTC=t._isUTC),c(t._offset)||(e._offset=t._offset),c(t._pf)||(e._pf=p(t)),c(t._locale)||(e._locale=t._locale),o>0)for(n=0;n<o;n++)c(i=t[r=y[n]])||(e[r]=i);return e}function w(e){b(this,e),this._d=new Date(null!=e._d?e._d.getTime():NaN),this.isValid()||(this._d=new Date(NaN)),!1===v&&(v=!0,r.updateOffset(this),v=!1)}function S(e){return e instanceof w||null!=e&&null!=e._isAMomentObject}function _(e){!1===r.suppressDeprecationWarnings&&"undefined"!=typeof console&&console.warn&&console.warn("Deprecation warning: "+e)}function I(e,t){var n=!0;return h((function(){if(null!=r.deprecationHandler&&r.deprecationHandler(null,e),n){var i,o,a,c=[],l=arguments.length;for(o=0;o<l;o++){if(i="","object"==typeof arguments[o]){for(a in i+="\n["+o+"] ",arguments[0])s(arguments[0],a)&&(i+=a+": "+arguments[0][a]+", ");i=i.slice(0,-2)}else i=arguments[o];c.push(i)}_(e+"\nArguments: "+Array.prototype.slice.call(c).join("")+"\n"+(new Error).stack),n=!1}return t.apply(this,arguments)}),t)}var x,k={};function E(e,t){null!=r.deprecationHandler&&r.deprecationHandler(e,t),k[e]||(_(t),k[e]=!0)}function C(e){return"undefined"!=typeof Function&&e instanceof Function||"[object Function]"===Object.prototype.toString.call(e)}function $(e,t){var n,r=h({},e);for(n in t)s(t,n)&&(o(e[n])&&o(t[n])?(r[n]={},h(r[n],e[n]),h(r[n],t[n])):null!=t[n]?r[n]=t[n]:delete r[n]);for(n in e)s(e,n)&&!s(t,n)&&o(e[n])&&(r[n]=h({},r[n]));return r}function O(e){null!=e&&this.set(e)}r.suppressDeprecationWarnings=!1,r.deprecationHandler=null,x=Object.keys?Object.keys:function(e){var t,n=[];for(t in e)s(e,t)&&n.push(t);return n};function N(e,t,n){var r=""+Math.abs(e),i=t-r.length;return(e>=0?n?"+":"":"-")+Math.pow(10,Math.max(0,i)).toString().substr(1)+r}var T=/(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|N{1,5}|YYYYYY|YYYYY|YYYY|YY|y{2,4}|yo?|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g,A=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,M={},P={};function D(e,t,n,r){var i=r;"string"==typeof r&&(i=function(){return this[r]()}),e&&(P[e]=i),t&&(P[t[0]]=function(){return N(i.apply(this,arguments),t[1],t[2])}),n&&(P[n]=function(){return this.localeData().ordinal(i.apply(this,arguments),e)})}function j(e){return e.match(/\[[\s\S]/)?e.replace(/^\[|\]$/g,""):e.replace(/\\/g,"")}function R(e,t){return e.isValid()?(t=L(t,e.localeData()),M[t]=M[t]||function(e){var t,n,r=e.match(T);for(t=0,n=r.length;t<n;t++)P[r[t]]?r[t]=P[r[t]]:r[t]=j(r[t]);return function(t){var i,o="";for(i=0;i<n;i++)o+=C(r[i])?r[i].call(t,e):r[i];return o}}(t),M[t](e)):e.localeData().invalidDate()}function L(e,t){var n=5;function r(e){return t.longDateFormat(e)||e}for(A.lastIndex=0;n>=0&&A.test(e);)e=e.replace(A,r),A.lastIndex=0,n-=1;return e}var F={D:"date",dates:"date",date:"date",d:"day",days:"day",day:"day",e:"weekday",weekdays:"weekday",weekday:"weekday",E:"isoWeekday",isoweekdays:"isoWeekday",isoweekday:"isoWeekday",DDD:"dayOfYear",dayofyears:"dayOfYear",dayofyear:"dayOfYear",h:"hour",hours:"hour",hour:"hour",ms:"millisecond",milliseconds:"millisecond",millisecond:"millisecond",m:"minute",minutes:"minute",minute:"minute",M:"month",months:"month",month:"month",Q:"quarter",quarters:"quarter",quarter:"quarter",s:"second",seconds:"second",second:"second",gg:"weekYear",weekyears:"weekYear",weekyear:"weekYear",GG:"isoWeekYear",isoweekyears:"isoWeekYear",isoweekyear:"isoWeekYear",w:"week",weeks:"week",week:"week",W:"isoWeek",isoweeks:"isoWeek",isoweek:"isoWeek",y:"year",years:"year",year:"year"};function U(e){return"string"==typeof e?F[e]||F[e.toLowerCase()]:void 0}function B(e){var t,n,r={};for(n in e)s(e,n)&&(t=U(n))&&(r[t]=e[n]);return r}var W={date:9,day:11,weekday:11,isoWeekday:11,dayOfYear:4,hour:13,millisecond:16,minute:14,month:8,quarter:7,second:15,weekYear:1,isoWeekYear:1,week:5,isoWeek:5,year:1};var G,V=/\d/,Y=/\d\d/,H=/\d{3}/,z=/\d{4}/,q=/[+-]?\d{6}/,K=/\d\d?/,J=/\d\d\d\d?/,Z=/\d\d\d\d\d\d?/,X=/\d{1,3}/,Q=/\d{1,4}/,ee=/[+-]?\d{1,6}/,te=/\d+/,ne=/[+-]?\d+/,re=/Z|[+-]\d\d:?\d\d/gi,ie=/Z|[+-]\d\d(?::?\d\d)?/gi,oe=/[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i,se=/^[1-9]\d?/,ae=/^([1-9]\d|\d)/;function ce(e,t,n){G[e]=C(t)?t:function(e){return e&&n?n:t}}function le(e,t){return s(G,e)?G[e](t._strict,t._locale):new RegExp(function(e){return ue(e.replace("\\","").replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g,(function(e,t,n,r,i){return t||n||r||i})))}(e))}function ue(e){return e.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")}function de(e){return e<0?Math.ceil(e)||0:Math.floor(e)}function he(e){var t=+e,n=0;return 0!==t&&isFinite(t)&&(n=de(t)),n}G={};var fe={};function pe(e,t){var n,r,i=t;for("string"==typeof e&&(e=[e]),l(t)&&(i=function(e,n){n[t]=he(e)}),r=e.length,n=0;n<r;n++)fe[e[n]]=i}function ge(e,t){pe(e,(function(e,n,r,i){r._w=r._w||{},t(e,r._w,r,i)}))}function me(e,t,n){null!=t&&s(fe,e)&&fe[e](t,n._a,n,e)}function ye(e){return e%4==0&&e%100!=0||e%400==0}var ve=0,be=1,we=2,Se=3,_e=4,Ie=5,xe=6,ke=7,Ee=8;function Ce(e){return ye(e)?366:365}D("Y",0,0,(function(){var e=this.year();return e<=9999?N(e,4):"+"+e})),D(0,["YY",2],0,(function(){return this.year()%100})),D(0,["YYYY",4],0,"year"),D(0,["YYYYY",5],0,"year"),D(0,["YYYYYY",6,!0],0,"year"),ce("Y",ne),ce("YY",K,Y),ce("YYYY",Q,z),ce("YYYYY",ee,q),ce("YYYYYY",ee,q),pe(["YYYYY","YYYYYY"],ve),pe("YYYY",(function(e,t){t[ve]=2===e.length?r.parseTwoDigitYear(e):he(e)})),pe("YY",(function(e,t){t[ve]=r.parseTwoDigitYear(e)})),pe("Y",(function(e,t){t[ve]=parseInt(e,10)})),r.parseTwoDigitYear=function(e){return he(e)+(he(e)>68?1900:2e3)};var $e,Oe=Ne("FullYear",!0);function Ne(e,t){return function(n){return null!=n?(Ae(this,e,n),r.updateOffset(this,t),this):Te(this,e)}}function Te(e,t){if(!e.isValid())return NaN;var n=e._d,r=e._isUTC;switch(t){case"Milliseconds":return r?n.getUTCMilliseconds():n.getMilliseconds();case"Seconds":return r?n.getUTCSeconds():n.getSeconds();case"Minutes":return r?n.getUTCMinutes():n.getMinutes();case"Hours":return r?n.getUTCHours():n.getHours();case"Date":return r?n.getUTCDate():n.getDate();case"Day":return r?n.getUTCDay():n.getDay();case"Month":return r?n.getUTCMonth():n.getMonth();case"FullYear":return r?n.getUTCFullYear():n.getFullYear();default:return NaN}}function Ae(e,t,n){var r,i,o,s,a;if(e.isValid()&&!isNaN(n)){switch(r=e._d,i=e._isUTC,t){case"Milliseconds":return void(i?r.setUTCMilliseconds(n):r.setMilliseconds(n));case"Seconds":return void(i?r.setUTCSeconds(n):r.setSeconds(n));case"Minutes":return void(i?r.setUTCMinutes(n):r.setMinutes(n));case"Hours":return void(i?r.setUTCHours(n):r.setHours(n));case"Date":return void(i?r.setUTCDate(n):r.setDate(n));case"FullYear":break;default:return}o=n,s=e.month(),a=29!==(a=e.date())||1!==s||ye(o)?a:28,i?r.setUTCFullYear(o,s,a):r.setFullYear(o,s,a)}}function Me(e,t){if(isNaN(e)||isNaN(t))return NaN;var n=function(e,t){return(e%t+t)%t}(t,12);return e+=(t-n)/12,1===n?ye(e)?29:28:31-n%7%2}$e=Array.prototype.indexOf?Array.prototype.indexOf:function(e){var t;for(t=0;t<this.length;++t)if(this[t]===e)return t;return-1},D("M",["MM",2],"Mo",(function(){return this.month()+1})),D("MMM",0,0,(function(e){return this.localeData().monthsShort(this,e)})),D("MMMM",0,0,(function(e){return this.localeData().months(this,e)})),ce("M",K,se),ce("MM",K,Y),ce("MMM",(function(e,t){return t.monthsShortRegex(e)})),ce("MMMM",(function(e,t){return t.monthsRegex(e)})),pe(["M","MM"],(function(e,t){t[be]=he(e)-1})),pe(["MMM","MMMM"],(function(e,t,n,r){var i=n._locale.monthsParse(e,r,n._strict);null!=i?t[be]=i:p(n).invalidMonth=e}));var Pe="January_February_March_April_May_June_July_August_September_October_November_December".split("_"),De="Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),je=/D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/,Re=oe,Le=oe;function Fe(e,t,n){var r,i,o,s=e.toLocaleLowerCase();if(!this._monthsParse)for(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[],r=0;r<12;++r)o=f([2e3,r]),this._shortMonthsParse[r]=this.monthsShort(o,"").toLocaleLowerCase(),this._longMonthsParse[r]=this.months(o,"").toLocaleLowerCase();return n?"MMM"===t?-1!==(i=$e.call(this._shortMonthsParse,s))?i:null:-1!==(i=$e.call(this._longMonthsParse,s))?i:null:"MMM"===t?-1!==(i=$e.call(this._shortMonthsParse,s))||-1!==(i=$e.call(this._longMonthsParse,s))?i:null:-1!==(i=$e.call(this._longMonthsParse,s))||-1!==(i=$e.call(this._shortMonthsParse,s))?i:null}function Ue(e,t){if(!e.isValid())return e;if("string"==typeof t)if(/^\d+$/.test(t))t=he(t);else if(!l(t=e.localeData().monthsParse(t)))return e;var n=t,r=e.date();return r=r<29?r:Math.min(r,Me(e.year(),n)),e._isUTC?e._d.setUTCMonth(n,r):e._d.setMonth(n,r),e}function Be(e){return null!=e?(Ue(this,e),r.updateOffset(this,!0),this):Te(this,"Month")}function We(){function e(e,t){return t.length-e.length}var t,n,r,i,o=[],s=[],a=[];for(t=0;t<12;t++)n=f([2e3,t]),r=ue(this.monthsShort(n,"")),i=ue(this.months(n,"")),o.push(r),s.push(i),a.push(i),a.push(r);o.sort(e),s.sort(e),a.sort(e),this._monthsRegex=new RegExp("^("+a.join("|")+")","i"),this._monthsShortRegex=this._monthsRegex,this._monthsStrictRegex=new RegExp("^("+s.join("|")+")","i"),this._monthsShortStrictRegex=new RegExp("^("+o.join("|")+")","i")}function Ge(e,t,n,r,i,o,s){var a;return e<100&&e>=0?(a=new Date(e+400,t,n,r,i,o,s),isFinite(a.getFullYear())&&a.setFullYear(e)):a=new Date(e,t,n,r,i,o,s),a}function Ve(e){var t,n;return e<100&&e>=0?((n=Array.prototype.slice.call(arguments))[0]=e+400,t=new Date(Date.UTC.apply(null,n)),isFinite(t.getUTCFullYear())&&t.setUTCFullYear(e)):t=new Date(Date.UTC.apply(null,arguments)),t}function Ye(e,t,n){var r=7+t-n;return-(7+Ve(e,0,r).getUTCDay()-t)%7+r-1}function He(e,t,n,r,i){var o,s,a=1+7*(t-1)+(7+n-r)%7+Ye(e,r,i);return a<=0?s=Ce(o=e-1)+a:a>Ce(e)?(o=e+1,s=a-Ce(e)):(o=e,s=a),{year:o,dayOfYear:s}}function ze(e,t,n){var r,i,o=Ye(e.year(),t,n),s=Math.floor((e.dayOfYear()-o-1)/7)+1;return s<1?r=s+qe(i=e.year()-1,t,n):s>qe(e.year(),t,n)?(r=s-qe(e.year(),t,n),i=e.year()+1):(i=e.year(),r=s),{week:r,year:i}}function qe(e,t,n){var r=Ye(e,t,n),i=Ye(e+1,t,n);return(Ce(e)-r+i)/7}D("w",["ww",2],"wo","week"),D("W",["WW",2],"Wo","isoWeek"),ce("w",K,se),ce("ww",K,Y),ce("W",K,se),ce("WW",K,Y),ge(["w","ww","W","WW"],(function(e,t,n,r){t[r.substr(0,1)]=he(e)}));function Ke(e,t){return e.slice(t,7).concat(e.slice(0,t))}D("d",0,"do","day"),D("dd",0,0,(function(e){return this.localeData().weekdaysMin(this,e)})),D("ddd",0,0,(function(e){return this.localeData().weekdaysShort(this,e)})),D("dddd",0,0,(function(e){return this.localeData().weekdays(this,e)})),D("e",0,0,"weekday"),D("E",0,0,"isoWeekday"),ce("d",K),ce("e",K),ce("E",K),ce("dd",(function(e,t){return t.weekdaysMinRegex(e)})),ce("ddd",(function(e,t){return t.weekdaysShortRegex(e)})),ce("dddd",(function(e,t){return t.weekdaysRegex(e)})),ge(["dd","ddd","dddd"],(function(e,t,n,r){var i=n._locale.weekdaysParse(e,r,n._strict);null!=i?t.d=i:p(n).invalidWeekday=e})),ge(["d","e","E"],(function(e,t,n,r){t[r]=he(e)}));var Je="Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),Ze="Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),Xe="Su_Mo_Tu_We_Th_Fr_Sa".split("_"),Qe=oe,et=oe,tt=oe;function nt(e,t,n){var r,i,o,s=e.toLocaleLowerCase();if(!this._weekdaysParse)for(this._weekdaysParse=[],this._shortWeekdaysParse=[],this._minWeekdaysParse=[],r=0;r<7;++r)o=f([2e3,1]).day(r),this._minWeekdaysParse[r]=this.weekdaysMin(o,"").toLocaleLowerCase(),this._shortWeekdaysParse[r]=this.weekdaysShort(o,"").toLocaleLowerCase(),this._weekdaysParse[r]=this.weekdays(o,"").toLocaleLowerCase();return n?"dddd"===t?-1!==(i=$e.call(this._weekdaysParse,s))?i:null:"ddd"===t?-1!==(i=$e.call(this._shortWeekdaysParse,s))?i:null:-1!==(i=$e.call(this._minWeekdaysParse,s))?i:null:"dddd"===t?-1!==(i=$e.call(this._weekdaysParse,s))||-1!==(i=$e.call(this._shortWeekdaysParse,s))||-1!==(i=$e.call(this._minWeekdaysParse,s))?i:null:"ddd"===t?-1!==(i=$e.call(this._shortWeekdaysParse,s))||-1!==(i=$e.call(this._weekdaysParse,s))||-1!==(i=$e.call(this._minWeekdaysParse,s))?i:null:-1!==(i=$e.call(this._minWeekdaysParse,s))||-1!==(i=$e.call(this._weekdaysParse,s))||-1!==(i=$e.call(this._shortWeekdaysParse,s))?i:null}function rt(){function e(e,t){return t.length-e.length}var t,n,r,i,o,s=[],a=[],c=[],l=[];for(t=0;t<7;t++)n=f([2e3,1]).day(t),r=ue(this.weekdaysMin(n,"")),i=ue(this.weekdaysShort(n,"")),o=ue(this.weekdays(n,"")),s.push(r),a.push(i),c.push(o),l.push(r),l.push(i),l.push(o);s.sort(e),a.sort(e),c.sort(e),l.sort(e),this._weekdaysRegex=new RegExp("^("+l.join("|")+")","i"),this._weekdaysShortRegex=this._weekdaysRegex,this._weekdaysMinRegex=this._weekdaysRegex,this._weekdaysStrictRegex=new RegExp("^("+c.join("|")+")","i"),this._weekdaysShortStrictRegex=new RegExp("^("+a.join("|")+")","i"),this._weekdaysMinStrictRegex=new RegExp("^("+s.join("|")+")","i")}function it(){return this.hours()%12||12}function ot(e,t){D(e,0,0,(function(){return this.localeData().meridiem(this.hours(),this.minutes(),t)}))}function st(e,t){return t._meridiemParse}D("H",["HH",2],0,"hour"),D("h",["hh",2],0,it),D("k",["kk",2],0,(function(){return this.hours()||24})),D("hmm",0,0,(function(){return""+it.apply(this)+N(this.minutes(),2)})),D("hmmss",0,0,(function(){return""+it.apply(this)+N(this.minutes(),2)+N(this.seconds(),2)})),D("Hmm",0,0,(function(){return""+this.hours()+N(this.minutes(),2)})),D("Hmmss",0,0,(function(){return""+this.hours()+N(this.minutes(),2)+N(this.seconds(),2)})),ot("a",!0),ot("A",!1),ce("a",st),ce("A",st),ce("H",K,ae),ce("h",K,se),ce("k",K,se),ce("HH",K,Y),ce("hh",K,Y),ce("kk",K,Y),ce("hmm",J),ce("hmmss",Z),ce("Hmm",J),ce("Hmmss",Z),pe(["H","HH"],Se),pe(["k","kk"],(function(e,t){var n=he(e);t[Se]=24===n?0:n})),pe(["a","A"],(function(e,t,n){n._isPm=n._locale.isPM(e),n._meridiem=e})),pe(["h","hh"],(function(e,t,n){t[Se]=he(e),p(n).bigHour=!0})),pe("hmm",(function(e,t,n){var r=e.length-2;t[Se]=he(e.substr(0,r)),t[_e]=he(e.substr(r)),p(n).bigHour=!0})),pe("hmmss",(function(e,t,n){var r=e.length-4,i=e.length-2;t[Se]=he(e.substr(0,r)),t[_e]=he(e.substr(r,2)),t[Ie]=he(e.substr(i)),p(n).bigHour=!0})),pe("Hmm",(function(e,t){var n=e.length-2;t[Se]=he(e.substr(0,n)),t[_e]=he(e.substr(n))})),pe("Hmmss",(function(e,t){var n=e.length-4,r=e.length-2;t[Se]=he(e.substr(0,n)),t[_e]=he(e.substr(n,2)),t[Ie]=he(e.substr(r))}));var at=Ne("Hours",!0);var ct,lt={calendar:{sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"},longDateFormat:{LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A"},invalidDate:"Invalid date",ordinal:"%d",dayOfMonthOrdinalParse:/\d{1,2}/,relativeTime:{future:"in %s",past:"%s ago",s:"a few seconds",ss:"%d seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",w:"a week",ww:"%d weeks",M:"a month",MM:"%d months",y:"a year",yy:"%d years"},months:Pe,monthsShort:De,week:{dow:0,doy:6},weekdays:Je,weekdaysMin:Xe,weekdaysShort:Ze,meridiemParse:/[ap]\.?m?\.?/i},ut={},dt={};function ht(e,t){var n,r=Math.min(e.length,t.length);for(n=0;n<r;n+=1)if(e[n]!==t[n])return n;return r}function ft(e){return e?e.toLowerCase().replace("_","-"):e}function pt(t){var n=null;if(void 0===ut[t]&&e&&e.exports&&function(e){return!(!e||!e.match("^[^/\\\\]*$"))}(t))try{n=ct._abbr,function(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}("./locale/"+t),gt(n)}catch(e){ut[t]=null}return ut[t]}function gt(e,t){var n;return e&&((n=c(t)?yt(e):mt(e,t))?ct=n:"undefined"!=typeof console&&console.warn&&console.warn("Locale "+e+" not found. Did you forget to load it?")),ct._abbr}function mt(e,t){if(null!==t){var n,r=lt;if(t.abbr=e,null!=ut[e])E("defineLocaleOverride","use moment.updateLocale(localeName, config) to change an existing locale. moment.defineLocale(localeName, config) should only be used for creating a new locale See http://momentjs.com/guides/#/warnings/define-locale/ for more info."),r=ut[e]._config;else if(null!=t.parentLocale)if(null!=ut[t.parentLocale])r=ut[t.parentLocale]._config;else{if(null==(n=pt(t.parentLocale)))return dt[t.parentLocale]||(dt[t.parentLocale]=[]),dt[t.parentLocale].push({name:e,config:t}),null;r=n._config}return ut[e]=new O($(r,t)),dt[e]&&dt[e].forEach((function(e){mt(e.name,e.config)})),gt(e),ut[e]}return delete ut[e],null}function yt(e){var t;if(e&&e._locale&&e._locale._abbr&&(e=e._locale._abbr),!e)return ct;if(!i(e)){if(t=pt(e))return t;e=[e]}return function(e){for(var t,n,r,i,o=0;o<e.length;){for(t=(i=ft(e[o]).split("-")).length,n=(n=ft(e[o+1]))?n.split("-"):null;t>0;){if(r=pt(i.slice(0,t).join("-")))return r;if(n&&n.length>=t&&ht(i,n)>=t-1)break;t--}o++}return ct}(e)}function vt(e){var t,n=e._a;return n&&-2===p(e).overflow&&(t=n[be]<0||n[be]>11?be:n[we]<1||n[we]>Me(n[ve],n[be])?we:n[Se]<0||n[Se]>24||24===n[Se]&&(0!==n[_e]||0!==n[Ie]||0!==n[xe])?Se:n[_e]<0||n[_e]>59?_e:n[Ie]<0||n[Ie]>59?Ie:n[xe]<0||n[xe]>999?xe:-1,p(e)._overflowDayOfYear&&(t<ve||t>we)&&(t=we),p(e)._overflowWeeks&&-1===t&&(t=ke),p(e)._overflowWeekday&&-1===t&&(t=Ee),p(e).overflow=t),e}var bt=/^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/,wt=/^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d|))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/,St=/Z|[+-]\d\d(?::?\d\d)?/,_t=[["YYYYYY-MM-DD",/[+-]\d{6}-\d\d-\d\d/],["YYYY-MM-DD",/\d{4}-\d\d-\d\d/],["GGGG-[W]WW-E",/\d{4}-W\d\d-\d/],["GGGG-[W]WW",/\d{4}-W\d\d/,!1],["YYYY-DDD",/\d{4}-\d{3}/],["YYYY-MM",/\d{4}-\d\d/,!1],["YYYYYYMMDD",/[+-]\d{10}/],["YYYYMMDD",/\d{8}/],["GGGG[W]WWE",/\d{4}W\d{3}/],["GGGG[W]WW",/\d{4}W\d{2}/,!1],["YYYYDDD",/\d{7}/],["YYYYMM",/\d{6}/,!1],["YYYY",/\d{4}/,!1]],It=[["HH:mm:ss.SSSS",/\d\d:\d\d:\d\d\.\d+/],["HH:mm:ss,SSSS",/\d\d:\d\d:\d\d,\d+/],["HH:mm:ss",/\d\d:\d\d:\d\d/],["HH:mm",/\d\d:\d\d/],["HHmmss.SSSS",/\d\d\d\d\d\d\.\d+/],["HHmmss,SSSS",/\d\d\d\d\d\d,\d+/],["HHmmss",/\d\d\d\d\d\d/],["HHmm",/\d\d\d\d/],["HH",/\d\d/]],xt=/^\/?Date\((-?\d+)/i,kt=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/,Et={UT:0,GMT:0,EDT:-240,EST:-300,CDT:-300,CST:-360,MDT:-360,MST:-420,PDT:-420,PST:-480};function Ct(e){var t,n,r,i,o,s,a=e._i,c=bt.exec(a)||wt.exec(a),l=_t.length,u=It.length;if(c){for(p(e).iso=!0,t=0,n=l;t<n;t++)if(_t[t][1].exec(c[1])){i=_t[t][0],r=!1!==_t[t][2];break}if(null==i)return void(e._isValid=!1);if(c[3]){for(t=0,n=u;t<n;t++)if(It[t][1].exec(c[3])){o=(c[2]||" ")+It[t][0];break}if(null==o)return void(e._isValid=!1)}if(!r&&null!=o)return void(e._isValid=!1);if(c[4]){if(!St.exec(c[4]))return void(e._isValid=!1);s="Z"}e._f=i+(o||"")+(s||""),Mt(e)}else e._isValid=!1}function $t(e){var t=parseInt(e,10);return t<=49?2e3+t:t<=999?1900+t:t}function Ot(e){var t,n=kt.exec(function(e){return e.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").replace(/^\s\s*/,"").replace(/\s\s*$/,"")}(e._i));if(n){if(t=function(e,t,n,r,i,o){var s=[$t(e),De.indexOf(t),parseInt(n,10),parseInt(r,10),parseInt(i,10)];return o&&s.push(parseInt(o,10)),s}(n[4],n[3],n[2],n[5],n[6],n[7]),!function(e,t,n){return!e||Ze.indexOf(e)===new Date(t[0],t[1],t[2]).getDay()||(p(n).weekdayMismatch=!0,n._isValid=!1,!1)}(n[1],t,e))return;e._a=t,e._tzm=function(e,t,n){if(e)return Et[e];if(t)return 0;var r=parseInt(n,10),i=r%100;return(r-i)/100*60+i}(n[8],n[9],n[10]),e._d=Ve.apply(null,e._a),e._d.setUTCMinutes(e._d.getUTCMinutes()-e._tzm),p(e).rfc2822=!0}else e._isValid=!1}function Nt(e,t,n){return null!=e?e:null!=t?t:n}function Tt(e){var t=new Date(r.now());return e._useUTC?[t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate()]:[t.getFullYear(),t.getMonth(),t.getDate()]}function At(e){var t,n,r,i,o,s=[];if(!e._d){for(r=Tt(e),e._w&&null==e._a[we]&&null==e._a[be]&&function(e){var t,n,r,i,o,s,a,c,l;null!=(t=e._w).GG||null!=t.W||null!=t.E?(o=1,s=4,n=Nt(t.GG,e._a[ve],ze(jt(),1,4).year),r=Nt(t.W,1),((i=Nt(t.E,1))<1||i>7)&&(c=!0)):(o=e._locale._week.dow,s=e._locale._week.doy,l=ze(jt(),o,s),n=Nt(t.gg,e._a[ve],l.year),r=Nt(t.w,l.week),null!=t.d?((i=t.d)<0||i>6)&&(c=!0):null!=t.e?(i=t.e+o,(t.e<0||t.e>6)&&(c=!0)):i=o),r<1||r>qe(n,o,s)?p(e)._overflowWeeks=!0:null!=c?p(e)._overflowWeekday=!0:(a=He(n,r,i,o,s),e._a[ve]=a.year,e._dayOfYear=a.dayOfYear)}(e),null!=e._dayOfYear&&(o=Nt(e._a[ve],r[ve]),(e._dayOfYear>Ce(o)||0===e._dayOfYear)&&(p(e)._overflowDayOfYear=!0),n=Ve(o,0,e._dayOfYear),e._a[be]=n.getUTCMonth(),e._a[we]=n.getUTCDate()),t=0;t<3&&null==e._a[t];++t)e._a[t]=s[t]=r[t];for(;t<7;t++)e._a[t]=s[t]=null==e._a[t]?2===t?1:0:e._a[t];24===e._a[Se]&&0===e._a[_e]&&0===e._a[Ie]&&0===e._a[xe]&&(e._nextDay=!0,e._a[Se]=0),e._d=(e._useUTC?Ve:Ge).apply(null,s),i=e._useUTC?e._d.getUTCDay():e._d.getDay(),null!=e._tzm&&e._d.setUTCMinutes(e._d.getUTCMinutes()-e._tzm),e._nextDay&&(e._a[Se]=24),e._w&&void 0!==e._w.d&&e._w.d!==i&&(p(e).weekdayMismatch=!0)}}function Mt(e){if(e._f!==r.ISO_8601)if(e._f!==r.RFC_2822){e._a=[],p(e).empty=!0;var t,n,i,o,s,a,c,l=""+e._i,u=l.length,d=0;for(c=(i=L(e._f,e._locale).match(T)||[]).length,t=0;t<c;t++)o=i[t],(n=(l.match(le(o,e))||[])[0])&&((s=l.substr(0,l.indexOf(n))).length>0&&p(e).unusedInput.push(s),l=l.slice(l.indexOf(n)+n.length),d+=n.length),P[o]?(n?p(e).empty=!1:p(e).unusedTokens.push(o),me(o,n,e)):e._strict&&!n&&p(e).unusedTokens.push(o);p(e).charsLeftOver=u-d,l.length>0&&p(e).unusedInput.push(l),e._a[Se]<=12&&!0===p(e).bigHour&&e._a[Se]>0&&(p(e).bigHour=void 0),p(e).parsedDateParts=e._a.slice(0),p(e).meridiem=e._meridiem,e._a[Se]=function(e,t,n){var r;return null==n?t:null!=e.meridiemHour?e.meridiemHour(t,n):null!=e.isPM?((r=e.isPM(n))&&t<12&&(t+=12),r||12!==t||(t=0),t):t}(e._locale,e._a[Se],e._meridiem),null!==(a=p(e).era)&&(e._a[ve]=e._locale.erasConvertYear(a,e._a[ve])),At(e),vt(e)}else Ot(e);else Ct(e)}function Pt(e){var t=e._i,n=e._f;return e._locale=e._locale||yt(e._l),null===t||void 0===n&&""===t?m({nullInput:!0}):("string"==typeof t&&(e._i=t=e._locale.preparse(t)),S(t)?new w(vt(t)):(u(t)?e._d=t:i(n)?function(e){var t,n,r,i,o,s,a=!1,c=e._f.length;if(0===c)return p(e).invalidFormat=!0,void(e._d=new Date(NaN));for(i=0;i<c;i++)o=0,s=!1,t=b({},e),null!=e._useUTC&&(t._useUTC=e._useUTC),t._f=e._f[i],Mt(t),g(t)&&(s=!0),o+=p(t).charsLeftOver,o+=10*p(t).unusedTokens.length,p(t).score=o,a?o<r&&(r=o,n=t):(null==r||o<r||s)&&(r=o,n=t,s&&(a=!0));h(e,n||t)}(e):n?Mt(e):function(e){var t=e._i;c(t)?e._d=new Date(r.now()):u(t)?e._d=new Date(t.valueOf()):"string"==typeof t?function(e){var t=xt.exec(e._i);null===t?(Ct(e),!1===e._isValid&&(delete e._isValid,Ot(e),!1===e._isValid&&(delete e._isValid,e._strict?e._isValid=!1:r.createFromInputFallback(e)))):e._d=new Date(+t[1])}(e):i(t)?(e._a=d(t.slice(0),(function(e){return parseInt(e,10)})),At(e)):o(t)?function(e){if(!e._d){var t=B(e._i),n=void 0===t.day?t.date:t.day;e._a=d([t.year,t.month,n,t.hour,t.minute,t.second,t.millisecond],(function(e){return e&&parseInt(e,10)})),At(e)}}(e):l(t)?e._d=new Date(t):r.createFromInputFallback(e)}(e),g(e)||(e._d=null),e))}function Dt(e,t,n,r,s){var c={};return!0!==t&&!1!==t||(r=t,t=void 0),!0!==n&&!1!==n||(r=n,n=void 0),(o(e)&&a(e)||i(e)&&0===e.length)&&(e=void 0),c._isAMomentObject=!0,c._useUTC=c._isUTC=s,c._l=n,c._i=e,c._f=t,c._strict=r,function(e){var t=new w(vt(Pt(e)));return t._nextDay&&(t.add(1,"d"),t._nextDay=void 0),t}(c)}function jt(e,t,n,r){return Dt(e,t,n,r,!1)}r.createFromInputFallback=I("value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.",(function(e){e._d=new Date(e._i+(e._useUTC?" UTC":""))})),r.ISO_8601=function(){},r.RFC_2822=function(){};var Rt=I("moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/",(function(){var e=jt.apply(null,arguments);return this.isValid()&&e.isValid()?e<this?this:e:m()})),Lt=I("moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/",(function(){var e=jt.apply(null,arguments);return this.isValid()&&e.isValid()?e>this?this:e:m()}));function Ft(e,t){var n,r;if(1===t.length&&i(t[0])&&(t=t[0]),!t.length)return jt();for(n=t[0],r=1;r<t.length;++r)t[r].isValid()&&!t[r][e](n)||(n=t[r]);return n}var Ut=["year","quarter","month","week","day","hour","minute","second","millisecond"];function Bt(e){var t,n,r=!1,i=Ut.length;for(t in e)if(s(e,t)&&(-1===$e.call(Ut,t)||null!=e[t]&&isNaN(e[t])))return!1;for(n=0;n<i;++n)if(e[Ut[n]]){if(r)return!1;parseFloat(e[Ut[n]])!==he(e[Ut[n]])&&(r=!0)}return!0}function Wt(e){var t=B(e),n=t.year||0,r=t.quarter||0,i=t.month||0,o=t.week||t.isoWeek||0,s=t.day||0,a=t.hour||0,c=t.minute||0,l=t.second||0,u=t.millisecond||0;this._isValid=Bt(t),this._milliseconds=+u+1e3*l+6e4*c+1e3*a*60*60,this._days=+s+7*o,this._months=+i+3*r+12*n,this._data={},this._locale=yt(),this._bubble()}function Gt(e){return e instanceof Wt}function Vt(e){return e<0?-1*Math.round(-1*e):Math.round(e)}function Yt(e,t){D(e,0,0,(function(){var e=this.utcOffset(),n="+";return e<0&&(e=-e,n="-"),n+N(~~(e/60),2)+t+N(~~e%60,2)}))}Yt("Z",":"),Yt("ZZ",""),ce("Z",ie),ce("ZZ",ie),pe(["Z","ZZ"],(function(e,t,n){n._useUTC=!0,n._tzm=zt(ie,e)}));var Ht=/([\+\-]|\d\d)/gi;function zt(e,t){var n,r,i=(t||"").match(e);return null===i?null:0===(r=60*(n=((i[i.length-1]||[])+"").match(Ht)||["-",0,0])[1]+he(n[2]))?0:"+"===n[0]?r:-r}function qt(e,t){var n,i;return t._isUTC?(n=t.clone(),i=(S(e)||u(e)?e.valueOf():jt(e).valueOf())-n.valueOf(),n._d.setTime(n._d.valueOf()+i),r.updateOffset(n,!1),n):jt(e).local()}function Kt(e){return-Math.round(e._d.getTimezoneOffset())}function Jt(){return!!this.isValid()&&this._isUTC&&0===this._offset}r.updateOffset=function(){};var Zt=/^(-|\+)?(?:(\d*)[. ])?(\d+):(\d+)(?::(\d+)(\.\d*)?)?$/,Xt=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;function Qt(e,t){var n,r,i,o=e,a=null;return Gt(e)?o={ms:e._milliseconds,d:e._days,M:e._months}:l(e)||!isNaN(+e)?(o={},t?o[t]=+e:o.milliseconds=+e):(a=Zt.exec(e))?(n="-"===a[1]?-1:1,o={y:0,d:he(a[we])*n,h:he(a[Se])*n,m:he(a[_e])*n,s:he(a[Ie])*n,ms:he(Vt(1e3*a[xe]))*n}):(a=Xt.exec(e))?(n="-"===a[1]?-1:1,o={y:en(a[2],n),M:en(a[3],n),w:en(a[4],n),d:en(a[5],n),h:en(a[6],n),m:en(a[7],n),s:en(a[8],n)}):null==o?o={}:"object"==typeof o&&("from"in o||"to"in o)&&(i=function(e,t){var n;return e.isValid()&&t.isValid()?(t=qt(t,e),e.isBefore(t)?n=tn(e,t):((n=tn(t,e)).milliseconds=-n.milliseconds,n.months=-n.months),n):{milliseconds:0,months:0}}(jt(o.from),jt(o.to)),(o={}).ms=i.milliseconds,o.M=i.months),r=new Wt(o),Gt(e)&&s(e,"_locale")&&(r._locale=e._locale),Gt(e)&&s(e,"_isValid")&&(r._isValid=e._isValid),r}function en(e,t){var n=e&&parseFloat(e.replace(",","."));return(isNaN(n)?0:n)*t}function tn(e,t){var n={};return n.months=t.month()-e.month()+12*(t.year()-e.year()),e.clone().add(n.months,"M").isAfter(t)&&--n.months,n.milliseconds=+t-+e.clone().add(n.months,"M"),n}function nn(e,t){return function(n,r){var i;return null===r||isNaN(+r)||(E(t,"moment()."+t+"(period, number) is deprecated. Please use moment()."+t+"(number, period). See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info."),i=n,n=r,r=i),rn(this,Qt(n,r),e),this}}function rn(e,t,n,i){var o=t._milliseconds,s=Vt(t._days),a=Vt(t._months);e.isValid()&&(i=null==i||i,a&&Ue(e,Te(e,"Month")+a*n),s&&Ae(e,"Date",Te(e,"Date")+s*n),o&&e._d.setTime(e._d.valueOf()+o*n),i&&r.updateOffset(e,s||a))}Qt.fn=Wt.prototype,Qt.invalid=function(){return Qt(NaN)};var on=nn(1,"add"),sn=nn(-1,"subtract");function an(e){return"string"==typeof e||e instanceof String}function cn(e){return S(e)||u(e)||an(e)||l(e)||function(e){var t=i(e),n=!1;return t&&(n=0===e.filter((function(t){return!l(t)&&an(e)})).length),t&&n}(e)||function(e){var t,n,r=o(e)&&!a(e),i=!1,c=["years","year","y","months","month","M","days","day","d","dates","date","D","hours","hour","h","minutes","minute","m","seconds","second","s","milliseconds","millisecond","ms"],l=c.length;for(t=0;t<l;t+=1)n=c[t],i=i||s(e,n);return r&&i}(e)||null==e}function ln(e){var t,n=o(e)&&!a(e),r=!1,i=["sameDay","nextDay","lastDay","nextWeek","lastWeek","sameElse"];for(t=0;t<i.length;t+=1)r=r||s(e,i[t]);return n&&r}function un(e,t){if(e.date()<t.date())return-un(t,e);var n=12*(t.year()-e.year())+(t.month()-e.month()),r=e.clone().add(n,"months");return-(n+(t-r<0?(t-r)/(r-e.clone().add(n-1,"months")):(t-r)/(e.clone().add(n+1,"months")-r)))||0}function dn(e){var t;return void 0===e?this._locale._abbr:(null!=(t=yt(e))&&(this._locale=t),this)}r.defaultFormat="YYYY-MM-DDTHH:mm:ssZ",r.defaultFormatUtc="YYYY-MM-DDTHH:mm:ss[Z]";var hn=I("moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.",(function(e){return void 0===e?this.localeData():this.locale(e)}));function fn(){return this._locale}var pn=1e3,gn=6e4,mn=60*gn,yn=3506328*mn;function vn(e,t){return(e%t+t)%t}function bn(e,t,n){return e<100&&e>=0?new Date(e+400,t,n)-yn:new Date(e,t,n).valueOf()}function wn(e,t,n){return e<100&&e>=0?Date.UTC(e+400,t,n)-yn:Date.UTC(e,t,n)}function Sn(e,t){return t.erasAbbrRegex(e)}function _n(){var e,t,n,r,i,o=[],s=[],a=[],c=[],l=this.eras();for(e=0,t=l.length;e<t;++e)n=ue(l[e].name),r=ue(l[e].abbr),i=ue(l[e].narrow),s.push(n),o.push(r),a.push(i),c.push(n),c.push(r),c.push(i);this._erasRegex=new RegExp("^("+c.join("|")+")","i"),this._erasNameRegex=new RegExp("^("+s.join("|")+")","i"),this._erasAbbrRegex=new RegExp("^("+o.join("|")+")","i"),this._erasNarrowRegex=new RegExp("^("+a.join("|")+")","i")}function In(e,t){D(0,[e,e.length],0,t)}function xn(e,t,n,r,i){var o;return null==e?ze(this,r,i).year:(t>(o=qe(e,r,i))&&(t=o),kn.call(this,e,t,n,r,i))}function kn(e,t,n,r,i){var o=He(e,t,n,r,i),s=Ve(o.year,0,o.dayOfYear);return this.year(s.getUTCFullYear()),this.month(s.getUTCMonth()),this.date(s.getUTCDate()),this}D("N",0,0,"eraAbbr"),D("NN",0,0,"eraAbbr"),D("NNN",0,0,"eraAbbr"),D("NNNN",0,0,"eraName"),D("NNNNN",0,0,"eraNarrow"),D("y",["y",1],"yo","eraYear"),D("y",["yy",2],0,"eraYear"),D("y",["yyy",3],0,"eraYear"),D("y",["yyyy",4],0,"eraYear"),ce("N",Sn),ce("NN",Sn),ce("NNN",Sn),ce("NNNN",(function(e,t){return t.erasNameRegex(e)})),ce("NNNNN",(function(e,t){return t.erasNarrowRegex(e)})),pe(["N","NN","NNN","NNNN","NNNNN"],(function(e,t,n,r){var i=n._locale.erasParse(e,r,n._strict);i?p(n).era=i:p(n).invalidEra=e})),ce("y",te),ce("yy",te),ce("yyy",te),ce("yyyy",te),ce("yo",(function(e,t){return t._eraYearOrdinalRegex||te})),pe(["y","yy","yyy","yyyy"],ve),pe(["yo"],(function(e,t,n){var r;n._locale._eraYearOrdinalRegex&&(r=e.match(n._locale._eraYearOrdinalRegex)),n._locale.eraYearOrdinalParse?t[ve]=n._locale.eraYearOrdinalParse(e,r):t[ve]=parseInt(e,10)})),D(0,["gg",2],0,(function(){return this.weekYear()%100})),D(0,["GG",2],0,(function(){return this.isoWeekYear()%100})),In("gggg","weekYear"),In("ggggg","weekYear"),In("GGGG","isoWeekYear"),In("GGGGG","isoWeekYear"),ce("G",ne),ce("g",ne),ce("GG",K,Y),ce("gg",K,Y),ce("GGGG",Q,z),ce("gggg",Q,z),ce("GGGGG",ee,q),ce("ggggg",ee,q),ge(["gggg","ggggg","GGGG","GGGGG"],(function(e,t,n,r){t[r.substr(0,2)]=he(e)})),ge(["gg","GG"],(function(e,t,n,i){t[i]=r.parseTwoDigitYear(e)})),D("Q",0,"Qo","quarter"),ce("Q",V),pe("Q",(function(e,t){t[be]=3*(he(e)-1)})),D("D",["DD",2],"Do","date"),ce("D",K,se),ce("DD",K,Y),ce("Do",(function(e,t){return e?t._dayOfMonthOrdinalParse||t._ordinalParse:t._dayOfMonthOrdinalParseLenient})),pe(["D","DD"],we),pe("Do",(function(e,t){t[we]=he(e.match(K)[0])}));var En=Ne("Date",!0);D("DDD",["DDDD",3],"DDDo","dayOfYear"),ce("DDD",X),ce("DDDD",H),pe(["DDD","DDDD"],(function(e,t,n){n._dayOfYear=he(e)})),D("m",["mm",2],0,"minute"),ce("m",K,ae),ce("mm",K,Y),pe(["m","mm"],_e);var Cn=Ne("Minutes",!1);D("s",["ss",2],0,"second"),ce("s",K,ae),ce("ss",K,Y),pe(["s","ss"],Ie);var $n,On,Nn=Ne("Seconds",!1);for(D("S",0,0,(function(){return~~(this.millisecond()/100)})),D(0,["SS",2],0,(function(){return~~(this.millisecond()/10)})),D(0,["SSS",3],0,"millisecond"),D(0,["SSSS",4],0,(function(){return 10*this.millisecond()})),D(0,["SSSSS",5],0,(function(){return 100*this.millisecond()})),D(0,["SSSSSS",6],0,(function(){return 1e3*this.millisecond()})),D(0,["SSSSSSS",7],0,(function(){return 1e4*this.millisecond()})),D(0,["SSSSSSSS",8],0,(function(){return 1e5*this.millisecond()})),D(0,["SSSSSSSSS",9],0,(function(){return 1e6*this.millisecond()})),ce("S",X,V),ce("SS",X,Y),ce("SSS",X,H),$n="SSSS";$n.length<=9;$n+="S")ce($n,te);function Tn(e,t){t[xe]=he(1e3*("0."+e))}for($n="S";$n.length<=9;$n+="S")pe($n,Tn);On=Ne("Milliseconds",!1),D("z",0,0,"zoneAbbr"),D("zz",0,0,"zoneName");var An=w.prototype;function Mn(e){return e}An.add=on,An.calendar=function(e,t){1===arguments.length&&(arguments[0]?cn(arguments[0])?(e=arguments[0],t=void 0):ln(arguments[0])&&(t=arguments[0],e=void 0):(e=void 0,t=void 0));var n=e||jt(),i=qt(n,this).startOf("day"),o=r.calendarFormat(this,i)||"sameElse",s=t&&(C(t[o])?t[o].call(this,n):t[o]);return this.format(s||this.localeData().calendar(o,this,jt(n)))},An.clone=function(){return new w(this)},An.diff=function(e,t,n){var r,i,o;if(!this.isValid())return NaN;if(!(r=qt(e,this)).isValid())return NaN;switch(i=6e4*(r.utcOffset()-this.utcOffset()),t=U(t)){case"year":o=un(this,r)/12;break;case"month":o=un(this,r);break;case"quarter":o=un(this,r)/3;break;case"second":o=(this-r)/1e3;break;case"minute":o=(this-r)/6e4;break;case"hour":o=(this-r)/36e5;break;case"day":o=(this-r-i)/864e5;break;case"week":o=(this-r-i)/6048e5;break;default:o=this-r}return n?o:de(o)},An.endOf=function(e){var t,n;if(void 0===(e=U(e))||"millisecond"===e||!this.isValid())return this;switch(n=this._isUTC?wn:bn,e){case"year":t=n(this.year()+1,0,1)-1;break;case"quarter":t=n(this.year(),this.month()-this.month()%3+3,1)-1;break;case"month":t=n(this.year(),this.month()+1,1)-1;break;case"week":t=n(this.year(),this.month(),this.date()-this.weekday()+7)-1;break;case"isoWeek":t=n(this.year(),this.month(),this.date()-(this.isoWeekday()-1)+7)-1;break;case"day":case"date":t=n(this.year(),this.month(),this.date()+1)-1;break;case"hour":t=this._d.valueOf(),t+=mn-vn(t+(this._isUTC?0:this.utcOffset()*gn),mn)-1;break;case"minute":t=this._d.valueOf(),t+=gn-vn(t,gn)-1;break;case"second":t=this._d.valueOf(),t+=pn-vn(t,pn)-1}return this._d.setTime(t),r.updateOffset(this,!0),this},An.format=function(e){e||(e=this.isUtc()?r.defaultFormatUtc:r.defaultFormat);var t=R(this,e);return this.localeData().postformat(t)},An.from=function(e,t){return this.isValid()&&(S(e)&&e.isValid()||jt(e).isValid())?Qt({to:this,from:e}).locale(this.locale()).humanize(!t):this.localeData().invalidDate()},An.fromNow=function(e){return this.from(jt(),e)},An.to=function(e,t){return this.isValid()&&(S(e)&&e.isValid()||jt(e).isValid())?Qt({from:this,to:e}).locale(this.locale()).humanize(!t):this.localeData().invalidDate()},An.toNow=function(e){return this.to(jt(),e)},An.get=function(e){return C(this[e=U(e)])?this[e]():this},An.invalidAt=function(){return p(this).overflow},An.isAfter=function(e,t){var n=S(e)?e:jt(e);return!(!this.isValid()||!n.isValid())&&("millisecond"===(t=U(t)||"millisecond")?this.valueOf()>n.valueOf():n.valueOf()<this.clone().startOf(t).valueOf())},An.isBefore=function(e,t){var n=S(e)?e:jt(e);return!(!this.isValid()||!n.isValid())&&("millisecond"===(t=U(t)||"millisecond")?this.valueOf()<n.valueOf():this.clone().endOf(t).valueOf()<n.valueOf())},An.isBetween=function(e,t,n,r){var i=S(e)?e:jt(e),o=S(t)?t:jt(t);return!!(this.isValid()&&i.isValid()&&o.isValid())&&("("===(r=r||"()")[0]?this.isAfter(i,n):!this.isBefore(i,n))&&(")"===r[1]?this.isBefore(o,n):!this.isAfter(o,n))},An.isSame=function(e,t){var n,r=S(e)?e:jt(e);return!(!this.isValid()||!r.isValid())&&("millisecond"===(t=U(t)||"millisecond")?this.valueOf()===r.valueOf():(n=r.valueOf(),this.clone().startOf(t).valueOf()<=n&&n<=this.clone().endOf(t).valueOf()))},An.isSameOrAfter=function(e,t){return this.isSame(e,t)||this.isAfter(e,t)},An.isSameOrBefore=function(e,t){return this.isSame(e,t)||this.isBefore(e,t)},An.isValid=function(){return g(this)},An.lang=hn,An.locale=dn,An.localeData=fn,An.max=Lt,An.min=Rt,An.parsingFlags=function(){return h({},p(this))},An.set=function(e,t){if("object"==typeof e){var n,r=function(e){var t,n=[];for(t in e)s(e,t)&&n.push({unit:t,priority:W[t]});return n.sort((function(e,t){return e.priority-t.priority})),n}(e=B(e)),i=r.length;for(n=0;n<i;n++)this[r[n].unit](e[r[n].unit])}else if(C(this[e=U(e)]))return this[e](t);return this},An.startOf=function(e){var t,n;if(void 0===(e=U(e))||"millisecond"===e||!this.isValid())return this;switch(n=this._isUTC?wn:bn,e){case"year":t=n(this.year(),0,1);break;case"quarter":t=n(this.year(),this.month()-this.month()%3,1);break;case"month":t=n(this.year(),this.month(),1);break;case"week":t=n(this.year(),this.month(),this.date()-this.weekday());break;case"isoWeek":t=n(this.year(),this.month(),this.date()-(this.isoWeekday()-1));break;case"day":case"date":t=n(this.year(),this.month(),this.date());break;case"hour":t=this._d.valueOf(),t-=vn(t+(this._isUTC?0:this.utcOffset()*gn),mn);break;case"minute":t=this._d.valueOf(),t-=vn(t,gn);break;case"second":t=this._d.valueOf(),t-=vn(t,pn)}return this._d.setTime(t),r.updateOffset(this,!0),this},An.subtract=sn,An.toArray=function(){var e=this;return[e.year(),e.month(),e.date(),e.hour(),e.minute(),e.second(),e.millisecond()]},An.toObject=function(){var e=this;return{years:e.year(),months:e.month(),date:e.date(),hours:e.hours(),minutes:e.minutes(),seconds:e.seconds(),milliseconds:e.milliseconds()}},An.toDate=function(){return new Date(this.valueOf())},An.toISOString=function(e){if(!this.isValid())return null;var t=!0!==e,n=t?this.clone().utc():this;return n.year()<0||n.year()>9999?R(n,t?"YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]":"YYYYYY-MM-DD[T]HH:mm:ss.SSSZ"):C(Date.prototype.toISOString)?t?this.toDate().toISOString():new Date(this.valueOf()+60*this.utcOffset()*1e3).toISOString().replace("Z",R(n,"Z")):R(n,t?"YYYY-MM-DD[T]HH:mm:ss.SSS[Z]":"YYYY-MM-DD[T]HH:mm:ss.SSSZ")},An.inspect=function(){if(!this.isValid())return"moment.invalid(/* "+this._i+" */)";var e,t,n,r="moment",i="";return this.isLocal()||(r=0===this.utcOffset()?"moment.utc":"moment.parseZone",i="Z"),e="["+r+'("]',t=0<=this.year()&&this.year()<=9999?"YYYY":"YYYYYY",n=i+'[")]',this.format(e+t+"-MM-DD[T]HH:mm:ss.SSS"+n)},"undefined"!=typeof Symbol&&null!=Symbol.for&&(An[Symbol.for("nodejs.util.inspect.custom")]=function(){return"Moment<"+this.format()+">"}),An.toJSON=function(){return this.isValid()?this.toISOString():null},An.toString=function(){return this.clone().locale("en").format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ")},An.unix=function(){return Math.floor(this.valueOf()/1e3)},An.valueOf=function(){return this._d.valueOf()-6e4*(this._offset||0)},An.creationData=function(){return{input:this._i,format:this._f,locale:this._locale,isUTC:this._isUTC,strict:this._strict}},An.eraName=function(){var e,t,n,r=this.localeData().eras();for(e=0,t=r.length;e<t;++e){if(n=this.clone().startOf("day").valueOf(),r[e].since<=n&&n<=r[e].until)return r[e].name;if(r[e].until<=n&&n<=r[e].since)return r[e].name}return""},An.eraNarrow=function(){var e,t,n,r=this.localeData().eras();for(e=0,t=r.length;e<t;++e){if(n=this.clone().startOf("day").valueOf(),r[e].since<=n&&n<=r[e].until)return r[e].narrow;if(r[e].until<=n&&n<=r[e].since)return r[e].narrow}return""},An.eraAbbr=function(){var e,t,n,r=this.localeData().eras();for(e=0,t=r.length;e<t;++e){if(n=this.clone().startOf("day").valueOf(),r[e].since<=n&&n<=r[e].until)return r[e].abbr;if(r[e].until<=n&&n<=r[e].since)return r[e].abbr}return""},An.eraYear=function(){var e,t,n,i,o=this.localeData().eras();for(e=0,t=o.length;e<t;++e)if(n=o[e].since<=o[e].until?1:-1,i=this.clone().startOf("day").valueOf(),o[e].since<=i&&i<=o[e].until||o[e].until<=i&&i<=o[e].since)return(this.year()-r(o[e].since).year())*n+o[e].offset;return this.year()},An.year=Oe,An.isLeapYear=function(){return ye(this.year())},An.weekYear=function(e){return xn.call(this,e,this.week(),this.weekday()+this.localeData()._week.dow,this.localeData()._week.dow,this.localeData()._week.doy)},An.isoWeekYear=function(e){return xn.call(this,e,this.isoWeek(),this.isoWeekday(),1,4)},An.quarter=An.quarters=function(e){return null==e?Math.ceil((this.month()+1)/3):this.month(3*(e-1)+this.month()%3)},An.month=Be,An.daysInMonth=function(){return Me(this.year(),this.month())},An.week=An.weeks=function(e){var t=this.localeData().week(this);return null==e?t:this.add(7*(e-t),"d")},An.isoWeek=An.isoWeeks=function(e){var t=ze(this,1,4).week;return null==e?t:this.add(7*(e-t),"d")},An.weeksInYear=function(){var e=this.localeData()._week;return qe(this.year(),e.dow,e.doy)},An.weeksInWeekYear=function(){var e=this.localeData()._week;return qe(this.weekYear(),e.dow,e.doy)},An.isoWeeksInYear=function(){return qe(this.year(),1,4)},An.isoWeeksInISOWeekYear=function(){return qe(this.isoWeekYear(),1,4)},An.date=En,An.day=An.days=function(e){if(!this.isValid())return null!=e?this:NaN;var t=Te(this,"Day");return null!=e?(e=function(e,t){return"string"!=typeof e?e:isNaN(e)?"number"==typeof(e=t.weekdaysParse(e))?e:null:parseInt(e,10)}(e,this.localeData()),this.add(e-t,"d")):t},An.weekday=function(e){if(!this.isValid())return null!=e?this:NaN;var t=(this.day()+7-this.localeData()._week.dow)%7;return null==e?t:this.add(e-t,"d")},An.isoWeekday=function(e){if(!this.isValid())return null!=e?this:NaN;if(null!=e){var t=function(e,t){return"string"==typeof e?t.weekdaysParse(e)%7||7:isNaN(e)?null:e}(e,this.localeData());return this.day(this.day()%7?t:t-7)}return this.day()||7},An.dayOfYear=function(e){var t=Math.round((this.clone().startOf("day")-this.clone().startOf("year"))/864e5)+1;return null==e?t:this.add(e-t,"d")},An.hour=An.hours=at,An.minute=An.minutes=Cn,An.second=An.seconds=Nn,An.millisecond=An.milliseconds=On,An.utcOffset=function(e,t,n){var i,o=this._offset||0;if(!this.isValid())return null!=e?this:NaN;if(null!=e){if("string"==typeof e){if(null===(e=zt(ie,e)))return this}else Math.abs(e)<16&&!n&&(e*=60);return!this._isUTC&&t&&(i=Kt(this)),this._offset=e,this._isUTC=!0,null!=i&&this.add(i,"m"),o!==e&&(!t||this._changeInProgress?rn(this,Qt(e-o,"m"),1,!1):this._changeInProgress||(this._changeInProgress=!0,r.updateOffset(this,!0),this._changeInProgress=null)),this}return this._isUTC?o:Kt(this)},An.utc=function(e){return this.utcOffset(0,e)},An.local=function(e){return this._isUTC&&(this.utcOffset(0,e),this._isUTC=!1,e&&this.subtract(Kt(this),"m")),this},An.parseZone=function(){if(null!=this._tzm)this.utcOffset(this._tzm,!1,!0);else if("string"==typeof this._i){var e=zt(re,this._i);null!=e?this.utcOffset(e):this.utcOffset(0,!0)}return this},An.hasAlignedHourOffset=function(e){return!!this.isValid()&&(e=e?jt(e).utcOffset():0,(this.utcOffset()-e)%60==0)},An.isDST=function(){return this.utcOffset()>this.clone().month(0).utcOffset()||this.utcOffset()>this.clone().month(5).utcOffset()},An.isLocal=function(){return!!this.isValid()&&!this._isUTC},An.isUtcOffset=function(){return!!this.isValid()&&this._isUTC},An.isUtc=Jt,An.isUTC=Jt,An.zoneAbbr=function(){return this._isUTC?"UTC":""},An.zoneName=function(){return this._isUTC?"Coordinated Universal Time":""},An.dates=I("dates accessor is deprecated. Use date instead.",En),An.months=I("months accessor is deprecated. Use month instead",Be),An.years=I("years accessor is deprecated. Use year instead",Oe),An.zone=I("moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/",(function(e,t){return null!=e?("string"!=typeof e&&(e=-e),this.utcOffset(e,t),this):-this.utcOffset()})),An.isDSTShifted=I("isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information",(function(){if(!c(this._isDSTShifted))return this._isDSTShifted;var e,t={};return b(t,this),(t=Pt(t))._a?(e=t._isUTC?f(t._a):jt(t._a),this._isDSTShifted=this.isValid()&&function(e,t){var n,r=Math.min(e.length,t.length),i=Math.abs(e.length-t.length),o=0;for(n=0;n<r;n++)he(e[n])!==he(t[n])&&o++;return o+i}(t._a,e.toArray())>0):this._isDSTShifted=!1,this._isDSTShifted}));var Pn=O.prototype;function Dn(e,t,n,r){var i=yt(),o=f().set(r,t);return i[n](o,e)}function jn(e,t,n){if(l(e)&&(t=e,e=void 0),e=e||"",null!=t)return Dn(e,t,n,"month");var r,i=[];for(r=0;r<12;r++)i[r]=Dn(e,r,n,"month");return i}function Rn(e,t,n,r){"boolean"==typeof e?(l(t)&&(n=t,t=void 0),t=t||""):(n=t=e,e=!1,l(t)&&(n=t,t=void 0),t=t||"");var i,o=yt(),s=e?o._week.dow:0,a=[];if(null!=n)return Dn(t,(n+s)%7,r,"day");for(i=0;i<7;i++)a[i]=Dn(t,(i+s)%7,r,"day");return a}Pn.calendar=function(e,t,n){var r=this._calendar[e]||this._calendar.sameElse;return C(r)?r.call(t,n):r},Pn.longDateFormat=function(e){var t=this._longDateFormat[e],n=this._longDateFormat[e.toUpperCase()];return t||!n?t:(this._longDateFormat[e]=n.match(T).map((function(e){return"MMMM"===e||"MM"===e||"DD"===e||"dddd"===e?e.slice(1):e})).join(""),this._longDateFormat[e])},Pn.invalidDate=function(){return this._invalidDate},Pn.ordinal=function(e){return this._ordinal.replace("%d",e)},Pn.preparse=Mn,Pn.postformat=Mn,Pn.relativeTime=function(e,t,n,r){var i=this._relativeTime[n];return C(i)?i(e,t,n,r):i.replace(/%d/i,e)},Pn.pastFuture=function(e,t){var n=this._relativeTime[e>0?"future":"past"];return C(n)?n(t):n.replace(/%s/i,t)},Pn.set=function(e){var t,n;for(n in e)s(e,n)&&(C(t=e[n])?this[n]=t:this["_"+n]=t);this._config=e,this._dayOfMonthOrdinalParseLenient=new RegExp((this._dayOfMonthOrdinalParse.source||this._ordinalParse.source)+"|"+/\d{1,2}/.source)},Pn.eras=function(){var e,t,n,i=this._eras||yt("en")._eras;for(e=0,t=i.length;e<t;++e)switch("string"==typeof i[e].since&&(n=r(i[e].since).startOf("day"),i[e].since=n.valueOf()),typeof i[e].until){case"undefined":i[e].until=1/0;break;case"string":n=r(i[e].until).startOf("day").valueOf(),i[e].until=n.valueOf()}return i},Pn.erasParse=function(e,t,n){var r,i,o,s,a,c=this.eras();for(e=e.toUpperCase(),r=0,i=c.length;r<i;++r)if(o=c[r].name.toUpperCase(),s=c[r].abbr.toUpperCase(),a=c[r].narrow.toUpperCase(),n)switch(t){case"N":case"NN":case"NNN":if(s===e)return c[r];break;case"NNNN":if(o===e)return c[r];break;case"NNNNN":if(a===e)return c[r]}else if([o,s,a].indexOf(e)>=0)return c[r]},Pn.erasConvertYear=function(e,t){var n=e.since<=e.until?1:-1;return void 0===t?r(e.since).year():r(e.since).year()+(t-e.offset)*n},Pn.erasAbbrRegex=function(e){return s(this,"_erasAbbrRegex")||_n.call(this),e?this._erasAbbrRegex:this._erasRegex},Pn.erasNameRegex=function(e){return s(this,"_erasNameRegex")||_n.call(this),e?this._erasNameRegex:this._erasRegex},Pn.erasNarrowRegex=function(e){return s(this,"_erasNarrowRegex")||_n.call(this),e?this._erasNarrowRegex:this._erasRegex},Pn.months=function(e,t){return e?i(this._months)?this._months[e.month()]:this._months[(this._months.isFormat||je).test(t)?"format":"standalone"][e.month()]:i(this._months)?this._months:this._months.standalone},Pn.monthsShort=function(e,t){return e?i(this._monthsShort)?this._monthsShort[e.month()]:this._monthsShort[je.test(t)?"format":"standalone"][e.month()]:i(this._monthsShort)?this._monthsShort:this._monthsShort.standalone},Pn.monthsParse=function(e,t,n){var r,i,o;if(this._monthsParseExact)return Fe.call(this,e,t,n);for(this._monthsParse||(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[]),r=0;r<12;r++){if(i=f([2e3,r]),n&&!this._longMonthsParse[r]&&(this._longMonthsParse[r]=new RegExp("^"+this.months(i,"").replace(".","")+"$","i"),this._shortMonthsParse[r]=new RegExp("^"+this.monthsShort(i,"").replace(".","")+"$","i")),n||this._monthsParse[r]||(o="^"+this.months(i,"")+"|^"+this.monthsShort(i,""),this._monthsParse[r]=new RegExp(o.replace(".",""),"i")),n&&"MMMM"===t&&this._longMonthsParse[r].test(e))return r;if(n&&"MMM"===t&&this._shortMonthsParse[r].test(e))return r;if(!n&&this._monthsParse[r].test(e))return r}},Pn.monthsRegex=function(e){return this._monthsParseExact?(s(this,"_monthsRegex")||We.call(this),e?this._monthsStrictRegex:this._monthsRegex):(s(this,"_monthsRegex")||(this._monthsRegex=Le),this._monthsStrictRegex&&e?this._monthsStrictRegex:this._monthsRegex)},Pn.monthsShortRegex=function(e){return this._monthsParseExact?(s(this,"_monthsRegex")||We.call(this),e?this._monthsShortStrictRegex:this._monthsShortRegex):(s(this,"_monthsShortRegex")||(this._monthsShortRegex=Re),this._monthsShortStrictRegex&&e?this._monthsShortStrictRegex:this._monthsShortRegex)},Pn.week=function(e){return ze(e,this._week.dow,this._week.doy).week},Pn.firstDayOfYear=function(){return this._week.doy},Pn.firstDayOfWeek=function(){return this._week.dow},Pn.weekdays=function(e,t){var n=i(this._weekdays)?this._weekdays:this._weekdays[e&&!0!==e&&this._weekdays.isFormat.test(t)?"format":"standalone"];return!0===e?Ke(n,this._week.dow):e?n[e.day()]:n},Pn.weekdaysMin=function(e){return!0===e?Ke(this._weekdaysMin,this._week.dow):e?this._weekdaysMin[e.day()]:this._weekdaysMin},Pn.weekdaysShort=function(e){return!0===e?Ke(this._weekdaysShort,this._week.dow):e?this._weekdaysShort[e.day()]:this._weekdaysShort},Pn.weekdaysParse=function(e,t,n){var r,i,o;if(this._weekdaysParseExact)return nt.call(this,e,t,n);for(this._weekdaysParse||(this._weekdaysParse=[],this._minWeekdaysParse=[],this._shortWeekdaysParse=[],this._fullWeekdaysParse=[]),r=0;r<7;r++){if(i=f([2e3,1]).day(r),n&&!this._fullWeekdaysParse[r]&&(this._fullWeekdaysParse[r]=new RegExp("^"+this.weekdays(i,"").replace(".","\\.?")+"$","i"),this._shortWeekdaysParse[r]=new RegExp("^"+this.weekdaysShort(i,"").replace(".","\\.?")+"$","i"),this._minWeekdaysParse[r]=new RegExp("^"+this.weekdaysMin(i,"").replace(".","\\.?")+"$","i")),this._weekdaysParse[r]||(o="^"+this.weekdays(i,"")+"|^"+this.weekdaysShort(i,"")+"|^"+this.weekdaysMin(i,""),this._weekdaysParse[r]=new RegExp(o.replace(".",""),"i")),n&&"dddd"===t&&this._fullWeekdaysParse[r].test(e))return r;if(n&&"ddd"===t&&this._shortWeekdaysParse[r].test(e))return r;if(n&&"dd"===t&&this._minWeekdaysParse[r].test(e))return r;if(!n&&this._weekdaysParse[r].test(e))return r}},Pn.weekdaysRegex=function(e){return this._weekdaysParseExact?(s(this,"_weekdaysRegex")||rt.call(this),e?this._weekdaysStrictRegex:this._weekdaysRegex):(s(this,"_weekdaysRegex")||(this._weekdaysRegex=Qe),this._weekdaysStrictRegex&&e?this._weekdaysStrictRegex:this._weekdaysRegex)},Pn.weekdaysShortRegex=function(e){return this._weekdaysParseExact?(s(this,"_weekdaysRegex")||rt.call(this),e?this._weekdaysShortStrictRegex:this._weekdaysShortRegex):(s(this,"_weekdaysShortRegex")||(this._weekdaysShortRegex=et),this._weekdaysShortStrictRegex&&e?this._weekdaysShortStrictRegex:this._weekdaysShortRegex)},Pn.weekdaysMinRegex=function(e){return this._weekdaysParseExact?(s(this,"_weekdaysRegex")||rt.call(this),e?this._weekdaysMinStrictRegex:this._weekdaysMinRegex):(s(this,"_weekdaysMinRegex")||(this._weekdaysMinRegex=tt),this._weekdaysMinStrictRegex&&e?this._weekdaysMinStrictRegex:this._weekdaysMinRegex)},Pn.isPM=function(e){return"p"===(e+"").toLowerCase().charAt(0)},Pn.meridiem=function(e,t,n){return e>11?n?"pm":"PM":n?"am":"AM"},gt("en",{eras:[{since:"0001-01-01",until:1/0,offset:1,name:"Anno Domini",narrow:"AD",abbr:"AD"},{since:"0000-12-31",until:-1/0,offset:1,name:"Before Christ",narrow:"BC",abbr:"BC"}],dayOfMonthOrdinalParse:/\d{1,2}(th|st|nd|rd)/,ordinal:function(e){var t=e%10;return e+(1===he(e%100/10)?"th":1===t?"st":2===t?"nd":3===t?"rd":"th")}}),r.lang=I("moment.lang is deprecated. Use moment.locale instead.",gt),r.langData=I("moment.langData is deprecated. Use moment.localeData instead.",yt);var Ln=Math.abs;function Fn(e,t,n,r){var i=Qt(t,n);return e._milliseconds+=r*i._milliseconds,e._days+=r*i._days,e._months+=r*i._months,e._bubble()}function Un(e){return e<0?Math.floor(e):Math.ceil(e)}function Bn(e){return 4800*e/146097}function Wn(e){return 146097*e/4800}function Gn(e){return function(){return this.as(e)}}var Vn=Gn("ms"),Yn=Gn("s"),Hn=Gn("m"),zn=Gn("h"),qn=Gn("d"),Kn=Gn("w"),Jn=Gn("M"),Zn=Gn("Q"),Xn=Gn("y"),Qn=Vn;function er(e){return function(){return this.isValid()?this._data[e]:NaN}}var tr=er("milliseconds"),nr=er("seconds"),rr=er("minutes"),ir=er("hours"),or=er("days"),sr=er("months"),ar=er("years");var cr=Math.round,lr={ss:44,s:45,m:45,h:22,d:26,w:null,M:11};function ur(e,t,n,r,i){return i.relativeTime(t||1,!!n,e,r)}var dr=Math.abs;function hr(e){return(e>0)-(e<0)||+e}function fr(){if(!this.isValid())return this.localeData().invalidDate();var e,t,n,r,i,o,s,a,c=dr(this._milliseconds)/1e3,l=dr(this._days),u=dr(this._months),d=this.asSeconds();return d?(e=de(c/60),t=de(e/60),c%=60,e%=60,n=de(u/12),u%=12,r=c?c.toFixed(3).replace(/\.?0+$/,""):"",i=d<0?"-":"",o=hr(this._months)!==hr(d)?"-":"",s=hr(this._days)!==hr(d)?"-":"",a=hr(this._milliseconds)!==hr(d)?"-":"",i+"P"+(n?o+n+"Y":"")+(u?o+u+"M":"")+(l?s+l+"D":"")+(t||e||c?"T":"")+(t?a+t+"H":"")+(e?a+e+"M":"")+(c?a+r+"S":"")):"P0D"}var pr=Wt.prototype;return pr.isValid=function(){return this._isValid},pr.abs=function(){var e=this._data;return this._milliseconds=Ln(this._milliseconds),this._days=Ln(this._days),this._months=Ln(this._months),e.milliseconds=Ln(e.milliseconds),e.seconds=Ln(e.seconds),e.minutes=Ln(e.minutes),e.hours=Ln(e.hours),e.months=Ln(e.months),e.years=Ln(e.years),this},pr.add=function(e,t){return Fn(this,e,t,1)},pr.subtract=function(e,t){return Fn(this,e,t,-1)},pr.as=function(e){if(!this.isValid())return NaN;var t,n,r=this._milliseconds;if("month"===(e=U(e))||"quarter"===e||"year"===e)switch(t=this._days+r/864e5,n=this._months+Bn(t),e){case"month":return n;case"quarter":return n/3;case"year":return n/12}else switch(t=this._days+Math.round(Wn(this._months)),e){case"week":return t/7+r/6048e5;case"day":return t+r/864e5;case"hour":return 24*t+r/36e5;case"minute":return 1440*t+r/6e4;case"second":return 86400*t+r/1e3;case"millisecond":return Math.floor(864e5*t)+r;default:throw new Error("Unknown unit "+e)}},pr.asMilliseconds=Vn,pr.asSeconds=Yn,pr.asMinutes=Hn,pr.asHours=zn,pr.asDays=qn,pr.asWeeks=Kn,pr.asMonths=Jn,pr.asQuarters=Zn,pr.asYears=Xn,pr.valueOf=Qn,pr._bubble=function(){var e,t,n,r,i,o=this._milliseconds,s=this._days,a=this._months,c=this._data;return o>=0&&s>=0&&a>=0||o<=0&&s<=0&&a<=0||(o+=864e5*Un(Wn(a)+s),s=0,a=0),c.milliseconds=o%1e3,e=de(o/1e3),c.seconds=e%60,t=de(e/60),c.minutes=t%60,n=de(t/60),c.hours=n%24,s+=de(n/24),a+=i=de(Bn(s)),s-=Un(Wn(i)),r=de(a/12),a%=12,c.days=s,c.months=a,c.years=r,this},pr.clone=function(){return Qt(this)},pr.get=function(e){return e=U(e),this.isValid()?this[e+"s"]():NaN},pr.milliseconds=tr,pr.seconds=nr,pr.minutes=rr,pr.hours=ir,pr.days=or,pr.weeks=function(){return de(this.days()/7)},pr.months=sr,pr.years=ar,pr.humanize=function(e,t){if(!this.isValid())return this.localeData().invalidDate();var n,r,i=!1,o=lr;return"object"==typeof e&&(t=e,e=!1),"boolean"==typeof e&&(i=e),"object"==typeof t&&(o=Object.assign({},lr,t),null!=t.s&&null==t.ss&&(o.ss=t.s-1)),r=function(e,t,n,r){var i=Qt(e).abs(),o=cr(i.as("s")),s=cr(i.as("m")),a=cr(i.as("h")),c=cr(i.as("d")),l=cr(i.as("M")),u=cr(i.as("w")),d=cr(i.as("y")),h=o<=n.ss&&["s",o]||o<n.s&&["ss",o]||s<=1&&["m"]||s<n.m&&["mm",s]||a<=1&&["h"]||a<n.h&&["hh",a]||c<=1&&["d"]||c<n.d&&["dd",c];return null!=n.w&&(h=h||u<=1&&["w"]||u<n.w&&["ww",u]),(h=h||l<=1&&["M"]||l<n.M&&["MM",l]||d<=1&&["y"]||["yy",d])[2]=t,h[3]=+e>0,h[4]=r,ur.apply(null,h)}(this,!i,o,n=this.localeData()),i&&(r=n.pastFuture(+this,r)),n.postformat(r)},pr.toISOString=fr,pr.toString=fr,pr.toJSON=fr,pr.locale=dn,pr.localeData=fn,pr.toIsoString=I("toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)",fr),pr.lang=hn,D("X",0,0,"unix"),D("x",0,0,"valueOf"),ce("x",ne),ce("X",/[+-]?\d+(\.\d{1,3})?/),pe("X",(function(e,t,n){n._d=new Date(1e3*parseFloat(e))})),pe("x",(function(e,t,n){n._d=new Date(he(e))})),
2
2
  //! moment.js
3
- r.version="2.30.1",function(e){t=e}(jt),r.fn=An,r.min=function(){return Ft("isBefore",[].slice.call(arguments,0))},r.max=function(){return Ft("isAfter",[].slice.call(arguments,0))},r.now=function(){return Date.now?Date.now():+new Date},r.utc=f,r.unix=function(e){return jt(1e3*e)},r.months=function(e,t){return jn(e,t,"months")},r.isDate=u,r.locale=gt,r.invalid=m,r.duration=Qt,r.isMoment=S,r.weekdays=function(e,t,n){return Rn(e,t,n,"weekdays")},r.parseZone=function(){return jt.apply(null,arguments).parseZone()},r.localeData=yt,r.isDuration=Gt,r.monthsShort=function(e,t){return jn(e,t,"monthsShort")},r.weekdaysMin=function(e,t,n){return Rn(e,t,n,"weekdaysMin")},r.defineLocale=mt,r.updateLocale=function(e,t){if(null!=t){var n,r,i=lt;null!=ut[e]&&null!=ut[e].parentLocale?ut[e].set($(ut[e]._config,t)):(null!=(r=pt(e))&&(i=r._config),t=$(i,t),null==r&&(t.abbr=e),(n=new O(t)).parentLocale=ut[e],ut[e]=n),gt(e)}else null!=ut[e]&&(null!=ut[e].parentLocale?(ut[e]=ut[e].parentLocale,e===gt()&&gt(e)):null!=ut[e]&&delete ut[e]);return ut[e]},r.locales=function(){return x(ut)},r.weekdaysShort=function(e,t,n){return Rn(e,t,n,"weekdaysShort")},r.normalizeUnits=U,r.relativeTimeRounding=function(e){return void 0===e?cr:"function"==typeof e&&(cr=e,!0)},r.relativeTimeThreshold=function(e,t){return void 0!==lr[e]&&(void 0===t?lr[e]:(lr[e]=t,"s"===e&&(lr.ss=t-1),!0))},r.calendarFormat=function(e,t){var n=e.diff(t,"days",!0);return n<-6?"sameElse":n<-1?"lastWeek":n<0?"lastDay":n<1?"sameDay":n<2?"nextDay":n<7?"nextWeek":"sameElse"},r.prototype=An,r.HTML5_FMT={DATETIME_LOCAL:"YYYY-MM-DDTHH:mm",DATETIME_LOCAL_SECONDS:"YYYY-MM-DDTHH:mm:ss",DATETIME_LOCAL_MS:"YYYY-MM-DDTHH:mm:ss.SSS",DATE:"YYYY-MM-DD",TIME:"HH:mm",TIME_SECONDS:"HH:mm:ss",TIME_MS:"HH:mm:ss.SSS",WEEK:"GGGG-[W]WW",MONTH:"YYYY-MM"},r}()),Sy.exports;var e}function Iy(){if(wy)return by;wy=1;
3
+ r.version="2.30.1",function(e){t=e}(jt),r.fn=An,r.min=function(){return Ft("isBefore",[].slice.call(arguments,0))},r.max=function(){return Ft("isAfter",[].slice.call(arguments,0))},r.now=function(){return Date.now?Date.now():+new Date},r.utc=f,r.unix=function(e){return jt(1e3*e)},r.months=function(e,t){return jn(e,t,"months")},r.isDate=u,r.locale=gt,r.invalid=m,r.duration=Qt,r.isMoment=S,r.weekdays=function(e,t,n){return Rn(e,t,n,"weekdays")},r.parseZone=function(){return jt.apply(null,arguments).parseZone()},r.localeData=yt,r.isDuration=Gt,r.monthsShort=function(e,t){return jn(e,t,"monthsShort")},r.weekdaysMin=function(e,t,n){return Rn(e,t,n,"weekdaysMin")},r.defineLocale=mt,r.updateLocale=function(e,t){if(null!=t){var n,r,i=lt;null!=ut[e]&&null!=ut[e].parentLocale?ut[e].set($(ut[e]._config,t)):(null!=(r=pt(e))&&(i=r._config),t=$(i,t),null==r&&(t.abbr=e),(n=new O(t)).parentLocale=ut[e],ut[e]=n),gt(e)}else null!=ut[e]&&(null!=ut[e].parentLocale?(ut[e]=ut[e].parentLocale,e===gt()&&gt(e)):null!=ut[e]&&delete ut[e]);return ut[e]},r.locales=function(){return x(ut)},r.weekdaysShort=function(e,t,n){return Rn(e,t,n,"weekdaysShort")},r.normalizeUnits=U,r.relativeTimeRounding=function(e){return void 0===e?cr:"function"==typeof e&&(cr=e,!0)},r.relativeTimeThreshold=function(e,t){return void 0!==lr[e]&&(void 0===t?lr[e]:(lr[e]=t,"s"===e&&(lr.ss=t-1),!0))},r.calendarFormat=function(e,t){var n=e.diff(t,"days",!0);return n<-6?"sameElse":n<-1?"lastWeek":n<0?"lastDay":n<1?"sameDay":n<2?"nextDay":n<7?"nextWeek":"sameElse"},r.prototype=An,r.HTML5_FMT={DATETIME_LOCAL:"YYYY-MM-DDTHH:mm",DATETIME_LOCAL_SECONDS:"YYYY-MM-DDTHH:mm:ss",DATETIME_LOCAL_MS:"YYYY-MM-DDTHH:mm:ss.SSS",DATE:"YYYY-MM-DD",TIME:"HH:mm",TIME_SECONDS:"HH:mm:ss",TIME_MS:"HH:mm:ss.SSS",WEEK:"GGGG-[W]WW",MONTH:"YYYY-MM"},r}()),by.exports;var e}function Sy(){if(vy)return yy;vy=1;
4
4
  /*!
5
5
  * FileStreamRotator
6
6
  * Copyright(c) 2012-2017 Holiday Extras.
7
7
  * Copyright(c) 2017 Roger C.
8
8
  * MIT Licensed
9
9
  */
10
- var e=$,t=I,n=_y(),r=l,o=D,s={};by=s;var a=["daily","test","m","h","custom"],c="YYYYMMDDHHmm";function u(t,n){if(t.hash===r.createHash(t.hashType).update(t.name+"LOG_FILE"+t.date).digest("hex"))try{e.existsSync(t.name)&&e.unlinkSync(t.name)}catch(e){n&&console.error(new Date,"[FileStreamRotator] Could not remove old log file: ",t.name)}}s.getFrequency=function(e){var t=e.toLowerCase().match(/^(\d+)([mh])$/);if(t)return function(e,t){if("number"==typeof t){switch(e){case"m":if(t<0||t>60)return!1;break;case"h":if(t<0||t>24)return!1}return{type:e,digit:t}}}(t[2],parseInt(t[1]));var n=function(e){switch(e){case"custom":case"daily":return{type:e,digit:void 0};case"test":return{type:e,digit:0}}return!1}(e);return n||!1},s.parseFileSize=function(e){if(e&&"string"==typeof e){var t=e.toLowerCase().match(/^((?:0\.)?\d+)([kmg])$/);if(t)switch(t[2]){case"k":return 1024*t[1];case"m":return 1024*t[1]*1024;case"g":return 1024*t[1]*1024*1024}}return null},s.getDate=function(e,t,r){t=t||c;let i=r?n.utc():n().local();if(e&&-1!==a.indexOf(e.type))switch(e.type){case"m":var o=Math.floor(i.minutes()/e.digit)*e.digit;return i.minutes(o).format(t);case"h":var s=Math.floor(i.hour()/e.digit)*e.digit;return i.hour(s).format(t);case"daily":case"custom":case"test":return i.format(t)}return i.format(t)},s.setAuditLog=function(n,r,i){var o=null;if(n){var s=n.toString().substr(-1),a=n.toString().match(/^(\d+)/);if(Number(a[1])>0){var c=t.dirname(i.replace(/%DATE%.+/,"_filename"));try{if(r){var l=t.resolve(r);o=JSON.parse(e.readFileSync(l,{encoding:"utf-8"}))}else l=t.resolve(c+"/.audit.json"),o=JSON.parse(e.readFileSync(l,{encoding:"utf-8"}))}catch(n){if("ENOENT"!==n.code)return null;o={keep:{days:!1,amount:Number(a[1])},auditLog:r||c+"/.audit.json",files:[]}}o.keep={days:"d"===s,amount:Number(a[1])}}}return o},s.writeAuditLog=function(t,n){try{d(t.auditLog),e.writeFileSync(t.auditLog,JSON.stringify(t,null,4))}catch(e){n&&console.error(new Date,"[FileStreamRotator] Failed to store log audit at:",t.auditLog,"Error:",e)}},s.addLogToAudit=function(e,t,i,o){if(t&&t.files){if(-1!==t.files.findIndex((function(t){return t.name===e})))return t;var a=Date.now();if(t.files.push({date:a,name:e,hash:r.createHash(t.hashType).update(e+"LOG_FILE"+a).digest("hex")}),t.keep.days){var c=n().subtract(t.keep.amount,"days").valueOf(),l=t.files.filter((function(e){return e.date>c||(e.hashType=t.hashType,u(e,o),i.emit("logRemoved",e),!1)}));t.files=l}else{var d=t.files.splice(-t.keep.amount);t.files.length>0&&t.files.filter((function(e){return e.hashType=t.hashType,u(e,o),i.emit("logRemoved",e),!1})),t.files=d}s.writeAuditLog(t,o)}return t},s.getStream=function(r){var l=null,u=null,f=this;if(!r.filename)return console.error(new Date,"[FileStreamRotator] No filename supplied. Defaulting to STDOUT"),process.stdout;r.frequency&&(l=f.getFrequency(r.frequency));let p=f.setAuditLog(r.max_logs,r.audit_file,r.filename);null!=p&&(p.hashType=void 0!==r.audit_hash_type?r.audit_hash_type:"md5"),f.verbose=void 0===r.verbose||r.verbose;var g=null,m=0,y=0;r.size&&(g=s.parseFileSize(r.size));var v=r.date_format||c;l&&"daily"==l.type&&(r.date_format||(v="YYYY-MM-DD"),n().format(v)==n().endOf("day").format(v)&&n().format(v)!=n().add(1,"day").format(v)||(f.verbose&&console.log(new Date,"[FileStreamRotator] Changing type to custom as date format changes more often than once a day or not every day"),l.type="custom")),l&&(u=r.frequency?f.getDate(l,v,r.utc):""),r.create_symlink=r.create_symlink||!1,r.extension=r.extension||"";var b=r.filename,w=null,S=b+(u?"."+u:"");if(b.match(/%DATE%/)&&(S=b.replace(/%DATE%/g,u||f.getDate(null,v,r.utc))),g){var _=null,I=S;if(p&&p.files&&p.files instanceof Array&&p.files.length>0){var x=p.files[p.files.length-1].name;if(x.match(I)){var k=x.match(I+"\\.(\\d+)");k&&(I=x,m=k[1])}}for(0==m&&I==S&&(I+=r.extension);e.existsSync(I);)_=I,m++,I=S+"."+m+r.extension;if(_){var E=e.statSync(_);E.size<g&&(I=_,m--,y=E.size)}S=I}else S+=r.extension;f.verbose&&console.log(new Date,"[FileStreamRotator] Logging to: ",S),d(S);var C=r.file_options||{flags:"a"},$=e.createWriteStream(S,C);if(u&&l&&a.indexOf(l.type)>-1||g>0){f.verbose&&console.log(new Date,"[FileStreamRotator] Rotating file: ",l?l.type:"",g?"size: "+g:"");var O,N=new o;return N.auditLog=p,N.end=function(){$.end.apply($,arguments)},h($,N),N.on("close",(function(){O&&O.close()})),N.on("new",(function(n){N.auditLog=f.addLogToAudit(n,N.auditLog,N,f.verbose),r.create_symlink&&function(n,r,i){let o=r||"current.log",s=t.dirname(n),a=t.basename(n),c=s+"/"+o;try{e.lstatSync(c).isSymbolicLink()&&(e.unlinkSync(c),e.symlinkSync(a,c))}catch(n){if(n&&"ENOENT"==n.code)try{e.symlinkSync(a,c)}catch(n){i&&console.error(new Date,"[FileStreamRotator] Could not create symlink file: ",c," -> ",a)}}}(n,r.symlink_name,f.verbose),r.watch_log&&N.emit("addWatcher",n)})),N.on("addWatcher",(function(t){O&&O.close(),r.watch_log&&(O=function(t,n){if(!t)return null;try{return e.lstatSync(t),e.watch(t,(function(n){if("rename"==n)try{e.lstatSync(t)}catch(e){!function(e,t){N.emit("createLog",t)}(0,t)}}))}catch(e){n&&console.log(new Date,"[FileStreamRotator] Could not add watcher for "+t)}}(t,f.verbose))})),N.on("createLog",(function(t){try{e.lstatSync(t)}catch(n){$&&"function"==$.end&&$.end(),$=e.createWriteStream(t,C),N.emit("new",t),h($,N)}})),N.write=function(t,n){var o=l?this.getDate(l,v,r.utc):u;if(o!=u||g&&y>g){var s=b+(u&&l?"."+o:"");b.match(/%DATE%/)&&u&&(s=b.replace(/%DATE%/g,o)),g&&y>g?s+="."+ ++m+r.extension:(m=0,s+=r.extension),y=0,f.verbose&&console.log(new Date,i.format("[FileStreamRotator] Changing logs from %s to %s",S,s)),u=o,w=S,S=s,!0===r.end_stream?$.end():$.destroy(),d(S),$=e.createWriteStream(s,C),N.emit("new",s),N.emit("rotate",w,s),h($,N)}$.write(t,n),y+=Buffer.byteLength(t,n)}.bind(this),process.nextTick((function(){N.emit("new",S)})),N.emit("new",S),N}return f.verbose&&console.log(new Date,"[FileStreamRotator] File won't be rotated: ",r.frequency,r.size),process.nextTick((function(){$.emit("new",S)})),$};var d=function(n){t.dirname(n).split(t.sep).reduce((function(n,r){if(n+=r+t.sep,!e.existsSync(n))try{e.mkdirSync(n)}catch(n){if("EEXIST"!==n.code)throw n}return n}),"")},h=function(e,t){e.on("close",(function(){t.emit("close")})),e.on("finish",(function(){t.emit("finish")})),e.on("error",(function(e){t.emit("error",e)})),e.on("open",(function(e){t.emit("open",e)}))};return by}const xy=$,ky=N,Ey=I,Cy=i,$y=j,Oy=yy.exports,Ny=rh.MESSAGE,Ty=M.PassThrough,Ay=Op,My={json:!1,colorize:!1,eol:ky.EOL,logstash:null,prettyPrint:!1,label:null,stringify:!1,depth:null,showLevel:!0,timestamp:()=>(new Date).toISOString()},Py=function(e){if(e=e||{},Ay.call(this,e),this.options=Object.assign({},My,e),e.stream)!function(t){Array.prototype.slice.call(arguments,1).forEach((n=>{if(e[n])throw new Error("Cannot set "+n+" and "+t+" together")}))}("stream","filename","maxsize"),this.logStream=new Ty,this.logStream.pipe(e.stream);else{if(this.filename=e.filename?Ey.basename(e.filename):"winston.log",this.dirname=e.dirname||Ey.dirname(e.filename),t=this.filename,/["<>|:*?\\/\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f]/g.test(t)||!function(e){return!/["<>|\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f]/g.test(e)}(this.dirname))throw new Error("Your path or filename contain an invalid character.");this.logStream=Iy().getStream({filename:Ey.join(this.dirname,this.filename),frequency:e.frequency?e.frequency:"custom",date_format:e.datePattern?e.datePattern:"YYYY-MM-DD",verbose:!1,size:function(e){if(e&&"string"==typeof e){if(e.toLowerCase().match(/^((?:0\.)?\d+)([kmg])$/))return e}else if(e&&Number.isInteger(e)){const t=Math.round(e/1024);return 0===t?"1k":t+"k"}return null}(e.maxSize),max_logs:e.maxFiles,end_stream:!0,audit_file:e.auditFile?e.auditFile:Ey.join(this.dirname,"."+Oy(e)+"-audit.json"),file_options:e.options?e.options:{flags:"a"},utc:!!e.utc&&e.utc,extension:e.extension?e.extension:"",create_symlink:!!e.createSymlink&&e.createSymlink,symlink_name:e.symlinkName?e.symlinkName:"current.log",watch_log:!!e.watchLog&&e.watchLog,audit_hash_type:e.auditHashType?e.auditHashType:"sha256"}),this.logStream.on("new",(e=>{this.emit("new",e)})),this.logStream.on("rotate",((e,t)=>{this.emit("rotate",e,t)})),this.logStream.on("logRemoved",(t=>{if(e.zippedArchive){const e=t.name+".gz";try{xy.unlinkSync(e)}catch(t){if("ENOENT"!==t.code)return t.message=`Error occurred while removing ${e}: ${t.message}`,void this.emit("error",t)}this.emit("logRemoved",e)}else this.emit("logRemoved",t.name)})),e.zippedArchive&&this.logStream.on("rotate",(e=>{try{if(!xy.existsSync(e))return}catch(t){return t.message=`Error occurred while checking existence of ${e}: ${t.message}`,void this.emit("error",t)}try{if(xy.existsSync(`${e}.gz`))return}catch(t){return t.message=`Error occurred while checking existence of ${e}.gz: ${t.message}`,void this.emit("error",t)}const t=$y.createGzip(),n=xy.createReadStream(e);n.on("error",(t=>{t.message=`Error occurred while reading ${e}: ${t.message}`,this.emit("error",t)}));const r=xy.createWriteStream(e+".gz");r.on("error",(t=>{t.message=`Error occurred while writing ${e}.gz: ${t.message}`,this.emit("error",t)})),n.pipe(t).pipe(r).on("finish",(()=>{try{xy.unlinkSync(e)}catch(t){if("ENOENT"!==t.code)return t.message=`Error occurred while removing ${e}: ${t.message}`,void this.emit("error",t)}this.emit("archive",e+".gz")}))})),e.watchLog&&this.logStream.on("addWatcher",(e=>{this.emit("addWatcher",e)}))}var t};var Dy=Py;Cy.inherits(Py,Ay),Py.prototype.name="dailyRotateFile";const jy=function(){};Py.prototype.log=function(e,t){t=t||jy,this.logStream.write(e[Ny]+this.options.eol),this.emit("logged",e),t(null,!0)},Py.prototype.close=function(){this.logStream&&this.logStream.end((()=>{this.emit("finish")}))},Py.prototype.query=function(e,t){if("function"==typeof e&&(t=e,e={}),!this.options.json)throw new Error("query() may not be used without the json option being set to true");if(!this.filename)throw new Error("query() may not be used when initializing with a stream");let n=[];(e=e||{}).rows=e.rows||e.limit||10,e.start=e.start||0,e.until=e.until||new Date,"object"!=typeof e.until&&(e.until=new Date(e.until)),e.from=e.from||e.until-864e5,"object"!=typeof e.from&&(e.from=new Date(e.from)),e.order=e.order||"desc";const r=(()=>{const e=new RegExp(this.filename.replace("%DATE%",".*"),"i");return xy.readdirSync(this.dirname).filter((t=>Ey.basename(t).match(e)))})();0===r.length&&t&&t(null,n);const i=o=>{if(!o)return;const s=Ey.join(this.dirname,o);let a,c="";if(o.endsWith(".gz")){a=new Ty;const e=xy.createReadStream(s);e.on("error",(e=>{e.message=`Error occurred while reading ${s}: ${e.message}`,a.emit("error",e)})),e.pipe($y.createGunzip()).pipe(a)}else a=xy.createReadStream(s,{encoding:"utf8"});function l(t,r){try{const r=JSON.parse(t);if(!r||"object"!=typeof r)return;const i=new Date(r.timestamp);if(e.from&&i<e.from||e.until&&i>e.until||e.level&&e.level!==r.level)return;n.push(r)}catch(e){r||a.emit("error",e)}}a.on("error",(e=>{if(a.readable&&a.destroy(),t)return"ENOENT"===e.code?t(null,n):t(e)})),a.on("data",(e=>{const t=(e=(c+e).split(/\n+/)).length-1;for(let n=0;n<t;n++)l(e[n]);c=e[t]})),a.on("end",(()=>{if(c&&l(c,!0),r.length)i(r.shift());else if(t){n.sort(((e,t)=>{const n=new Date(e.timestamp).getTime(),r=new Date(t.timestamp).getTime();return n>r?1:n<r?-1:0})),"desc"===e.order&&(n=n.reverse());const r=e.start||0,i=e.limit||n.length;n=n.slice(r,r+i),e.fields&&(n=n.map((t=>{const n={};return e.fields.forEach((e=>{n[e]=t[e]})),n}))),t(null,n)}}))};i(r.shift())};const Ry=Dy;kd.transports.DailyRotateFile=Ry;var Ly=ad(Ry);const Fy=Date.now();let Uy=Math.ceil(Fy/1e3);var By=()=>Uy+=1;const Wy=x(T(),"kemu-user-services"),Gy=x(T(),"kemu-test-services"),Vy="KMU-CB-v1",Yy=process.env.HUB_PKG_VERSION||'"1.10.1"';var Hy;!function(e){e.input="input",e.counter="counter",e.play="play",e.elapsed="elapsed",e.ifGate="ifGate",e.skipEvent="skipEvent",e.between="between",e.map="map",e.parser="parser",e.slider="slider",e.suspend="suspend",e.display="display",e.pixelfy="pixelfy",e.json="json",e.arrayItem="arrayItem",e.extractImage="extractImage",e.imageConvolution="imageConvolution",e.firstEvent="firstEvent",e.pixelDraw="pixelDraw",e.randomBetween="randomBetween",e.arrayCombine="arrayCombine",e.clock="clock",e.multiplication="multiplication",e.object="object",e.widgetGroup="widgetGroup",e.script="script",e.base64ToImageData="base64ToImageData",e.jsonParse="jsonParse",e.text="text",e.imageCrop="imageCrop",e.imageResize="imageResize",e.value="value",e.imageWarp="imageWarp",e.widgetBundle="widgetBundle",e.sequence="sequence",e.variable="variable",e.hubService="hubService"}(Hy||(Hy={}));const zy=e=>({...e,type:Array.isArray(e.type)?e.type.map((e=>ju[e])):ju[e.type]}),qy=async e=>{try{return await S(e,"utf-8")}catch(e){return null}},Ky=e=>{if(e&&e.startsWith(Vy)){const t=e.slice(9),n=decodeURI(t);return qu(n)}return null},Jy=async(e,t,n)=>{let r=[];e.variants?.length&&(r=e.variants.map((e=>({...e,...e.inputs?{inputs:e.inputs.map(zy)}:{},...e.outputs?{outputs:e.outputs.map(zy)}:{}}))));const i={...e,path:t,customWidgets:[],...e.inputs?{inputs:e.inputs.map(zy)}:{inputs:[]},...e.outputs?{outputs:e.outputs.map(zy)}:{outputs:[]},variants:r,...e.widgetUI&&n?.widgetUIContents?{widgetUIContents:n.widgetUIContents}:{}},o=await(async(e,t,n=console.log)=>{const r=[];if(t.customWidgets?.length)for(const i of t.customWidgets){const t=await qy(x(e,i));if(!t){n(`Error loading custom widget file ${i}`);continue}const o=t.startsWith(Vy)?t:`${Vy}${t}`,s=Ky(o);if(!s){n(`Custom widget file "${i}" is not a valid Kemu Clipboard item`);continue}const a=Object.values(s).filter((e=>e.type===Hy.widgetGroup&&!e.groupId));if(a.length>1){n(`Custom widget file "${i}" contains more than one top level widgetGroup`);continue}const c=a[0];if(!c){n(`Custom widget file "${i}" does not contain a top level widgetGroup`);continue}const l=c.state,u={name:l.name,color:l.color,description:l.description,contents:o,rootGroupId:c.id,icon:l.icon,protocolVersion:l.protocolVersion||"2"};r.push(u)}return r})(t,e,n?.log);if(o.length?i.customWidgets=o:delete i.customWidgets,i.variants?.length)for(const e of i.variants)if(e.svgIcon)try{const n=await S(x(t,e.svgIcon),"utf-8");e.svgIcon=n}catch(t){n?.log&&n?.log(`Error loading svgIcon for variant ${e.id}: ${t}`)}return i},Zy=async e=>{try{return await y(e,v.F_OK),!0}catch{return!1}};let Xy=null,Qy=null;const ev=()=>Xy||Wy,tv=()=>Qy||Gy;let nv=null;const rv={setGlobalUserId:e=>nv?.setGlobalUserId?.(e),captureError:e=>nv?.captureError?.(e),flushMessages:async()=>nv?.flushMessages?.(),isEnabled:()=>!!nv};var iv={...rv,setTracker:e=>{nv=e}};const ov=xd("servicesManager"),sv={};let av=null,cv=null,lv=null,uv=!1;class dv extends Error{code;originalError;constructor(e,t,n){super(e),this.code=t,this.originalError=n,this.name="ServiceError"}}const hv=async e=>{try{return await y(e),!0}catch{return!1}},fv=async e=>{if(!av)throw new Error('IPC config not set, call "setHubIpcConfig" first.');let t;if(e.info.internal)if("linux"===A()){const n=process.env.XDG_STATE_HOME||I.join(T(),".local","state");t=I.join(n,"kemu-hub","service-logs",e.info.name);try{await m(t,{recursive:!0})}catch(n){ov(`Failed to create log directory ${t}, falling back to service path`),t=e.info.path}}else t=e.info.path;else t=I.join(e.info.path,"..");const n=e.logsEnabled?((e,t)=>{const n=my.createLogger({level:"info",format:my.format.combine(my.format.timestamp(),my.format.errors({stack:!0}),my.format.json()),defaultMeta:{service:e},transports:[new Ly({filename:I.join(t,"service-%DATE%.log"),datePattern:"YYYY-MM-DD",maxSize:"5m",maxFiles:"5d",auditFile:I.join(t,".service-log-audit.json")})]});return n.getLastLogs=async(n=100)=>{try{const r=I.join(t,".service-log-audit.json"),i=await g.readFile(r,"utf-8"),o=qu(i);if(!o)return console.warn(`Missing audit file for ${e}, skipping log retrieval.`),[];const s=async e=>(await g.readFile(e,"utf-8")).split("\n").filter((e=>e.trim())),a=[],c=[...o.files].reverse();for(const e of c){const t=await s(e.name);if(a.push(...t),a.length>=n)break}return a}catch(t){return console.warn(`Failed to read service logs for ${e}: `,t),[]}},n})(e.info.name,t):null,r=t=>{if(!e.devMode){const{childProcess:r,...i}=e;iv.isEnabled()&&iv.captureError({error:t,data:{logs:n?.getLastLogs(),service:{...i,spawnargs:r?.spawnargs,info:void 0,name:e.info.name,version:e.info.version}}})}};try{if(e.info.processor===Lu.Javascript){ov(`Spawning service ${e.info.name} with sessionId ${e.info.sessionId}`);const t=I.join(e.info.path,"processor.js"),i=I.join(e.info.path,"processor.mjs"),o=await hv(t)?t:i,s=[`--sessionId=${e.info.sessionId.toString()}`,`--ipcSpace=${av.appSpace}`,`--ipcId=${av?.id}`,`--recipePath=${av.recipePath||""}`];if(e.info.internal&&s.push("--internal=true"),!lv)throw new Error('Get secrets function not set, call "setGetSecretsFunction" first.');const a=await lv({name:e.info.name,version:e.info.version,requiredSecrets:e.info.requiredSecrets||{}}),c=Object.entries(e.info.requiredSecrets||{}).filter((([e,t])=>null==a[e]&&!t.optional)).map((([e])=>e));if(c?.length)throw new dv(`Missing required environment variables: ${c.join(", ")}`,"MISSING_REQUIRED_SECRETS");return new Promise(((t,i)=>{if(!cv)throw new Error('Spawn function not set, call "setSpawnNodeFunction" first.');const c=cv({args:[o,...s],serviceInfo:{name:e.info.name,version:e.info.version},options:{env:{...a}}});c.stdout.on("data",(t=>{const r=t.toString().trim();r&&(n?.info(r),ov(`[${e.info.name}] - stdout: ${r}`))})),c.stderr.on("data",(t=>{const i=t.toString().trim();i&&(n?.error(i),r(new Error(i)),ov(`[${e.info.name}] - stderr: ${i}`))})),c.on("exit",(t=>{const r=`exited with code ${t}`;n?.info(r,{code:t}),ov(`[${e.info.name}] ${r}`)})),c.on("spawn",(()=>{const r=`spawned with PID ${c.pid}`;n?.info(r,{pid:c.pid}),ov(`[${e.info.name}] ${r}`),t(c)})),c.on("error",(t=>{n?.error(`[${e.info.name}] error`,t),ov(`[${e.info.name}] error: ${t}`),r(t),i(new dv(`Error spawning service ${e.info.name}: ${t}`,"SPAWN_ERROR"))}))}))}throw`Unsupported processor type ${e.info.processor}`}catch(t){if(r(t),t instanceof dv)throw t;throw`Error spawning service ${e.info.name}: ${t}`}},pv=e=>e?.name?e?.version?e?.description?e?.processor?[Lu.Javascript,Lu.Executable,Lu.Python].includes(e?.processor)?null:"Invalid processor":"Missing processor":"Missing description":"Missing version":"Missing name",gv=async(e,t)=>{const n=I.join(e,"manifest.json");if(!await hv(n)){const t=`Missing manifest for service ${e}. Aborting.`;return ov(t),{error:t}}const r=await S(n,"utf-8"),i=qu(r),o=pv(i);if(!i||o){const t=`Invalid service manifest [${e}]: ${o}. Aborting.`;return ov(t),{error:t}}let s;if(delete i.internal,t?.singleServiceName&&i.name!==t.singleServiceName)return{error:`Skipping service ${i.name} as it does not match the singleServiceName option`};await Promise.all([(async()=>{if(i.widgetUI)try{s=await S(I.join(e,"widgetUI.js"))}catch(e){const t=`Error loading widgetUI file ${i.name}: ${e}`;return ov(t),{error:t}}})(),(async()=>{if(i.svgIcon){const t=await qy(I.join(e,i.svgIcon));if(!t)return{error:`Error loading icon for service ${i.name}`};i.svgIcon=t}})(),(async()=>{if(i.subServices?.length)for(const t of i.subServices){const n=I.join(e,t),{error:r,service:o}=await gv(n);r?ov(`Error loading sub-service ${t}: ${r}`):o&&(o.info.parentService={name:i.name,version:i.version})}delete i.subServices})(),(async()=>{if(i.variants?.length)for(const t of i.variants)if(t.svgIcon)try{const n=await S(I.join(e,t.svgIcon),"utf-8");t.svgIcon=n}catch(e){ov(`Error loading svgIcon for variant ${t.id}: ${e}`)}})()]);const a=By(),c=t?.fixedSession||a;ov(`Loaded service ${i.name} with sessionId ${c}`);const l=await Jy(i,e,{widgetUIContents:s});return mv(l),sv[c]={info:{...l,path:e,sessionId:c},status:"loaded",childProcess:null,logsEnabled:t?.logsEnabled},{service:sv[c]}},mv=e=>{e.widgetUIContents?e.uiContentChecksum=(e=>{const t=h("sha256");return t.update(e),t.digest("hex")})(e.widgetUIContents):e.uiContentChecksum=void 0},yv=async e=>{try{return e.childProcess=await fv(e),e.status="started",e.errorMsg=void 0,e.errorCode=void 0,!0}catch(t){return ov(`Service [${e.info.name}] error: ${t}`),e.status="error",t instanceof dv?(e.errorMsg=t.message,e.errorCode=t.code):(e.errorMsg="string"==typeof t?t:JSON.stringify(t),e.errorCode="UNKNOWN_ERROR"),!1}},vv=e=>{const{path:t,...n}=e.info;return{...n}},bv=()=>Object.values(sv).filter((e=>"running"===e.status)).map(vv),wv=e=>{if(!e?.kill)return ov(`Failed to kill service ${e?.pid} because it is not a child process`),!1;let t=e.kill("SIGINT");return t||(ov(`Failed to send SIGINT to service ${e.pid} using SIGINT`),t=e.kill("SIGTERM"),t||(ov(`Failed to send SIGTERM to service ${e.pid} using SIGTERM`),t=e.kill("SIGKILL"),t||ov(`Failed to send SIGKILL to service ${e.pid} using SIGKILL`))),t},Sv=async e=>{const{serviceName:t,version:n,force:r,timeout:i=15e3}=e,o=Object.values(sv).find((t=>t.info.name===e.serviceName&&t.info.version===e.version));if(!o)return null;if(o.info.internal&&!r)throw`Cannot stop internal service ${t}`;if(o.childProcess){ov(`Stopping service "${t} (v${n})"`);const r=new Promise(((e,n)=>{const r=setTimeout((()=>{n(new Error(`Timeout waiting for service ${t} to stop after ${i}ms`))}),i);o.childProcess.once("exit",((n,i)=>{clearTimeout(r),ov(`Service ${t} process exited with code ${n} and signal ${i}`),e()})),o.childProcess.once("error",(n=>{clearTimeout(r),ov(`Service ${t} process error: ${n.message}`),e()}))}));wv(o.childProcess);try{await r,ov(`Service ${t} process successfully terminated`)}catch(e){ov(`Warning: ${e instanceof Error?e.message:"Unknown error"} while waiting for service ${t} to stop`)}}return o.status="stopped",ov(`Service ${t} stopped`),o},_v=e=>e.info.internal?e.info.path:I.join(e.info.path,".."),Iv=e=>!!e.internal;var xv={isOfficialKemuService:e=>e.name.startsWith("kemu.io"),loadServices:async(e,t)=>{if(!await Zy(e))return void ov(`Failed to load services from "${e}". Directory does not exist.`);const n=(await b(e,{withFileTypes:!0})).filter((e=>e.isDirectory())).map((e=>e.name));ov(`Found ${n.length} services in "${e}"`);for(let r=0;r<n.length;r++){const i=n[r],o=I.join(e,i),{error:s,service:a}=await gv(`${o}${t?.internalServices?"":"/dist"}`,{...t,logsEnabled:Array.isArray(t?.enableLogs)?t?.enableLogs.includes(i):t?.enableLogs});s&&ov(`Failed to load service ${o}. Please check logs`),a&&t?.internalServices&&(a.info.internal=!0)}},launchServices:async e=>{if(ov("Initializing services"),!av)throw new Error('IPC config not set, call "setHubIpcConfig" first.');for(const t in sv){const n=sv[t];e.noSpawningList&&e.noSpawningList.includes(n.info.name)?ov(`Service ${n.info.name} is in the noSpawningList. Skipping.`):yv(n)}ov("Services initialized")},setServiceStatus:(e,t)=>{const n=sv[e];return n?(n.status=t,!0):(ov(`Service with serviceId ${e} not found`),!1)},getActiveServices:bv,getMatchingService:(e,t)=>{const n=Object.values(sv).filter((e=>"running"===e.status));for(const r of n)if(r.info.name===e){if(r.info.version===t)return r;if(nd(r.info.version,t,">="))return r}return null},getServiceBySessionId:e=>sv[e]||null,killAllServices:()=>{for(const e in sv){const t=sv[e];if(t.childProcess)try{ov(`Killing service ${t.info.name} with PID ${t.childProcess.pid}`),wv(t.childProcess)}catch(e){ov(`Error killing service ${t.info.name}: ${e}`)}}},addDevService:async(e,t,n)=>{const r={info:{...await Jy(t,t.path),sessionId:e},status:n,startedAt:new Date,devMode:!0,childProcess:null};sv[e]=r,mv(sv[e].info)},setServiceManifest:(e,t,n)=>{const r=sv[e];if(!r)return ov(`Service with sessionId ${e} not found`),!1;const i=pv(t);if(i)return ov(`Invalid manifest for service ${r.info.name}: ${i}`),!1;mv(t),r.info={...r.info,...t},n&&(r.status=n)},getMatchingDevService:(e,t,n)=>{const r=Object.values(sv).filter((e=>e.devMode));for(const i of r)if(i.info.name===e&&i.status===n&&i.info.version===t)return i;return null},getInternalServices:()=>bv().filter((e=>e.internal)),getAllServices:()=>Object.values(sv),stopService:Sv,uninstallService:async(e,t)=>{ov(`Uninstalling service ${e} v${t}`);const n=await Sv({serviceName:e,version:t});if(!n)return!1;ov(`Service ${e} stopped. Removing from disk...`);const r=_v(n),i=ev();return r.startsWith(i)?(await w(r,{recursive:!0,force:!0,maxRetries:3}),ov(`Service ${e} successfully removed from disk`),(e=>{sv[e],delete sv[e]})(n.info.sessionId),!0):(ov(`Service ${e} is not installed in the user services directory. Aborting.`),!1)},getAllServiceVersions:e=>Object.values(sv).filter((t=>t.info.name===e)),setHubIpcConfig:e=>{av={...e}},setEnableServiceLogsConfig:e=>{uv=e},loadAndLaunch:async(e,t,n)=>{const r=E(e,t),{error:i,service:o}=await gv(r,{logsEnabled:uv});if(i||!o)return{errorMsg:i};try{o.info.internal=!!n,o.childProcess=await fv(o),o.status="started"}catch(e){o.status="error",e instanceof dv?(ov(`Service spawning error: ${e.message} (${e.code})`),o.errorMsg=e.message,o.errorCode=e.code):(ov(`Error launching service ${o.info.name}: ${e}`),o.errorMsg="string"==typeof e?e:JSON.stringify(e))}return{service:o,errorCode:o.errorCode,errorMsg:o.errorMsg}},getServiceRootDirectory:_v,setSpawnNodeFunction:e=>{cv=e},setGetSecretsFunction:e=>{lv=e},restartService:async(e,t)=>{ov(`Restarting service ${e} v${t}`);const n=await Sv({serviceName:e,version:t,force:!0});return!!n&&yv(n)},getFailedServices:()=>Object.values(sv).filter((e=>"error"===e.status)).map((e=>({...vv(e),errorMsg:e.errorMsg||"",errorCode:e.errorCode,status:e.status}))),isInternalKemuService:Iv,isNotInternalKemuService:e=>!Iv(e),isNotDevService:e=>!e.devMode};class kv{constructor(){}appspace="app.";socketRoot="/tmp/";id=N.hostname();encoding="utf8";rawBuffer=!1;sync=!1;unlink=!0;delimiter="\f";silent=!1;logDepth=5;logInColor=!0;logger=console.log.bind(console);maxConnections=100;retry=500;maxRetries=1/0;stopRetrying=!1;IPType=function(){const e=N.networkInterfaces();let t="";return e&&Array.isArray(e)&&e.length>0&&(t=e[Object.keys(e)[0]][0].family),t}();tls=!1;networkHost="IPv6"==this.IPType?"::1":"127.0.0.1";networkPort=8e3;readableAll=!1;writableAll=!1;interface={localAddress:!1,localPort:!1,family:!1,hints:!1,lookup:!1}}class Ev{constructor(e){e||(e=new kv),this.delimiter=e.delimiter}format(e){return e.data||!1===e.data||0===e.data||(e.data={}),e.data._maxListeners&&(e.data={}),e.JSON+this.delimiter}parse(e){let t=e.split(this.delimiter);return t.pop(),t}}var Cv=ad((function(){Object.defineProperties(this,{data:{enumerable:!0,get:function(){return t},set:function(e){t=e}},type:{enumerable:!0,get:function(){return e},set:function(t){e=t}},load:{enumerable:!0,writable:!1,value:function(n){try{n=JSON.parse(n),e=n.type,t=n.data}catch(r){e="error",t={message:"Invalid JSON response format",err:r,response:n}}}},JSON:{enumerable:!0,get:function(){return JSON.stringify({type:e,data:t})}}});var e="",t={}})),$v=ad((function(){Object.defineProperties(this,{add:{enumerable:!0,writable:!1,value:function(){for(var n in arguments)e.push(arguments[n]);t||this.stop||!this.autoRun||this.next()}},next:{enumerable:!0,writable:!1,value:function(){t=!0,e.length<1||this.stop?t=!1:e.shift().bind(this)()}},clear:{enumerable:!0,writable:!1,value:function(){return e=[]}},contents:{enumerable:!1,get:function(){return e},set:function(t){return e=t}},autoRun:{enumerable:!0,writable:!0,value:!0},stop:{enumerable:!0,writable:!0,value:!1}});var e=[],t=!1}));class Ov{}class Nv{}const Tv=new class{constructor(e=!0){this.strict=e}throw(e,t){let n=new TypeError;if(n.message=`expected type of ${e} to be ${t}`,!this.strict)return!1;throw n}typeCheck(e,t){return typeof e===t||this.throw(typeof e,t)}instanceCheck(e=new Ov,t=Nv){return e instanceof t||this.throw(typeof e,t.name)}symbolStringCheck(e,t){return Object.prototype.toString.call(e)==`[object ${t}]`||this.throw(Object.prototype.toString.call(e),`[object ${t}]`)}compare(e,t,n){return e==t||this.throw(typeof e,n)}finite(e){return!!isFinite(e)||this.throw(typeof e,"finite")}NaN(e){return this.number(e)?!!isNaN(e)||this.throw(typeof e,"NaN"):this.number(e)}null(e){return this.compare(e,null,"null")}array(e){return this.instanceCheck(e,Array)}boolean(e){return this.typeCheck(e,"boolean")}bigint(e){return this.typeCheck(e,"bigint")}date(e){return this.instanceCheck(e,Date)}generator(e){return this.symbolStringCheck(e,"Generator")}asyncGenerator(e){return this.symbolStringCheck(e,"AsyncGenerator")}globalThis(e){return this.compare(e,globalThis,"explicitly globalThis, not window, global nor self")}infinity(e){return this.compare(e,1/0,"Infinity")}map(e){return this.instanceCheck(e,Map)}weakMap(e){return this.instanceCheck(e,WeakMap)}number(e){return this.typeCheck(e,"number")}object(e){return this.typeCheck(e,"object")}promise(e){return this.instanceCheck(e,Promise)}regExp(e){return this.instanceCheck(e,RegExp)}undefined(e){return this.typeCheck(e,"undefined")}set(e){return this.instanceCheck(e,Set)}weakSet(e){return this.instanceCheck(e,WeakSet)}string(e){return this.typeCheck(e,"string")}symbol(e){return this.typeCheck(e,"symbol")}function(e){return this.typeCheck(e,"function")}asyncFunction(e){return this.symbolStringCheck(e,"AsyncFunction")}generatorFunction(e){return this.symbolStringCheck(e,"GeneratorFunction")}asyncGeneratorFunction(e){return this.symbolStringCheck(e,"AsyncGeneratorFunction")}error(e){return this.instanceCheck(e,Error)}evalError(e){return this.instanceCheck(e,EvalError)}rangeError(e){return this.instanceCheck(e,RangeError)}referenceError(e){return this.instanceCheck(e,ReferenceError)}syntaxError(e){return this.instanceCheck(e,SyntaxError)}typeError(e){return this.instanceCheck(e,TypeError)}URIError(e){return this.instanceCheck(e,URIError)}bigInt64Array(e){return this.instanceCheck(e,BigInt64Array)}bigUint64Array(e){return this.instanceCheck(e,BigUint64Array)}float32Array(e){return this.instanceCheck(e,Float32Array)}float64Array(e){return this.instanceCheck(e,Float64Array)}int8Array(e){return this.instanceCheck(e,Int8Array)}int16Array(e){return this.instanceCheck(e,Int16Array)}int32Array(e){return this.instanceCheck(e,Int32Array)}uint8Array(e){return this.instanceCheck(e,Uint8Array)}uint8ClampedArray(e){return this.instanceCheck(e,Uint8ClampedArray)}uint16Array(e){return this.instanceCheck(e,Uint16Array)}uint32Array(e){return this.instanceCheck(e,Uint32Array)}arrayBuffer(e){return this.instanceCheck(e,ArrayBuffer)}dataView(e){return this.instanceCheck(e,DataView)}sharedArrayBuffer(e){return this.instanceCheck(e,function(){try{return SharedArrayBuffer}catch{return Ov}}())}intlDateTimeFormat(e){return this.instanceCheck(e,Intl.DateTimeFormat)}intlCollator(e){return this.instanceCheck(e,Intl.Collator)}intlDisplayNames(e){return this.instanceCheck(e,Intl.DisplayNames)}intlListFormat(e){return this.instanceCheck(e,Intl.ListFormat)}intlLocale(e){return this.instanceCheck(e,Intl.Locale)}intlNumberFormat(e){return this.instanceCheck(e,Intl.NumberFormat)}intlPluralRules(e){return this.instanceCheck(e,Intl.PluralRules)}intlRelativeTimeFormat(e){return this.instanceCheck(e,Intl.RelativeTimeFormat)}intlRelativeTimeFormat(e){return this.instanceCheck(e,Intl.RelativeTimeFormat)}finalizationRegistry(e){return this.instanceCheck(e,FinalizationRegistry)}weakRef(e){return this.instanceCheck(e,WeakRef)}};class Av{constructor(){}on(e,t,n=!1){return Tv.string(e),Tv.function(t),Tv.boolean(n),"*"==e&&(e=this.#e),this.#t[e]||(this.#t[e]=[]),t[this.#n]=n,this.#t[e].push(t),this}once(e,t){return this.on(e,t,!0)}off(e="*",t="*"){if(Tv.string(e),e!=this.#e.toString()&&"*"!=e||(e=this.#e),!this.#t[e])return this;if("*"==t)return delete this.#t[e],this;Tv.function(t);const n=this.#t[e];for(;n.includes(t);)n.splice(n.indexOf(t),1);return n.length<1&&delete this.#t[e],this}emit(e,...t){Tv.string(e);const n=this.#t[this.#e]||[];if(this.#r(this.#e.toString(),n,e,...t),!this.#t[e])return this;const r=this.#t[e];return this.#r(e,r,...t),this}reset(){this.off(this.#e.toString());for(let e in this.#t)this.off(e);return this}get list(){return Object.assign({},this.#t)}#r=(e,t,...n)=>{Tv.string(e),Tv.array(t);const r=[];for(let e of t)e(...n),e[this.#n]&&r.push(e);for(let t of r)this.off(e,t)};#e=Symbol.for("event-pubsub-all");#n=Symbol.for("event-pubsub-once");#t={}}let Mv=new Ev;class Pv extends Av{constructor(e,t){super(),this.config=e,this.log=t,this.publish=super.emit,e.maxRetries&&(this.retriesRemaining=e.maxRetries),Mv=new Ev(this.config)}Client=Pv;queue=new $v;socket=!1;connect=Rv;emit=Dv;retriesRemaining=0;explicitlyDisconnected=!1}function Dv(e,t){this.log("dispatching event to ",this.id,this.path," : ",e,",",t);let n=new Cv;n.type=e,n.data=t,n=this.config.rawBuffer?Buffer.from(e,this.config.encoding):Mv.format(n),this.config.sync?this.queue.add(jv.bind(this,n)):this.socket.write(n)}function jv(e){this.log("dispatching event to ",this.id,this.path," : ",e),this.socket.write(e)}function Rv(){let e=this;if(e.log("requested connection to ",e.id,e.path),!this.path)return void e.log("\n\n######\nerror: ",e.id," client has not specified socket path it wishes to connect to.");const t={};if(e.port)if(t.host=e.path,t.port=e.port,e.config.interface.localAddress&&(t.localAddress=e.config.interface.localAddress),e.config.interface.localPort&&(t.localPort=e.config.interface.localPort),e.config.interface.family&&(t.family=e.config.interface.family),e.config.interface.hints&&(t.hints=e.config.interface.hints),e.config.interface.lookup&&(t.lookup=e.config.interface.lookup),e.config.tls){if(e.log("Connecting client via TLS to",e.path,e.port,e.config.tls),e.config.tls.private&&(e.config.tls.key=$.readFileSync(e.config.tls.private)),e.config.tls.public&&(e.config.tls.cert=$.readFileSync(e.config.tls.public)),e.config.tls.trustedConnections){"string"==typeof e.config.tls.trustedConnections&&(e.config.tls.trustedConnections=[e.config.tls.trustedConnections]),e.config.tls.ca=[];for(let t=0;t<e.config.tls.trustedConnections.length;t++)e.config.tls.ca.push($.readFileSync(e.config.tls.trustedConnections[t]))}Object.assign(e.config.tls,t),e.socket=B.connect(e.config.tls)}else e.log("Connecting client via TCP to",t),e.socket=U.connect(t);else e.log("Connecting client on Unix Socket :",e.path),t.path=e.path,"win32"!==process.platform||e.path.startsWith("\\\\.\\pipe\\")||(t.path=t.path.replace(/^\//,""),t.path=t.path.replace(/\//g,"-"),t.path=`\\\\.\\pipe\\${t.path}`),e.socket=U.connect(t);e.socket.setEncoding(this.config.encoding),e.socket.on("error",(function(t){e.log("\n\n######\nerror: ",t),e.publish("error",t)})),e.socket.on("connect",(function(){e.publish("connect"),e.retriesRemaining=e.config.maxRetries,e.log("retrying reset")})),e.socket.on("close",(function(){if(e.log("connection closed",e.id,e.path,e.retriesRemaining,"tries remaining of",e.config.maxRetries),e.config.stopRetrying||e.retriesRemaining<1||e.explicitlyDisconnected)return e.publish("disconnect"),e.log(e.config.id,"exceeded connection rety amount of"," or stopRetrying flag set."),e.socket.destroy(),e.publish("destroy"),void(e=void 0);setTimeout(function(){e.explicitlyDisconnected||(e.retriesRemaining--,e.connect())}.bind(null,e),e.config.retry),e.publish("disconnect")})),e.socket.on("data",(function(t){if(e.log("## received events ##"),e.config.rawBuffer){if(e.publish("data",Buffer.from(t,e.config.encoding)),!e.config.sync)return;return void e.queue.next()}if(this.ipcBuffer||(this.ipcBuffer=""),(t=this.ipcBuffer+=t).slice(-1)!=Mv.delimiter||-1==t.indexOf(Mv.delimiter))return void e.log("Messages are large, You may want to consider smaller messages.");this.ipcBuffer="";const n=Mv.parse(t),r=n.length;for(let t=0;t<r;t++){let r=new Cv;r.load(n[t]),e.log("detected event",r.type,r.data),e.publish(r.type,r.data)}e.config.sync&&e.queue.next()}))}let Lv=new Ev;class Fv extends Av{constructor(e,t,n,r){super(),this.config=t,this.path=e,this.port=r,this.log=n,this.publish=super.emit,Lv=new Ev(this.config),this.on("close",Wv.bind(this))}udp4=!1;udp6=!1;server=!1;sockets=[];emit=Uv;broadcast=Bv;onStart(e){this.publish("start",e)}stop(){this.server.close()}start(){this.path?this.config.unlink?$.unlink(this.path,Hv.bind(this)):Hv.bind(this)():this.log("Socket Server Path not specified, refusing to start")}}function Uv(e,t,n){this.log("dispatching event to socket"," : ",t,n);let r=new Cv;if(r.type=t,r.data=n,this.config.rawBuffer?(this.log(this.config.encoding),r=Buffer.from(t,this.config.encoding)):r=Lv.format(r),this.udp4||this.udp6)return e.address&&e.port?void this.server.write(r,e):(this.log("Attempting to emit to a single UDP socket without supplying socket address or port. Redispatching event as broadcast to all connected sockets"),void this.broadcast(t,n));e.write(r)}function Bv(e,t){this.log("broadcasting event to all known sockets listening to ",this.path," : ",this.port?this.port:"",e,t);let n=new Cv;if(n.type=e,n.data=t,n=this.config.rawBuffer?Buffer.from(e,this.config.encoding):Lv.format(n),this.udp4||this.udp6)for(let e=1,t=this.sockets.length;e<t;e++)this.server.write(n,this.sockets[e]);else for(let e=0,t=this.sockets.length;e<t;e++)this.sockets[e].write(n)}function Wv(){for(let e=0,t=this.sockets.length;e<t;e++){let t=this.sockets[e],n=!1;if(!t||!t.readable)return t.id&&(n=t.id),this.log("socket disconnected",n.toString()),t&&t.destroy&&t.destroy(),this.sockets.splice(e,1),void this.publish("socket.disconnected",t,n)}}function Gv(e,t,n){let r=this.udp4||this.udp6?n:e;if(this.config.rawBuffer)return t=Buffer.from(t,this.config.encoding),void this.publish("data",t,r);if(r.ipcBuffer||(r.ipcBuffer=""),(t=r.ipcBuffer+=t).slice(-1)==Lv.delimiter&&-1!=t.indexOf(Lv.delimiter))for(r.ipcBuffer="",t=Lv.parse(t);t.length>0;){let e=new Cv;e.load(t.shift()),e.data&&e.data.id&&(r.id=e.data.id),this.log("received event of : ",e.type,e.data),this.publish(e.type,e.data,r)}else this.log("Messages are large, You may want to consider smaller messages.")}function Vv(e){this.publish("close",e)}function Yv(e){this.sockets.push(e),e.setEncoding&&e.setEncoding(this.config.encoding),this.log("## socket connection to server detected ##"),e.on("close",Vv.bind(this)),e.on("error",function(e){this.log("server socket error",e),this.publish("error",e)}.bind(this)),e.on("data",Gv.bind(this,e)),e.on("message",function(t,n){if(!n)return;let r;this.log("Received UDP message from ",n.address,n.port),r=this.config.rawSocket?Buffer.from(t,this.config.encoding):t.toString(),e.emit("data",r,n)}.bind(this)),this.publish("connect",e),this.config.rawBuffer}function Hv(){return this.log("starting server on ",this.path,this.port?`:${this.port}`:""),this.udp4||this.udp6?(this.server=W.createSocket(this.udp4?"udp4":"udp6"),this.server.write=qv.bind(this),this.server.on("listening",function(){Yv.bind(this)(this.server)}.bind(this))):(this.log("starting TLS server",this.config.tls),this.config.tls?zv.bind(this)():this.server=U.createServer(Yv.bind(this))),this.server.on("error",function(e){this.log("server error",e),this.publish("error",e)}.bind(this)),this.server.maxConnections=this.config.maxConnections,this.port?this.udp4||this.udp6?(this.log("starting server as",this.udp4?"udp4":"udp6"),this.server.bind(this.port,this.path),void this.onStart({address:this.path,port:this.port})):(this.log("starting server as",this.config.tls?"TLS":"TCP"),void this.server.listen(this.port,this.path,this.onStart.bind(this))):(this.log("starting server as","Unix || Windows Socket"),"win32"===process.platform&&(this.path=this.path.replace(/^\//,""),this.path=this.path.replace(/\//g,"-"),this.path=`\\\\.\\pipe\\${this.path}`),void this.server.listen({path:this.path,readableAll:this.config.readableAll,writableAll:this.config.writableAll},this.onStart.bind(this)))}function zv(){if(this.log("starting TLS server",this.config.tls),this.config.tls.private?this.config.tls.key=$.readFileSync(this.config.tls.private):this.config.tls.key=$.readFileSync(`${__dirname}/../local-node-ipc-certs/private/server.key`),this.config.tls.public?this.config.tls.cert=$.readFileSync(this.config.tls.public):this.config.tls.cert=$.readFileSync(`${__dirname}/../local-node-ipc-certs/server.pub`),this.config.tls.dhparam&&(this.config.tls.dhparam=$.readFileSync(this.config.tls.dhparam)),this.config.tls.trustedConnections){"string"==typeof this.config.tls.trustedConnections&&(this.config.tls.trustedConnections=[this.config.tls.trustedConnections]),this.config.tls.ca=[];for(let e=0;e<this.config.tls.trustedConnections.length;e++)this.config.tls.ca.push($.readFileSync(this.config.tls.trustedConnections[e]))}this.server=B.createServer(this.config.tls,Yv.bind(this))}function qv(e,t){let n=Buffer.from(e,this.config.encoding);this.server.send(n,0,n.length,t.port,t.address,(function(e){e&&(this.log("error writing data to socket",e),this.publish("error",(function(e){this.publish("error",e)})))}))}class Kv{constructor(){}config=new kv;of={};server=!1;get connectTo(){return tb}get connectToNet(){return nb}get disconnect(){return Zv}get serve(){return Xv}get serveNet(){return eb}get log(){return Jv}set connectTo(e){return tb}set connectToNet(e){return nb}set disconnect(e){return Zv}set serve(e){return Xv}set serveNet(e){return eb}set log(e){return Jv}}function Jv(...e){if(!this.config.silent){for(let t=0,n=e.length;t<n;t++)"object"==typeof e[t]&&(e[t]=i.inspect(e[t],{depth:this.config.logDepth,colors:this.config.logInColor}));this.config.logger(e.join(" "))}}function Zv(e){this.of[e]&&(this.of[e].explicitlyDisconnected=!0,this.of[e].off("*","*"),this.of[e].socket&&this.of[e].socket.destroy&&this.of[e].socket.destroy(),delete this.of[e])}function Xv(e,t){"function"==typeof e&&(t=e,e=!1),e||(this.log("Server path not specified, so defaulting to","ipc.config.socketRoot + ipc.config.appspace + ipc.config.id",this.config.socketRoot+this.config.appspace+this.config.id),e=this.config.socketRoot+this.config.appspace+this.config.id),t||(t=Qv),this.server=new Fv(e,this.config,Jv),this.server.on("start",t)}function Qv(){}function eb(e,t,n,r){"number"==typeof e&&(r=n,n=t,t=e,e=!1),"function"==typeof e&&(r=e,n=!1,e=!1,t=!1),e||(this.log("Server host not specified, so defaulting to","ipc.config.networkHost",this.config.networkHost),e=this.config.networkHost),"udp4"!=e.toLowerCase()&&"udp6"!=e.toLowerCase()||(r=t,n=e.toLowerCase(),t=!1,e=this.config.networkHost),"string"==typeof t&&(r=n,n=t,t=!1),"function"==typeof t&&(r=t,n=!1,t=!1),t||(this.log("Server port not specified, so defaulting to","ipc.config.networkPort",this.config.networkPort),t=this.config.networkPort),"function"==typeof n&&(r=n,n=!1),r||(r=Qv),this.server=new Fv(e,this.config,Jv,t),n&&(this.server[n]=!0,"udp4"===n&&"::1"===e&&(this.server.path="127.0.0.1")),this.server.on("start",r)}function tb(e,t,n){if("function"==typeof t&&(n=t,t=!1),n||(n=Qv),e){if(t||(this.log("Service path not specified, so defaulting to","ipc.config.socketRoot + ipc.config.appspace + id",(this.config.socketRoot+this.config.appspace+e).data),t=this.config.socketRoot+this.config.appspace+e),this.of[e]){if(!this.of[e].socket.destroyed)return this.log("Already Connected to",e,"- So executing success without connection"),void n();this.of[e].socket.destroy()}this.of[e]=new Pv(this.config,this.log),this.of[e].id=e,this.of[e].socket&&(this.of[e].socket.id=e),this.of[e].path=t,this.of[e].connect(),n(this)}else this.log("Service id required","Requested service connection without specifying service id. Aborting connection attempt")}function nb(e,t,n,r){if(e){if("number"==typeof t&&(r=n,n=t,t=!1),"function"==typeof t&&(r=t,t=!1,n=!1),t||(this.log("Server host not specified, so defaulting to","ipc.config.networkHost",this.config.networkHost),t=this.config.networkHost),"function"==typeof n&&(r=n,n=!1),n||(this.log("Server port not specified, so defaulting to","ipc.config.networkPort",this.config.networkPort),n=this.config.networkPort),"string"==typeof r&&(UDPType=r,r=!1),r||(r=Qv),this.of[e]){if(!this.of[e].socket.destroyed)return this.log("Already Connected to",e,"- So executing success without connection"),void r();this.of[e].socket.destroy()}this.of[e]=new Pv(this.config,this.log),this.of[e].id=e,this.of[e].socket&&(this.of[e].socket.id=e),this.of[e].path=t,this.of[e].port=n,this.of[e].connect(),r(this)}else this.log("Service id required","Requested service connection without specifying service id. Aborting connection attempt")}const rb=new class extends Kv{constructor(){super()}IPC=Kv};const ib=Object.values({protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8}).reduce(((e,t)=>e+t),0),ob=e=>{try{return JSON.parse(e)}catch(e){return null}},sb="undefined"!=typeof window,ab={protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8},cb={protocolPrefix:4,txtLength:4},lb=Object.values(ab).reduce(((e,t)=>e+t),0),ub=Object.values(cb).reduce(((e,t)=>e+t),0),db=["width","height","colorSpace"],hb=(e,t)=>{const n={},r=[];let i=0,o=Array.isArray(e)?[]:{};const s=(e,o)=>{const a=(e=>{const t="undefined"!=typeof Buffer&&e instanceof Buffer,n=e instanceof ArrayBuffer,r=e instanceof Uint8ClampedArray,i=e instanceof Uint8Array,o=e instanceof Int8Array;return t?"Buffer":n?"ArrayBuffer":r?"Uint8ClampedArray":i?"Uint8Array":o?"Int8Array":null})(e);if(!a){if(Array.isArray(e)){const t=[];for(let n=0;n<e.length;n++)t[n]=s(e[n],`${o}[${n}]`);return t}if("object"==typeof e){const t={},n=(e=>{const t=e instanceof Int16Array,n=e instanceof Uint16Array,r=e instanceof Int32Array,i=e instanceof Uint32Array,o=e instanceof Float32Array,s=e instanceof Float64Array,a=e instanceof BigInt64Array,c=e instanceof BigUint64Array;return t?"Int16Array":n?"Uint16Array":r?"Int32Array":i?"Uint32Array":o?"Float32Array":s?"Float64Array":a?"BigInt64Array":c?"BigUint64Array":null})(e);if(n)throw new Error(`Unsupported binary type [${n}] at path "${o}"`);for(const n in e)Object.hasOwn(e,n)||db.includes(n)||console.warn(`Allowing inherited property: ${n} from path: ${o}`),t[n]=s(e[n],`${o.length?`${o}.`:""}${n}`);return t}return e}n[o]={index:i,length:e.byteLength,binaryType:a},"Buffer"===t?r.push(Buffer.from(e)):"ArrayBuffer"===a?r.push(e):r.push(e.buffer),i+=e.byteLength};o=s(e,"");let a=null;if(r.length>1)if("ArrayBuffer"===t){const e=r.reduce(((e,t)=>e+t.byteLength),0),t=new Uint8Array(e);let n=0;for(let e=0;e<r.length;e++)t.set(new Uint8Array(r[e]),n),n+=r[e].byteLength;a=t.buffer}else a=Buffer.concat(r);else 1===r.length&&(a=r[0]);return a?{map:n,combinedData:a,sourceCopy:o}:null},fb=(e,t,n)=>{const r=t.match(/(\[\d+\])|([^[\].]+)/g)||[];let i=e;for(let e=0;e<r.length;e++){let t=r[e];const o=t.startsWith("[")&&t.endsWith("]"),s=e===r.length-1;if(o){t=t.slice(1,-1);const o=parseInt(t,10);if(!Array.isArray(i))throw new Error(`Expected an array at key "${r.slice(0,e).join(".")}" but found an object.`);s?i[o]=n:(i[o]||(i[o]=r[e+1].startsWith("[")?[]:{}),i=i[o])}else s?i[t]=n:(i[t]||(i[t]=r[e+1].startsWith("[")?[]:{}),i=i[t])}return e},pb=(e,t,n)=>{const r="undefined"!=typeof Buffer,i=t instanceof Uint8Array;for(const o in n)if(Object.hasOwn(n,o)){const{index:s,length:a,binaryType:c}=n[o];let l=null;if(r&&t instanceof Buffer)switch(c){case"Buffer":l=t.subarray(s,s+a);break;case"ArrayBuffer":l=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(s,s+a);break;case"Uint8Array":l=new Uint8Array(t.subarray(s,s+a));break;case"Uint8ClampedArray":l=new Uint8ClampedArray(t.subarray(s,s+a));break;case"Int8Array":l=new Int8Array(t.subarray(s,s+a))}else if(t instanceof ArrayBuffer||t instanceof Uint8Array)switch(c){case"Buffer":if(r){l=Buffer.from(t.slice(s,s+a));break}case"ArrayBuffer":l=i?t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(s,s+a):t.slice(s,s+a);break;case"Uint8Array":l=i?t.slice(s,s+a):new Uint8Array(t.slice(s,s+a));break;case"Uint8ClampedArray":l=new Uint8ClampedArray(t.slice(s,s+a));break;case"Int8Array":l=new Int8Array(t.slice(s,s+a))}l&&fb(e,o,l)}return e},gb=e=>Id(e),mb="KMSG",yb="KCMD",vb=gb("klProtocol");var bb={encode:(e,t,n)=>{const r={json:e.json},i=hb(r.json,"Buffer"),o=i?.combinedData;i&&(r.jsonBinaryMap=i.map,r.json=i.sourceCopy);const s=o?o.byteLength:0,a=JSON.stringify(r),c=Buffer.from(a),l=c.byteLength,u=ab.protocolPrefix+ab.protocolVersion+ab.jsonLength+ab.binaryLength+ab.fromServiceId+ab.toServiceId+ab.sentAt+l+s,d=Buffer.alloc(u),h=Date.now();let f=0;return d.write(mb,f),f+=ab.protocolPrefix,d.writeUInt8(1,f),f+=ab.protocolVersion,d.writeUInt32LE(l,f),f+=ab.jsonLength,d.writeUInt32LE(s,f),f+=ab.binaryLength,d.writeUInt32LE(t,f),f+=ab.fromServiceId,d.writeUInt32LE(n,f),f+=ab.toServiceId,d.writeBigInt64LE(BigInt(h),f),f+=ab.sentAt,c.copy(d,f),f+=l,o&&s&&o.copy(d,f),d},decodeHeader:e=>{let t=0;const n=e.toString("utf-8",t,ab.protocolPrefix);if(t+=ab.protocolPrefix,n!==mb)return null;if(e.byteLength<lb)return vb(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const r=e.readUInt8(t);t+=ab.protocolVersion;const i=e.readUInt32LE(t);t+=ab.jsonLength;const o=e.readUInt32LE(t);t+=ab.binaryLength;const s=e.readUInt32LE(t);t+=ab.fromServiceId;const a=e.readUInt32LE(t);t+=ab.toServiceId;const c=e.readBigInt64LE(t);t+=ab.sentAt;const l=i+o,u=e.subarray(t,t+l),d=e.subarray(0,lb);let h=null;return e.byteLength-lb-i-o>0&&(h=e.subarray(lb+i+o)),{header:{protocolVersion:r,jsonLength:i,binaryLength:o,fromServiceId:s,toServiceId:a,sentAt:new Date(Number(c)),packages:[u],headerPackage:d},remaining:h}},decodeFullKlMessage:e=>{const t=Buffer.concat(e.packages),n=t.subarray(0,e.jsonLength).toString(),r=t.subarray(e.jsonLength,e.jsonLength+e.binaryLength),i=ob(n);if(!i?.json)return vb("Invalid JSON in KL message"),null;i.jsonBinaryMap&&r.byteLength&&pb(i.json,r,i.jsonBinaryMap);const o=Buffer.concat([e.headerPackage,t]);let s=o,a=null;const c=lb+e.jsonLength+e.binaryLength;return o.byteLength>c&&(a=o.subarray(c),s=o.subarray(0,c)),{message:{json:i.json,rawMessage:s},remaining:a}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<lb)return vb("Invalid Header Size"),e;let n=0;return n+=ab.protocolPrefix,n+=ab.protocolVersion,n+=ab.jsonLength,n+=ab.binaryLength,void 0!==t.fromServiceId&&e.writeUInt32LE(t.fromServiceId,n),n+=ab.fromServiceId,void 0!==t.toServiceId&&e.writeUInt32LE(t.toServiceId,n),e},encodeCommand:e=>{let t=0;const n=Buffer.from(e),r=n.byteLength,i=ub+r,o=Buffer.alloc(i);return o.write(yb,t),t+=cb.protocolPrefix,o.writeUint32LE(r,t),t+=cb.txtLength,n.copy(o,t),o},decodeCommand:e=>{let t=0;if(e.byteLength<ub)return{command:null};const n=e.toString("utf-8",t,cb.protocolPrefix);if(t+=cb.protocolPrefix,n!==yb)return{command:null};const r=e.readUInt32LE(t);t+=cb.txtLength;const i=e.toString("utf-8",t,t+r),o=e.byteLength-ub-r;let s=null;o>0&&(s=e.subarray(ub+r));let a=0;return o<0&&(a=Math.abs(o)),{command:i,remainingData:s,missing:a}}};const wb="KMSG",Sb="KCMD",_b=gb("klProtocol"),Ib=new TextEncoder;var xb={encode:(e,t,n)=>{const r={json:e.json},i=hb(e.json,"ArrayBuffer"),o=i?.combinedData;i&&(r.jsonBinaryMap=i.map,r.json=i.sourceCopy);const s=o?o.byteLength:0,a=JSON.stringify(r),c=Ib.encode(a),l=c.byteLength,u=new ArrayBuffer(ab.protocolPrefix+ab.protocolVersion+ab.jsonLength+ab.binaryLength+ab.fromServiceId+ab.toServiceId+ab.sentAt+l+s),d=new DataView(u),h=new Uint8Array(u),f=Date.now();let p=0;for(let e=0;e<4;++e)h[p++]=wb.charCodeAt(e);return d.setUint8(p,1),p+=ab.protocolVersion,d.setUint32(p,l,!0),p+=ab.jsonLength,d.setUint32(p,s,!0),p+=ab.binaryLength,d.setUint32(p,t,!0),p+=ab.fromServiceId,d.setUint32(p,n,!0),p+=ab.toServiceId,d.setBigInt64(p,BigInt(f),!0),p+=ab.sentAt,h.set(c,p),p+=l,o&&s&&h.set(new Uint8Array(o),p),u},decodeHeader:e=>{const t=new DataView(e);let n=0,r="";for(let e=0;e<ab.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==wb)return null;if(e.byteLength<lb)return _b.log(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const i=t.getUint8(n);n+=ab.protocolVersion;const o=t.getUint32(n,!0);n+=ab.jsonLength;const s=t.getUint32(n,!0);n+=ab.binaryLength;const a=t.getUint32(n,!0);n+=ab.fromServiceId;const c=t.getUint32(n,!0);n+=ab.toServiceId;const l=t.getBigInt64(n,!0);n+=ab.sentAt;const u=o+s,d=e.slice(n,n+u),h=new Uint8Array(e,0,lb);let f=null;return e.byteLength-lb-o-s>0&&(f=new Uint8Array(e,lb+o+s).slice().buffer),{header:{protocolVersion:i,jsonLength:o,binaryLength:s,fromServiceId:a,toServiceId:c,sentAt:new Date(Number(l)),packages:[d],headerPackage:h.slice().buffer},remaining:f}},decodeFullKlMessage:e=>{const t=e.packages.reduce(((e,t)=>e+t.byteLength),0),n=new Uint8Array(t);let r,i=0;for(const t of e.packages)r=new Uint8Array(t),n.set(r,i),i+=r.byteLength;const o=(new TextDecoder).decode(n.subarray(0,e.jsonLength)),s=n.subarray(e.jsonLength,e.jsonLength+e.binaryLength),a=ob(o);if(!a?.json)return _b.log("Invalid JSON in KL message"),null;a.jsonBinaryMap&&s.byteLength&&pb(a.json,s,a.jsonBinaryMap);const c=new Uint8Array(e.headerPackage.byteLength+n.byteLength);c.set(new Uint8Array(e.headerPackage),0),c.set(n,e.headerPackage.byteLength);let l=c,u=null;const d=lb+e.jsonLength+e.binaryLength;return c.byteLength>d&&(u=c.subarray(d),l=c.subarray(0,d)),{message:{json:a.json,...s.length?{binaryData:s.buffer}:{},rawMessage:l.buffer},remaining:u?.buffer??null}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<lb)return _b("Invalid Header Size"),e;let n=0;n+=ab.protocolPrefix,n+=ab.protocolVersion,n+=ab.jsonLength,n+=ab.binaryLength;const r=new DataView(e);return void 0!==t.fromServiceId&&r.setUint32(n,t.fromServiceId,!0),n+=ab.fromServiceId,void 0!==t.toServiceId&&r.setUint32(n,t.toServiceId,!0),e},encodeCommand:e=>{let t=0;const n=Ib.encode(e),r=n.byteLength,i=new ArrayBuffer(ub+r),o=new DataView(i),s=new Uint8Array(i);for(let e=0;e<4;++e)s[t++]=Sb.charCodeAt(e);return o.setUint32(t,r,!0),t+=cb.txtLength,s.set(n,t),i},decodeCommand:e=>{const t=new DataView(e);let n=0;if(e.byteLength<ub)return{command:null};let r="";for(let e=0;e<cb.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==Sb)return{command:null};const i=t.getUint32(n,!0);n+=cb.txtLength;const o=e.byteLength-ub-i,s=new Uint8Array(e,n,Math.min(i,e.byteLength-ub)),a=(new TextDecoder).decode(s);let c=null;o>0&&(c=e.slice(ub+i));let l=0;return o<0&&(l=Math.abs(o)),{command:a,remainingData:c,missing:l}}};const kb=gb("klTransmissionManager"),Eb=()=>{const e=(t,n,r,i)=>{let o=n,s=null;const a=t instanceof ArrayBuffer;if(kb(`RAW: ${t.toString()}`),!o||o.partialHeaderData){let c;if(a?(c=o?.partialHeaderData?new Uint8Array([...new Uint8Array(o.partialHeaderData),...new Uint8Array(t)]).buffer:t,s=xb.decodeHeader(c)):(c=o?.partialHeaderData?Buffer.concat([o.partialHeaderData,t]):t,s=bb.decodeHeader(c)),!s){const{command:t,missing:o,remainingData:s}=a?xb.decodeCommand(c):bb.decodeCommand(c);return t?i({command:t,complete:!0,rawMessage:c}):kb(o?`ERROR: Missing ${o} bytes to complete the command. This partial command will be aborted.`:`ERROR: Invalid state, message was decoded without a header or partial header data. Discarding ${c.byteLength} bytes`),s?(kb(`${s.byteLength} bytes remain after processing command. Re-analyzing...`),e(s,n,r,i)):void 0}if(s.partialHeader)return o={firstPackageAt:Date.now(),partialHeaderData:c},r(o);if(!s.header)return kb(`ERROR: Invalid state, message was decoded without a header or partial header data. Discarding ${c.byteLength} bytes`);const l=s.header;o={firstPackageAt:Date.now(),header:{...l,totalBytesReceived:l.packages[0].byteLength,totalBytesExpected:l.binaryLength+l.jsonLength,remaining:s.remaining}},r(o)}else o.header&&o.header.totalBytesReceived<o.header.totalBytesExpected&&(o.header.packages.push(t),o.header.totalBytesReceived+=t.byteLength,r(o));if(o.header&&o.header.totalBytesReceived>=o.header.totalBytesExpected){const t=Date.now()-o.header.sentAt.getTime(),n=Date.now()-o.firstPackageAt;kb(`Received ${o.header.totalBytesReceived} of ${o.header.totalBytesExpected} expected in ${t} ms, elapsed since first package: ${n}ms`);const s=a?xb.decodeFullKlMessage(o.header):bb.decodeFullKlMessage(o.header),c=o.header.totalBytesReceived,l=o.header.remaining;r(null),s&&i({klMessage:s.message,complete:!0,sourceServiceId:o.header.fromServiceId,targetServiceId:o.header.toServiceId,rawMessage:s.message.rawMessage});let u=l;if(s?.remaining&&(u=a?l?((e,t)=>{const n=e.byteLength+t.byteLength,r=new ArrayBuffer(n),i=new Uint8Array(e),o=new Uint8Array(t),s=new Uint8Array(r);return s.set(i),s.set(o,i.length),r})(l,s.remaining):s.remaining:l?Buffer.concat([l,s.remaining]):s.remaining),u)return kb(`${u.byteLength} bytes remaining after processing message with ${c} bytes of data. Re-analyzing...`),e(u,null,r,i)}};return e};rb.config={...rb.config,id:"widgets",retry:1500,silent:!0,rawBuffer:!0,appspace:"kemu.",encoding:"hex"};const Cb={info:xd("ipcServer:info"),data:xd("ipcServer:data")};let $b,Ob,Nb,Tb,Ab={};const Mb=Eb(),Pb=e=>{Ab[e]&&(Cb.info(`Client disconnected [${e}]`),delete Ab[e],Ob&&Ob(e))};var Db=(e,t)=>{const n=Ab[e];if(!n)return Cb.info(`Cannot send message to unknown client [${e}]`),!1;if(t.length>=ib)return Cb.info("Message is too long to be a command. Use sendMessage instead."),!1;const r=bb.encodeCommand(t);return n.socket.write(r),!0},jb=(e,t)=>{const n=Ab[e];return!!n&&(Cb.info(`Renaming socket id [${e}] to [${t}]`),delete Ab[e],n.socket.id=t,Ab[t]=n,n.socket.removeListener("close",n.disconnectHandler),n.disconnectHandler=()=>Pb(t),n.socket.on("close",n.disconnectHandler),!0)};let Rb=bb;sb&&(Rb=xb);var Lb,Fb=Rb;!function(e){e.FunctionNotFound="FNC_NOT_FOUND",e.FunctionNotAllowed="FNC_NOT_ALLOWED",e.ParentEventCallbackError="PARENT_EVENT_CALLBACK_ERROR"}(Lb||(Lb={}));let Ub=Math.ceil(Date.now()/1e3);var Bb={exports:{}};const Wb=["nodebuffer","arraybuffer","fragments"],Gb="undefined"!=typeof Blob;Gb&&Wb.push("blob");var Vb={BINARY_TYPES:Wb,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Gb,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}};const{EMPTY_BUFFER:Yb}=Vb,Hb=Buffer[Symbol.species];function zb(e,t,n,r,i){for(let o=0;o<i;o++)n[r+o]=e[o]^t[3&o]}function qb(e,t){for(let n=0;n<e.length;n++)e[n]^=t[3&n]}if(Bb.exports={concat:function(e,t){if(0===e.length)return Yb;if(1===e.length)return e[0];const n=Buffer.allocUnsafe(t);let r=0;for(let t=0;t<e.length;t++){const i=e[t];n.set(i,r),r+=i.length}return r<t?new Hb(n.buffer,n.byteOffset,r):n},mask:zb,toArrayBuffer:function(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)},toBuffer:function e(t){if(e.readOnly=!0,Buffer.isBuffer(t))return t;let n;return t instanceof ArrayBuffer?n=new Hb(t):ArrayBuffer.isView(t)?n=new Hb(t.buffer,t.byteOffset,t.byteLength):(n=Buffer.from(t),e.readOnly=!1),n},unmask:qb},!process.env.WS_NO_BUFFER_UTIL)try{const e=require("bufferutil");Bb.exports.mask=function(t,n,r,i,o){o<48?zb(t,n,r,i,o):e.mask(t,n,r,i,o)},Bb.exports.unmask=function(t,n){t.length<32?qb(t,n):e.unmask(t,n)}}catch(I){}var Kb=Bb.exports;const Jb=Symbol("kDone"),Zb=Symbol("kRun"),Xb=j,Qb=Kb,ew=class{constructor(e){this[Jb]=()=>{this.pending--,this[Zb]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Zb]()}[Zb](){if(this.pending!==this.concurrency&&this.jobs.length){const e=this.jobs.shift();this.pending++,e(this[Jb])}}},{kStatusCode:tw}=Vb,nw=Buffer[Symbol.species],rw=Buffer.from([0,0,255,255]),iw=Symbol("permessage-deflate"),ow=Symbol("total-length"),sw=Symbol("callback"),aw=Symbol("buffers"),cw=Symbol("error");let lw;var uw=class{constructor(e,t,n){if(this._maxPayload=0|n,this._options=e||{},this._threshold=void 0!==this._options.threshold?this._options.threshold:1024,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,!lw){const e=void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10;lw=new ew(e)}}static get extensionName(){return"permessage-deflate"}offer(){const e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:null==this._options.clientMaxWindowBits&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){const e=this._deflate[sw];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){const t=this._options,n=e.find((e=>!(!1===t.serverNoContextTakeover&&e.server_no_context_takeover||e.server_max_window_bits&&(!1===t.serverMaxWindowBits||"number"==typeof t.serverMaxWindowBits&&t.serverMaxWindowBits>e.server_max_window_bits)||"number"==typeof t.clientMaxWindowBits&&!e.client_max_window_bits)));if(!n)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),"number"==typeof t.serverMaxWindowBits&&(n.server_max_window_bits=t.serverMaxWindowBits),"number"==typeof t.clientMaxWindowBits?n.client_max_window_bits=t.clientMaxWindowBits:!0!==n.client_max_window_bits&&!1!==t.clientMaxWindowBits||delete n.client_max_window_bits,n}acceptAsClient(e){const t=e[0];if(!1===this._options.clientNoContextTakeover&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(t.client_max_window_bits){if(!1===this._options.clientMaxWindowBits||"number"==typeof this._options.clientMaxWindowBits&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"')}else"number"==typeof this._options.clientMaxWindowBits&&(t.client_max_window_bits=this._options.clientMaxWindowBits);return t}normalizeParams(e){return e.forEach((e=>{Object.keys(e).forEach((t=>{let n=e[t];if(n.length>1)throw new Error(`Parameter "${t}" must have only a single value`);if(n=n[0],"client_max_window_bits"===t){if(!0!==n){const e=+n;if(!Number.isInteger(e)||e<8||e>15)throw new TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${t}": ${n}`)}else if("server_max_window_bits"===t){const e=+n;if(!Number.isInteger(e)||e<8||e>15)throw new TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else{if("client_no_context_takeover"!==t&&"server_no_context_takeover"!==t)throw new Error(`Unknown parameter "${t}"`);if(!0!==n)throw new TypeError(`Invalid value for parameter "${t}": ${n}`)}e[t]=n}))})),e}decompress(e,t,n){lw.add((r=>{this._decompress(e,t,((e,t)=>{r(),n(e,t)}))}))}compress(e,t,n){lw.add((r=>{this._compress(e,t,((e,t)=>{r(),n(e,t)}))}))}_decompress(e,t,n){const r=this._isServer?"client":"server";if(!this._inflate){const e=`${r}_max_window_bits`,t="number"!=typeof this.params[e]?Xb.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=Xb.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[iw]=this,this._inflate[ow]=0,this._inflate[aw]=[],this._inflate.on("error",fw),this._inflate.on("data",hw)}this._inflate[sw]=n,this._inflate.write(e),t&&this._inflate.write(rw),this._inflate.flush((()=>{const e=this._inflate[cw];if(e)return this._inflate.close(),this._inflate=null,void n(e);const i=Qb.concat(this._inflate[aw],this._inflate[ow]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[ow]=0,this._inflate[aw]=[],t&&this.params[`${r}_no_context_takeover`]&&this._inflate.reset()),n(null,i)}))}_compress(e,t,n){const r=this._isServer?"server":"client";if(!this._deflate){const e=`${r}_max_window_bits`,t="number"!=typeof this.params[e]?Xb.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=Xb.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[ow]=0,this._deflate[aw]=[],this._deflate.on("data",dw)}this._deflate[sw]=n,this._deflate.write(e),this._deflate.flush(Xb.Z_SYNC_FLUSH,(()=>{if(!this._deflate)return;let e=Qb.concat(this._deflate[aw],this._deflate[ow]);t&&(e=new nw(e.buffer,e.byteOffset,e.length-4)),this._deflate[sw]=null,this._deflate[ow]=0,this._deflate[aw]=[],t&&this.params[`${r}_no_context_takeover`]&&this._deflate.reset(),n(null,e)}))}};function dw(e){this[aw].push(e),this[ow]+=e.length}function hw(e){this[ow]+=e.length,this[iw]._maxPayload<1||this[ow]<=this[iw]._maxPayload?this[aw].push(e):(this[cw]=new RangeError("Max payload size exceeded"),this[cw].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[cw][tw]=1009,this.removeListener("data",hw),this.reset())}function fw(e){this[iw]._inflate=null,e[tw]=1007,this[sw](e)}var pw={exports:{}};const{isUtf8:gw}=P,{hasBlob:mw}=Vb;function yw(e){const t=e.length;let n=0;for(;n<t;)if(128&e[n])if(192==(224&e[n])){if(n+1===t||128!=(192&e[n+1])||192==(254&e[n]))return!1;n+=2}else if(224==(240&e[n])){if(n+2>=t||128!=(192&e[n+1])||128!=(192&e[n+2])||224===e[n]&&128==(224&e[n+1])||237===e[n]&&160==(224&e[n+1]))return!1;n+=3}else{if(240!=(248&e[n]))return!1;if(n+3>=t||128!=(192&e[n+1])||128!=(192&e[n+2])||128!=(192&e[n+3])||240===e[n]&&128==(240&e[n+1])||244===e[n]&&e[n+1]>143||e[n]>244)return!1;n+=4}else n++;return!0}if(pw.exports={isBlob:function(e){return mw&&"object"==typeof e&&"function"==typeof e.arrayBuffer&&"string"==typeof e.type&&"function"==typeof e.stream&&("Blob"===e[Symbol.toStringTag]||"File"===e[Symbol.toStringTag])},isValidStatusCode:function(e){return e>=1e3&&e<=1014&&1004!==e&&1005!==e&&1006!==e||e>=3e3&&e<=4999},isValidUTF8:yw,tokenChars:[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0]},gw)pw.exports.isValidUTF8=function(e){return e.length<24?yw(e):gw(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{const e=require("utf-8-validate");pw.exports.isValidUTF8=function(t){return t.length<32?yw(t):e(t)}}catch(I){}var vw=pw.exports;const{Writable:bw}=M,ww=uw,{BINARY_TYPES:Sw,EMPTY_BUFFER:_w,kStatusCode:Iw,kWebSocket:xw}=Vb,{concat:kw,toArrayBuffer:Ew,unmask:Cw}=Kb,{isValidStatusCode:$w,isValidUTF8:Ow}=vw,Nw=Buffer[Symbol.species];const{randomFillSync:Tw}=l,Aw=uw,{EMPTY_BUFFER:Mw,kWebSocket:Pw,NOOP:Dw}=Vb,{isBlob:jw,isValidStatusCode:Rw}=vw,{mask:Lw,toBuffer:Fw}=Kb,Uw=Symbol("kByteLength"),Bw=Buffer.alloc(4),Ww=8192;let Gw,Vw=Ww;function Yw(e,t,n){"function"==typeof n&&n(t);for(let n=0;n<e._queue.length;n++){const r=e._queue[n],i=r[r.length-1];"function"==typeof i&&i(t)}}function Hw(e,t,n){Yw(e,t,n),e.onerror(t)}const{kForOnEventAttribute:zw,kListener:qw}=Vb,Kw=Symbol("kCode"),Jw=Symbol("kData"),Zw=Symbol("kError"),Xw=Symbol("kMessage"),Qw=Symbol("kReason"),eS=Symbol("kTarget"),tS=Symbol("kType"),nS=Symbol("kWasClean");class rS{constructor(e){this[eS]=null,this[tS]=e}get target(){return this[eS]}get type(){return this[tS]}}Object.defineProperty(rS.prototype,"target",{enumerable:!0}),Object.defineProperty(rS.prototype,"type",{enumerable:!0});class iS extends rS{constructor(e,t={}){super(e),this[Kw]=void 0===t.code?0:t.code,this[Qw]=void 0===t.reason?"":t.reason,this[nS]=void 0!==t.wasClean&&t.wasClean}get code(){return this[Kw]}get reason(){return this[Qw]}get wasClean(){return this[nS]}}Object.defineProperty(iS.prototype,"code",{enumerable:!0}),Object.defineProperty(iS.prototype,"reason",{enumerable:!0}),Object.defineProperty(iS.prototype,"wasClean",{enumerable:!0});class oS extends rS{constructor(e,t={}){super(e),this[Zw]=void 0===t.error?null:t.error,this[Xw]=void 0===t.message?"":t.message}get error(){return this[Zw]}get message(){return this[Xw]}}Object.defineProperty(oS.prototype,"error",{enumerable:!0}),Object.defineProperty(oS.prototype,"message",{enumerable:!0});class sS extends rS{constructor(e,t={}){super(e),this[Jw]=void 0===t.data?null:t.data}get data(){return this[Jw]}}Object.defineProperty(sS.prototype,"data",{enumerable:!0});const aS={addEventListener(e,t,n={}){for(const r of this.listeners(e))if(!n[zw]&&r[qw]===t&&!r[zw])return;let r;if("message"===e)r=function(e,n){const r=new sS("message",{data:n?e:e.toString()});r[eS]=this,lS(t,this,r)};else if("close"===e)r=function(e,n){const r=new iS("close",{code:e,reason:n.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[eS]=this,lS(t,this,r)};else if("error"===e)r=function(e){const n=new oS("error",{error:e,message:e.message});n[eS]=this,lS(t,this,n)};else{if("open"!==e)return;r=function(){const e=new rS("open");e[eS]=this,lS(t,this,e)}}r[zw]=!!n[zw],r[qw]=t,n.once?this.once(e,r):this.on(e,r)},removeEventListener(e,t){for(const n of this.listeners(e))if(n[qw]===t&&!n[zw]){this.removeListener(e,n);break}}};var cS={CloseEvent:iS,ErrorEvent:oS,Event:rS,EventTarget:aS,MessageEvent:sS};function lS(e,t,n){"object"==typeof e&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}const{tokenChars:uS}=vw;function dS(e,t,n){void 0===e[t]?e[t]=[n]:e[t].push(n)}var hS={format:function(e){return Object.keys(e).map((t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map((e=>[t].concat(Object.keys(e).map((t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map((e=>!0===e?t:`${t}=${e}`)).join("; ")}))).join("; "))).join(", ")})).join(", ")},parse:function(e){const t=Object.create(null);let n,r,i=Object.create(null),o=!1,s=!1,a=!1,c=-1,l=-1,u=-1,d=0;for(;d<e.length;d++)if(l=e.charCodeAt(d),void 0===n)if(-1===u&&1===uS[l])-1===c&&(c=d);else if(0===d||32!==l&&9!==l){if(59!==l&&44!==l)throw new SyntaxError(`Unexpected character at index ${d}`);{if(-1===c)throw new SyntaxError(`Unexpected character at index ${d}`);-1===u&&(u=d);const r=e.slice(c,u);44===l?(dS(t,r,i),i=Object.create(null)):n=r,c=u=-1}}else-1===u&&-1!==c&&(u=d);else if(void 0===r)if(-1===u&&1===uS[l])-1===c&&(c=d);else if(32===l||9===l)-1===u&&-1!==c&&(u=d);else if(59===l||44===l){if(-1===c)throw new SyntaxError(`Unexpected character at index ${d}`);-1===u&&(u=d),dS(i,e.slice(c,u),!0),44===l&&(dS(t,n,i),i=Object.create(null),n=void 0),c=u=-1}else{if(61!==l||-1===c||-1!==u)throw new SyntaxError(`Unexpected character at index ${d}`);r=e.slice(c,d),c=u=-1}else if(s){if(1!==uS[l])throw new SyntaxError(`Unexpected character at index ${d}`);-1===c?c=d:o||(o=!0),s=!1}else if(a)if(1===uS[l])-1===c&&(c=d);else if(34===l&&-1!==c)a=!1,u=d;else{if(92!==l)throw new SyntaxError(`Unexpected character at index ${d}`);s=!0}else if(34===l&&61===e.charCodeAt(d-1))a=!0;else if(-1===u&&1===uS[l])-1===c&&(c=d);else if(-1===c||32!==l&&9!==l){if(59!==l&&44!==l)throw new SyntaxError(`Unexpected character at index ${d}`);{if(-1===c)throw new SyntaxError(`Unexpected character at index ${d}`);-1===u&&(u=d);let s=e.slice(c,u);o&&(s=s.replace(/\\/g,""),o=!1),dS(i,r,s),44===l&&(dS(t,n,i),i=Object.create(null),n=void 0),r=void 0,c=u=-1}}else-1===u&&(u=d);if(-1===c||a||32===l||9===l)throw new SyntaxError("Unexpected end of input");-1===u&&(u=d);const h=e.slice(c,u);return void 0===n?dS(t,h,i):(void 0===r?dS(i,h,!0):dS(i,r,o?h.replace(/\\/g,""):h),dS(t,n,i)),t}};const fS=D,pS=F,gS=L,mS=U,yS=B,{randomBytes:vS,createHash:bS}=l,{URL:wS}=G,SS=uw,_S=class extends bw{constructor(e={}){super(),this._allowSynchronousEvents=void 0===e.allowSynchronousEvents||e.allowSynchronousEvents,this._binaryType=e.binaryType||Sw[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=0|e.maxPayload,this._skipUTF8Validation=!!e.skipUTF8Validation,this[xw]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,n){if(8===this._opcode&&0==this._state)return n();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){const t=this._buffers[0];return this._buffers[0]=new Nw(t.buffer,t.byteOffset+e,t.length-e),new Nw(t.buffer,t.byteOffset,e)}const t=Buffer.allocUnsafe(e);do{const n=this._buffers[0],r=t.length-e;e>=n.length?t.set(this._buffers.shift(),r):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),r),this._buffers[0]=new Nw(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do{switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:return void(this._loop=!1)}}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2)return void(this._loop=!1);const t=this.consume(2);if(48&t[0])return void e(this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3"));const n=!(64&~t[0]);if(!n||this._extensions[ww.extensionName]){if(this._fin=!(128&~t[0]),this._opcode=15&t[0],this._payloadLength=127&t[1],0===this._opcode){if(n)return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"));if(!this._fragmented)return void e(this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE"));this._opcode=this._fragmented}else if(1===this._opcode||2===this._opcode){if(this._fragmented)return void e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE"));this._compressed=n}else{if(!(this._opcode>7&&this._opcode<11))return void e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE"));if(!this._fin)return void e(this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN"));if(n)return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"));if(this._payloadLength>125||8===this._opcode&&1===this._payloadLength)return void e(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"))}if(this._fin||this._fragmented||(this._fragmented=this._opcode),this._masked=!(128&~t[1]),this._isServer){if(!this._masked)return void e(this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK"))}else if(this._masked)return void e(this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK"));126===this._payloadLength?this._state=1:127===this._payloadLength?this._state=2:this.haveLength(e)}else e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"))}getPayloadLength16(e){this._bufferedBytes<2?this._loop=!1:(this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e))}getPayloadLength64(e){if(this._bufferedBytes<8)return void(this._loop=!1);const t=this.consume(8),n=t.readUInt32BE(0);n>Math.pow(2,21)-1?e(this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH")):(this._payloadLength=n*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e))}haveLength(e){this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)?e(this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH")):this._masked?this._state=3:this._state=4}getMask(){this._bufferedBytes<4?this._loop=!1:(this._mask=this.consume(4),this._state=4)}getData(e){let t=_w;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength)return void(this._loop=!1);t=this.consume(this._payloadLength),this._masked&&this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3]&&Cw(t,this._mask)}if(this._opcode>7)this.controlMessage(t,e);else{if(this._compressed)return this._state=5,void this.decompress(t,e);t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}}decompress(e,t){this._extensions[ww.extensionName].decompress(e,this._fin,((e,n)=>{if(e)return t(e);if(n.length){if(this._messageLength+=n.length,this._messageLength>this._maxPayload&&this._maxPayload>0){const e=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");return void t(e)}this._fragments.push(n)}this.dataMessage(t),0===this._state&&this.startLoop(t)}))}dataMessage(e){if(!this._fin)return void(this._state=0);const t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],2===this._opcode){let r;r="nodebuffer"===this._binaryType?kw(n,t):"arraybuffer"===this._binaryType?Ew(kw(n,t)):"blob"===this._binaryType?new Blob(n):n,this._allowSynchronousEvents?(this.emit("message",r,!0),this._state=0):(this._state=6,setImmediate((()=>{this.emit("message",r,!0),this._state=0,this.startLoop(e)})))}else{const r=kw(n,t);if(!this._skipUTF8Validation&&!Ow(r)){const t=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");return void e(t)}5===this._state||this._allowSynchronousEvents?(this.emit("message",r,!1),this._state=0):(this._state=6,setImmediate((()=>{this.emit("message",r,!1),this._state=0,this.startLoop(e)})))}}controlMessage(e,t){if(8!==this._opcode)this._allowSynchronousEvents?(this.emit(9===this._opcode?"ping":"pong",e),this._state=0):(this._state=6,setImmediate((()=>{this.emit(9===this._opcode?"ping":"pong",e),this._state=0,this.startLoop(t)})));else{if(0===e.length)this._loop=!1,this.emit("conclude",1005,_w),this.end();else{const n=e.readUInt16BE(0);if(!$w(n)){const e=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");return void t(e)}const r=new Nw(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Ow(r)){const e=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");return void t(e)}this._loop=!1,this.emit("conclude",n,r),this.end()}this._state=0}}createError(e,t,n,r,i){this._loop=!1,this._errored=!0;const o=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(o,this.createError),o.code=i,o[Iw]=r,o}},IS=class e{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=Dw,this[Pw]=void 0}static frame(e,t){let n,r,i=!1,o=2,s=!1;t.mask&&(n=t.maskBuffer||Bw,t.generateMask?t.generateMask(n):(Vw===Ww&&(void 0===Gw&&(Gw=Buffer.alloc(Ww)),Tw(Gw,0,Ww),Vw=0),n[0]=Gw[Vw++],n[1]=Gw[Vw++],n[2]=Gw[Vw++],n[3]=Gw[Vw++]),s=!(n[0]|n[1]|n[2]|n[3]),o=6),"string"==typeof e?r=t.mask&&!s||void 0===t[Uw]?(e=Buffer.from(e)).length:t[Uw]:(r=e.length,i=t.mask&&t.readOnly&&!s);let a=r;r>=65536?(o+=8,a=127):r>125&&(o+=2,a=126);const c=Buffer.allocUnsafe(i?r+o:o);return c[0]=t.fin?128|t.opcode:t.opcode,t.rsv1&&(c[0]|=64),c[1]=a,126===a?c.writeUInt16BE(r,2):127===a&&(c[2]=c[3]=0,c.writeUIntBE(r,4,6)),t.mask?(c[1]|=128,c[o-4]=n[0],c[o-3]=n[1],c[o-2]=n[2],c[o-1]=n[3],s?[c,e]:i?(Lw(e,n,c,o,r),[c]):(Lw(e,n,e,0,r),[c,e])):[c,e]}close(t,n,r,i){let o;if(void 0===t)o=Mw;else{if("number"!=typeof t||!Rw(t))throw new TypeError("First argument must be a valid error code number");if(void 0!==n&&n.length){const e=Buffer.byteLength(n);if(e>123)throw new RangeError("The message must not be greater than 123 bytes");o=Buffer.allocUnsafe(2+e),o.writeUInt16BE(t,0),"string"==typeof n?o.write(n,2):o.set(n,2)}else o=Buffer.allocUnsafe(2),o.writeUInt16BE(t,0)}const s={[Uw]:o.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};0!==this._state?this.enqueue([this.dispatch,o,!1,s,i]):this.sendFrame(e.frame(o,s),i)}ping(t,n,r){let i,o;if("string"==typeof t?(i=Buffer.byteLength(t),o=!1):jw(t)?(i=t.size,o=!1):(i=(t=Fw(t)).length,o=Fw.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");const s={[Uw]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:o,rsv1:!1};jw(t)?0!==this._state?this.enqueue([this.getBlobData,t,!1,s,r]):this.getBlobData(t,!1,s,r):0!==this._state?this.enqueue([this.dispatch,t,!1,s,r]):this.sendFrame(e.frame(t,s),r)}pong(t,n,r){let i,o;if("string"==typeof t?(i=Buffer.byteLength(t),o=!1):jw(t)?(i=t.size,o=!1):(i=(t=Fw(t)).length,o=Fw.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");const s={[Uw]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:o,rsv1:!1};jw(t)?0!==this._state?this.enqueue([this.getBlobData,t,!1,s,r]):this.getBlobData(t,!1,s,r):0!==this._state?this.enqueue([this.dispatch,t,!1,s,r]):this.sendFrame(e.frame(t,s),r)}send(e,t,n){const r=this._extensions[Aw.extensionName];let i,o,s=t.binary?2:1,a=t.compress;"string"==typeof e?(i=Buffer.byteLength(e),o=!1):jw(e)?(i=e.size,o=!1):(i=(e=Fw(e)).length,o=Fw.readOnly),this._firstFragment?(this._firstFragment=!1,a&&r&&r.params[r._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(a=i>=r._threshold),this._compress=a):(a=!1,s=0),t.fin&&(this._firstFragment=!0);const c={[Uw]:i,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:s,readOnly:o,rsv1:a};jw(e)?0!==this._state?this.enqueue([this.getBlobData,e,this._compress,c,n]):this.getBlobData(e,this._compress,c,n):0!==this._state?this.enqueue([this.dispatch,e,this._compress,c,n]):this.dispatch(e,this._compress,c,n)}getBlobData(t,n,r,i){this._bufferedBytes+=r[Uw],this._state=2,t.arrayBuffer().then((t=>{if(this._socket.destroyed){const e=new Error("The socket was closed while the blob was being read");return void process.nextTick(Yw,this,e,i)}this._bufferedBytes-=r[Uw];const o=Fw(t);n?this.dispatch(o,n,r,i):(this._state=0,this.sendFrame(e.frame(o,r),i),this.dequeue())})).catch((e=>{process.nextTick(Hw,this,e,i)}))}dispatch(t,n,r,i){if(!n)return void this.sendFrame(e.frame(t,r),i);const o=this._extensions[Aw.extensionName];this._bufferedBytes+=r[Uw],this._state=1,o.compress(t,r.fin,((t,n)=>{this._socket.destroyed?Yw(this,new Error("The socket was closed while data was being compressed"),i):(this._bufferedBytes-=r[Uw],this._state=0,r.readOnly=!1,this.sendFrame(e.frame(n,r),i),this.dequeue())}))}dequeue(){for(;0===this._state&&this._queue.length;){const e=this._queue.shift();this._bufferedBytes-=e[3][Uw],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Uw],this._queue.push(e)}sendFrame(e,t){2===e.length?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}},{isBlob:xS}=vw,{BINARY_TYPES:kS,EMPTY_BUFFER:ES,GUID:CS,kForOnEventAttribute:$S,kListener:OS,kStatusCode:NS,kWebSocket:TS,NOOP:AS}=Vb,{EventTarget:{addEventListener:MS,removeEventListener:PS}}=cS,{format:DS,parse:jS}=hS,{toBuffer:RS}=Kb,LS=3e4,FS=Symbol("kAborted"),US=[8,13],BS=["CONNECTING","OPEN","CLOSING","CLOSED"],WS=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;let GS=class e extends fS{constructor(t,n,r){super(),this._binaryType=kS[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=ES,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,null!==t?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,void 0===n?n=[]:Array.isArray(n)||("object"==typeof n&&null!==n?(r=n,n=[]):n=[n]),YS(this,t,n,r)):(this._autoPong=r.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){kS.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,n,r){const i=new _S({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),o=new IS(t,this._extensions,r.generateMask);this._receiver=i,this._sender=o,this._socket=t,i[TS]=this,o[TS]=this,t[TS]=this,i.on("conclude",ZS),i.on("drain",XS),i.on("error",QS),i.on("message",t_),i.on("ping",n_),i.on("pong",r_),o.onerror=o_,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on("close",a_),t.on("data",c_),t.on("end",l_),t.on("error",u_),this._readyState=e.OPEN,this.emit("open")}emitClose(){if(!this._socket)return this._readyState=e.CLOSED,void this.emit("close",this._closeCode,this._closeMessage);this._extensions[SS.extensionName]&&this._extensions[SS.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(t,n){if(this.readyState!==e.CLOSED)if(this.readyState!==e.CONNECTING)this.readyState!==e.CLOSING?(this._readyState=e.CLOSING,this._sender.close(t,n,!this._isServer,(e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())})),s_(this)):this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();else{const e="WebSocket was closed before the connection was established";KS(this,this._req,e)}}pause(){this.readyState!==e.CONNECTING&&this.readyState!==e.CLOSED&&(this._paused=!0,this._socket.pause())}ping(t,n,r){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");"function"==typeof t?(r=t,t=n=void 0):"function"==typeof n&&(r=n,n=void 0),"number"==typeof t&&(t=t.toString()),this.readyState===e.OPEN?(void 0===n&&(n=!this._isServer),this._sender.ping(t||ES,n,r)):JS(this,t,r)}pong(t,n,r){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");"function"==typeof t?(r=t,t=n=void 0):"function"==typeof n&&(r=n,n=void 0),"number"==typeof t&&(t=t.toString()),this.readyState===e.OPEN?(void 0===n&&(n=!this._isServer),this._sender.pong(t||ES,n,r)):JS(this,t,r)}resume(){this.readyState!==e.CONNECTING&&this.readyState!==e.CLOSED&&(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,n,r){if(this.readyState===e.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if("function"==typeof n&&(r=n,n={}),"number"==typeof t&&(t=t.toString()),this.readyState!==e.OPEN)return void JS(this,t,r);const i={binary:"string"!=typeof t,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[SS.extensionName]||(i.compress=!1),this._sender.send(t||ES,i,r)}terminate(){if(this.readyState!==e.CLOSED)if(this.readyState!==e.CONNECTING)this._socket&&(this._readyState=e.CLOSING,this._socket.destroy());else{const e="WebSocket was closed before the connection was established";KS(this,this._req,e)}}};Object.defineProperty(GS,"CONNECTING",{enumerable:!0,value:BS.indexOf("CONNECTING")}),Object.defineProperty(GS.prototype,"CONNECTING",{enumerable:!0,value:BS.indexOf("CONNECTING")}),Object.defineProperty(GS,"OPEN",{enumerable:!0,value:BS.indexOf("OPEN")}),Object.defineProperty(GS.prototype,"OPEN",{enumerable:!0,value:BS.indexOf("OPEN")}),Object.defineProperty(GS,"CLOSING",{enumerable:!0,value:BS.indexOf("CLOSING")}),Object.defineProperty(GS.prototype,"CLOSING",{enumerable:!0,value:BS.indexOf("CLOSING")}),Object.defineProperty(GS,"CLOSED",{enumerable:!0,value:BS.indexOf("CLOSED")}),Object.defineProperty(GS.prototype,"CLOSED",{enumerable:!0,value:BS.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((e=>{Object.defineProperty(GS.prototype,e,{enumerable:!0})})),["open","error","close","message"].forEach((e=>{Object.defineProperty(GS.prototype,`on${e}`,{enumerable:!0,get(){for(const t of this.listeners(e))if(t[$S])return t[OS];return null},set(t){for(const t of this.listeners(e))if(t[$S]){this.removeListener(e,t);break}"function"==typeof t&&this.addEventListener(e,t,{[$S]:!0})}})})),GS.prototype.addEventListener=MS,GS.prototype.removeEventListener=PS;var VS=GS;function YS(e,t,n,r){const i={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:US[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(e._autoPong=i.autoPong,!US.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${US.join(", ")})`);let o;if(t instanceof wS)o=t;else try{o=new wS(t)}catch(e){throw new SyntaxError(`Invalid URL: ${t}`)}"http:"===o.protocol?o.protocol="ws:":"https:"===o.protocol&&(o.protocol="wss:"),e._url=o.href;const s="wss:"===o.protocol,a="ws+unix:"===o.protocol;let c;if("ws:"===o.protocol||s||a?a&&!o.pathname?c="The URL's pathname is empty":o.hash&&(c="The URL contains a fragment identifier"):c='The URL\'s protocol must be one of "ws:", "wss:", "http:", "https", or "ws+unix:"',c){const t=new SyntaxError(c);if(0===e._redirects)throw t;return void HS(e,t)}const l=s?443:80,u=vS(16).toString("base64"),d=s?pS.request:gS.request,h=new Set;let f,p;if(i.createConnection=i.createConnection||(s?qS:zS),i.defaultPort=i.defaultPort||l,i.port=o.port||l,i.host=o.hostname.startsWith("[")?o.hostname.slice(1,-1):o.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":u,Connection:"Upgrade",Upgrade:"websocket"},i.path=o.pathname+o.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(f=new SS(!0!==i.perMessageDeflate?i.perMessageDeflate:{},!1,i.maxPayload),i.headers["Sec-WebSocket-Extensions"]=DS({[SS.extensionName]:f.offer()})),n.length){for(const e of n){if("string"!=typeof e||!WS.test(e)||h.has(e))throw new SyntaxError("An invalid or duplicated subprotocol was specified");h.add(e)}i.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(i.origin&&(i.protocolVersion<13?i.headers["Sec-WebSocket-Origin"]=i.origin:i.headers.Origin=i.origin),(o.username||o.password)&&(i.auth=`${o.username}:${o.password}`),a){const e=i.path.split(":");i.socketPath=e[0],i.path=e[1]}if(i.followRedirects){if(0===e._redirects){e._originalIpc=a,e._originalSecure=s,e._originalHostOrSocketPath=a?i.socketPath:o.host;const t=r&&r.headers;if(r={...r,headers:{}},t)for(const[e,n]of Object.entries(t))r.headers[e.toLowerCase()]=n}else if(0===e.listenerCount("redirect")){const t=a?!!e._originalIpc&&i.socketPath===e._originalHostOrSocketPath:!e._originalIpc&&o.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!s)&&(delete i.headers.authorization,delete i.headers.cookie,t||delete i.headers.host,i.auth=void 0)}i.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(i.auth).toString("base64")),p=e._req=d(i),e._redirects&&e.emit("redirect",e.url,p)}else p=e._req=d(i);i.timeout&&p.on("timeout",(()=>{KS(e,p,"Opening handshake has timed out")})),p.on("error",(t=>{null===p||p[FS]||(p=e._req=null,HS(e,t))})),p.on("response",(o=>{const s=o.headers.location,a=o.statusCode;if(s&&i.followRedirects&&a>=300&&a<400){if(++e._redirects>i.maxRedirects)return void KS(e,p,"Maximum redirects exceeded");let o;p.abort();try{o=new wS(s,t)}catch(t){const n=new SyntaxError(`Invalid URL: ${s}`);return void HS(e,n)}YS(e,o,n,r)}else e.emit("unexpected-response",p,o)||KS(e,p,`Unexpected server response: ${o.statusCode}`)})),p.on("upgrade",((t,n,r)=>{if(e.emit("upgrade",t),e.readyState!==GS.CONNECTING)return;p=e._req=null;const o=t.headers.upgrade;if(void 0===o||"websocket"!==o.toLowerCase())return void KS(e,n,"Invalid Upgrade header");const s=bS("sha1").update(u+CS).digest("base64");if(t.headers["sec-websocket-accept"]!==s)return void KS(e,n,"Invalid Sec-WebSocket-Accept header");const a=t.headers["sec-websocket-protocol"];let c;if(void 0!==a?h.size?h.has(a)||(c="Server sent an invalid subprotocol"):c="Server sent a subprotocol but none was requested":h.size&&(c="Server sent no subprotocol"),c)return void KS(e,n,c);a&&(e._protocol=a);const l=t.headers["sec-websocket-extensions"];if(void 0!==l){if(!f)return void KS(e,n,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");let r;try{r=jS(l)}catch(t){return void KS(e,n,"Invalid Sec-WebSocket-Extensions header")}const i=Object.keys(r);if(1!==i.length||i[0]!==SS.extensionName)return void KS(e,n,"Server indicated an extension that was not requested");try{f.accept(r[SS.extensionName])}catch(t){return void KS(e,n,"Invalid Sec-WebSocket-Extensions header")}e._extensions[SS.extensionName]=f}e.setSocket(n,r,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})})),i.finishRequest?i.finishRequest(p,e):p.end()}function HS(e,t){e._readyState=GS.CLOSING,e._errorEmitted=!0,e.emit("error",t),e.emitClose()}function zS(e){return e.path=e.socketPath,mS.connect(e)}function qS(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=mS.isIP(e.host)?"":e.host),yS.connect(e)}function KS(e,t,n){e._readyState=GS.CLOSING;const r=new Error(n);Error.captureStackTrace(r,KS),t.setHeader?(t[FS]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(HS,e,r)):(t.destroy(r),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function JS(e,t,n){if(t){const n=xS(t)?t.size:RS(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){const t=new Error(`WebSocket is not open: readyState ${e.readyState} (${BS[e.readyState]})`);process.nextTick(n,t)}}function ZS(e,t){const n=this[TS];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,void 0!==n._socket[TS]&&(n._socket.removeListener("data",c_),process.nextTick(i_,n._socket),1005===e?n.close():n.close(e,t))}function XS(){const e=this[TS];e.isPaused||e._socket.resume()}function QS(e){const t=this[TS];void 0!==t._socket[TS]&&(t._socket.removeListener("data",c_),process.nextTick(i_,t._socket),t.close(e[NS])),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e))}function e_(){this[TS].emitClose()}function t_(e,t){this[TS].emit("message",e,t)}function n_(e){const t=this[TS];t._autoPong&&t.pong(e,!this._isServer,AS),t.emit("ping",e)}function r_(e){this[TS].emit("pong",e)}function i_(e){e.resume()}function o_(e){const t=this[TS];t.readyState!==GS.CLOSED&&(t.readyState===GS.OPEN&&(t._readyState=GS.CLOSING,s_(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e)))}function s_(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),LS)}function a_(){const e=this[TS];let t;this.removeListener("close",a_),this.removeListener("data",c_),this.removeListener("end",l_),e._readyState=GS.CLOSING,this._readableState.endEmitted||e._closeFrameReceived||e._receiver._writableState.errorEmitted||null===(t=e._socket.read())||e._receiver.write(t),e._receiver.end(),this[TS]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",e_),e._receiver.on("finish",e_))}function c_(e){this[TS]._receiver.write(e)||this.pause()}function l_(){const e=this[TS];e._readyState=GS.CLOSING,e._receiver.end(),this.end()}function u_(){const e=this[TS];this.removeListener("error",u_),this.on("error",AS),e&&(e._readyState=GS.CLOSING,this.destroy())}const{tokenChars:d_}=vw;var h_={parse:function(e){const t=new Set;let n=-1,r=-1,i=0;for(;i<e.length;i++){const o=e.charCodeAt(i);if(-1===r&&1===d_[o])-1===n&&(n=i);else if(0===i||32!==o&&9!==o){if(44!==o)throw new SyntaxError(`Unexpected character at index ${i}`);{if(-1===n)throw new SyntaxError(`Unexpected character at index ${i}`);-1===r&&(r=i);const o=e.slice(n,r);if(t.has(o))throw new SyntaxError(`The "${o}" subprotocol is duplicated`);t.add(o),n=r=-1}}else-1===r&&-1!==n&&(r=i)}if(-1===n||-1!==r)throw new SyntaxError("Unexpected end of input");const o=e.slice(n,i);if(t.has(o))throw new SyntaxError(`The "${o}" subprotocol is duplicated`);return t.add(o),t}};const f_=D,p_=L,{createHash:g_}=l,m_=hS,y_=uw,v_=h_,b_=VS,{GUID:w_,kWebSocket:S_}=Vb,__=/^[+/0-9A-Za-z]{22}==$/;function I_(e){e._state=2,e.emit("close")}function x_(){this.destroy()}function k_(e,t,n,r){n=n||p_.STATUS_CODES[t],r={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(n),...r},e.once("finish",e.destroy),e.end(`HTTP/1.1 ${t} ${p_.STATUS_CODES[t]}\r\n`+Object.keys(r).map((e=>`${e}: ${r[e]}`)).join("\r\n")+"\r\n\r\n"+n)}function E_(e,t,n,r,i){if(e.listenerCount("wsClientError")){const r=new Error(i);Error.captureStackTrace(r,E_),e.emit("wsClientError",r,n,t)}else k_(n,r,i)}var C_=ad(class extends f_{constructor(e,t){if(super(),null==(e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:b_,...e}).port&&!e.server&&!e.noServer||null!=e.port&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(null!=e.port?(this._server=p_.createServer(((e,t)=>{const n=p_.STATUS_CODES[426];t.writeHead(426,{"Content-Length":n.length,"Content-Type":"text/plain"}),t.end(n)})),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){const e=this.emit.bind(this,"connection");this._removeListeners=function(e,t){for(const n of Object.keys(t))e.on(n,t[n]);return function(){for(const n of Object.keys(t))e.removeListener(n,t[n])}}(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(t,n,r)=>{this.handleUpgrade(t,n,r,e)}})}!0===e.perMessageDeflate&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(2===this._state)return e&&this.once("close",(()=>{e(new Error("The server is not running"))})),void process.nextTick(I_,this);if(e&&this.once("close",e),1!==this._state)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(I_,this);else{const e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close((()=>{I_(this)}))}}shouldHandle(e){if(this.options.path){const t=e.url.indexOf("?");if((-1!==t?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,r){t.on("error",x_);const i=e.headers["sec-websocket-key"],o=e.headers.upgrade,s=+e.headers["sec-websocket-version"];if("GET"!==e.method)return void E_(this,e,t,405,"Invalid HTTP method");if(void 0===o||"websocket"!==o.toLowerCase())return void E_(this,e,t,400,"Invalid Upgrade header");if(void 0===i||!__.test(i))return void E_(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");if(8!==s&&13!==s)return void E_(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header");if(!this.shouldHandle(e))return void k_(t,400);const a=e.headers["sec-websocket-protocol"];let c=new Set;if(void 0!==a)try{c=v_.parse(a)}catch(n){return void E_(this,e,t,400,"Invalid Sec-WebSocket-Protocol header")}const l=e.headers["sec-websocket-extensions"],u={};if(this.options.perMessageDeflate&&void 0!==l){const r=new y_(this.options.perMessageDeflate,!0,this.options.maxPayload);try{const e=m_.parse(l);e[y_.extensionName]&&(r.accept(e[y_.extensionName]),u[y_.extensionName]=r)}catch(n){return void E_(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header")}}if(this.options.verifyClient){const o={origin:e.headers[8===s?"sec-websocket-origin":"origin"],secure:!(!e.socket.authorized&&!e.socket.encrypted),req:e};if(2===this.options.verifyClient.length)return void this.options.verifyClient(o,((o,s,a,l)=>{if(!o)return k_(t,s||401,a,l);this.completeUpgrade(u,i,c,e,t,n,r)}));if(!this.options.verifyClient(o))return k_(t,401)}this.completeUpgrade(u,i,c,e,t,n,r)}completeUpgrade(e,t,n,r,i,o,s){if(!i.readable||!i.writable)return i.destroy();if(i[S_])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return k_(i,503);const a=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${g_("sha1").update(t+w_).digest("base64")}`],c=new this.options.WebSocket(null,void 0,this.options);if(n.size){const e=this.options.handleProtocols?this.options.handleProtocols(n,r):n.values().next().value;e&&(a.push(`Sec-WebSocket-Protocol: ${e}`),c._protocol=e)}if(e[y_.extensionName]){const t=e[y_.extensionName].params,n=m_.format({[y_.extensionName]:[t]});a.push(`Sec-WebSocket-Extensions: ${n}`),c._extensions=e}this.emit("headers",a,r),i.write(a.concat("\r\n").join("\r\n")),i.removeListener("error",x_),c.setSocket(i,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(c),c.on("close",(()=>{this.clients.delete(c),this._shouldEmitClose&&!this.clients.size&&process.nextTick(I_,this)}))),s(c,r)}});const $_=xd("websocketServer"),O_={},N_=Eb();let T_,A_,M_,P_,D_;const j_=["https://app.kemu.io","https://dev.kemu.io","https://stage.kemu.io","https://local.kemu.io:3003"],R_=e=>{const t=O_[e];t&&t.socket.close()};var L_=e=>{D_=new C_({port:e,maxPayload:1048576e3,verifyClient:(e,t)=>{const n=e.req.headers.origin;n&&j_.includes(n)?t(!0):t(!1,401,"Origin not allowed")}}),D_.on("connection",(e=>{const t=By();$_(`New client connected. Registered as "${t}"`),e.id=t,O_[t]={socket:e,activeMessage:null},T_&&T_(t),e.on("message",(t=>{if(t instanceof Buffer){const n=O_[e.id];N_(t,n.activeMessage,(e=>n.activeMessage=e),(t=>{if(!t.complete)return;const r=t=>{e.send(t),$_(`Writing ${t.byteLength} bytes to socket [${n.socket.id}]: ${t.toString()}`)},i=()=>{R_(n.socket.id)};if(t.command)return $_(`Received command from client [${n.socket.id}]: ${t.command}`),void(M_&&M_(n.socket.id,t.command,r,i));t.klMessage&&P_&&P_({send:r,terminateWebsocket:i,websocketId:n.socket.id,transmission:{sourceServiceId:t.sourceServiceId??-1,targetServiceId:t.targetServiceId??-1,rawMessage:t.rawMessage},json:t.klMessage.json})}))}})),e.on("close",(()=>{$_(`Client disconnected: ${e.id}`),A_&&A_(e.id),delete O_[e.id]})),e.on("error",(()=>{$_(`Error on client connection: ${e.id}`)}))})),console.log(`WebSocket server is running on port ${e}`)},F_=e=>{T_=e},U_=e=>{A_=e},B_=e=>{M_=e},W_=(e,t)=>{const n=O_[e];if(!n)return $_(`Cannot send message to unknown client [${e}]`),!1;if(t.length>=ib)return $_("Message is too long to be a command. Use sendMessage instead."),!1;const r=bb.encodeCommand(t);return n.socket.send(r),!0},G_=e=>P_=e,V_=R_;const Y_=xd("stopService"),H_=async e=>{const t=e.args[0];if(!t)return e.reply({error:"No service name provided"});const n=xv.getAllServiceVersions(t);Y_(`Stopping ${n.length} services with name: ${t}`);for(const e of n)await xv.stopService({serviceName:e.info.name,version:e.info.version});const r=n.map((e=>`${e.info.name}@${e.info.version}`));e.reply({success:[r]})},z_=xd("removeService"),q_=async e=>{const t=e.args[0],n=e.args[1];if(!t)return e.reply({error:"No service name provided"});let r=xv.getAllServiceVersions(t);n&&(r=r.filter((e=>e.info.version===n))),z_(`Removing ${r.length} service(s) with name: ${t}`);for(const e of r)await xv.uninstallService(e.info.name,e.info.version);const i=r.map((e=>`${e.info.name}@${e.info.version}`));e.reply({success:[i]})},K_=xd("launchService"),J_=async e=>{const t=e.args[0],n=e.args[1];if(!t)return e.reply({error:"No service name provided"});if(!n)return e.reply({error:"No service version provided"});const r=`${t}@${n}/dist`;try{const i=ev();K_(`Loading service ${t}@${n} from ${i}`);const{errorMsg:o,service:s,errorCode:a}=await xv.loadAndLaunch(i,r,!1);if(o||"started"!==s?.status)return e.reply({error:`Failed to launch service ${t}@${n}: ${o||"error-not-provided"}`,errCode:a});const c=Date.now(),l=3e4,u=async()=>{const r=s.status;return"running"===r?(K_(`Service ${t}@${n} loaded and started`),e.reply({success:[]})):(K_(`Service ${t}@${n} not yet started, status: ${r}`),"stopped"===r||"error"===r?e.reply({error:`Error launching service: "${s.errorMsg||"failed to initiate"}"`}):Date.now()-c>l?e.reply({error:"Timeout waiting for service to start"}):(K_("Retrying in 1 second..."),void setTimeout(u,1e3)))};u()}catch(r){return K_(`Error loading service ${t}@${n}: ${r?.message||r}`),e.reply({error:r?.message||"There was an error loading the service"})}},Z_=xd("getMatchingServices"),X_=async e=>{const t=e.args[0],n=[],r=[];Z_(`Checking for matching services: ${t.map((e=>e.name)).join(", ")}`);for(const{name:e,version:i}of t){const t=xv.getMatchingService(e,i);t?n.push({name:e,version:i,installationPath:xv.getServiceRootDirectory(t)}):r.push({name:e,version:i})}Z_(`Found ${n.length} available services and ${r.length} missing services.`),e.reply({success:[{available:n,missing:r}]})},Q_=xd("getSecretsValues");let eI;var tI=async e=>{const t=e.args[0].services;if(!eI)throw new Error("getSecretValuesFn is not set. Please call setGetSecretValuesFunction before using this function.");Q_(`Checking for secrets values for services: ${t.map((e=>`${e.name}@${e.version}`)).join(", ")}`);const n=[];for(const e of t){const t=e.secrets,r=await eI({name:e.name,version:e.version,requiredSecrets:t.reduce(((e,t)=>(e[t]={optional:!1,description:""},e)),{})});n.push({name:e.name,version:e.version,secrets:t.map((e=>({name:e,value:r[e]})))})}const r=[{services:n}];e.reply({success:r})},nI=e=>{eI=e};const rI=xd("getMappedSecrets");let iI;var oI=async e=>{const t=e.args[0].services;rI(`Getting mapped secrets for services: ${t.map((e=>`${e.name}@${e.version}`)).join(", ")}`);const n=await iI(t),r=[{services:t.map((e=>({name:e.name,version:e.version,secrets:n[e.name]||[]})))}];e.reply({success:r})};const sI=xd("getServiceContents"),aI=({reply:e,args:t})=>{const[n]=t;sI(`Received GetServiceContents request for service ${n.serviceName} v${n.version}`);const r=xv.getMatchingService(n.serviceName,n.version);if(r)return e({success:[{serviceName:r.info.name,serviceVersion:r.info.version,uiContent:r.info.widgetUIContents,uiContentsChecksum:r.info.uiContentChecksum}]});sI(`Service ${n.serviceName} v${n.version} not found`),e({error:`Service ${n.serviceName} v${n.version} not found`})};let cI={globalApiKey:void 0,environment:"production"};const lI=()=>({...cI}),uI=xd("apis"),dI=()=>{const e=lI();if(!e.serviceUrl)throw new Error("Unknown server URL. Please call `edgeConfig.setEdgeConfig` before using the APIs.");return e.serviceUrl},hI=async(e,t,n={})=>{try{const r=await fetch(e,{method:"POST",body:JSON.stringify(t),headers:{...n}});return r.ok?{data:await r.json(),statusCode:r.status,success:!0}:{statusCode:r.status,error:await r.text(),success:!1}}catch(e){return{statusCode:500,error:e instanceof Error?e.message:"Internal server error",success:!1}}},fI={},pI=async e=>{const t=(e=>{const t=fI[e],n=Date.now()-(t?.lastCheckedAt.getTime()??0);return t&&n<3e5?t.features:null})(e);if(t)return{valid:!0,features:t,error:null};const{valid:n,features:r,error:i}=await(async e=>{const{data:t,error:n}=await hI(`${dI()}/v1/organization/validate/apiKey`,{apiKey:e},{"Content-Type":"application/json"});return n?(uI(`Error validating Kemu API key: ${n}`),{valid:!1,features:{},error:n}):t?.features?{valid:!0,features:t.features,error:null}:{valid:!1,features:{},error:"No features returned from the server"}})(e);return n&&(fI[e]={features:r,lastCheckedAt:new Date}),{valid:n,features:r,error:i}};function gI(e){return"number"==typeof e||!!/^0x[0-9a-f]+$/i.test(e)||/^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(e)}function mI(e,t){return"constructor"===t&&"function"==typeof e[t]||"__proto__"===t}var yI=ad((function(e,t){t||(t={});var n={bools:{},strings:{},unknownFn:null};"function"==typeof t.unknown&&(n.unknownFn=t.unknown),"boolean"==typeof t.boolean&&t.boolean?n.allBools=!0:[].concat(t.boolean).filter(Boolean).forEach((function(e){n.bools[e]=!0}));var r={};function i(e){return r[e].some((function(e){return n.bools[e]}))}Object.keys(t.alias||{}).forEach((function(e){r[e]=[].concat(t.alias[e]),r[e].forEach((function(t){r[t]=[e].concat(r[e].filter((function(e){return t!==e})))}))})),[].concat(t.string).filter(Boolean).forEach((function(e){n.strings[e]=!0,r[e]&&[].concat(r[e]).forEach((function(e){n.strings[e]=!0}))}));var o=t.default||{},s={_:[]};function a(e,t,r){for(var i=e,o=0;o<t.length-1;o++){var s=t[o];if(mI(i,s))return;void 0===i[s]&&(i[s]={}),i[s]!==Object.prototype&&i[s]!==Number.prototype&&i[s]!==String.prototype||(i[s]={}),i[s]===Array.prototype&&(i[s]=[]),i=i[s]}var a=t[t.length-1];mI(i,a)||(i!==Object.prototype&&i!==Number.prototype&&i!==String.prototype||(i={}),i===Array.prototype&&(i=[]),void 0===i[a]||n.bools[a]||"boolean"==typeof i[a]?i[a]=r:Array.isArray(i[a])?i[a].push(r):i[a]=[i[a],r])}function c(e,t,i){if(!i||!n.unknownFn||function(e,t){return n.allBools&&/^--[^=]+$/.test(t)||n.strings[e]||n.bools[e]||r[e]}(e,i)||!1!==n.unknownFn(i)){var o=!n.strings[e]&&gI(t)?Number(t):t;a(s,e.split("."),o),(r[e]||[]).forEach((function(e){a(s,e.split("."),o)}))}}Object.keys(n.bools).forEach((function(e){c(e,void 0!==o[e]&&o[e])}));var l=[];-1!==e.indexOf("--")&&(l=e.slice(e.indexOf("--")+1),e=e.slice(0,e.indexOf("--")));for(var u=0;u<e.length;u++){var d,h,f=e[u];if(/^--.+=/.test(f)){var p=f.match(/^--([^=]+)=([\s\S]*)$/);d=p[1];var g=p[2];n.bools[d]&&(g="false"!==g),c(d,g,f)}else if(/^--no-.+/.test(f))c(d=f.match(/^--no-(.+)/)[1],!1,f);else if(/^--.+/.test(f))d=f.match(/^--(.+)/)[1],void 0===(h=e[u+1])||/^(-|--)[^-]/.test(h)||n.bools[d]||n.allBools||r[d]&&i(d)?/^(true|false)$/.test(h)?(c(d,"true"===h,f),u+=1):c(d,!n.strings[d]||"",f):(c(d,h,f),u+=1);else if(/^-[^-]+/.test(f)){for(var m=f.slice(1,-1).split(""),y=!1,v=0;v<m.length;v++)if("-"!==(h=f.slice(v+2))){if(/[A-Za-z]/.test(m[v])&&"="===h[0]){c(m[v],h.slice(1),f),y=!0;break}if(/[A-Za-z]/.test(m[v])&&/-?\d+(\.\d*)?(e-?\d+)?$/.test(h)){c(m[v],h,f),y=!0;break}if(m[v+1]&&m[v+1].match(/\W/)){c(m[v],f.slice(v+2),f),y=!0;break}c(m[v],!n.strings[m[v]]||"",f)}else c(m[v],h,f);d=f.slice(-1)[0],y||"-"===d||(!e[u+1]||/^(-|--)[^-]/.test(e[u+1])||n.bools[d]||r[d]&&i(d)?e[u+1]&&/^(true|false)$/.test(e[u+1])?(c(d,"true"===e[u+1],f),u+=1):c(d,!n.strings[d]||"",f):(c(d,e[u+1],f),u+=1))}else if(n.unknownFn&&!1===n.unknownFn(f)||s._.push(n.strings._||!gI(f)?f:Number(f)),t.stopEarly){s._.push.apply(s._,e.slice(u+1));break}}return Object.keys(o).forEach((function(e){var t,n,i;t=s,n=e.split("."),i=t,n.slice(0,-1).forEach((function(e){i=i[e]||{}})),n[n.length-1]in i||(a(s,e.split("."),o[e]),(r[e]||[]).forEach((function(t){a(s,t.split("."),o[e])})))})),t["--"]?s["--"]=l.slice():l.forEach((function(e){s._.push(e)})),s}));gb("ipcClient"),gb("kemuWidgetService"),yI(process.argv.slice(2));const vI=xd("activeClients");let bI,wI={},SI={};const _I=(e,t)=>`${e}_${t}`,II=e=>wI[e]||null,xI=(e,t)=>{const n=_I(e,t);return SI[n]||[]},kI=()=>{for(const e in wI){const t=wI[e];if(t?.transport===Wu.WS){const e=bb.encodeCommand(Fu.ServicesListChanged);t.send(e)}}},EI=async e=>{const t=[],{serviceSessionId:n,transport:r,send:i,terminateFn:o,extraInfo:s,isDevClient:a}=e,c=e=>{console.warn(e),o&&o()};if(r===Wu.WS){if(!s.user?.wsApiKey)return void c(`Attempted to register a WebSocket client without an API key. SessionId: ${n}`);const{valid:e,error:t}=await pI(s.user?.wsApiKey);if(!e&&!t)return void c(`Attempted to register a WebSocket client with an invalid API key. SessionId: ${n}`);t&&(s.user?.wsApiKey&&iv.captureError({error:new Error(t),message:`Error validating api key "${s.user?.wsApiKey}"`,data:s}),vI(`Unable to validate API Key, usage will be limited. SessionId: ${n}`))}wI[n]={serviceSessionId:n,transport:r,isDevClient:!!a,broadcastSubscriptions:t,send:i,extraInfo:s,terminate:()=>{o&&o()},addSubscription:e=>{if(!t.some((t=>t.targetService.serviceName===e.serviceName&&t.targetService.version===e.version))){t.push({targetService:e});const r=_I(e.serviceName,e.version);return SI[r]=SI[r]||[],SI[r].some((e=>e.serviceId===n))||SI[r].push({sendFn:i,serviceId:n}),!0}return!1},removeSubscription:e=>{const r=t.findIndex((t=>t.targetService.serviceName===e.serviceName));if(-1!==r){t.splice(r,1);const i=_I(e.serviceName,e.version),o=SI[i]?.findIndex((e=>e.serviceId===n));if(-1!==o&&(SI[i]?.splice(o,1),!SI[i]?.length)){const t=xv.getMatchingService(e.serviceName,e.version);if(t?.info.eventEmitter&&"running"===t.status){const e=II(t.info.sessionId);e?.extraInfo.ipcSocketId&&Db(e?.extraInfo.ipcSocketId,Fu.BroadcastEnd)}}}},removeAllSubscriptions:()=>{for(const e of t){const t=_I(e.targetService.serviceName,e.targetService.version),r=SI[t]?.findIndex((e=>e.serviceId===n));-1!==r&&SI[t]?.splice(r,1)}t.length=0}},r===Wu.IPC&&(kI(),CI(n))},CI=e=>{const t=xv.getServiceBySessionId(e);if(t?.info.eventEmitter&&xI(t.info.name,t.info.version).length){const t=II(e);t?.extraInfo.ipcSocketId&&Db(t?.extraInfo.ipcSocketId,Fu.BroadcastStart)}},$I=e=>{const t=wI[e];var n;t?.transport===Wu.IPC?kI():(t?.removeAllSubscriptions(),(()=>{const e=Object.values(wI);for(const t of e)if(t.transport===Wu.IPC){const e=t.extraInfo.ipcSocketId,n=xv.getServiceBySessionId(t.serviceSessionId);n?.info.eventEmitter&&(xI(n.info.name,n.info.version).length||e&&Db(e,Fu.BroadcastEnd))}})(),t?.extraInfo.user?.wsApiKey&&(n=t.extraInfo.user.wsApiKey,delete fI[n]),(e=>{const t=wI[e];if(t?.transport===Wu.WS&&t.extraInfo.recipe){const n=[{recipe:t.extraInfo.recipe}];vI(`Notifying IPC clients that a Kemu Compose client [${t.extraInfo.recipe.name} (${t.extraInfo.recipe.poolId})] has disconnected. ServiceSessionId: ${e}`);for(const e in wI){const t=wI[e];t?.transport===Wu.IPC&&bI.execute(Uu.KemuComposerDisconnected,n,t.send,0,t.serviceSessionId,{async:!0}).catch((t=>{vI(`Error notifying IPC client [${e}] that a Kemu Compose client has disconnected: ${t?.message||t}`)}))}}})(e)),delete wI[e]},OI=xd("ipc:handleIpcClientCommand"),NI=(e,t,n)=>{const r=((e,t)=>{if(e.startsWith(Fu.AcknowledgeResponse)){const n=e.split(":"),r=parseInt(n[1]),i=parseInt(n[2]);return t&&t(r,isNaN(i)?void 0:i),!0}return!1})(t,((e,t)=>{if(!e)return void OI(`Ignoring ACK response from IPC service ${e} with no service id`);OI(`Received ACK from IPC service ${e}. Marking as running.`);let r=e;t&&e&&e!==t&&(jb(e,t),r=t);let i=!1;t&&(i=xv.setServiceStatus(t,"running")),i?EI({serviceSessionId:t||e,transport:Wu.IPC,send:n,extraInfo:{ipcSocketId:t}}):Db(r,Fu.SendManifest)}));!r&&OI(`Received unknown command [${t}] from service ${e}`)};let TI={};Y.platform();const AI=async e=>{const t=e.args[0];if(TI.chooseDirectory)try{const n=await TI.chooseDirectory(t);return e.reply({success:[String(n).trim()]})}catch(t){return console.error(t),e.reply({error:t instanceof Error?t.message:"Unknown error"})}return e.reply({error:"This hub does not support showing file dialogs",errCode:"GUI_NOT_SUPPORTED"})},MI=async e=>{const t=e.args[0];if(TI.chooseFile)try{const n=await TI.chooseFile(t);return e.reply({success:[String(n).trim()]})}catch(t){return console.error(t),e.reply({error:t instanceof Error?t.message:"Unknown error"})}return e.reply({error:"This hub does not support showing file dialogs",errCode:"GUI_NOT_SUPPORTED"})};var PI={},DI={},jI={};function RI(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`positive integer expected, not ${e}`)}function LI(e){if("boolean"!=typeof e)throw new Error(`boolean expected, not ${e}`)}function FI(e){return e instanceof Uint8Array||null!=e&&"object"==typeof e&&"Uint8Array"===e.constructor.name}function UI(e,...t){if(!FI(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error(`Uint8Array expected of length ${t}, not of length=${e.length}`)}function BI(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.wrapConstructor");RI(e.outputLen),RI(e.blockLen)}function WI(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function GI(e,t){UI(e);const n=t.outputLen;if(e.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}Object.defineProperty(jI,"__esModule",{value:!0}),jI.output=jI.exists=jI.hash=jI.bytes=jI.bool=jI.number=jI.isBytes=void 0,jI.number=RI,jI.bool=LI,jI.isBytes=FI,jI.bytes=UI,jI.hash=BI,jI.exists=WI,jI.output=GI;const VI={number:RI,bool:LI,bytes:UI,hash:BI,exists:WI,output:GI};jI.default=VI;var YI={};Object.defineProperty(YI,"__esModule",{value:!0}),YI.add5L=YI.add5H=YI.add4H=YI.add4L=YI.add3H=YI.add3L=YI.add=YI.rotlBL=YI.rotlBH=YI.rotlSL=YI.rotlSH=YI.rotr32L=YI.rotr32H=YI.rotrBL=YI.rotrBH=YI.rotrSL=YI.rotrSH=YI.shrSL=YI.shrSH=YI.toBig=YI.split=YI.fromBig=void 0;const HI=BigInt(2**32-1),zI=BigInt(32);function qI(e,t=!1){return t?{h:Number(e&HI),l:Number(e>>zI&HI)}:{h:0|Number(e>>zI&HI),l:0|Number(e&HI)}}function KI(e,t=!1){let n=new Uint32Array(e.length),r=new Uint32Array(e.length);for(let i=0;i<e.length;i++){const{h:o,l:s}=qI(e[i],t);[n[i],r[i]]=[o,s]}return[n,r]}YI.fromBig=qI,YI.split=KI;const JI=(e,t)=>BigInt(e>>>0)<<zI|BigInt(t>>>0);YI.toBig=JI;const ZI=(e,t,n)=>e>>>n;YI.shrSH=ZI;const XI=(e,t,n)=>e<<32-n|t>>>n;YI.shrSL=XI;const QI=(e,t,n)=>e>>>n|t<<32-n;YI.rotrSH=QI;const ex=(e,t,n)=>e<<32-n|t>>>n;YI.rotrSL=ex;const tx=(e,t,n)=>e<<64-n|t>>>n-32;YI.rotrBH=tx;const nx=(e,t,n)=>e>>>n-32|t<<64-n;YI.rotrBL=nx;const rx=(e,t)=>t;YI.rotr32H=rx;const ix=e=>e;YI.rotr32L=ix;const ox=(e,t,n)=>e<<n|t>>>32-n;YI.rotlSH=ox;const sx=(e,t,n)=>t<<n|e>>>32-n;YI.rotlSL=sx;const ax=(e,t,n)=>t<<n-32|e>>>64-n;YI.rotlBH=ax;const cx=(e,t,n)=>e<<n-32|t>>>64-n;function lx(e,t,n,r){const i=(t>>>0)+(r>>>0);return{h:e+n+(i/2**32|0)|0,l:0|i}}YI.rotlBL=cx,YI.add=lx;const ux=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0);YI.add3L=ux;const dx=(e,t,n,r)=>t+n+r+(e/2**32|0)|0;YI.add3H=dx;const hx=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0);YI.add4L=hx;const fx=(e,t,n,r,i)=>t+n+r+i+(e/2**32|0)|0;YI.add4H=fx;const px=(e,t,n,r,i)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(i>>>0);YI.add5L=px;const gx=(e,t,n,r,i,o)=>t+n+r+i+o+(e/2**32|0)|0;YI.add5H=gx;const mx={fromBig:qI,split:KI,toBig:JI,shrSH:ZI,shrSL:XI,rotrSH:QI,rotrSL:ex,rotrBH:tx,rotrBL:nx,rotr32H:rx,rotr32L:ix,rotlSH:ox,rotlSL:sx,rotlBH:ax,rotlBL:cx,add:lx,add3L:ux,add3H:dx,add4L:hx,add4H:fx,add5H:gx,add5L:px};YI.default=mx;var yx={},vx={};Object.defineProperty(vx,"__esModule",{value:!0}),vx.crypto=void 0,vx.crypto="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0,function(e){
10
+ var e=x,t=b,n=wy(),r=j,o=T,s={};yy=s;var a=["daily","test","m","h","custom"],c="YYYYMMDDHHmm";function l(t,n){if(t.hash===r.createHash(t.hashType).update(t.name+"LOG_FILE"+t.date).digest("hex"))try{e.existsSync(t.name)&&e.unlinkSync(t.name)}catch(e){n&&console.error(new Date,"[FileStreamRotator] Could not remove old log file: ",t.name)}}s.getFrequency=function(e){var t=e.toLowerCase().match(/^(\d+)([mh])$/);if(t)return function(e,t){if("number"==typeof t){switch(e){case"m":if(t<0||t>60)return!1;break;case"h":if(t<0||t>24)return!1}return{type:e,digit:t}}}(t[2],parseInt(t[1]));var n=function(e){switch(e){case"custom":case"daily":return{type:e,digit:void 0};case"test":return{type:e,digit:0}}return!1}(e);return n||!1},s.parseFileSize=function(e){if(e&&"string"==typeof e){var t=e.toLowerCase().match(/^((?:0\.)?\d+)([kmg])$/);if(t)switch(t[2]){case"k":return 1024*t[1];case"m":return 1024*t[1]*1024;case"g":return 1024*t[1]*1024*1024}}return null},s.getDate=function(e,t,r){t=t||c;let i=r?n.utc():n().local();if(e&&-1!==a.indexOf(e.type))switch(e.type){case"m":var o=Math.floor(i.minutes()/e.digit)*e.digit;return i.minutes(o).format(t);case"h":var s=Math.floor(i.hour()/e.digit)*e.digit;return i.hour(s).format(t);case"daily":case"custom":case"test":return i.format(t)}return i.format(t)},s.setAuditLog=function(n,r,i){var o=null;if(n){var s=n.toString().substr(-1),a=n.toString().match(/^(\d+)/);if(Number(a[1])>0){var c=t.dirname(i.replace(/%DATE%.+/,"_filename"));try{if(r){var l=t.resolve(r);o=JSON.parse(e.readFileSync(l,{encoding:"utf-8"}))}else l=t.resolve(c+"/.audit.json"),o=JSON.parse(e.readFileSync(l,{encoding:"utf-8"}))}catch(n){if("ENOENT"!==n.code)return null;o={keep:{days:!1,amount:Number(a[1])},auditLog:r||c+"/.audit.json",files:[]}}o.keep={days:"d"===s,amount:Number(a[1])}}}return o},s.writeAuditLog=function(t,n){try{u(t.auditLog),e.writeFileSync(t.auditLog,JSON.stringify(t,null,4))}catch(e){n&&console.error(new Date,"[FileStreamRotator] Failed to store log audit at:",t.auditLog,"Error:",e)}},s.addLogToAudit=function(e,t,i,o){if(t&&t.files){if(-1!==t.files.findIndex((function(t){return t.name===e})))return t;var a=Date.now();if(t.files.push({date:a,name:e,hash:r.createHash(t.hashType).update(e+"LOG_FILE"+a).digest("hex")}),t.keep.days){var c=n().subtract(t.keep.amount,"days").valueOf(),u=t.files.filter((function(e){return e.date>c||(e.hashType=t.hashType,l(e,o),i.emit("logRemoved",e),!1)}));t.files=u}else{var d=t.files.splice(-t.keep.amount);t.files.length>0&&t.files.filter((function(e){return e.hashType=t.hashType,l(e,o),i.emit("logRemoved",e),!1})),t.files=d}s.writeAuditLog(t,o)}return t},s.getStream=function(r){var l=null,h=null,f=this;if(!r.filename)return console.error(new Date,"[FileStreamRotator] No filename supplied. Defaulting to STDOUT"),process.stdout;r.frequency&&(l=f.getFrequency(r.frequency));let p=f.setAuditLog(r.max_logs,r.audit_file,r.filename);null!=p&&(p.hashType=void 0!==r.audit_hash_type?r.audit_hash_type:"md5"),f.verbose=void 0===r.verbose||r.verbose;var g=null,m=0,y=0;r.size&&(g=s.parseFileSize(r.size));var v=r.date_format||c;l&&"daily"==l.type&&(r.date_format||(v="YYYY-MM-DD"),n().format(v)==n().endOf("day").format(v)&&n().format(v)!=n().add(1,"day").format(v)||(f.verbose&&console.log(new Date,"[FileStreamRotator] Changing type to custom as date format changes more often than once a day or not every day"),l.type="custom")),l&&(h=r.frequency?f.getDate(l,v,r.utc):""),r.create_symlink=r.create_symlink||!1,r.extension=r.extension||"";var b=r.filename,w=null,S=b+(h?"."+h:"");if(b.match(/%DATE%/)&&(S=b.replace(/%DATE%/g,h||f.getDate(null,v,r.utc))),g){var _=null,I=S;if(p&&p.files&&p.files instanceof Array&&p.files.length>0){var x=p.files[p.files.length-1].name;if(x.match(I)){var k=x.match(I+"\\.(\\d+)");k&&(I=x,m=k[1])}}for(0==m&&I==S&&(I+=r.extension);e.existsSync(I);)_=I,m++,I=S+"."+m+r.extension;if(_){var E=e.statSync(_);E.size<g&&(I=_,m--,y=E.size)}S=I}else S+=r.extension;f.verbose&&console.log(new Date,"[FileStreamRotator] Logging to: ",S),u(S);var C=r.file_options||{flags:"a"},$=e.createWriteStream(S,C);if(h&&l&&a.indexOf(l.type)>-1||g>0){f.verbose&&console.log(new Date,"[FileStreamRotator] Rotating file: ",l?l.type:"",g?"size: "+g:"");var O,N=new o;return N.auditLog=p,N.end=function(){$.end.apply($,arguments)},d($,N),N.on("close",(function(){O&&O.close()})),N.on("new",(function(n){N.auditLog=f.addLogToAudit(n,N.auditLog,N,f.verbose),r.create_symlink&&function(n,r,i){let o=r||"current.log",s=t.dirname(n),a=t.basename(n),c=s+"/"+o;try{e.lstatSync(c).isSymbolicLink()&&(e.unlinkSync(c),e.symlinkSync(a,c))}catch(n){if(n&&"ENOENT"==n.code)try{e.symlinkSync(a,c)}catch(n){i&&console.error(new Date,"[FileStreamRotator] Could not create symlink file: ",c," -> ",a)}}}(n,r.symlink_name,f.verbose),r.watch_log&&N.emit("addWatcher",n)})),N.on("addWatcher",(function(t){O&&O.close(),r.watch_log&&(O=function(t,n){if(!t)return null;try{return e.lstatSync(t),e.watch(t,(function(n){if("rename"==n)try{e.lstatSync(t)}catch(e){!function(e,t){N.emit("createLog",t)}(0,t)}}))}catch(e){n&&console.log(new Date,"[FileStreamRotator] Could not add watcher for "+t)}}(t,f.verbose))})),N.on("createLog",(function(t){try{e.lstatSync(t)}catch(n){$&&"function"==$.end&&$.end(),$=e.createWriteStream(t,C),N.emit("new",t),d($,N)}})),N.write=function(t,n){var o=l?this.getDate(l,v,r.utc):h;if(o!=h||g&&y>g){var s=b+(h&&l?"."+o:"");b.match(/%DATE%/)&&h&&(s=b.replace(/%DATE%/g,o)),g&&y>g?s+="."+ ++m+r.extension:(m=0,s+=r.extension),y=0,f.verbose&&console.log(new Date,i.format("[FileStreamRotator] Changing logs from %s to %s",S,s)),h=o,w=S,S=s,!0===r.end_stream?$.end():$.destroy(),u(S),$=e.createWriteStream(s,C),N.emit("new",s),N.emit("rotate",w,s),d($,N)}$.write(t,n),y+=Buffer.byteLength(t,n)}.bind(this),process.nextTick((function(){N.emit("new",S)})),N.emit("new",S),N}return f.verbose&&console.log(new Date,"[FileStreamRotator] File won't be rotated: ",r.frequency,r.size),process.nextTick((function(){$.emit("new",S)})),$};var u=function(n){t.dirname(n).split(t.sep).reduce((function(n,r){if(n+=r+t.sep,!e.existsSync(n))try{e.mkdirSync(n)}catch(n){if("EEXIST"!==n.code)throw n}return n}),"")},d=function(e,t){e.on("close",(function(){t.emit("close")})),e.on("finish",(function(){t.emit("finish")})),e.on("error",(function(e){t.emit("error",e)})),e.on("open",(function(e){t.emit("open",e)}))};return yy}const _y=x,Iy=E,xy=b,ky=i,Ey=A,Cy=gy.exports,$y=th.MESSAGE,Oy=O.PassThrough,Ny=Cp,Ty={json:!1,colorize:!1,eol:Iy.EOL,logstash:null,prettyPrint:!1,label:null,stringify:!1,depth:null,showLevel:!0,timestamp:()=>(new Date).toISOString()},Ay=function(e){if(e=e||{},Ny.call(this,e),this.options=Object.assign({},Ty,e),e.stream)!function(t){Array.prototype.slice.call(arguments,1).forEach((n=>{if(e[n])throw new Error("Cannot set "+n+" and "+t+" together")}))}("stream","filename","maxsize"),this.logStream=new Oy,this.logStream.pipe(e.stream);else{if(this.filename=e.filename?xy.basename(e.filename):"winston.log",this.dirname=e.dirname||xy.dirname(e.filename),t=this.filename,/["<>|:*?\\/\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f]/g.test(t)||!function(e){return!/["<>|\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f]/g.test(e)}(this.dirname))throw new Error("Your path or filename contain an invalid character.");this.logStream=Sy().getStream({filename:xy.join(this.dirname,this.filename),frequency:e.frequency?e.frequency:"custom",date_format:e.datePattern?e.datePattern:"YYYY-MM-DD",verbose:!1,size:function(e){if(e&&"string"==typeof e){if(e.toLowerCase().match(/^((?:0\.)?\d+)([kmg])$/))return e}else if(e&&Number.isInteger(e)){const t=Math.round(e/1024);return 0===t?"1k":t+"k"}return null}(e.maxSize),max_logs:e.maxFiles,end_stream:!0,audit_file:e.auditFile?e.auditFile:xy.join(this.dirname,"."+Cy(e)+"-audit.json"),file_options:e.options?e.options:{flags:"a"},utc:!!e.utc&&e.utc,extension:e.extension?e.extension:"",create_symlink:!!e.createSymlink&&e.createSymlink,symlink_name:e.symlinkName?e.symlinkName:"current.log",watch_log:!!e.watchLog&&e.watchLog,audit_hash_type:e.auditHashType?e.auditHashType:"sha256"}),this.logStream.on("new",(e=>{this.emit("new",e)})),this.logStream.on("rotate",((e,t)=>{this.emit("rotate",e,t)})),this.logStream.on("logRemoved",(t=>{if(e.zippedArchive){const e=t.name+".gz";try{_y.unlinkSync(e)}catch(t){if("ENOENT"!==t.code)return t.message=`Error occurred while removing ${e}: ${t.message}`,void this.emit("error",t)}this.emit("logRemoved",e)}else this.emit("logRemoved",t.name)})),e.zippedArchive&&this.logStream.on("rotate",(e=>{try{if(!_y.existsSync(e))return}catch(t){return t.message=`Error occurred while checking existence of ${e}: ${t.message}`,void this.emit("error",t)}try{if(_y.existsSync(`${e}.gz`))return}catch(t){return t.message=`Error occurred while checking existence of ${e}.gz: ${t.message}`,void this.emit("error",t)}const t=Ey.createGzip(),n=_y.createReadStream(e);n.on("error",(t=>{t.message=`Error occurred while reading ${e}: ${t.message}`,this.emit("error",t)}));const r=_y.createWriteStream(e+".gz");r.on("error",(t=>{t.message=`Error occurred while writing ${e}.gz: ${t.message}`,this.emit("error",t)})),n.pipe(t).pipe(r).on("finish",(()=>{try{_y.unlinkSync(e)}catch(t){if("ENOENT"!==t.code)return t.message=`Error occurred while removing ${e}: ${t.message}`,void this.emit("error",t)}this.emit("archive",e+".gz")}))})),e.watchLog&&this.logStream.on("addWatcher",(e=>{this.emit("addWatcher",e)}))}var t};var My=Ay;ky.inherits(Ay,Ny),Ay.prototype.name="dailyRotateFile";const Py=function(){};Ay.prototype.log=function(e,t){t=t||Py,this.logStream.write(e[$y]+this.options.eol),this.emit("logged",e),t(null,!0)},Ay.prototype.close=function(){this.logStream&&this.logStream.end((()=>{this.emit("finish")}))},Ay.prototype.query=function(e,t){if("function"==typeof e&&(t=e,e={}),!this.options.json)throw new Error("query() may not be used without the json option being set to true");if(!this.filename)throw new Error("query() may not be used when initializing with a stream");let n=[];(e=e||{}).rows=e.rows||e.limit||10,e.start=e.start||0,e.until=e.until||new Date,"object"!=typeof e.until&&(e.until=new Date(e.until)),e.from=e.from||e.until-864e5,"object"!=typeof e.from&&(e.from=new Date(e.from)),e.order=e.order||"desc";const r=(()=>{const e=new RegExp(this.filename.replace("%DATE%",".*"),"i");return _y.readdirSync(this.dirname).filter((t=>xy.basename(t).match(e)))})();0===r.length&&t&&t(null,n);const i=o=>{if(!o)return;const s=xy.join(this.dirname,o);let a,c="";if(o.endsWith(".gz")){a=new Oy;const e=_y.createReadStream(s);e.on("error",(e=>{e.message=`Error occurred while reading ${s}: ${e.message}`,a.emit("error",e)})),e.pipe(Ey.createGunzip()).pipe(a)}else a=_y.createReadStream(s,{encoding:"utf8"});function l(t,r){try{const r=JSON.parse(t);if(!r||"object"!=typeof r)return;const i=new Date(r.timestamp);if(e.from&&i<e.from||e.until&&i>e.until||e.level&&e.level!==r.level)return;n.push(r)}catch(e){r||a.emit("error",e)}}a.on("error",(e=>{if(a.readable&&a.destroy(),t)return"ENOENT"===e.code?t(null,n):t(e)})),a.on("data",(e=>{const t=(e=(c+e).split(/\n+/)).length-1;for(let n=0;n<t;n++)l(e[n]);c=e[t]})),a.on("end",(()=>{if(c&&l(c,!0),r.length)i(r.shift());else if(t){n.sort(((e,t)=>{const n=new Date(e.timestamp).getTime(),r=new Date(t.timestamp).getTime();return n>r?1:n<r?-1:0})),"desc"===e.order&&(n=n.reverse());const r=e.start||0,i=e.limit||n.length;n=n.slice(r,r+i),e.fields&&(n=n.map((t=>{const n={};return e.fields.forEach((e=>{n[e]=t[e]})),n}))),t(null,n)}}))};i(r.shift())};const Dy=My;Id.transports.DailyRotateFile=Dy;var jy=od(Dy);const Ry=Date.now();let Ly=Math.ceil(Ry/1e3);var Fy=()=>Ly+=1;const Uy=w(C(),"kemu-user-services"),By=w(C(),"kemu-test-services"),Wy="KMU-CB-v1",Gy=process.env.HUB_PKG_VERSION||'"1.10.1"';var Vy;!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"}(Vy||(Vy={}));const Yy=e=>({...e,type:Array.isArray(e.type)?e.type.map((e=>Pu[e])):Pu[e.type]}),Hy=async e=>{try{return await y(e,"utf-8")}catch(e){return null}},zy=e=>{if(e&&e.startsWith(Wy)){const t=e.slice(9),n=decodeURI(t);return Hu(n)}return null},qy=async(e,t,n)=>{let r=[];e.variants?.length&&(r=e.variants.map((e=>({...e,...e.inputs?{inputs:e.inputs.map(Yy)}:{},...e.outputs?{outputs:e.outputs.map(Yy)}:{}}))));const i={...e,path:t,customWidgets:[],...e.inputs?{inputs:e.inputs.map(Yy)}:{inputs:[]},...e.outputs?{outputs:e.outputs.map(Yy)}:{outputs:[]},variants:r,...e.widgetUI&&n?.widgetUIContents?{widgetUIContents:n.widgetUIContents}:{}},o=await(async(e,t,n=console.log)=>{const r=[];if(t.customWidgets?.length)for(const i of t.customWidgets){const t=await Hy(w(e,i));if(!t){n(`Error loading custom widget file ${i}`);continue}const o=t.startsWith(Wy)?t:`${Wy}${t}`,s=zy(o);if(!s){n(`Custom widget file "${i}" is not a valid Kemu Clipboard item`);continue}const a=Object.values(s).filter((e=>e.type===Vy.widgetGroup&&!e.groupId));if(a.length>1){n(`Custom widget file "${i}" contains more than one top level widgetGroup`);continue}const c=a[0];if(!c){n(`Custom widget file "${i}" does not contain a top level widgetGroup`);continue}const l=c.state,u={name:l.name,color:l.color,description:l.description,contents:o,rootGroupId:c.id,icon:l.icon,protocolVersion:l.protocolVersion||"2"};r.push(u)}return r})(t,e,n?.log);if(o.length?i.customWidgets=o:delete i.customWidgets,i.variants?.length)for(const e of i.variants)if(e.svgIcon)try{const n=await y(w(t,e.svgIcon),"utf-8");e.svgIcon=n}catch(t){n?.log&&n?.log(`Error loading svgIcon for variant ${e.id}: ${t}`)}return i},Ky=async e=>{try{return await f(e,p.F_OK),!0}catch{return!1}};let Jy=null,Zy=null;const Xy=()=>Jy||Uy,Qy=()=>Zy||By;let ev=null;const tv={setGlobalUserId:e=>ev?.setGlobalUserId?.(e),captureError:e=>ev?.captureError?.(e),flushMessages:async()=>ev?.flushMessages?.(),isEnabled:()=>!!ev};var nv={...tv,setTracker:e=>{ev=e}};const rv=_d("servicesManager"),iv={};let ov=null,sv=null,av=null,cv=!1;class lv extends Error{code;originalError;constructor(e,t,n){super(e),this.code=t,this.originalError=n,this.name="ServiceError"}}const uv=async e=>{try{return await f(e),!0}catch{return!1}},dv=async e=>{if(!ov)throw new Error('IPC config not set, call "setHubIpcConfig" first.');let t;if(e.info.internal)if("linux"===$()){const n=process.env.XDG_STATE_HOME||b.join(C(),".local","state");t=b.join(n,"kemu-hub","service-logs",e.info.name);try{await h(t,{recursive:!0})}catch(n){rv(`Failed to create log directory ${t}, falling back to service path`),t=e.info.path}}else t=e.info.path;else t=b.join(e.info.path,"..");const n=e.logsEnabled?((e,t)=>{const n=py.createLogger({level:"info",format:py.format.combine(py.format.timestamp(),py.format.errors({stack:!0}),py.format.json()),defaultMeta:{service:e},transports:[new jy({filename:b.join(t,"service-%DATE%.log"),datePattern:"YYYY-MM-DD",maxSize:"5m",maxFiles:"5d",auditFile:b.join(t,".service-log-audit.json")})]});return n.getLastLogs=async(n=100)=>{try{const r=b.join(t,".service-log-audit.json"),i=await d.readFile(r,"utf-8"),o=Hu(i);if(!o)return console.warn(`Missing audit file for ${e}, skipping log retrieval.`),[];const s=async e=>(await d.readFile(e,"utf-8")).split("\n").filter((e=>e.trim())),a=[],c=[...o.files].reverse();for(const e of c){const t=await s(e.name);if(a.push(...t),a.length>=n)break}return a}catch(t){return console.warn(`Failed to read service logs for ${e}: `,t),[]}},n})(e.info.name,t):null,r=t=>{if(!e.devMode){const{childProcess:r,...i}=e;nv.isEnabled()&&nv.captureError({error:t,data:{logs:n?.getLastLogs(),service:{...i,spawnargs:r?.spawnargs,info:void 0,name:e.info.name,version:e.info.version}}})}};try{if(e.info.processor===ju.Javascript){rv(`Spawning service ${e.info.name} with sessionId ${e.info.sessionId}`);const t=b.join(e.info.path,"processor.js"),i=b.join(e.info.path,"processor.mjs"),o=await uv(t)?t:i,s=[`--sessionId=${e.info.sessionId.toString()}`,`--ipcSpace=${ov.appSpace}`,`--ipcId=${ov?.id}`,`--recipePath=${ov.recipePath||""}`];if(e.info.internal&&s.push("--internal=true"),!av)throw new Error('Get secrets function not set, call "setGetSecretsFunction" first.');const a=await av({name:e.info.name,version:e.info.version,requiredSecrets:e.info.requiredSecrets||{}}),c=Object.entries(e.info.requiredSecrets||{}).filter((([e,t])=>null==a[e]&&!t.optional)).map((([e])=>e));if(c?.length)throw new lv(`Missing required environment variables: ${c.join(", ")}`,"MISSING_REQUIRED_SECRETS");return new Promise(((t,i)=>{if(!sv)throw new Error('Spawn function not set, call "setSpawnNodeFunction" first.');const c=sv({args:[o,...s],serviceInfo:{name:e.info.name,version:e.info.version},options:{env:{...a}}});c.stdout.on("data",(t=>{const r=t.toString().trim();r&&(n?.info(r),rv(`[${e.info.name}] - stdout: ${r}`))})),c.stderr.on("data",(t=>{const i=t.toString().trim();i&&(n?.error(i),r(new Error(i)),rv(`[${e.info.name}] - stderr: ${i}`))})),c.on("exit",(t=>{const r=`exited with code ${t}`;n?.info(r,{code:t}),rv(`[${e.info.name}] ${r}`)})),c.on("spawn",(()=>{const r=`spawned with PID ${c.pid}`;n?.info(r,{pid:c.pid}),rv(`[${e.info.name}] ${r}`),t(c)})),c.on("error",(t=>{n?.error(`[${e.info.name}] error`,t),rv(`[${e.info.name}] error: ${t}`),r(t),i(new lv(`Error spawning service ${e.info.name}: ${t}`,"SPAWN_ERROR"))}))}))}throw`Unsupported processor type ${e.info.processor}`}catch(t){if(r(t),t instanceof lv)throw t;throw`Error spawning service ${e.info.name}: ${t}`}},hv=e=>e?.name?e?.version?e?.description?e?.processor?[ju.Javascript,ju.Executable,ju.Python].includes(e?.processor)?null:"Invalid processor":"Missing processor":"Missing description":"Missing version":"Missing name",fv=async(e,t)=>{const n=b.join(e,"manifest.json");if(!await uv(n)){const t=`Missing manifest for service ${e}. Aborting.`;return rv(t),{error:t}}const r=await y(n,"utf-8"),i=Hu(r),o=hv(i);if(!i||o){const t=`Invalid service manifest [${e}]: ${o}. Aborting.`;return rv(t),{error:t}}let s;if(delete i.internal,t?.singleServiceName&&i.name!==t.singleServiceName)return{error:`Skipping service ${i.name} as it does not match the singleServiceName option`};await Promise.all([(async()=>{if(i.widgetUI)try{s=await y(b.join(e,"widgetUI.js"))}catch(e){const t=`Error loading widgetUI file ${i.name}: ${e}`;return rv(t),{error:t}}})(),(async()=>{if(i.svgIcon){const t=await Hy(b.join(e,i.svgIcon));if(!t)return{error:`Error loading icon for service ${i.name}`};i.svgIcon=t}})(),(async()=>{if(i.subServices?.length)for(const t of i.subServices){const n=b.join(e,t),{error:r,service:o}=await fv(n);r?rv(`Error loading sub-service ${t}: ${r}`):o&&(o.info.parentService={name:i.name,version:i.version})}delete i.subServices})(),(async()=>{if(i.variants?.length)for(const t of i.variants)if(t.svgIcon)try{const n=await y(b.join(e,t.svgIcon),"utf-8");t.svgIcon=n}catch(e){rv(`Error loading svgIcon for variant ${t.id}: ${e}`)}})()]);const a=Fy(),c=t?.fixedSession||a;rv(`Loaded service ${i.name} with sessionId ${c}`);const l=await qy(i,e,{widgetUIContents:s});return pv(l),iv[c]={info:{...l,path:e,sessionId:c},status:"loaded",childProcess:null,logsEnabled:t?.logsEnabled},{service:iv[c]}},pv=e=>{e.widgetUIContents?e.uiContentChecksum=(e=>{const t=R("sha256");return t.update(e),t.digest("hex")})(e.widgetUIContents):e.uiContentChecksum=void 0},gv=async e=>{try{return e.childProcess=await dv(e),e.status="started",e.errorMsg=void 0,e.errorCode=void 0,!0}catch(t){return rv(`Service [${e.info.name}] error: ${t}`),e.status="error",t instanceof lv?(e.errorMsg=t.message,e.errorCode=t.code):(e.errorMsg="string"==typeof t?t:JSON.stringify(t),e.errorCode="UNKNOWN_ERROR"),!1}},mv=e=>{const{path:t,...n}=e.info;return{...n}},yv=()=>Object.values(iv).filter((e=>"running"===e.status)).map(mv),vv=e=>{if(!e?.kill)return rv(`Failed to kill service ${e?.pid} because it is not a child process`),!1;let t=e.kill("SIGINT");return t||(rv(`Failed to send SIGINT to service ${e.pid} using SIGINT`),t=e.kill("SIGTERM"),t||(rv(`Failed to send SIGTERM to service ${e.pid} using SIGTERM`),t=e.kill("SIGKILL"),t||rv(`Failed to send SIGKILL to service ${e.pid} using SIGKILL`))),t},bv=async e=>{const{serviceName:t,version:n,force:r,timeout:i=15e3}=e,o=Object.values(iv).find((t=>t.info.name===e.serviceName&&t.info.version===e.version));if(!o)return null;if(o.info.internal&&!r)throw`Cannot stop internal service ${t}`;if(o.childProcess){rv(`Stopping service "${t} (v${n})"`);const r=new Promise(((e,n)=>{const r=setTimeout((()=>{n(new Error(`Timeout waiting for service ${t} to stop after ${i}ms`))}),i);o.childProcess.once("exit",((n,i)=>{clearTimeout(r),rv(`Service ${t} process exited with code ${n} and signal ${i}`),e()})),o.childProcess.once("error",(n=>{clearTimeout(r),rv(`Service ${t} process error: ${n.message}`),e()}))}));vv(o.childProcess);try{await r,rv(`Service ${t} process successfully terminated`)}catch(e){rv(`Warning: ${e instanceof Error?e.message:"Unknown error"} while waiting for service ${t} to stop`)}}return o.status="stopped",rv(`Service ${t} stopped`),o},wv=e=>e.info.internal?e.info.path:b.join(e.info.path,".."),Sv=e=>!!e.internal;var _v={isOfficialKemuService:e=>e.name.startsWith("kemu.io"),loadServices:async(e,t)=>{if(!await Ky(e))return void rv(`Failed to load services from "${e}". Directory does not exist.`);const n=(await g(e,{withFileTypes:!0})).filter((e=>e.isDirectory())).map((e=>e.name));rv(`Found ${n.length} services in "${e}"`);for(let r=0;r<n.length;r++){const i=n[r],o=b.join(e,i),{error:s,service:a}=await fv(`${o}${t?.internalServices?"":"/dist"}`,{...t,logsEnabled:Array.isArray(t?.enableLogs)?t?.enableLogs.includes(i):t?.enableLogs});s&&rv(`Failed to load service ${o}. Please check logs`),a&&t?.internalServices&&(a.info.internal=!0)}},launchServices:async e=>{if(rv("Initializing services"),!ov)throw new Error('IPC config not set, call "setHubIpcConfig" first.');for(const t in iv){const n=iv[t];e.noSpawningList&&e.noSpawningList.includes(n.info.name)?rv(`Service ${n.info.name} is in the noSpawningList. Skipping.`):gv(n)}rv("Services initialized")},setServiceStatus:(e,t)=>{const n=iv[e];return n?(n.status=t,!0):(rv(`Service with serviceId ${e} not found`),!1)},getActiveServices:yv,getMatchingService:(e,t)=>{const n=Object.values(iv).filter((e=>"running"===e.status));for(const r of n)if(r.info.name===e){if(r.info.version===t)return r;if(ed(r.info.version,t,">="))return r}return null},getServiceBySessionId:e=>iv[e]||null,killAllServices:()=>{for(const e in iv){const t=iv[e];if(t.childProcess)try{rv(`Killing service ${t.info.name} with PID ${t.childProcess.pid}`),vv(t.childProcess)}catch(e){rv(`Error killing service ${t.info.name}: ${e}`)}}},addDevService:async(e,t,n)=>{const r={info:{...await qy(t,t.path),sessionId:e},status:n,startedAt:new Date,devMode:!0,childProcess:null};iv[e]=r,pv(iv[e].info)},setServiceManifest:(e,t,n)=>{const r=iv[e];if(!r)return rv(`Service with sessionId ${e} not found`),!1;const i=hv(t);if(i)return rv(`Invalid manifest for service ${r.info.name}: ${i}`),!1;pv(t),r.info={...r.info,...t},n&&(r.status=n)},getMatchingDevService:(e,t,n)=>{const r=Object.values(iv).filter((e=>e.devMode));for(const i of r)if(i.info.name===e&&i.status===n&&i.info.version===t)return i;return null},getInternalServices:()=>yv().filter((e=>e.internal)),getAllServices:()=>Object.values(iv),stopService:bv,uninstallService:async(e,t)=>{rv(`Uninstalling service ${e} v${t}`);const n=await bv({serviceName:e,version:t});if(!n)return!1;rv(`Service ${e} stopped. Removing from disk...`);const r=wv(n),i=Xy();return r.startsWith(i)?(await m(r,{recursive:!0,force:!0,maxRetries:3}),rv(`Service ${e} successfully removed from disk`),(e=>{iv[e],delete iv[e]})(n.info.sessionId),!0):(rv(`Service ${e} is not installed in the user services directory. Aborting.`),!1)},getAllServiceVersions:e=>Object.values(iv).filter((t=>t.info.name===e)),setHubIpcConfig:e=>{ov={...e}},setEnableServiceLogsConfig:e=>{cv=e},loadAndLaunch:async(e,t,n)=>{const r=_(e,t),{error:i,service:o}=await fv(r,{logsEnabled:cv});if(i||!o)return{errorMsg:i};try{o.info.internal=!!n,o.childProcess=await dv(o),o.status="started"}catch(e){o.status="error",e instanceof lv?(rv(`Service spawning error: ${e.message} (${e.code})`),o.errorMsg=e.message,o.errorCode=e.code):(rv(`Error launching service ${o.info.name}: ${e}`),o.errorMsg="string"==typeof e?e:JSON.stringify(e))}return{service:o,errorCode:o.errorCode,errorMsg:o.errorMsg}},getServiceRootDirectory:wv,setSpawnNodeFunction:e=>{sv=e},setGetSecretsFunction:e=>{av=e},restartService:async(e,t)=>{rv(`Restarting service ${e} v${t}`);const n=await bv({serviceName:e,version:t,force:!0});return!!n&&gv(n)},getFailedServices:()=>Object.values(iv).filter((e=>"error"===e.status)).map((e=>({...mv(e),errorMsg:e.errorMsg||"",errorCode:e.errorCode,status:e.status}))),isInternalKemuService:Sv,isNotInternalKemuService:e=>!Sv(e),isNotDevService:e=>!e.devMode};class Iv{constructor(){}appspace="app.";socketRoot="/tmp/";id=E.hostname();encoding="utf8";rawBuffer=!1;sync=!1;unlink=!0;delimiter="\f";silent=!1;logDepth=5;logInColor=!0;logger=console.log.bind(console);maxConnections=100;retry=500;maxRetries=1/0;stopRetrying=!1;IPType=function(){const e=E.networkInterfaces();let t="";return e&&Array.isArray(e)&&e.length>0&&(t=e[Object.keys(e)[0]][0].family),t}();tls=!1;networkHost="IPv6"==this.IPType?"::1":"127.0.0.1";networkPort=8e3;readableAll=!1;writableAll=!1;interface={localAddress:!1,localPort:!1,family:!1,hints:!1,lookup:!1}}class xv{constructor(e){e||(e=new Iv),this.delimiter=e.delimiter}format(e){return e.data||!1===e.data||0===e.data||(e.data={}),e.data._maxListeners&&(e.data={}),e.JSON+this.delimiter}parse(e){let t=e.split(this.delimiter);return t.pop(),t}}var kv=od((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={}})),Ev=od((function(){Object.defineProperties(this,{add:{enumerable:!0,writable:!1,value:function(){for(var n in arguments)e.push(arguments[n]);t||this.stop||!this.autoRun||this.next()}},next:{enumerable:!0,writable:!1,value:function(){t=!0,e.length<1||this.stop?t=!1:e.shift().bind(this)()}},clear:{enumerable:!0,writable:!1,value:function(){return e=[]}},contents:{enumerable:!1,get:function(){return e},set:function(t){return e=t}},autoRun:{enumerable:!0,writable:!0,value:!0},stop:{enumerable:!0,writable:!0,value:!1}});var e=[],t=!1}));class Cv{}class $v{}const Ov=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 Cv,t=$v){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 Cv}}())}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 Nv{constructor(){}on(e,t,n=!1){return Ov.string(e),Ov.function(t),Ov.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(Ov.string(e),e!=this.#e.toString()&&"*"!=e||(e=this.#e),!this.#t[e])return this;if("*"==t)return delete this.#t[e],this;Ov.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){Ov.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)=>{Ov.string(e),Ov.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 Tv=new xv;class Av extends Nv{constructor(e,t){super(),this.config=e,this.log=t,this.publish=super.emit,e.maxRetries&&(this.retriesRemaining=e.maxRetries),Tv=new xv(this.config)}Client=Av;queue=new Ev;socket=!1;connect=Dv;emit=Mv;retriesRemaining=0;explicitlyDisconnected=!1}function Mv(e,t){this.log("dispatching event to ",this.id,this.path," : ",e,",",t);let n=new kv;n.type=e,n.data=t,n=this.config.rawBuffer?Buffer.from(e,this.config.encoding):Tv.format(n),this.config.sync?this.queue.add(Pv.bind(this,n)):this.socket.write(n)}function Pv(e){this.log("dispatching event to ",this.id,this.path," : ",e),this.socket.write(e)}function Dv(){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=F.connect(e.config.tls)}else e.log("Connecting client via TCP to",t),e.socket=L.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=L.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)!=Tv.delimiter||-1==t.indexOf(Tv.delimiter))return void e.log("Messages are large, You may want to consider smaller messages.");this.ipcBuffer="";const n=Tv.parse(t),r=n.length;for(let t=0;t<r;t++){let r=new kv;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 jv=new xv;class Rv extends Nv{constructor(e,t,n,r){super(),this.config=t,this.path=e,this.port=r,this.log=n,this.publish=super.emit,jv=new xv(this.config),this.on("close",Uv.bind(this))}udp4=!1;udp6=!1;server=!1;sockets=[];emit=Lv;broadcast=Fv;onStart(e){this.publish("start",e)}stop(){this.server.close()}start(){this.path?this.config.unlink?x.unlink(this.path,Vv.bind(this)):Vv.bind(this)():this.log("Socket Server Path not specified, refusing to start")}}function Lv(e,t,n){this.log("dispatching event to socket"," : ",t,n);let r=new kv;if(r.type=t,r.data=n,this.config.rawBuffer?(this.log(this.config.encoding),r=Buffer.from(t,this.config.encoding)):r=jv.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 Fv(e,t){this.log("broadcasting event to all known sockets listening to ",this.path," : ",this.port?this.port:"",e,t);let n=new kv;if(n.type=e,n.data=t,n=this.config.rawBuffer?Buffer.from(e,this.config.encoding):jv.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 Uv(){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 Bv(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)==jv.delimiter&&-1!=t.indexOf(jv.delimiter))for(r.ipcBuffer="",t=jv.parse(t);t.length>0;){let e=new kv;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 Wv(e){this.publish("close",e)}function Gv(e){this.sockets.push(e),e.setEncoding&&e.setEncoding(this.config.encoding),this.log("## socket connection to server detected ##"),e.on("close",Wv.bind(this)),e.on("error",function(e){this.log("server socket error",e),this.publish("error",e)}.bind(this)),e.on("data",Bv.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 Vv(){return this.log("starting server on ",this.path,this.port?`:${this.port}`:""),this.udp4||this.udp6?(this.server=U.createSocket(this.udp4?"udp4":"udp6"),this.server.write=Hv.bind(this),this.server.on("listening",function(){Gv.bind(this)(this.server)}.bind(this))):(this.log("starting TLS server",this.config.tls),this.config.tls?Yv.bind(this)():this.server=L.createServer(Gv.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 Yv(){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=F.createServer(this.config.tls,Gv.bind(this))}function Hv(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 zv{constructor(){}config=new Iv;of={};server=!1;get connectTo(){return Qv}get connectToNet(){return eb}get disconnect(){return Kv}get serve(){return Jv}get serveNet(){return Xv}get log(){return qv}set connectTo(e){return Qv}set connectToNet(e){return eb}set disconnect(e){return Kv}set serve(e){return Jv}set serveNet(e){return Xv}set log(e){return qv}}function qv(...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 Kv(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 Jv(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=Zv),this.server=new Rv(e,this.config,qv),this.server.on("start",t)}function Zv(){}function Xv(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=Zv),this.server=new Rv(e,this.config,qv,t),n&&(this.server[n]=!0,"udp4"===n&&"::1"===e&&(this.server.path="127.0.0.1")),this.server.on("start",r)}function Qv(e,t,n){if("function"==typeof t&&(n=t,t=!1),n||(n=Zv),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 Av(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 eb(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=Zv),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 Av(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 tb=new class extends zv{constructor(){super()}IPC=zv};const nb=Object.values({protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8}).reduce(((e,t)=>e+t),0),rb=e=>{try{return JSON.parse(e)}catch(e){return null}},ib="undefined"!=typeof window,ob={protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8},sb={protocolPrefix:4,txtLength:4},ab=Object.values(ob).reduce(((e,t)=>e+t),0),cb=Object.values(sb).reduce(((e,t)=>e+t),0),lb=["width","height","colorSpace"],ub=(e,t)=>{const n={},r=[];let i=0,o=Array.isArray(e)?[]:{};const s=(e,o)=>{const a=(e=>{const t="undefined"!=typeof Buffer&&e instanceof Buffer,n=e instanceof ArrayBuffer,r=e instanceof Uint8ClampedArray,i=e instanceof Uint8Array,o=e instanceof Int8Array;return t?"Buffer":n?"ArrayBuffer":r?"Uint8ClampedArray":i?"Uint8Array":o?"Int8Array":null})(e);if(!a){if(Array.isArray(e)){const t=[];for(let n=0;n<e.length;n++)t[n]=s(e[n],`${o}[${n}]`);return t}if("object"==typeof e){const t={},n=(e=>{const t=e instanceof Int16Array,n=e instanceof Uint16Array,r=e instanceof Int32Array,i=e instanceof Uint32Array,o=e instanceof Float32Array,s=e instanceof Float64Array,a=e instanceof BigInt64Array,c=e instanceof BigUint64Array;return t?"Int16Array":n?"Uint16Array":r?"Int32Array":i?"Uint32Array":o?"Float32Array":s?"Float64Array":a?"BigInt64Array":c?"BigUint64Array":null})(e);if(n)throw new Error(`Unsupported binary type [${n}] at path "${o}"`);for(const n in e)Object.hasOwn(e,n)||lb.includes(n)||console.warn(`Allowing inherited property: ${n} from path: ${o}`),t[n]=s(e[n],`${o.length?`${o}.`:""}${n}`);return t}return e}n[o]={index:i,length:e.byteLength,binaryType:a},"Buffer"===t?r.push(Buffer.from(e)):"ArrayBuffer"===a?r.push(e):r.push(e.buffer),i+=e.byteLength};o=s(e,"");let a=null;if(r.length>1)if("ArrayBuffer"===t){const e=r.reduce(((e,t)=>e+t.byteLength),0),t=new Uint8Array(e);let n=0;for(let e=0;e<r.length;e++)t.set(new Uint8Array(r[e]),n),n+=r[e].byteLength;a=t.buffer}else a=Buffer.concat(r);else 1===r.length&&(a=r[0]);return a?{map:n,combinedData:a,sourceCopy:o}:null},db=(e,t,n)=>{const r=t.match(/(\[\d+\])|([^[\].]+)/g)||[];let i=e;for(let e=0;e<r.length;e++){let t=r[e];const o=t.startsWith("[")&&t.endsWith("]"),s=e===r.length-1;if(o){t=t.slice(1,-1);const o=parseInt(t,10);if(!Array.isArray(i))throw new Error(`Expected an array at key "${r.slice(0,e).join(".")}" but found an object.`);s?i[o]=n:(i[o]||(i[o]=r[e+1].startsWith("[")?[]:{}),i=i[o])}else s?i[t]=n:(i[t]||(i[t]=r[e+1].startsWith("[")?[]:{}),i=i[t])}return e},hb=(e,t,n)=>{const r="undefined"!=typeof Buffer,i=t instanceof Uint8Array;for(const o in n)if(Object.hasOwn(n,o)){const{index:s,length:a,binaryType:c}=n[o];let l=null;if(r&&t instanceof Buffer)switch(c){case"Buffer":l=t.subarray(s,s+a);break;case"ArrayBuffer":l=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(s,s+a);break;case"Uint8Array":l=new Uint8Array(t.subarray(s,s+a));break;case"Uint8ClampedArray":l=new Uint8ClampedArray(t.subarray(s,s+a));break;case"Int8Array":l=new Int8Array(t.subarray(s,s+a))}else if(t instanceof ArrayBuffer||t instanceof Uint8Array)switch(c){case"Buffer":if(r){l=Buffer.from(t.slice(s,s+a));break}case"ArrayBuffer":l=i?t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(s,s+a):t.slice(s,s+a);break;case"Uint8Array":l=i?t.slice(s,s+a):new Uint8Array(t.slice(s,s+a));break;case"Uint8ClampedArray":l=new Uint8ClampedArray(t.slice(s,s+a));break;case"Int8Array":l=new Int8Array(t.slice(s,s+a))}l&&db(e,o,l)}return e},fb=e=>Sd(e),pb="KMSG",gb="KCMD",mb=fb("klProtocol");var yb={encode:(e,t,n)=>{const r={json:e.json},i=ub(r.json,"Buffer"),o=i?.combinedData;i&&(r.jsonBinaryMap=i.map,r.json=i.sourceCopy);const s=o?o.byteLength:0,a=JSON.stringify(r),c=Buffer.from(a),l=c.byteLength,u=ob.protocolPrefix+ob.protocolVersion+ob.jsonLength+ob.binaryLength+ob.fromServiceId+ob.toServiceId+ob.sentAt+l+s,d=Buffer.alloc(u),h=Date.now();let f=0;return d.write(pb,f),f+=ob.protocolPrefix,d.writeUInt8(1,f),f+=ob.protocolVersion,d.writeUInt32LE(l,f),f+=ob.jsonLength,d.writeUInt32LE(s,f),f+=ob.binaryLength,d.writeUInt32LE(t,f),f+=ob.fromServiceId,d.writeUInt32LE(n,f),f+=ob.toServiceId,d.writeBigInt64LE(BigInt(h),f),f+=ob.sentAt,c.copy(d,f),f+=l,o&&s&&o.copy(d,f),d},decodeHeader:e=>{let t=0;const n=e.toString("utf-8",t,ob.protocolPrefix);if(t+=ob.protocolPrefix,n!==pb)return null;if(e.byteLength<ab)return mb(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const r=e.readUInt8(t);t+=ob.protocolVersion;const i=e.readUInt32LE(t);t+=ob.jsonLength;const o=e.readUInt32LE(t);t+=ob.binaryLength;const s=e.readUInt32LE(t);t+=ob.fromServiceId;const a=e.readUInt32LE(t);t+=ob.toServiceId;const c=e.readBigInt64LE(t);t+=ob.sentAt;const l=i+o,u=e.subarray(t,t+l),d=e.subarray(0,ab);let h=null;return e.byteLength-ab-i-o>0&&(h=e.subarray(ab+i+o)),{header:{protocolVersion:r,jsonLength:i,binaryLength:o,fromServiceId:s,toServiceId:a,sentAt:new Date(Number(c)),packages:[u],headerPackage:d},remaining:h}},decodeFullKlMessage:e=>{const t=Buffer.concat(e.packages),n=t.subarray(0,e.jsonLength).toString(),r=t.subarray(e.jsonLength,e.jsonLength+e.binaryLength),i=rb(n);if(!i?.json)return mb("Invalid JSON in KL message"),null;i.jsonBinaryMap&&r.byteLength&&hb(i.json,r,i.jsonBinaryMap);const o=Buffer.concat([e.headerPackage,t]);let s=o,a=null;const c=ab+e.jsonLength+e.binaryLength;return o.byteLength>c&&(a=o.subarray(c),s=o.subarray(0,c)),{message:{json:i.json,rawMessage:s},remaining:a}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<ab)return mb("Invalid Header Size"),e;let n=0;return n+=ob.protocolPrefix,n+=ob.protocolVersion,n+=ob.jsonLength,n+=ob.binaryLength,void 0!==t.fromServiceId&&e.writeUInt32LE(t.fromServiceId,n),n+=ob.fromServiceId,void 0!==t.toServiceId&&e.writeUInt32LE(t.toServiceId,n),e},encodeCommand:e=>{let t=0;const n=Buffer.from(e),r=n.byteLength,i=cb+r,o=Buffer.alloc(i);return o.write(gb,t),t+=sb.protocolPrefix,o.writeUint32LE(r,t),t+=sb.txtLength,n.copy(o,t),o},decodeCommand:e=>{let t=0;if(e.byteLength<cb)return{command:null};const n=e.toString("utf-8",t,sb.protocolPrefix);if(t+=sb.protocolPrefix,n!==gb)return{command:null};const r=e.readUInt32LE(t);t+=sb.txtLength;const i=e.toString("utf-8",t,t+r),o=e.byteLength-cb-r;let s=null;o>0&&(s=e.subarray(cb+r));let a=0;return o<0&&(a=Math.abs(o)),{command:i,remainingData:s,missing:a}}};const vb="KMSG",bb="KCMD",wb=fb("klProtocol"),Sb=new TextEncoder;var _b={encode:(e,t,n)=>{const r={json:e.json},i=ub(e.json,"ArrayBuffer"),o=i?.combinedData;i&&(r.jsonBinaryMap=i.map,r.json=i.sourceCopy);const s=o?o.byteLength:0,a=JSON.stringify(r),c=Sb.encode(a),l=c.byteLength,u=new ArrayBuffer(ob.protocolPrefix+ob.protocolVersion+ob.jsonLength+ob.binaryLength+ob.fromServiceId+ob.toServiceId+ob.sentAt+l+s),d=new DataView(u),h=new Uint8Array(u),f=Date.now();let p=0;for(let e=0;e<4;++e)h[p++]=vb.charCodeAt(e);return d.setUint8(p,1),p+=ob.protocolVersion,d.setUint32(p,l,!0),p+=ob.jsonLength,d.setUint32(p,s,!0),p+=ob.binaryLength,d.setUint32(p,t,!0),p+=ob.fromServiceId,d.setUint32(p,n,!0),p+=ob.toServiceId,d.setBigInt64(p,BigInt(f),!0),p+=ob.sentAt,h.set(c,p),p+=l,o&&s&&h.set(new Uint8Array(o),p),u},decodeHeader:e=>{const t=new DataView(e);let n=0,r="";for(let e=0;e<ob.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==vb)return null;if(e.byteLength<ab)return wb.log(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const i=t.getUint8(n);n+=ob.protocolVersion;const o=t.getUint32(n,!0);n+=ob.jsonLength;const s=t.getUint32(n,!0);n+=ob.binaryLength;const a=t.getUint32(n,!0);n+=ob.fromServiceId;const c=t.getUint32(n,!0);n+=ob.toServiceId;const l=t.getBigInt64(n,!0);n+=ob.sentAt;const u=o+s,d=e.slice(n,n+u),h=new Uint8Array(e,0,ab);let f=null;return e.byteLength-ab-o-s>0&&(f=new Uint8Array(e,ab+o+s).slice().buffer),{header:{protocolVersion:i,jsonLength:o,binaryLength:s,fromServiceId:a,toServiceId:c,sentAt:new Date(Number(l)),packages:[d],headerPackage:h.slice().buffer},remaining:f}},decodeFullKlMessage:e=>{const t=e.packages.reduce(((e,t)=>e+t.byteLength),0),n=new Uint8Array(t);let r,i=0;for(const t of e.packages)r=new Uint8Array(t),n.set(r,i),i+=r.byteLength;const o=(new TextDecoder).decode(n.subarray(0,e.jsonLength)),s=n.subarray(e.jsonLength,e.jsonLength+e.binaryLength),a=rb(o);if(!a?.json)return wb.log("Invalid JSON in KL message"),null;a.jsonBinaryMap&&s.byteLength&&hb(a.json,s,a.jsonBinaryMap);const c=new Uint8Array(e.headerPackage.byteLength+n.byteLength);c.set(new Uint8Array(e.headerPackage),0),c.set(n,e.headerPackage.byteLength);let l=c,u=null;const d=ab+e.jsonLength+e.binaryLength;return c.byteLength>d&&(u=c.subarray(d),l=c.subarray(0,d)),{message:{json:a.json,...s.length?{binaryData:s.buffer}:{},rawMessage:l.buffer},remaining:u?.buffer??null}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<ab)return wb("Invalid Header Size"),e;let n=0;n+=ob.protocolPrefix,n+=ob.protocolVersion,n+=ob.jsonLength,n+=ob.binaryLength;const r=new DataView(e);return void 0!==t.fromServiceId&&r.setUint32(n,t.fromServiceId,!0),n+=ob.fromServiceId,void 0!==t.toServiceId&&r.setUint32(n,t.toServiceId,!0),e},encodeCommand:e=>{let t=0;const n=Sb.encode(e),r=n.byteLength,i=new ArrayBuffer(cb+r),o=new DataView(i),s=new Uint8Array(i);for(let e=0;e<4;++e)s[t++]=bb.charCodeAt(e);return o.setUint32(t,r,!0),t+=sb.txtLength,s.set(n,t),i},decodeCommand:e=>{const t=new DataView(e);let n=0;if(e.byteLength<cb)return{command:null};let r="";for(let e=0;e<sb.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==bb)return{command:null};const i=t.getUint32(n,!0);n+=sb.txtLength;const o=e.byteLength-cb-i,s=new Uint8Array(e,n,Math.min(i,e.byteLength-cb)),a=(new TextDecoder).decode(s);let c=null;o>0&&(c=e.slice(cb+i));let l=0;return o<0&&(l=Math.abs(o)),{command:a,remainingData:c,missing:l}}};const Ib=fb("klTransmissionManager"),xb=()=>{const e=(t,n,r,i)=>{let o=n,s=null;const a=t instanceof ArrayBuffer;if(Ib(`RAW: ${t.toString()}`),!o||o.partialHeaderData){let c;if(a?(c=o?.partialHeaderData?new Uint8Array([...new Uint8Array(o.partialHeaderData),...new Uint8Array(t)]).buffer:t,s=_b.decodeHeader(c)):(c=o?.partialHeaderData?Buffer.concat([o.partialHeaderData,t]):t,s=yb.decodeHeader(c)),!s){const{command:t,missing:o,remainingData:s}=a?_b.decodeCommand(c):yb.decodeCommand(c);return t?i({command:t,complete:!0,rawMessage:c}):Ib(o?`ERROR: Missing ${o} bytes to complete the command. This partial command will be aborted.`:`ERROR: Invalid state, message was decoded without a header or partial header data. Discarding ${c.byteLength} bytes`),s?(Ib(`${s.byteLength} bytes remain after processing command. Re-analyzing...`),e(s,n,r,i)):void 0}if(s.partialHeader)return o={firstPackageAt:Date.now(),partialHeaderData:c},r(o);if(!s.header)return Ib(`ERROR: Invalid state, message was decoded without a header or partial header data. Discarding ${c.byteLength} bytes`);const l=s.header;o={firstPackageAt:Date.now(),header:{...l,totalBytesReceived:l.packages[0].byteLength,totalBytesExpected:l.binaryLength+l.jsonLength,remaining:s.remaining}},r(o)}else o.header&&o.header.totalBytesReceived<o.header.totalBytesExpected&&(o.header.packages.push(t),o.header.totalBytesReceived+=t.byteLength,r(o));if(o.header&&o.header.totalBytesReceived>=o.header.totalBytesExpected){const t=Date.now()-o.header.sentAt.getTime(),n=Date.now()-o.firstPackageAt;Ib(`Received ${o.header.totalBytesReceived} of ${o.header.totalBytesExpected} expected in ${t} ms, elapsed since first package: ${n}ms`);const s=a?_b.decodeFullKlMessage(o.header):yb.decodeFullKlMessage(o.header),c=o.header.totalBytesReceived,l=o.header.remaining;r(null),s&&i({klMessage:s.message,complete:!0,sourceServiceId:o.header.fromServiceId,targetServiceId:o.header.toServiceId,rawMessage:s.message.rawMessage});let u=l;if(s?.remaining&&(u=a?l?((e,t)=>{const n=e.byteLength+t.byteLength,r=new ArrayBuffer(n),i=new Uint8Array(e),o=new Uint8Array(t),s=new Uint8Array(r);return s.set(i),s.set(o,i.length),r})(l,s.remaining):s.remaining:l?Buffer.concat([l,s.remaining]):s.remaining),u)return Ib(`${u.byteLength} bytes remaining after processing message with ${c} bytes of data. Re-analyzing...`),e(u,null,r,i)}};return e};tb.config={...tb.config,id:"widgets",retry:1500,silent:!0,rawBuffer:!0,appspace:"kemu.",encoding:"hex"};const kb={info:_d("ipcServer:info"),data:_d("ipcServer:data")};let Eb,Cb,$b,Ob,Nb={};const Tb=xb(),Ab=e=>{Nb[e]&&(kb.info(`Client disconnected [${e}]`),delete Nb[e],Cb&&Cb(e))};var Mb=(e,t)=>{const n=Nb[e];if(!n)return kb.info(`Cannot send message to unknown client [${e}]`),!1;if(t.length>=nb)return kb.info("Message is too long to be a command. Use sendMessage instead."),!1;const r=yb.encodeCommand(t);return n.socket.write(r),!0},Pb=(e,t)=>{const n=Nb[e];return!!n&&(kb.info(`Renaming socket id [${e}] to [${t}]`),delete Nb[e],n.socket.id=t,Nb[t]=n,n.socket.removeListener("close",n.disconnectHandler),n.disconnectHandler=()=>Ab(t),n.socket.on("close",n.disconnectHandler),!0)};let Db=yb;ib&&(Db=_b);var jb,Rb=Db;!function(e){e.FunctionNotFound="FNC_NOT_FOUND",e.FunctionNotAllowed="FNC_NOT_ALLOWED",e.ParentEventCallbackError="PARENT_EVENT_CALLBACK_ERROR"}(jb||(jb={}));let Lb=Math.ceil(Date.now()/1e3);var Fb={exports:{}};const Ub=["nodebuffer","arraybuffer","fragments"],Bb="undefined"!=typeof Blob;Bb&&Ub.push("blob");var Wb={BINARY_TYPES:Ub,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Bb,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}};const{EMPTY_BUFFER:Gb}=Wb,Vb=Buffer[Symbol.species];function Yb(e,t,n,r,i){for(let o=0;o<i;o++)n[r+o]=e[o]^t[3&o]}function Hb(e,t){for(let n=0;n<e.length;n++)e[n]^=t[3&n]}if(Fb.exports={concat:function(e,t){if(0===e.length)return Gb;if(1===e.length)return e[0];const n=Buffer.allocUnsafe(t);let r=0;for(let t=0;t<e.length;t++){const i=e[t];n.set(i,r),r+=i.length}return r<t?new Vb(n.buffer,n.byteOffset,r):n},mask:Yb,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 Vb(t):ArrayBuffer.isView(t)?n=new Vb(t.buffer,t.byteOffset,t.byteLength):(n=Buffer.from(t),e.readOnly=!1),n},unmask:Hb},!process.env.WS_NO_BUFFER_UTIL)try{const e=require("bufferutil");Fb.exports.mask=function(t,n,r,i,o){o<48?Yb(t,n,r,i,o):e.mask(t,n,r,i,o)},Fb.exports.unmask=function(t,n){t.length<32?Hb(t,n):e.unmask(t,n)}}catch(b){}var zb=Fb.exports;const qb=Symbol("kDone"),Kb=Symbol("kRun"),Jb=A,Zb=zb,Xb=class{constructor(e){this[qb]=()=>{this.pending--,this[Kb]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Kb]()}[Kb](){if(this.pending!==this.concurrency&&this.jobs.length){const e=this.jobs.shift();this.pending++,e(this[qb])}}},{kStatusCode:Qb}=Wb,ew=Buffer[Symbol.species],tw=Buffer.from([0,0,255,255]),nw=Symbol("permessage-deflate"),rw=Symbol("total-length"),iw=Symbol("callback"),ow=Symbol("buffers"),sw=Symbol("error");let aw;var cw=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,!aw){const e=void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10;aw=new Xb(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[iw];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){aw.add((r=>{this._decompress(e,t,((e,t)=>{r(),n(e,t)}))}))}compress(e,t,n){aw.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]?Jb.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=Jb.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[nw]=this,this._inflate[rw]=0,this._inflate[ow]=[],this._inflate.on("error",dw),this._inflate.on("data",uw)}this._inflate[iw]=n,this._inflate.write(e),t&&this._inflate.write(tw),this._inflate.flush((()=>{const e=this._inflate[sw];if(e)return this._inflate.close(),this._inflate=null,void n(e);const i=Zb.concat(this._inflate[ow],this._inflate[rw]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[rw]=0,this._inflate[ow]=[],t&&this.params[`${r}_no_context_takeover`]&&this._inflate.reset()),n(null,i)}))}_compress(e,t,n){const r=this._isServer?"server":"client";if(!this._deflate){const e=`${r}_max_window_bits`,t="number"!=typeof this.params[e]?Jb.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=Jb.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[rw]=0,this._deflate[ow]=[],this._deflate.on("data",lw)}this._deflate[iw]=n,this._deflate.write(e),this._deflate.flush(Jb.Z_SYNC_FLUSH,(()=>{if(!this._deflate)return;let e=Zb.concat(this._deflate[ow],this._deflate[rw]);t&&(e=new ew(e.buffer,e.byteOffset,e.length-4)),this._deflate[iw]=null,this._deflate[rw]=0,this._deflate[ow]=[],t&&this.params[`${r}_no_context_takeover`]&&this._deflate.reset(),n(null,e)}))}};function lw(e){this[ow].push(e),this[rw]+=e.length}function uw(e){this[rw]+=e.length,this[nw]._maxPayload<1||this[rw]<=this[nw]._maxPayload?this[ow].push(e):(this[sw]=new RangeError("Max payload size exceeded"),this[sw].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[sw][Qb]=1009,this.removeListener("data",uw),this.reset())}function dw(e){this[nw]._inflate=null,e[Qb]=1007,this[iw](e)}var hw={exports:{}};const{isUtf8:fw}=N,{hasBlob:pw}=Wb;function gw(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(hw.exports={isBlob:function(e){return pw&&"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:gw,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]},fw)hw.exports.isValidUTF8=function(e){return e.length<24?gw(e):fw(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{const e=require("utf-8-validate");hw.exports.isValidUTF8=function(t){return t.length<32?gw(t):e(t)}}catch(b){}var mw=hw.exports;const{Writable:yw}=O,vw=cw,{BINARY_TYPES:bw,EMPTY_BUFFER:ww,kStatusCode:Sw,kWebSocket:_w}=Wb,{concat:Iw,toArrayBuffer:xw,unmask:kw}=zb,{isValidStatusCode:Ew,isValidUTF8:Cw}=mw,$w=Buffer[Symbol.species];const{randomFillSync:Ow}=j,Nw=cw,{EMPTY_BUFFER:Tw,kWebSocket:Aw,NOOP:Mw}=Wb,{isBlob:Pw,isValidStatusCode:Dw}=mw,{mask:jw,toBuffer:Rw}=zb,Lw=Symbol("kByteLength"),Fw=Buffer.alloc(4),Uw=8192;let Bw,Ww=Uw;function Gw(e,t,n){"function"==typeof n&&n(t);for(let n=0;n<e._queue.length;n++){const r=e._queue[n],i=r[r.length-1];"function"==typeof i&&i(t)}}function Vw(e,t,n){Gw(e,t,n),e.onerror(t)}const{kForOnEventAttribute:Yw,kListener:Hw}=Wb,zw=Symbol("kCode"),qw=Symbol("kData"),Kw=Symbol("kError"),Jw=Symbol("kMessage"),Zw=Symbol("kReason"),Xw=Symbol("kTarget"),Qw=Symbol("kType"),eS=Symbol("kWasClean");class tS{constructor(e){this[Xw]=null,this[Qw]=e}get target(){return this[Xw]}get type(){return this[Qw]}}Object.defineProperty(tS.prototype,"target",{enumerable:!0}),Object.defineProperty(tS.prototype,"type",{enumerable:!0});class nS extends tS{constructor(e,t={}){super(e),this[zw]=void 0===t.code?0:t.code,this[Zw]=void 0===t.reason?"":t.reason,this[eS]=void 0!==t.wasClean&&t.wasClean}get code(){return this[zw]}get reason(){return this[Zw]}get wasClean(){return this[eS]}}Object.defineProperty(nS.prototype,"code",{enumerable:!0}),Object.defineProperty(nS.prototype,"reason",{enumerable:!0}),Object.defineProperty(nS.prototype,"wasClean",{enumerable:!0});class rS extends tS{constructor(e,t={}){super(e),this[Kw]=void 0===t.error?null:t.error,this[Jw]=void 0===t.message?"":t.message}get error(){return this[Kw]}get message(){return this[Jw]}}Object.defineProperty(rS.prototype,"error",{enumerable:!0}),Object.defineProperty(rS.prototype,"message",{enumerable:!0});class iS extends tS{constructor(e,t={}){super(e),this[qw]=void 0===t.data?null:t.data}get data(){return this[qw]}}Object.defineProperty(iS.prototype,"data",{enumerable:!0});const oS={addEventListener(e,t,n={}){for(const r of this.listeners(e))if(!n[Yw]&&r[Hw]===t&&!r[Yw])return;let r;if("message"===e)r=function(e,n){const r=new iS("message",{data:n?e:e.toString()});r[Xw]=this,aS(t,this,r)};else if("close"===e)r=function(e,n){const r=new nS("close",{code:e,reason:n.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[Xw]=this,aS(t,this,r)};else if("error"===e)r=function(e){const n=new rS("error",{error:e,message:e.message});n[Xw]=this,aS(t,this,n)};else{if("open"!==e)return;r=function(){const e=new tS("open");e[Xw]=this,aS(t,this,e)}}r[Yw]=!!n[Yw],r[Hw]=t,n.once?this.once(e,r):this.on(e,r)},removeEventListener(e,t){for(const n of this.listeners(e))if(n[Hw]===t&&!n[Yw]){this.removeListener(e,n);break}}};var sS={CloseEvent:nS,ErrorEvent:rS,Event:tS,EventTarget:oS,MessageEvent:iS};function aS(e,t,n){"object"==typeof e&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}const{tokenChars:cS}=mw;function lS(e,t,n){void 0===e[t]?e[t]=[n]:e[t].push(n)}var uS={format:function(e){return Object.keys(e).map((t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map((e=>[t].concat(Object.keys(e).map((t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map((e=>!0===e?t:`${t}=${e}`)).join("; ")}))).join("; "))).join(", ")})).join(", ")},parse:function(e){const t=Object.create(null);let n,r,i=Object.create(null),o=!1,s=!1,a=!1,c=-1,l=-1,u=-1,d=0;for(;d<e.length;d++)if(l=e.charCodeAt(d),void 0===n)if(-1===u&&1===cS[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?(lS(t,r,i),i=Object.create(null)):n=r,c=u=-1}}else-1===u&&-1!==c&&(u=d);else if(void 0===r)if(-1===u&&1===cS[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),lS(i,e.slice(c,u),!0),44===l&&(lS(t,n,i),i=Object.create(null),n=void 0),c=u=-1}else{if(61!==l||-1===c||-1!==u)throw new SyntaxError(`Unexpected character at index ${d}`);r=e.slice(c,d),c=u=-1}else if(s){if(1!==cS[l])throw new SyntaxError(`Unexpected character at index ${d}`);-1===c?c=d:o||(o=!0),s=!1}else if(a)if(1===cS[l])-1===c&&(c=d);else if(34===l&&-1!==c)a=!1,u=d;else{if(92!==l)throw new SyntaxError(`Unexpected character at index ${d}`);s=!0}else if(34===l&&61===e.charCodeAt(d-1))a=!0;else if(-1===u&&1===cS[l])-1===c&&(c=d);else if(-1===c||32!==l&&9!==l){if(59!==l&&44!==l)throw new SyntaxError(`Unexpected character at index ${d}`);{if(-1===c)throw new SyntaxError(`Unexpected character at index ${d}`);-1===u&&(u=d);let s=e.slice(c,u);o&&(s=s.replace(/\\/g,""),o=!1),lS(i,r,s),44===l&&(lS(t,n,i),i=Object.create(null),n=void 0),r=void 0,c=u=-1}}else-1===u&&(u=d);if(-1===c||a||32===l||9===l)throw new SyntaxError("Unexpected end of input");-1===u&&(u=d);const h=e.slice(c,u);return void 0===n?lS(t,h,i):(void 0===r?lS(i,h,!0):lS(i,r,o?h.replace(/\\/g,""):h),lS(t,n,i)),t}};const dS=T,hS=D,fS=P,pS=L,gS=F,{randomBytes:mS,createHash:yS}=j,{URL:vS}=B,bS=cw,wS=class extends yw{constructor(e={}){super(),this._allowSynchronousEvents=void 0===e.allowSynchronousEvents||e.allowSynchronousEvents,this._binaryType=e.binaryType||bw[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=0|e.maxPayload,this._skipUTF8Validation=!!e.skipUTF8Validation,this[_w]=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 $w(t.buffer,t.byteOffset+e,t.length-e),new $w(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 $w(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[vw.extensionName]){if(this._fin=!(128&~t[0]),this._opcode=15&t[0],this._payloadLength=127&t[1],0===this._opcode){if(n)return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"));if(!this._fragmented)return void e(this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE"));this._opcode=this._fragmented}else if(1===this._opcode||2===this._opcode){if(this._fragmented)return void e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE"));this._compressed=n}else{if(!(this._opcode>7&&this._opcode<11))return void e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE"));if(!this._fin)return void e(this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN"));if(n)return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"));if(this._payloadLength>125||8===this._opcode&&1===this._payloadLength)return void e(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"))}if(this._fin||this._fragmented||(this._fragmented=this._opcode),this._masked=!(128&~t[1]),this._isServer){if(!this._masked)return void e(this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK"))}else if(this._masked)return void e(this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK"));126===this._payloadLength?this._state=1:127===this._payloadLength?this._state=2:this.haveLength(e)}else e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"))}getPayloadLength16(e){this._bufferedBytes<2?this._loop=!1:(this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e))}getPayloadLength64(e){if(this._bufferedBytes<8)return void(this._loop=!1);const t=this.consume(8),n=t.readUInt32BE(0);n>Math.pow(2,21)-1?e(this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH")):(this._payloadLength=n*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e))}haveLength(e){this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)?e(this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH")):this._masked?this._state=3:this._state=4}getMask(){this._bufferedBytes<4?this._loop=!1:(this._mask=this.consume(4),this._state=4)}getData(e){let t=ww;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]&&kw(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[vw.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?Iw(n,t):"arraybuffer"===this._binaryType?xw(Iw(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=Iw(n,t);if(!this._skipUTF8Validation&&!Cw(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,ww),this.end();else{const n=e.readUInt16BE(0);if(!Ew(n)){const e=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");return void t(e)}const r=new $w(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Cw(r)){const e=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");return void t(e)}this._loop=!1,this.emit("conclude",n,r),this.end()}this._state=0}}createError(e,t,n,r,i){this._loop=!1,this._errored=!0;const o=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(o,this.createError),o.code=i,o[Sw]=r,o}},SS=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=Mw,this[Aw]=void 0}static frame(e,t){let n,r,i=!1,o=2,s=!1;t.mask&&(n=t.maskBuffer||Fw,t.generateMask?t.generateMask(n):(Ww===Uw&&(void 0===Bw&&(Bw=Buffer.alloc(Uw)),Ow(Bw,0,Uw),Ww=0),n[0]=Bw[Ww++],n[1]=Bw[Ww++],n[2]=Bw[Ww++],n[3]=Bw[Ww++]),s=!(n[0]|n[1]|n[2]|n[3]),o=6),"string"==typeof e?r=t.mask&&!s||void 0===t[Lw]?(e=Buffer.from(e)).length:t[Lw]:(r=e.length,i=t.mask&&t.readOnly&&!s);let a=r;r>=65536?(o+=8,a=127):r>125&&(o+=2,a=126);const c=Buffer.allocUnsafe(i?r+o:o);return c[0]=t.fin?128|t.opcode:t.opcode,t.rsv1&&(c[0]|=64),c[1]=a,126===a?c.writeUInt16BE(r,2):127===a&&(c[2]=c[3]=0,c.writeUIntBE(r,4,6)),t.mask?(c[1]|=128,c[o-4]=n[0],c[o-3]=n[1],c[o-2]=n[2],c[o-1]=n[3],s?[c,e]:i?(jw(e,n,c,o,r),[c]):(jw(e,n,e,0,r),[c,e])):[c,e]}close(t,n,r,i){let o;if(void 0===t)o=Tw;else{if("number"!=typeof t||!Dw(t))throw new TypeError("First argument must be a valid error code number");if(void 0!==n&&n.length){const e=Buffer.byteLength(n);if(e>123)throw new RangeError("The message must not be greater than 123 bytes");o=Buffer.allocUnsafe(2+e),o.writeUInt16BE(t,0),"string"==typeof n?o.write(n,2):o.set(n,2)}else o=Buffer.allocUnsafe(2),o.writeUInt16BE(t,0)}const s={[Lw]:o.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};0!==this._state?this.enqueue([this.dispatch,o,!1,s,i]):this.sendFrame(e.frame(o,s),i)}ping(t,n,r){let i,o;if("string"==typeof t?(i=Buffer.byteLength(t),o=!1):Pw(t)?(i=t.size,o=!1):(i=(t=Rw(t)).length,o=Rw.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");const s={[Lw]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:o,rsv1:!1};Pw(t)?0!==this._state?this.enqueue([this.getBlobData,t,!1,s,r]):this.getBlobData(t,!1,s,r):0!==this._state?this.enqueue([this.dispatch,t,!1,s,r]):this.sendFrame(e.frame(t,s),r)}pong(t,n,r){let i,o;if("string"==typeof t?(i=Buffer.byteLength(t),o=!1):Pw(t)?(i=t.size,o=!1):(i=(t=Rw(t)).length,o=Rw.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");const s={[Lw]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:o,rsv1:!1};Pw(t)?0!==this._state?this.enqueue([this.getBlobData,t,!1,s,r]):this.getBlobData(t,!1,s,r):0!==this._state?this.enqueue([this.dispatch,t,!1,s,r]):this.sendFrame(e.frame(t,s),r)}send(e,t,n){const r=this._extensions[Nw.extensionName];let i,o,s=t.binary?2:1,a=t.compress;"string"==typeof e?(i=Buffer.byteLength(e),o=!1):Pw(e)?(i=e.size,o=!1):(i=(e=Rw(e)).length,o=Rw.readOnly),this._firstFragment?(this._firstFragment=!1,a&&r&&r.params[r._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(a=i>=r._threshold),this._compress=a):(a=!1,s=0),t.fin&&(this._firstFragment=!0);const c={[Lw]:i,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:s,readOnly:o,rsv1:a};Pw(e)?0!==this._state?this.enqueue([this.getBlobData,e,this._compress,c,n]):this.getBlobData(e,this._compress,c,n):0!==this._state?this.enqueue([this.dispatch,e,this._compress,c,n]):this.dispatch(e,this._compress,c,n)}getBlobData(t,n,r,i){this._bufferedBytes+=r[Lw],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(Gw,this,e,i)}this._bufferedBytes-=r[Lw];const o=Rw(t);n?this.dispatch(o,n,r,i):(this._state=0,this.sendFrame(e.frame(o,r),i),this.dequeue())})).catch((e=>{process.nextTick(Vw,this,e,i)}))}dispatch(t,n,r,i){if(!n)return void this.sendFrame(e.frame(t,r),i);const o=this._extensions[Nw.extensionName];this._bufferedBytes+=r[Lw],this._state=1,o.compress(t,r.fin,((t,n)=>{this._socket.destroyed?Gw(this,new Error("The socket was closed while data was being compressed"),i):(this._bufferedBytes-=r[Lw],this._state=0,r.readOnly=!1,this.sendFrame(e.frame(n,r),i),this.dequeue())}))}dequeue(){for(;0===this._state&&this._queue.length;){const e=this._queue.shift();this._bufferedBytes-=e[3][Lw],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Lw],this._queue.push(e)}sendFrame(e,t){2===e.length?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}},{isBlob:_S}=mw,{BINARY_TYPES:IS,EMPTY_BUFFER:xS,GUID:kS,kForOnEventAttribute:ES,kListener:CS,kStatusCode:$S,kWebSocket:OS,NOOP:NS}=Wb,{EventTarget:{addEventListener:TS,removeEventListener:AS}}=sS,{format:MS,parse:PS}=uS,{toBuffer:DS}=zb,jS=3e4,RS=Symbol("kAborted"),LS=[8,13],FS=["CONNECTING","OPEN","CLOSING","CLOSED"],US=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;let BS=class e extends dS{constructor(t,n,r){super(),this._binaryType=IS[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=xS,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]),GS(this,t,n,r)):(this._autoPong=r.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){IS.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,n,r){const i=new wS({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),o=new SS(t,this._extensions,r.generateMask);this._receiver=i,this._sender=o,this._socket=t,i[OS]=this,o[OS]=this,t[OS]=this,i.on("conclude",KS),i.on("drain",JS),i.on("error",ZS),i.on("message",QS),i.on("ping",e_),i.on("pong",t_),o.onerror=r_,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on("close",o_),t.on("data",s_),t.on("end",a_),t.on("error",c_),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[bS.extensionName]&&this._extensions[bS.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())})),i_(this)):this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();else{const e="WebSocket was closed before the connection was established";zS(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||xS,n,r)):qS(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||xS,n,r)):qS(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 qS(this,t,r);const i={binary:"string"!=typeof t,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[bS.extensionName]||(i.compress=!1),this._sender.send(t||xS,i,r)}terminate(){if(this.readyState!==e.CLOSED)if(this.readyState!==e.CONNECTING)this._socket&&(this._readyState=e.CLOSING,this._socket.destroy());else{const e="WebSocket was closed before the connection was established";zS(this,this._req,e)}}};Object.defineProperty(BS,"CONNECTING",{enumerable:!0,value:FS.indexOf("CONNECTING")}),Object.defineProperty(BS.prototype,"CONNECTING",{enumerable:!0,value:FS.indexOf("CONNECTING")}),Object.defineProperty(BS,"OPEN",{enumerable:!0,value:FS.indexOf("OPEN")}),Object.defineProperty(BS.prototype,"OPEN",{enumerable:!0,value:FS.indexOf("OPEN")}),Object.defineProperty(BS,"CLOSING",{enumerable:!0,value:FS.indexOf("CLOSING")}),Object.defineProperty(BS.prototype,"CLOSING",{enumerable:!0,value:FS.indexOf("CLOSING")}),Object.defineProperty(BS,"CLOSED",{enumerable:!0,value:FS.indexOf("CLOSED")}),Object.defineProperty(BS.prototype,"CLOSED",{enumerable:!0,value:FS.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((e=>{Object.defineProperty(BS.prototype,e,{enumerable:!0})})),["open","error","close","message"].forEach((e=>{Object.defineProperty(BS.prototype,`on${e}`,{enumerable:!0,get(){for(const t of this.listeners(e))if(t[ES])return t[CS];return null},set(t){for(const t of this.listeners(e))if(t[ES]){this.removeListener(e,t);break}"function"==typeof t&&this.addEventListener(e,t,{[ES]:!0})}})})),BS.prototype.addEventListener=TS,BS.prototype.removeEventListener=AS;var WS=BS;function GS(e,t,n,r){const i={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:LS[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(e._autoPong=i.autoPong,!LS.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${LS.join(", ")})`);let o;if(t instanceof vS)o=t;else try{o=new vS(t)}catch(e){throw new SyntaxError(`Invalid URL: ${t}`)}"http:"===o.protocol?o.protocol="ws:":"https:"===o.protocol&&(o.protocol="wss:"),e._url=o.href;const s="wss:"===o.protocol,a="ws+unix:"===o.protocol;let c;if("ws:"===o.protocol||s||a?a&&!o.pathname?c="The URL's pathname is empty":o.hash&&(c="The URL contains a fragment identifier"):c='The URL\'s protocol must be one of "ws:", "wss:", "http:", "https", or "ws+unix:"',c){const t=new SyntaxError(c);if(0===e._redirects)throw t;return void VS(e,t)}const l=s?443:80,u=mS(16).toString("base64"),d=s?hS.request:fS.request,h=new Set;let f,p;if(i.createConnection=i.createConnection||(s?HS:YS),i.defaultPort=i.defaultPort||l,i.port=o.port||l,i.host=o.hostname.startsWith("[")?o.hostname.slice(1,-1):o.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":u,Connection:"Upgrade",Upgrade:"websocket"},i.path=o.pathname+o.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(f=new bS(!0!==i.perMessageDeflate?i.perMessageDeflate:{},!1,i.maxPayload),i.headers["Sec-WebSocket-Extensions"]=MS({[bS.extensionName]:f.offer()})),n.length){for(const e of n){if("string"!=typeof e||!US.test(e)||h.has(e))throw new SyntaxError("An invalid or duplicated subprotocol was specified");h.add(e)}i.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(i.origin&&(i.protocolVersion<13?i.headers["Sec-WebSocket-Origin"]=i.origin:i.headers.Origin=i.origin),(o.username||o.password)&&(i.auth=`${o.username}:${o.password}`),a){const e=i.path.split(":");i.socketPath=e[0],i.path=e[1]}if(i.followRedirects){if(0===e._redirects){e._originalIpc=a,e._originalSecure=s,e._originalHostOrSocketPath=a?i.socketPath:o.host;const t=r&&r.headers;if(r={...r,headers:{}},t)for(const[e,n]of Object.entries(t))r.headers[e.toLowerCase()]=n}else if(0===e.listenerCount("redirect")){const t=a?!!e._originalIpc&&i.socketPath===e._originalHostOrSocketPath:!e._originalIpc&&o.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!s)&&(delete i.headers.authorization,delete i.headers.cookie,t||delete i.headers.host,i.auth=void 0)}i.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(i.auth).toString("base64")),p=e._req=d(i),e._redirects&&e.emit("redirect",e.url,p)}else p=e._req=d(i);i.timeout&&p.on("timeout",(()=>{zS(e,p,"Opening handshake has timed out")})),p.on("error",(t=>{null===p||p[RS]||(p=e._req=null,VS(e,t))})),p.on("response",(o=>{const s=o.headers.location,a=o.statusCode;if(s&&i.followRedirects&&a>=300&&a<400){if(++e._redirects>i.maxRedirects)return void zS(e,p,"Maximum redirects exceeded");let o;p.abort();try{o=new vS(s,t)}catch(t){const n=new SyntaxError(`Invalid URL: ${s}`);return void VS(e,n)}GS(e,o,n,r)}else e.emit("unexpected-response",p,o)||zS(e,p,`Unexpected server response: ${o.statusCode}`)})),p.on("upgrade",((t,n,r)=>{if(e.emit("upgrade",t),e.readyState!==BS.CONNECTING)return;p=e._req=null;const o=t.headers.upgrade;if(void 0===o||"websocket"!==o.toLowerCase())return void zS(e,n,"Invalid Upgrade header");const s=yS("sha1").update(u+kS).digest("base64");if(t.headers["sec-websocket-accept"]!==s)return void zS(e,n,"Invalid Sec-WebSocket-Accept header");const a=t.headers["sec-websocket-protocol"];let c;if(void 0!==a?h.size?h.has(a)||(c="Server sent an invalid subprotocol"):c="Server sent a subprotocol but none was requested":h.size&&(c="Server sent no subprotocol"),c)return void zS(e,n,c);a&&(e._protocol=a);const l=t.headers["sec-websocket-extensions"];if(void 0!==l){if(!f)return void zS(e,n,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");let r;try{r=PS(l)}catch(t){return void zS(e,n,"Invalid Sec-WebSocket-Extensions header")}const i=Object.keys(r);if(1!==i.length||i[0]!==bS.extensionName)return void zS(e,n,"Server indicated an extension that was not requested");try{f.accept(r[bS.extensionName])}catch(t){return void zS(e,n,"Invalid Sec-WebSocket-Extensions header")}e._extensions[bS.extensionName]=f}e.setSocket(n,r,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})})),i.finishRequest?i.finishRequest(p,e):p.end()}function VS(e,t){e._readyState=BS.CLOSING,e._errorEmitted=!0,e.emit("error",t),e.emitClose()}function YS(e){return e.path=e.socketPath,pS.connect(e)}function HS(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=pS.isIP(e.host)?"":e.host),gS.connect(e)}function zS(e,t,n){e._readyState=BS.CLOSING;const r=new Error(n);Error.captureStackTrace(r,zS),t.setHeader?(t[RS]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(VS,e,r)):(t.destroy(r),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function qS(e,t,n){if(t){const n=_S(t)?t.size:DS(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){const t=new Error(`WebSocket is not open: readyState ${e.readyState} (${FS[e.readyState]})`);process.nextTick(n,t)}}function KS(e,t){const n=this[OS];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,void 0!==n._socket[OS]&&(n._socket.removeListener("data",s_),process.nextTick(n_,n._socket),1005===e?n.close():n.close(e,t))}function JS(){const e=this[OS];e.isPaused||e._socket.resume()}function ZS(e){const t=this[OS];void 0!==t._socket[OS]&&(t._socket.removeListener("data",s_),process.nextTick(n_,t._socket),t.close(e[$S])),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e))}function XS(){this[OS].emitClose()}function QS(e,t){this[OS].emit("message",e,t)}function e_(e){const t=this[OS];t._autoPong&&t.pong(e,!this._isServer,NS),t.emit("ping",e)}function t_(e){this[OS].emit("pong",e)}function n_(e){e.resume()}function r_(e){const t=this[OS];t.readyState!==BS.CLOSED&&(t.readyState===BS.OPEN&&(t._readyState=BS.CLOSING,i_(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e)))}function i_(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),jS)}function o_(){const e=this[OS];let t;this.removeListener("close",o_),this.removeListener("data",s_),this.removeListener("end",a_),e._readyState=BS.CLOSING,this._readableState.endEmitted||e._closeFrameReceived||e._receiver._writableState.errorEmitted||null===(t=e._socket.read())||e._receiver.write(t),e._receiver.end(),this[OS]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",XS),e._receiver.on("finish",XS))}function s_(e){this[OS]._receiver.write(e)||this.pause()}function a_(){const e=this[OS];e._readyState=BS.CLOSING,e._receiver.end(),this.end()}function c_(){const e=this[OS];this.removeListener("error",c_),this.on("error",NS),e&&(e._readyState=BS.CLOSING,this.destroy())}const{tokenChars:l_}=mw;var u_={parse:function(e){const t=new Set;let n=-1,r=-1,i=0;for(;i<e.length;i++){const o=e.charCodeAt(i);if(-1===r&&1===l_[o])-1===n&&(n=i);else if(0===i||32!==o&&9!==o){if(44!==o)throw new SyntaxError(`Unexpected character at index ${i}`);{if(-1===n)throw new SyntaxError(`Unexpected character at index ${i}`);-1===r&&(r=i);const o=e.slice(n,r);if(t.has(o))throw new SyntaxError(`The "${o}" subprotocol is duplicated`);t.add(o),n=r=-1}}else-1===r&&-1!==n&&(r=i)}if(-1===n||-1!==r)throw new SyntaxError("Unexpected end of input");const o=e.slice(n,i);if(t.has(o))throw new SyntaxError(`The "${o}" subprotocol is duplicated`);return t.add(o),t}};const d_=T,h_=P,{createHash:f_}=j,p_=uS,g_=cw,m_=u_,y_=WS,{GUID:v_,kWebSocket:b_}=Wb,w_=/^[+/0-9A-Za-z]{22}==$/;function S_(e){e._state=2,e.emit("close")}function __(){this.destroy()}function I_(e,t,n,r){n=n||h_.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} ${h_.STATUS_CODES[t]}\r\n`+Object.keys(r).map((e=>`${e}: ${r[e]}`)).join("\r\n")+"\r\n\r\n"+n)}function x_(e,t,n,r,i){if(e.listenerCount("wsClientError")){const r=new Error(i);Error.captureStackTrace(r,x_),e.emit("wsClientError",r,n,t)}else I_(n,r,i)}var k_=od(class extends d_{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:y_,...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=h_.createServer(((e,t)=>{const n=h_.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(S_,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(S_,this);else{const e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close((()=>{S_(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",__);const i=e.headers["sec-websocket-key"],o=e.headers.upgrade,s=+e.headers["sec-websocket-version"];if("GET"!==e.method)return void x_(this,e,t,405,"Invalid HTTP method");if(void 0===o||"websocket"!==o.toLowerCase())return void x_(this,e,t,400,"Invalid Upgrade header");if(void 0===i||!w_.test(i))return void x_(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");if(8!==s&&13!==s)return void x_(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header");if(!this.shouldHandle(e))return void I_(t,400);const a=e.headers["sec-websocket-protocol"];let c=new Set;if(void 0!==a)try{c=m_.parse(a)}catch(n){return void x_(this,e,t,400,"Invalid Sec-WebSocket-Protocol header")}const l=e.headers["sec-websocket-extensions"],u={};if(this.options.perMessageDeflate&&void 0!==l){const r=new g_(this.options.perMessageDeflate,!0,this.options.maxPayload);try{const e=p_.parse(l);e[g_.extensionName]&&(r.accept(e[g_.extensionName]),u[g_.extensionName]=r)}catch(n){return void x_(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header")}}if(this.options.verifyClient){const o={origin:e.headers[8===s?"sec-websocket-origin":"origin"],secure:!(!e.socket.authorized&&!e.socket.encrypted),req:e};if(2===this.options.verifyClient.length)return void this.options.verifyClient(o,((o,s,a,l)=>{if(!o)return I_(t,s||401,a,l);this.completeUpgrade(u,i,c,e,t,n,r)}));if(!this.options.verifyClient(o))return I_(t,401)}this.completeUpgrade(u,i,c,e,t,n,r)}completeUpgrade(e,t,n,r,i,o,s){if(!i.readable||!i.writable)return i.destroy();if(i[b_])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return I_(i,503);const a=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${f_("sha1").update(t+v_).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[g_.extensionName]){const t=e[g_.extensionName].params,n=p_.format({[g_.extensionName]:[t]});a.push(`Sec-WebSocket-Extensions: ${n}`),c._extensions=e}this.emit("headers",a,r),i.write(a.concat("\r\n").join("\r\n")),i.removeListener("error",__),c.setSocket(i,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(c),c.on("close",(()=>{this.clients.delete(c),this._shouldEmitClose&&!this.clients.size&&process.nextTick(S_,this)}))),s(c,r)}});const E_=_d("websocketServer"),C_={},$_=xb();let O_,N_,T_,A_,M_;const P_=["https://app.kemu.io","https://dev.kemu.io","https://stage.kemu.io","https://local.kemu.io:3003"],D_=e=>{const t=C_[e];t&&t.socket.close()};var j_=e=>{M_=new k_({port:e,maxPayload:1048576e3,verifyClient:(e,t)=>{const n=e.req.headers.origin;n&&P_.includes(n)?t(!0):t(!1,401,"Origin not allowed")}}),M_.on("connection",(e=>{const t=Fy();E_(`New client connected. Registered as "${t}"`),e.id=t,C_[t]={socket:e,activeMessage:null},O_&&O_(t),e.on("message",(t=>{if(t instanceof Buffer){const n=C_[e.id];$_(t,n.activeMessage,(e=>n.activeMessage=e),(t=>{if(!t.complete)return;const r=t=>{e.send(t),E_(`Writing ${t.byteLength} bytes to socket [${n.socket.id}]: ${t.toString()}`)},i=()=>{D_(n.socket.id)};if(t.command)return E_(`Received command from client [${n.socket.id}]: ${t.command}`),void(T_&&T_(n.socket.id,t.command,r,i));t.klMessage&&A_&&A_({send:r,terminateWebsocket:i,websocketId:n.socket.id,transmission:{sourceServiceId:t.sourceServiceId??-1,targetServiceId:t.targetServiceId??-1,rawMessage:t.rawMessage},json:t.klMessage.json})}))}})),e.on("close",(()=>{E_(`Client disconnected: ${e.id}`),N_&&N_(e.id),delete C_[e.id]})),e.on("error",(()=>{E_(`Error on client connection: ${e.id}`)}))})),console.log(`WebSocket server is running on port ${e}`)},R_=e=>{O_=e},L_=e=>{N_=e},F_=e=>{T_=e},U_=(e,t)=>{const n=C_[e];if(!n)return E_(`Cannot send message to unknown client [${e}]`),!1;if(t.length>=nb)return E_("Message is too long to be a command. Use sendMessage instead."),!1;const r=yb.encodeCommand(t);return n.socket.send(r),!0},B_=e=>A_=e,W_=D_;const G_=_d("stopService"),V_=async e=>{const t=e.args[0];if(!t)return e.reply({error:"No service name provided"});const n=_v.getAllServiceVersions(t);G_(`Stopping ${n.length} services with name: ${t}`);for(const e of n)await _v.stopService({serviceName:e.info.name,version:e.info.version});const r=n.map((e=>`${e.info.name}@${e.info.version}`));e.reply({success:[r]})},Y_=_d("removeService"),H_=async e=>{const t=e.args[0],n=e.args[1];if(!t)return e.reply({error:"No service name provided"});let r=_v.getAllServiceVersions(t);n&&(r=r.filter((e=>e.info.version===n))),Y_(`Removing ${r.length} service(s) with name: ${t}`);for(const e of r)await _v.uninstallService(e.info.name,e.info.version);const i=r.map((e=>`${e.info.name}@${e.info.version}`));e.reply({success:[i]})},z_=_d("launchService"),q_=async e=>{const t=e.args[0],n=e.args[1];if(!t)return e.reply({error:"No service name provided"});if(!n)return e.reply({error:"No service version provided"});const r=`${t}@${n}/dist`;try{const i=Xy();z_(`Loading service ${t}@${n} from ${i}`);const{errorMsg:o,service:s,errorCode:a}=await _v.loadAndLaunch(i,r,!1);if(o||"started"!==s?.status)return e.reply({error:`Failed to launch service ${t}@${n}: ${o||"error-not-provided"}`,errCode:a});const c=Date.now(),l=3e4,u=async()=>{const r=s.status;return"running"===r?(z_(`Service ${t}@${n} loaded and started`),e.reply({success:[]})):(z_(`Service ${t}@${n} not yet started, status: ${r}`),"stopped"===r||"error"===r?e.reply({error:`Error launching service: "${s.errorMsg||"failed to initiate"}"`}):Date.now()-c>l?e.reply({error:"Timeout waiting for service to start"}):(z_("Retrying in 1 second..."),void setTimeout(u,1e3)))};u()}catch(r){return z_(`Error loading service ${t}@${n}: ${r?.message||r}`),e.reply({error:r?.message||"There was an error loading the service"})}},K_=_d("getMatchingServices"),J_=async e=>{const t=e.args[0],n=[],r=[];K_(`Checking for matching services: ${t.map((e=>e.name)).join(", ")}`);for(const{name:e,version:i}of t){const t=_v.getMatchingService(e,i);t?n.push({name:e,version:i,installationPath:_v.getServiceRootDirectory(t)}):r.push({name:e,version:i})}K_(`Found ${n.length} available services and ${r.length} missing services.`),e.reply({success:[{available:n,missing:r}]})},Z_=_d("getSecretsValues");let X_;var Q_=async e=>{const t=e.args[0].services;if(!X_)throw new Error("getSecretValuesFn is not set. Please call setGetSecretValuesFunction before using this function.");Z_(`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 X_({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})},eI=e=>{X_=e};const tI=_d("getMappedSecrets");let nI;var rI=async e=>{const t=e.args[0].services;tI(`Getting mapped secrets for services: ${t.map((e=>`${e.name}@${e.version}`)).join(", ")}`);const n=await nI(t),r=[{services:t.map((e=>({name:e.name,version:e.version,secrets:n[e.name]||[]})))}];e.reply({success:r})};const iI=_d("getServiceContents"),oI=({reply:e,args:t})=>{const[n]=t;iI(`Received GetServiceContents request for service ${n.serviceName} v${n.version}`);const r=_v.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}]});iI(`Service ${n.serviceName} v${n.version} not found`),e({error:`Service ${n.serviceName} v${n.version} not found`})};let sI={globalApiKey:void 0,environment:"production"};const aI=()=>({...sI}),cI=_d("apis"),lI=()=>{const e=aI();if(!e.serviceUrl)throw new Error("Unknown server URL. Please call `edgeConfig.setEdgeConfig` before using the APIs.");return e.serviceUrl},uI=async(e,t,n={})=>{try{const r=await fetch(e,{method:"POST",body:JSON.stringify(t),headers:{...n}});return r.ok?{data:await r.json(),statusCode:r.status,success:!0}:{statusCode:r.status,error:await r.text(),success:!1}}catch(e){return{statusCode:500,error:e instanceof Error?e.message:"Internal server error",success:!1}}},dI={},hI=async e=>{const t=(e=>{const t=dI[e],n=Date.now()-(t?.lastCheckedAt.getTime()??0);return t&&n<3e5?t.features:null})(e);if(t)return{valid:!0,features:t,error:null};const{valid:n,features:r,error:i}=await(async e=>{const{data:t,error:n}=await uI(`${lI()}/v1/organization/validate/apiKey`,{apiKey:e},{"Content-Type":"application/json"});return n?(cI(`Error validating Kemu API key: ${n}`),{valid:!1,features:{},error:n}):t?.features?{valid:!0,features:t.features,error:null}:{valid:!1,features:{},error:"No features returned from the server"}})(e);return n&&(dI[e]={features:r,lastCheckedAt:new Date}),{valid:n,features:r,error:i}};function fI(e){return"number"==typeof e||!!/^0x[0-9a-f]+$/i.test(e)||/^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(e)}function pI(e,t){return"constructor"===t&&"function"==typeof e[t]||"__proto__"===t}var gI=od((function(e,t){t||(t={});var n={bools:{},strings:{},unknownFn:null};"function"==typeof t.unknown&&(n.unknownFn=t.unknown),"boolean"==typeof t.boolean&&t.boolean?n.allBools=!0:[].concat(t.boolean).filter(Boolean).forEach((function(e){n.bools[e]=!0}));var r={};function i(e){return r[e].some((function(e){return n.bools[e]}))}Object.keys(t.alias||{}).forEach((function(e){r[e]=[].concat(t.alias[e]),r[e].forEach((function(t){r[t]=[e].concat(r[e].filter((function(e){return t!==e})))}))})),[].concat(t.string).filter(Boolean).forEach((function(e){n.strings[e]=!0,r[e]&&[].concat(r[e]).forEach((function(e){n.strings[e]=!0}))}));var o=t.default||{},s={_:[]};function a(e,t,r){for(var i=e,o=0;o<t.length-1;o++){var s=t[o];if(pI(i,s))return;void 0===i[s]&&(i[s]={}),i[s]!==Object.prototype&&i[s]!==Number.prototype&&i[s]!==String.prototype||(i[s]={}),i[s]===Array.prototype&&(i[s]=[]),i=i[s]}var a=t[t.length-1];pI(i,a)||(i!==Object.prototype&&i!==Number.prototype&&i!==String.prototype||(i={}),i===Array.prototype&&(i=[]),void 0===i[a]||n.bools[a]||"boolean"==typeof i[a]?i[a]=r:Array.isArray(i[a])?i[a].push(r):i[a]=[i[a],r])}function c(e,t,i){if(!i||!n.unknownFn||function(e,t){return n.allBools&&/^--[^=]+$/.test(t)||n.strings[e]||n.bools[e]||r[e]}(e,i)||!1!==n.unknownFn(i)){var o=!n.strings[e]&&fI(t)?Number(t):t;a(s,e.split("."),o),(r[e]||[]).forEach((function(e){a(s,e.split("."),o)}))}}Object.keys(n.bools).forEach((function(e){c(e,void 0!==o[e]&&o[e])}));var l=[];-1!==e.indexOf("--")&&(l=e.slice(e.indexOf("--")+1),e=e.slice(0,e.indexOf("--")));for(var u=0;u<e.length;u++){var d,h,f=e[u];if(/^--.+=/.test(f)){var p=f.match(/^--([^=]+)=([\s\S]*)$/);d=p[1];var g=p[2];n.bools[d]&&(g="false"!==g),c(d,g,f)}else if(/^--no-.+/.test(f))c(d=f.match(/^--no-(.+)/)[1],!1,f);else if(/^--.+/.test(f))d=f.match(/^--(.+)/)[1],void 0===(h=e[u+1])||/^(-|--)[^-]/.test(h)||n.bools[d]||n.allBools||r[d]&&i(d)?/^(true|false)$/.test(h)?(c(d,"true"===h,f),u+=1):c(d,!n.strings[d]||"",f):(c(d,h,f),u+=1);else if(/^-[^-]+/.test(f)){for(var m=f.slice(1,-1).split(""),y=!1,v=0;v<m.length;v++)if("-"!==(h=f.slice(v+2))){if(/[A-Za-z]/.test(m[v])&&"="===h[0]){c(m[v],h.slice(1),f),y=!0;break}if(/[A-Za-z]/.test(m[v])&&/-?\d+(\.\d*)?(e-?\d+)?$/.test(h)){c(m[v],h,f),y=!0;break}if(m[v+1]&&m[v+1].match(/\W/)){c(m[v],f.slice(v+2),f),y=!0;break}c(m[v],!n.strings[m[v]]||"",f)}else c(m[v],h,f);d=f.slice(-1)[0],y||"-"===d||(!e[u+1]||/^(-|--)[^-]/.test(e[u+1])||n.bools[d]||r[d]&&i(d)?e[u+1]&&/^(true|false)$/.test(e[u+1])?(c(d,"true"===e[u+1],f),u+=1):c(d,!n.strings[d]||"",f):(c(d,e[u+1],f),u+=1))}else if(n.unknownFn&&!1===n.unknownFn(f)||s._.push(n.strings._||!fI(f)?f:Number(f)),t.stopEarly){s._.push.apply(s._,e.slice(u+1));break}}return Object.keys(o).forEach((function(e){var t,n,i;t=s,n=e.split("."),i=t,n.slice(0,-1).forEach((function(e){i=i[e]||{}})),n[n.length-1]in i||(a(s,e.split("."),o[e]),(r[e]||[]).forEach((function(t){a(s,t.split("."),o[e])})))})),t["--"]?s["--"]=l.slice():l.forEach((function(e){s._.push(e)})),s}));fb("ipcClient"),fb("kemuWidgetService"),gI(process.argv.slice(2));const mI=_d("activeClients");let yI,vI={},bI={};const wI=(e,t)=>`${e}_${t}`,SI=e=>vI[e]||null,_I=(e,t)=>{const n=wI(e,t);return bI[n]||[]},II=()=>{for(const e in vI){const t=vI[e];if(t?.transport===Uu.WS){const e=yb.encodeCommand(Ru.ServicesListChanged);t.send(e)}}},xI=async e=>{const t=[],{serviceSessionId:n,transport:r,send:i,terminateFn:o,extraInfo:s,isDevClient:a}=e,c=e=>{console.warn(e),o&&o()};if(r===Uu.WS){if(!s.user?.wsApiKey)return void c(`Attempted to register a WebSocket client without an API key. SessionId: ${n}`);const{valid:e,error:t}=await hI(s.user?.wsApiKey);if(!e&&!t)return void c(`Attempted to register a WebSocket client with an invalid API key. SessionId: ${n}`);t&&(s.user?.wsApiKey&&nv.captureError({error:new Error(t),message:`Error validating api key "${s.user?.wsApiKey}"`,data:s}),mI(`Unable to validate API Key, usage will be limited. SessionId: ${n}`))}vI[n]={serviceSessionId:n,transport:r,isDevClient:!!a,broadcastSubscriptions:t,send:i,extraInfo:s,terminate:()=>{o&&o()},addSubscription:e=>{if(!t.some((t=>t.targetService.serviceName===e.serviceName&&t.targetService.version===e.version))){t.push({targetService:e});const r=wI(e.serviceName,e.version);return bI[r]=bI[r]||[],bI[r].some((e=>e.serviceId===n))||bI[r].push({sendFn:i,serviceId:n}),!0}return!1},removeSubscription:e=>{const r=t.findIndex((t=>t.targetService.serviceName===e.serviceName));if(-1!==r){t.splice(r,1);const i=wI(e.serviceName,e.version),o=bI[i]?.findIndex((e=>e.serviceId===n));if(-1!==o&&(bI[i]?.splice(o,1),!bI[i]?.length)){const t=_v.getMatchingService(e.serviceName,e.version);if(t?.info.eventEmitter&&"running"===t.status){const e=SI(t.info.sessionId);e?.extraInfo.ipcSocketId&&Mb(e?.extraInfo.ipcSocketId,Ru.BroadcastEnd)}}}},removeAllSubscriptions:()=>{for(const e of t){const t=wI(e.targetService.serviceName,e.targetService.version),r=bI[t]?.findIndex((e=>e.serviceId===n));-1!==r&&bI[t]?.splice(r,1)}t.length=0}},r===Uu.IPC&&(II(),kI(n))},kI=e=>{const t=_v.getServiceBySessionId(e);if(t?.info.eventEmitter&&_I(t.info.name,t.info.version).length){const t=SI(e);t?.extraInfo.ipcSocketId&&Mb(t?.extraInfo.ipcSocketId,Ru.BroadcastStart)}},EI=e=>{const t=vI[e];var n;t?.transport===Uu.IPC?II():(t?.removeAllSubscriptions(),(()=>{const e=Object.values(vI);for(const t of e)if(t.transport===Uu.IPC){const e=t.extraInfo.ipcSocketId,n=_v.getServiceBySessionId(t.serviceSessionId);n?.info.eventEmitter&&(_I(n.info.name,n.info.version).length||e&&Mb(e,Ru.BroadcastEnd))}})(),t?.extraInfo.user?.wsApiKey&&(n=t.extraInfo.user.wsApiKey,delete dI[n]),(e=>{const t=vI[e];if(t?.transport===Uu.WS&&t.extraInfo.recipe){const n=[{recipe:t.extraInfo.recipe}];mI(`Notifying IPC clients that a Kemu Compose client [${t.extraInfo.recipe.name} (${t.extraInfo.recipe.poolId})] has disconnected. ServiceSessionId: ${e}`);for(const e in vI){const t=vI[e];t?.transport===Uu.IPC&&yI.execute(Lu.KemuComposerDisconnected,n,t.send,0,t.serviceSessionId,{async:!0}).catch((t=>{mI(`Error notifying IPC client [${e}] that a Kemu Compose client has disconnected: ${t?.message||t}`)}))}}})(e)),delete vI[e]},CI=_d("ipc:handleIpcClientCommand"),$I=(e,t,n)=>{const r=((e,t)=>{if(e.startsWith(Ru.AcknowledgeResponse)){const n=e.split(":"),r=parseInt(n[1]),i=parseInt(n[2]);return t&&t(r,isNaN(i)?void 0:i),!0}return!1})(t,((e,t)=>{if(!e)return void CI(`Ignoring ACK response from IPC service ${e} with no service id`);CI(`Received ACK from IPC service ${e}. Marking as running.`);let r=e;t&&e&&e!==t&&(Pb(e,t),r=t);let i=!1;t&&(i=_v.setServiceStatus(t,"running")),i?xI({serviceSessionId:t||e,transport:Uu.IPC,send:n,extraInfo:{ipcSocketId:t}}):Mb(r,Ru.SendManifest)}));!r&&CI(`Received unknown command [${t}] from service ${e}`)};let OI={};G.platform();const NI=async e=>{const t=e.args[0];if(OI.chooseDirectory)try{const n=await OI.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"})},TI=async e=>{const t=e.args[0];if(OI.chooseFile)try{const n=await OI.chooseFile(t);return e.reply({success:[String(n).trim()]})}catch(t){return console.error(t),e.reply({error:t instanceof Error?t.message:"Unknown error"})}return e.reply({error:"This hub does not support showing file dialogs",errCode:"GUI_NOT_SUPPORTED"})};var AI={},MI={},PI={};function DI(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`positive integer expected, not ${e}`)}function jI(e){if("boolean"!=typeof e)throw new Error(`boolean expected, not ${e}`)}function RI(e){return e instanceof Uint8Array||null!=e&&"object"==typeof e&&"Uint8Array"===e.constructor.name}function LI(e,...t){if(!RI(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 FI(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.wrapConstructor");DI(e.outputLen),DI(e.blockLen)}function UI(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 BI(e,t){LI(e);const n=t.outputLen;if(e.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}Object.defineProperty(PI,"__esModule",{value:!0}),PI.output=PI.exists=PI.hash=PI.bytes=PI.bool=PI.number=PI.isBytes=void 0,PI.number=DI,PI.bool=jI,PI.isBytes=RI,PI.bytes=LI,PI.hash=FI,PI.exists=UI,PI.output=BI;const WI={number:DI,bool:jI,bytes:LI,hash:FI,exists:UI,output:BI};PI.default=WI;var GI={};Object.defineProperty(GI,"__esModule",{value:!0}),GI.add5L=GI.add5H=GI.add4H=GI.add4L=GI.add3H=GI.add3L=GI.add=GI.rotlBL=GI.rotlBH=GI.rotlSL=GI.rotlSH=GI.rotr32L=GI.rotr32H=GI.rotrBL=GI.rotrBH=GI.rotrSL=GI.rotrSH=GI.shrSL=GI.shrSH=GI.toBig=GI.split=GI.fromBig=void 0;const VI=BigInt(2**32-1),YI=BigInt(32);function HI(e,t=!1){return t?{h:Number(e&VI),l:Number(e>>YI&VI)}:{h:0|Number(e>>YI&VI),l:0|Number(e&VI)}}function zI(e,t=!1){let n=new Uint32Array(e.length),r=new Uint32Array(e.length);for(let i=0;i<e.length;i++){const{h:o,l:s}=HI(e[i],t);[n[i],r[i]]=[o,s]}return[n,r]}GI.fromBig=HI,GI.split=zI;const qI=(e,t)=>BigInt(e>>>0)<<YI|BigInt(t>>>0);GI.toBig=qI;const KI=(e,t,n)=>e>>>n;GI.shrSH=KI;const JI=(e,t,n)=>e<<32-n|t>>>n;GI.shrSL=JI;const ZI=(e,t,n)=>e>>>n|t<<32-n;GI.rotrSH=ZI;const XI=(e,t,n)=>e<<32-n|t>>>n;GI.rotrSL=XI;const QI=(e,t,n)=>e<<64-n|t>>>n-32;GI.rotrBH=QI;const ex=(e,t,n)=>e>>>n-32|t<<64-n;GI.rotrBL=ex;const tx=(e,t)=>t;GI.rotr32H=tx;const nx=e=>e;GI.rotr32L=nx;const rx=(e,t,n)=>e<<n|t>>>32-n;GI.rotlSH=rx;const ix=(e,t,n)=>t<<n|e>>>32-n;GI.rotlSL=ix;const ox=(e,t,n)=>t<<n-32|e>>>64-n;GI.rotlBH=ox;const sx=(e,t,n)=>e<<n-32|t>>>64-n;function ax(e,t,n,r){const i=(t>>>0)+(r>>>0);return{h:e+n+(i/2**32|0)|0,l:0|i}}GI.rotlBL=sx,GI.add=ax;const cx=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0);GI.add3L=cx;const lx=(e,t,n,r)=>t+n+r+(e/2**32|0)|0;GI.add3H=lx;const ux=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0);GI.add4L=ux;const dx=(e,t,n,r,i)=>t+n+r+i+(e/2**32|0)|0;GI.add4H=dx;const hx=(e,t,n,r,i)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(i>>>0);GI.add5L=hx;const fx=(e,t,n,r,i,o)=>t+n+r+i+o+(e/2**32|0)|0;GI.add5H=fx;const px={fromBig:HI,split:zI,toBig:qI,shrSH:KI,shrSL:JI,rotrSH:ZI,rotrSL:XI,rotrBH:QI,rotrBL:ex,rotr32H:tx,rotr32L:nx,rotlSH:rx,rotlSL:ix,rotlBH:ox,rotlBL:sx,add:ax,add3L:cx,add3H:lx,add4L:ux,add4H:dx,add5H:fx,add5L:hx};GI.default=px;var gx={},mx={};Object.defineProperty(mx,"__esModule",{value:!0}),mx.crypto=void 0,mx.crypto="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0,function(e){
11
11
  /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
12
- Object.defineProperty(e,"__esModule",{value:!0}),e.randomBytes=e.wrapXOFConstructorWithOpts=e.wrapConstructorWithOpts=e.wrapConstructor=e.checkOpts=e.Hash=e.concatBytes=e.toBytes=e.utf8ToBytes=e.asyncLoop=e.nextTick=e.hexToBytes=e.bytesToHex=e.byteSwap32=e.byteSwapIfBE=e.byteSwap=e.isLE=e.rotl=e.rotr=e.createView=e.u32=e.u8=e.isBytes=void 0;const t=vx,n=jI;e.isBytes=function(e){return e instanceof Uint8Array||null!=e&&"object"==typeof e&&"Uint8Array"===e.constructor.name},e.u8=e=>new Uint8Array(e.buffer,e.byteOffset,e.byteLength),e.u32=e=>new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4)),e.createView=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),e.rotr=(e,t)=>e<<32-t|e>>>t,e.rotl=(e,t)=>e<<t|e>>>32-t>>>0,e.isLE=68===new Uint8Array(new Uint32Array([287454020]).buffer)[0],e.byteSwap=e=>e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255,e.byteSwapIfBE=e.isLE?e=>e:t=>(0,e.byteSwap)(t),e.byteSwap32=function(t){for(let n=0;n<t.length;n++)t[n]=(0,e.byteSwap)(t[n])};const r=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));e.bytesToHex=function(e){(0,n.bytes)(e);let t="";for(let n=0;n<e.length;n++)t+=r[e[n]];return t};const i=48,o=57,s=65,a=70,c=97,l=102;function u(e){return e>=i&&e<=o?e-i:e>=s&&e<=a?e-(s-10):e>=c&&e<=l?e-(c-10):void 0}function d(e){if("string"!=typeof e)throw new Error("utf8ToBytes expected string, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))}function h(e){return"string"==typeof e&&(e=d(e)),(0,n.bytes)(e),e}e.hexToBytes=function(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);const t=e.length,n=t/2;if(t%2)throw new Error("padded hex string expected, got unpadded hex of length "+t);const r=new Uint8Array(n);for(let t=0,i=0;t<n;t++,i+=2){const n=u(e.charCodeAt(i)),o=u(e.charCodeAt(i+1));if(void 0===n||void 0===o){const t=e[i]+e[i+1];throw new Error('hex string expected, got non-hex character "'+t+'" at index '+i)}r[t]=16*n+o}return r},e.nextTick=async()=>{},e.asyncLoop=async function(t,n,r){let i=Date.now();for(let o=0;o<t;o++){r(o);const t=Date.now()-i;t>=0&&t<n||(await(0,e.nextTick)(),i+=t)}},e.utf8ToBytes=d,e.toBytes=h,e.concatBytes=function(...e){let t=0;for(let r=0;r<e.length;r++){const i=e[r];(0,n.bytes)(i),t+=i.length}const r=new Uint8Array(t);for(let t=0,n=0;t<e.length;t++){const i=e[t];r.set(i,n),n+=i.length}return r},e.Hash=class{clone(){return this._cloneInto()}};const f={}.toString;e.checkOpts=function(e,t){if(void 0!==t&&"[object Object]"!==f.call(t))throw new Error("Options should be object or undefined");return Object.assign(e,t)},e.wrapConstructor=function(e){const t=t=>e().update(h(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t},e.wrapConstructorWithOpts=function(e){const t=(t,n)=>e(n).update(h(t)).digest(),n=e({});return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=t=>e(t),t},e.wrapXOFConstructorWithOpts=function(e){const t=(t,n)=>e(n).update(h(t)).digest(),n=e({});return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=t=>e(t),t},e.randomBytes=function(e=32){if(t.crypto&&"function"==typeof t.crypto.getRandomValues)return t.crypto.getRandomValues(new Uint8Array(e));throw new Error("crypto.getRandomValues must be defined")}}(yx),Object.defineProperty(DI,"__esModule",{value:!0}),DI.shake256=DI.shake128=DI.keccak_512=DI.keccak_384=DI.keccak_256=DI.keccak_224=DI.sha3_512=DI.sha3_384=DI.sha3_256=DI.sha3_224=DI.Keccak=DI.keccakP=void 0;const bx=jI,wx=YI,Sx=yx,_x=[],Ix=[],xx=[],kx=BigInt(0),Ex=BigInt(1),Cx=BigInt(2),$x=BigInt(7),Ox=BigInt(256),Nx=BigInt(113);for(let e=0,t=Ex,n=1,r=0;e<24;e++){[n,r]=[r,(2*n+3*r)%5],_x.push(2*(5*r+n)),Ix.push((e+1)*(e+2)/2%64);let i=kx;for(let e=0;e<7;e++)t=(t<<Ex^(t>>$x)*Nx)%Ox,t&Cx&&(i^=Ex<<(Ex<<BigInt(e))-Ex);xx.push(i)}const[Tx,Ax]=(0,wx.split)(xx,!0),Mx=(e,t,n)=>n>32?(0,wx.rotlBH)(e,t,n):(0,wx.rotlSH)(e,t,n),Px=(e,t,n)=>n>32?(0,wx.rotlBL)(e,t,n):(0,wx.rotlSL)(e,t,n);function Dx(e,t=24){const n=new Uint32Array(10);for(let r=24-t;r<24;r++){for(let t=0;t<10;t++)n[t]=e[t]^e[t+10]^e[t+20]^e[t+30]^e[t+40];for(let t=0;t<10;t+=2){const r=(t+8)%10,i=(t+2)%10,o=n[i],s=n[i+1],a=Mx(o,s,1)^n[r],c=Px(o,s,1)^n[r+1];for(let n=0;n<50;n+=10)e[t+n]^=a,e[t+n+1]^=c}let t=e[2],i=e[3];for(let n=0;n<24;n++){const r=Ix[n],o=Mx(t,i,r),s=Px(t,i,r),a=_x[n];t=e[a],i=e[a+1],e[a]=o,e[a+1]=s}for(let t=0;t<50;t+=10){for(let r=0;r<10;r++)n[r]=e[t+r];for(let r=0;r<10;r++)e[t+r]^=~n[(r+2)%10]&n[(r+4)%10]}e[0]^=Tx[r],e[1]^=Ax[r]}n.fill(0)}DI.keccakP=Dx;class jx extends Sx.Hash{constructor(e,t,n,r=!1,i=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=n,this.enableXOF=r,this.rounds=i,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,(0,bx.number)(n),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=(0,Sx.u32)(this.state)}keccak(){Sx.isLE||(0,Sx.byteSwap32)(this.state32),Dx(this.state32,this.rounds),Sx.isLE||(0,Sx.byteSwap32)(this.state32),this.posOut=0,this.pos=0}update(e){(0,bx.exists)(this);const{blockLen:t,state:n}=this,r=(e=(0,Sx.toBytes)(e)).length;for(let i=0;i<r;){const o=Math.min(t-this.pos,r-i);for(let t=0;t<o;t++)n[this.pos++]^=e[i++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:n,blockLen:r}=this;e[n]^=t,128&t&&n===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){(0,bx.exists)(this,!1),(0,bx.bytes)(e),this.finish();const t=this.state,{blockLen:n}=this;for(let r=0,i=e.length;r<i;){this.posOut>=n&&this.keccak();const o=Math.min(n-this.posOut,i-r);e.set(t.subarray(this.posOut,this.posOut+o),r),this.posOut+=o,r+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return(0,bx.number)(e),this.xofInto(new Uint8Array(e))}digestInto(e){if((0,bx.output)(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:t,suffix:n,outputLen:r,rounds:i,enableXOF:o}=this;return e||(e=new jx(t,n,r,o,i)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=n,e.outputLen=r,e.enableXOF=o,e.destroyed=this.destroyed,e}}DI.Keccak=jx;const Rx=(e,t,n)=>(0,Sx.wrapConstructor)((()=>new jx(t,e,n)));DI.sha3_224=Rx(6,144,28),DI.sha3_256=Rx(6,136,32),DI.sha3_384=Rx(6,104,48),DI.sha3_512=Rx(6,72,64),DI.keccak_224=Rx(1,144,28),DI.keccak_256=Rx(1,136,32),DI.keccak_384=Rx(1,104,48),DI.keccak_512=Rx(1,72,64);const Lx=(e,t,n)=>(0,Sx.wrapXOFConstructorWithOpts)(((r={})=>new jx(t,e,void 0===r.dkLen?n:r.dkLen,!0)));DI.shake128=Lx(31,168,16),DI.shake256=Lx(31,136,32);const{sha3_512:Fx}=DI,Ux=(e=4,t=Math.random)=>{let n="";for(;n.length<e;)n+=Math.floor(36*t()).toString(36);return n};function Bx(e){let t=0n;for(const n of e.values())t=(t<<8n)+BigInt(n);return t}const Wx=(e="")=>Bx(Fx(e)).toString(36).slice(1),Gx=Array.from({length:26},((e,t)=>String.fromCharCode(t+97))),Vx=({globalObj:e=(void 0!==sd?sd:"undefined"!=typeof window?window:{}),random:t=Math.random}={})=>{const n=Object.keys(e).toString(),r=n.length?n+Ux(32,t):Ux(32,t);return Wx(r).substring(0,32)},Yx=e=>()=>e++,Hx=({random:e=Math.random,counter:t=Yx(Math.floor(476782367*e())),length:n=24,fingerprint:r=Vx({random:e})}={})=>function(){const i=(e=>Gx[Math.floor(e()*Gx.length)])(e),o=Date.now().toString(36),s=t().toString(36),a=Ux(n,e);return`${i+Wx(`${o+a+s+r}`).substring(1,n)}`},zx=Hx();PI.getConstants=()=>({defaultLength:24,bigLength:32}),PI.init=Hx,PI.createId=zx,PI.bufToBigInt=Bx,PI.createCounter=Yx,PI.createFingerprint=Vx,PI.isCuid=(e,{minLength:t=2,maxLength:n=32}={})=>{const r=e.length,i=/^[0-9a-z]+$/;try{if("string"==typeof e&&r>=t&&r<=n&&i.test(e))return!0}finally{}return!1};const{createId:qx,init:Kx,getConstants:Jx,isCuid:Zx}=PI;var Xx=qx;const Qx=xd("getUniqueId"),ek=({reply:e,sourceServiceId:t})=>(Qx(`Generating unique id for service "${t}"`),e({success:[Xx()]})),tk=xd("getActiveServices"),nk=async({transport:e,sourceServiceId:t,reply:n})=>{if(tk(`Received GetServices request from ${e} [${t}]`),e===Wu.WS){let e=xv.getActiveServices();const r=II(t);if(!r)return n({error:"Client not found",errCode:"CLIENT_NOT_FOUND"});let i=[];if(r.transport===Wu.WS){if(!r?.extraInfo.user?.wsApiKey)return n({error:"Client does not have an API key",errCode:"CLIENT_NO_API_KEY"});const t=e.filter(xv.isInternalKemuService),o=e.filter((e=>e.devMode&&xv.isNotInternalKemuService(e))),s=e.filter((e=>xv.isOfficialKemuService(e)&&xv.isNotInternalKemuService(e)&&xv.isNotDevService(e))).sort(((e,t)=>e.name.localeCompare(t.name))),a=e.filter((e=>xv.isNotDevService(e)&&xv.isNotInternalKemuService(e)&&!xv.isOfficialKemuService(e))),c=await(async e=>{const{features:t}=await pI(e);return t})(r.extraInfo.user?.wsApiKey),l=c?.hub_services??0,u=s.slice(0,-1!==l?l:s.length);-1!==l&&(i=s.slice(l).map((e=>({name:e.name,version:e.version,svgIcon:e.svgIcon,color:e.color,description:e.description,title:e.title,shortTitle:e.shortTitle})))),e=[...t,...o,...u,...a]}const o=xv.getFailedServices().map((e=>({name:e.name,version:e.version,description:e.description,title:e.title,status:e.status,errorMsg:e.errorMsg,errorCode:e.errorCode,internal:xv.isInternalKemuService(e),svgIcon:e.svgIcon,color:e.color,shortTitle:e.shortTitle})));n({success:[{available:e.map((e=>{const{widgetUIContents:t,...n}=e;return{...n}})),failed:o,installed:i}]})}};let rk="runtime",ik=null;const ok=()=>rk,sk=xd("getSystemInfo"),ak=async({reply:e})=>{sk("Received GetSystemInfo request"),e({success:[await(async()=>({platformArch:Ku(),isDesktopHub:"desktop"===ok(),isRuntimeHub:"runtime"===ok(),hubVersion:Yy,...ik?{updateAvailable:ik}:{}}))()]})},ck=xd("removeService"),lk=async({args:e,sourceServiceId:t,reply:n})=>{const r=e[0],i=r.serviceName,o=r.version;if(!i)return n({error:"No service name provided"});if(!o)return n({error:"No service version provided"});const s=xv.getAllServiceVersions(i),a=s.find((e=>e.info.version===o));if(!a)return n({error:"Service not found"});ck(`Removing ${s.length} service(s) with name: ${i}`);const c=a.info.publicationId;let l;if(await xv.uninstallService(a.info.name,a.info.version),c){const e=II(t);if(!e)return n({error:"Client not found",errCode:"CLIENT_NOT_FOUND"});const r=e.extraInfo.user?.wsApiKey;if(!r)return n({error:"Client does not have an API key",errCode:"CLIENT_NO_API_KEY"});ck(`Updating license details for "${c}"`);const i=await(async e=>{const{data:t,error:n}=await hI(`${dI()}/v1/organization/validate/uninstall_hub_service`,e,{"Content-Type":"application/json"});if(n)throw new Error(n);return t})({apiKey:r,hubService:{id:c}}).catch((e=>(ck(`Error updating license details for "${c}": ${e}`),{error:e.message,remaining:void 0})));l=i?.remaining}n({success:[{remaining:l,service:{name:i,version:o}}]})},uk=xd("getDecryptedEdgeApiKey"),dk=({reply:e})=>(uk("Getting decrypted edge API key"),e({success:[lI().globalApiKey]})),hk=({reply:e})=>{uk("Getting hub config");const t=lI();return e({success:[{kemuApiKey:t.globalApiKey,environment:t.environment}]})};let fk,pk,gk,mk,yk;const vk=e=>e.transport===Wu.IPC&&(e.reply({error:"Transport is not allowed to call this function"}),!0);var bk=async e=>{const t=e.args,n=t[0].recipeUuid,r=t[0].secretNames;if(!r||!n)return e.reply({error:"Invalid request parameters"});if(!fk)return e.reply({error:"Get recipe secrets function not set"});const i=await fk({...t[0]}),o={};for(const e of r)o[e]=e in i?i[e]:null;const s=[{secrets:o}];e.reply({success:s})},wk=async e=>{const t=e.args,n=t[0].recipeUuid,r=t[0].secretsMap;if(vk(e))return;if(!pk)return e.reply({error:"Add recipe secret mapping function not set"});if(!r||!n)return e.reply({error:"Invalid request parameters"});const i=[{secrets:await pk({recipeUuid:n,secretsMap:r})}];e.reply({success:i})},Sk=async e=>{const t=e.args,n=t[0].recipeUuid,r=t[0].secretName;if(vk(e))return;if(!gk)return e.reply({error:"Delete recipe secret mapping function not set"});if(!r||!n)return e.reply({error:"Invalid request parameters"});const i=[{secrets:await gk({recipeUuid:n,secretName:r})}];e.reply({success:i})},_k=async e=>{const t=e.args[0].recipeUuid;if(!mk)return e.reply({error:"Get recipe secret mappings function not set"});if(!t)return e.reply({error:"Invalid request parameters"});const n=[{secrets:await mk({recipeUuid:t})}];e.reply({success:n})},Ik=async e=>{const t=e.args,n=t[0].hubServiceName,r=t[0].secrets;return yk?n&&r?Array.isArray(r)?(await yk({hubServiceName:n,secrets:r}),void e.reply({success:[]})):e.reply({error:'Expected "secrets" to be an array'}):e.reply({error:"Invalid request parameters"}):e.reply({error:"Add service secret function not set"})};let xk,kk,Ek;const Ck=e=>e.transport===Wu.IPC&&(e.reply({error:"You are not allowed to manage secrets using this transport"}),!0);var $k=async e=>{if(e.args,Ck(e))return;if(!Ek)return e.reply({error:"Get hub secrets function not set"});const t=[{contexts:await Ek()}];e.reply({success:t})},Ok=async e=>{const t=e.args;if(Ck(e))return;if(!xk)return e.reply({error:"Add hub secret function not set"});const n=[{contexts:await xk(t[0])}];e.reply({success:n})},Nk=async e=>{const t=e.args;if(Ck(e))return;if(!kk)return e.reply({error:"Delete hub secret function not set"});const n=[{contexts:await kk(t[0])}];e.reply({success:n})};const Tk=k(V(import.meta.url));let Ak=null;const Mk=xd("hub"),Pk=new function(){const e={};let t,n=console.log;const r={};let i="hub";const o={},s=e=>!o[e],a=(e,t,n,r,i,o)=>{let a=sb?new ArrayBuffer(0):Buffer.alloc(0);const c={json:{functionName:e,args:o.success?o.success:[o],messageId:t,type:o.success?"response":"error"}};return s(r)&&(a=Fb.encode(c,n,r)),i(a,{msg:c,sourceServiceId:n,targetServiceId:r})};return{setLogger:e=>{n=e},processMessage:(i,o,s,c)=>{if(!c)return!1;const l=c;if(e[l.messageId]){const t=e[l.messageId];return t&&(clearTimeout(t.timer),t.fulfilled||(t.fulfilled=!0,"response"===l.type?t.resolve(l.args):"error"===l.type&&t.reject(l.args[0])),delete e[l.messageId]),!0}if("execute"!==l.type&&n&&n(`No pending execution found for message id "${l.messageId}"`),"execute"===l.type){const e=r[l.functionName];if(e){const r=e=>{a(l.functionName,l.messageId,s.targetServiceId,s.sourceServiceId,o,e)};if(t&&!t({args:l.args,functionName:l.functionName,transport:i,messageId:l.messageId,sourceServiceId:s.sourceServiceId,reply:r,send:o}))return n&&n(`Function "${l.functionName}" not allowed to be invoked by client [${s.sourceServiceId}]`),r({error:"Function not allowed",errCode:"FNC_NOT_ALLOWED"}),!0;e({transport:i,args:l.args,reply:r,messageId:l.messageId,sourceServiceId:s.sourceServiceId,send:o})}else{const e=`Function "${l.functionName}" not found.`;n&&n(e),a(l.functionName,l.messageId,s.targetServiceId,s.sourceServiceId,o,{error:e,errCode:"FNC_NOT_FOUND"})}return!0}return!1},execute:async(t,r,o,a,c,l)=>{if(!o){const e="No send buffer function provided.";throw n&&n(e),e}Ub+=1;const u=`${i}-${Ub}-exec-${t.substring(0,10)}`,d={messageId:u,functionName:t,send:o,sourceServiceId:a,targetServiceId:c,args:r||[],fulfilled:!1,resolve:()=>{},reject:()=>{}};d.promise=new Promise(((e,t)=>{d.resolve=e,d.reject=t}));let h=sb?new ArrayBuffer(0):Buffer.alloc(0);const f={json:{functionName:t,args:r,messageId:u,type:"execute"}};s(c)&&(h=Fb.encode(f,a,c)),e[u]=d,n&&n(`Calling remote function "${t}" with message id "${u}"`);const p="true"===process.env.NO_INVOKE_TIMEOUT;return l?.async?(d.fulfilled=!0,d.resolve([void 0]),delete e[u]):0===l?.timeout||p||(d.timer=setTimeout((()=>{n&&n(`Remote function ${u} timed out`);const r=e[u];r&&!r.fulfilled&&(r.fulfilled=!0,d.reject(`Function ${t} Timed out`)),delete e[u]}),l?.timeout||3e4)),o(h,{sourceServiceId:a,targetServiceId:c,msg:f}),d.promise},sendResponse:a,registerFunction:(e,t)=>{r[e]=t},registerFunctionsMiddleware:e=>{t=e},unregisterAllFunctions:()=>{Object.keys(r).forEach((e=>{delete r[e]}))},getTransportSendFunction:t=>{const n=e[t];return n?n.send:null},setServiceName:e=>{i=e},getPendingExecutions:()=>e,rejectAllPending:t=>{Object.keys(e).forEach((n=>{const r=e[n];r&&!r.fulfilled&&(clearTimeout(r.timer),r.fulfilled=!0,r.reject(t),delete e[n])}))},broadcast:(e,t,r,o)=>{Ub+=1;const a=`${i}-${Ub}-multicast-${e.substring(0,10)}`;let c=sb?new ArrayBuffer(0):Buffer.alloc(0);const l={json:{functionName:e,args:t,messageId:a,type:"execute"}};let u=s(r[0].serviceId);u&&(c=Fb.encode(l,o,r[0].serviceId));for(let t=0;t<r.length;t++)try{const i=r[t];n&&n(`Broadcasting function "${e}" with message id "${a}" to client [${i.serviceId}]`),0!==t&&(u=s(i.serviceId),u&&(c=Fb.patchEncodedHeader(c,{toServiceId:i.serviceId}))),i.sendFn(c,{msg:l,sourceServiceId:o,targetServiceId:i.serviceId})}catch(e){n&&n(`Error broadcasting to client at index ${t}`)}},disableServiceEncoding:(e,t)=>{o[e]=t}}}("hub");bI=Pk,Pk.setLogger(Mk);const Dk={[Uu.RebootToInstallUpdate]:null,[Uu.GetFileContentFromCacheId]:null,[Uu.SaveRecipeToFile]:null},jk=(e,t)=>{const{transmission:n}=t;if(0!==n.targetServiceId){const r=II(n.targetServiceId);if(!r)return Mk(`Service [${e}] ${n.sourceServiceId} is sending data to an unknown service ["${n.targetServiceId}"]`),!0;r.transport,Wu.IPC;const i=t.json?.messageId;return Mk(`Forwarding message from ${n.sourceServiceId} to ${n.targetServiceId}, msgId: ${i}`),r.send(n.rawMessage,{sourceServiceId:n.sourceServiceId,targetServiceId:n.targetServiceId,msg:{json:t.json}}),!0}return!1},Rk=({sourceServiceId:e,args:t})=>{const n=xv.getServiceBySessionId(e);if(n){const r=xI(n.info.name,n.info.version),i=xI(n.info.name,"*");if(!r.length&&!i.length)return;const o=[...r,...i],s={...t[0],source:{serviceName:n.info.name,serviceVersion:n.info.version,sessionId:e}};Pk.broadcast(Uu.BroadcastEvent,[s],o,0)}},Lk=async({args:e,reply:t})=>{const n=e[0];if(!n)return Mk("Invalid config for SendToRecipe"),t({error:"Invalid config for SendToRecipe"});const r=(i=n.recipePoolId,Object.values(wI).find((e=>e.extraInfo.recipe?.poolId===i))||null);var i;if(!r)return Mk(`No client found for recipe pool id ${n.recipePoolId}`),t({error:`No client found for recipe pool id "${n.recipePoolId}"`});try{const e=Pk.execute(Uu.SendToRecipe,[n],r.send,0,r.serviceSessionId,{async:!n.waitForResponse,timeout:n.timeout});n.waitForResponse?t({success:await e}):t({success:[]})}catch(e){return Mk(`Error sending to recipe ${n.recipePoolId}: ${e?.message||e}`),t({error:e?.message||"There was an error sending to the recipe"})}},Fk=e=>{const{send:t,transmission:n,json:r}=e;Mk(`Raw message Id received from WS: ${r?.messageId}`),jk(Wu.WS,e)||Pk.processMessage(Wu.WS,t,n,r)},Uk=e=>{const t=(n=e,`${Fu.SocketAcknowledge}${n}`);var n;W_(e,t)},Bk=(e,t)=>{Mk(`Received unknown command [${t}] from service ${e}`)},Wk=async e=>{const{args:t,sourceServiceId:n,send:r,reply:i}=e,o=n,s=t[0],a=s?.user?.apiKey||lI().globalApiKey;if(!a)return Mk(`Received ACK from WS service ${n} but no API key was provided`),i({error:"No API key was provided",errCode:"MISSING_API_KEY"});s.user?.id&&iv.setGlobalUserId(s.user?.id),await EI({serviceSessionId:n,transport:Wu.WS,send:r,terminateFn:()=>{V_(n)},extraInfo:{websocketId:o,recipe:s.recipe,user:{wsApiKey:a,userEmail:s.user?.email,userId:s.user?.id}}}),i({success:[]})},Gk=e=>{Mk(`WS Client ${e} disconnected`),$I(e)},Vk=e=>1===e.sourceServiceId?e.functionName===Uu.GetFileContentFromCacheId:e.functionName===Uu.SocketAckResponse||e.functionName===Uu.ServiceManifest||e.functionName===Uu.SubscribeToService||(!!II(e.sourceServiceId)||(e.reply({error:`Session id "${e.sourceServiceId}" not found. Please acknowledge the session first.`}),!1)),Yk=async({sourceServiceId:e,args:t,transport:n,send:r})=>{if(n!==Wu.IPC){var i;Mk(`Received manifest from non IPC service ${e}.`)}else{const n=t[0];if(n.devMode){const t=xv.getMatchingDevService(n.name,n.version,"stopped");if(t){Mk(`Found matching previous service ${t.info.name} (${t.info.version}). Reactivating previous client with session id ${t.info.sessionId}`);const o=II(t.info.sessionId);if(!o)return void Mk(`Could not find previous client instance for ${t.info.name} (${t.info.version}). Aborting manifest injection`);o.send=r,wI[i=e]?delete wI[i]:vI(`Could not find source client with session id ${i}`),jb(e,t.info.sessionId);const s=await Jy(n,n.path);t.info={...t.info,...s},Mk(`Updating manifest for dev service ${t.info.sessionId}`),xv.setServiceManifest(t.info.sessionId,s,"running"),Mk(`Asking service ${e} to assume previous session id ${t.info.sessionId}`),Db(t.info.sessionId,(e=>`${Fu.AssumeSession}${e}`)(t.info.sessionId)),(e=>{const t=wI[e];t?t.isDevClient?(t.disconnected=!1,t.transport===Wu.IPC&&(kI(),CI(e))):vI(`Client with session id ${e} is not a dev client`):vI(`Could not find source client with session id ${e}`)})(t.info.sessionId)}else{xv.addDevService(e,n,"running");const t=II(e);t?t.isDevClient=!0:EI({serviceSessionId:e,transport:Wu.IPC,send:r,extraInfo:{ipcSocketId:e},isDevClient:!0})}return}Mk(`Received manifest from non dev service ${e} [${n.name}@(${n.version})]. Ignoring...`)}};var Hk=async e=>{var t;Mk("Starting Kemu Hub..."),t=e.desktopMode?"desktop":"runtime",rk=t;const n=e?.ipc?.appSpace||"kemu.",r=e?.ipc?.id||"widgets";if(!e.serviceUrl)throw new Error("Missing service url, please set the `apiUrl` option.");e.errorTracker&&iv.setTracker(e.errorTracker),(e=>{cI={...cI,...e}})({serviceUrl:e.serviceUrl,globalApiKey:e.globalApiKey,environment:e.environment}),Pk.registerFunctionsMiddleware(Vk),e.secrets?.serviceSecrets&&(e=>{yk=e})(e.secrets.serviceSecrets.addServiceSecretFn),e.secrets?.recipeSecrets&&((e=>{fk=e})(e.secrets.recipeSecrets.getRecipeDecryptedSecretsFn),(e=>{pk=e})(e.secrets.recipeSecrets.addRecipeSecretFn),(e=>{gk=e})(e.secrets.recipeSecrets.deleteRecipeSecretFn),(e=>{mk=e})(e.secrets.recipeSecrets.getRecipeSecretMappingsFn)),e.secrets?.hubSecrets&&((e=>{Ek=e})(e.secrets.hubSecrets.getHubSecretsFn),(e=>{xk=e})(e.secrets.hubSecrets.addHubSecretsFn),(e=>{kk=e})(e.secrets.hubSecrets.deleteHubSecretFn)),Pk.registerFunction(Uu.GetServiceContents,aI),Pk.registerFunction(Uu.GetServices,nk),Pk.registerFunction(Uu.GetSystemInfo,ak),Pk.registerFunction(Uu.ShowSecretsConfigScreen,(async({args:t,reply:n})=>{const[{name:r,version:i}]=t;e?.onShowSecretsScreen?(await e.onShowSecretsScreen(r,i),n({success:[]})):n({error:"This hub does not support showing secrets configuration screens",errCode:"GUI_NOT_SUPPORTED"})})),Pk.registerFunction(Uu.UnsubscribeFromService,(({transport:e,reply:t,args:n,sourceServiceId:r})=>{if(e===Wu.WS){const[e]=n,i=II(r);if(!i)return t({error:`Session id "${r}" not found`});Mk(`Service ${r} unsubscribing from "${e.targetService.serviceName} (${e.targetService.version})"`),t({success:[]}),i?.removeSubscription({serviceName:e.targetService.serviceName,version:e.targetService.version})}})),Pk.registerFunction(Uu.SubscribeToService,(({transport:e,reply:t,args:n,sourceServiceId:r})=>{if(e===Wu.WS){const[e]=n,i=II(r),o=e.targetService;if(!i)return t({error:`Session id "${r}" not found`});if(Mk(`Service ${r} subscribing to "${o.serviceName} (${o.version})"`),"hub"===o.serviceName)return i.addSubscription(o),void t({success:[]});if(!i.addSubscription(o))return Mk(`Service ${r} already subscribed to "${o.serviceName} (${o.version})", ignoring request.`),t({success:[]});const s=xv.getMatchingService(o.serviceName,o.version);if(!s)return Mk(`Service ${o.serviceName} ${o.version} not active yet`),t({success:[]});if(!s.info.eventEmitter)return Mk(`Service ${o.serviceName} ${o.version} does not have an event emitter, removing subscription`),i.removeSubscription(o),t({error:`Service "${o.serviceName} (${o.version})" does not produce events`});const a=II(s.info.sessionId);return a?.extraInfo.ipcSocketId&&(Mk(`Sending Broadcast START command to service ${s.info.sessionId}`),Db(a?.extraInfo.ipcSocketId,Fu.BroadcastStart)),t({success:[]})}})),Pk.registerFunction("stopService",H_),Pk.registerFunction("removeService",q_),Pk.registerFunction("launchService",J_),Pk.registerFunction("getMatchingServices",X_),Pk.registerFunction("getSecretsValues",tI),Pk.registerFunction(Uu.GetMappedSecrets,oI),Pk.registerFunction(Uu.BroadcastEvent,Rk),Pk.registerFunction(Uu.ServiceManifest,Yk),Pk.registerFunction(Uu.ChooseDirectoryDialog,AI),Pk.registerFunction(Uu.ChooseFileDialog,MI),Pk.registerFunction(Uu.GetUniqueId,ek),Pk.registerFunction(Uu.SendToRecipe,Lk),Pk.registerFunction(Uu.GetDecryptedEdgeApiKey,dk),Pk.registerFunction(Uu.GetHubConfig,hk),Pk.registerFunction(Uu.SocketAckResponse,Wk),Pk.registerFunction(Uu.UninstallService,lk),Pk.registerFunction(Uu.GetRecipeDecryptedSecretsValues,bk),Pk.registerFunction(Uu.GetRecipeSecretMappings,_k),Pk.registerFunction(Uu.AddRecipeSecretMapping,wk),Pk.registerFunction(Uu.DeleteRecipeSecretMapping,Sk),Pk.registerFunction(Uu.GetHubSecrets,$k),Pk.registerFunction(Uu.AddHubSecrets,Ok),Pk.registerFunction(Uu.DeleteHubSecret,Nk),Pk.registerFunction(Uu.AddServiceSecret,Ik),Object.entries(Dk).forEach((([e,t])=>{t?Pk.registerFunction(e,t):(Mk(`Skipping registration of "${e}" because it's not implemented`),Pk.registerFunction(e,(({reply:t})=>{t({error:`This hub does not support "${e}"`,errCode:"FUNCTION_NOT_SUPPORTED"})})))})),(e=>{Tb=e})((e=>{const{send:t,transmission:n,json:r}=e;Mk(`Raw message Id received from IPC: ${r?.messageId}`),jk(Wu.IPC,e)||Pk.processMessage(Wu.IPC,t,n,r)})),G_(Fk),F_(Uk),B_(Bk),U_(Gk),(e=>{Nb=e})(NI),(e=>{$b=e})((e=>{const t=(e=>`${Fu.IpcAcknowledge}${e}`)(e);Db(e,t)})),(e=>{Ob=e})((e=>{Mk(`IPC socket [${e}] disconnected`);const t=II(e);if(t){Mk(`Found matching service for disconnected socket. SessionId: ${t.serviceSessionId}`);const e=xv.getServiceBySessionId(t.serviceSessionId);xv.setServiceStatus(t.serviceSessionId,"stopped"),e?.devMode?(t.disconnected=!0,kI()):$I(t.serviceSessionId)}})),await(e=>(e?.ipcId&&(rb.config.id=e.ipcId),e?.ipcAppSpace&&(rb.config.appspace=e.ipcAppSpace),new Promise((e=>{rb.serve((()=>{Cb.info("IPC Server Initiated"),rb.server.on("data",((e,t)=>{const n=Ab[t.id];n?(Cb.data(`IPC Socket [${t.id}] data ${e.byteLength} bytes`),Mb(e,n.activeMessage,(e=>n.activeMessage=e),(e=>{if(!e.complete)return;const n=e=>{t.write(e)};if(e.command)return Cb.data(`Received command from client [${t.id}]: ${e.command}`),void(Nb&&Nb(t.id,e.command,n));e.klMessage&&Tb&&Tb({send:n,transmission:{sourceServiceId:e.sourceServiceId??-1,targetServiceId:e.targetServiceId??-1,rawMessage:e.rawMessage},json:e.klMessage.json})}))):Cb.data(`Received data from unknown client [${t.id}]. Ignoring.`)})),rb.server.on("connect",(e=>{const t=By();Cb.info(`New client connected. Registered as "${t}"`),e.id=t,Ab[t]={socket:e,activeMessage:null,disconnectHandler:()=>Pb(t)},e.on("close",Ab[t].disconnectHandler),$b&&$b(t)})),rb.server.on("disconnect",(e=>{Pb(e.id)})),rb.server.on("error",(e=>{console.log(`IPC Server Error: ${e}`)})),e()})),rb.server.start()}))))({ipcAppSpace:n,ipcId:r}),e?.ws?.disabled||await L_(e?.ws?.port||5368);const i=e?.defaultServicesPath||I.resolve(Tk,"defaultServices");Ak=i;const o=process.env.DEV_SESSION_ID;xv.setHubIpcConfig({recipePath:e?.recipeRootPath,appSpace:n,id:r}),xv.setEnableServiceLogsConfig(!!e?.enableServiceLogs),e?.servicesInstallPath&&(e=>{Xy=e})(e.servicesInstallPath),e?.testServicesInstallPath&&(e=>{Qy=e})(e.testServicesInstallPath);const s=ev(),a=tv(),c=async({requiredSecrets:e})=>{const t=Object.keys(e).reduce(((e,t)=>({...e,[t]:process.env[t]})),{});return t.__KEMU_USER_SERVICES_PATH=s,t.__KEMU_USER_TEST_SERVICES_PATH=a,t.__KEMU_SERVICE_URL=lI().serviceUrl,t.__KEMU_ENVIRONMENT=lI().environment,t};e?.getServiceSecretsFn?(xv.setGetSecretsFunction(e.getServiceSecretsFn),nI(e.getServiceSecretsFn)):(xv.setGetSecretsFunction(c),nI(c)),(e=>{iI=e})(e?.getMappedSecretsFn?e.getMappedSecretsFn:async e=>e.reduce(((e,t)=>({...e,[t.name]:[]})),{})),xv.setSpawnNodeFunction(e?.spawnFn?e.spawnFn:({args:e,options:t})=>{const n={...process.env};return H("node",e||[],{...t,env:{...n,...t?.env}})}),e?.noDefaultServices||await xv.loadServices(i,{fixedSession:o?parseInt(o):void 0,singleServiceName:process.env.DEV_SINGLE_SERVICE_NAME,internalServices:!0,enableLogs:!0}),null!==e?.servicesInstallPath&&(await Zy(s)||await m(s,{recursive:!0}),await xv.loadServices(s,{internalServices:!1,singleServiceName:process.env.DEV_SINGLE_SERVICE_NAME,enableLogs:!!e?.enableServiceLogs}));const l=process.env.DEV_NO_SPAWN_LIST?.split(",");await xv.launchServices({noSpawningList:l||[]}),Mk("Kemu Hub started"),(e?.onChooseDirectory||e?.onChooseFile)&&(e=>{TI=e})({chooseDirectory:e.onChooseDirectory,chooseFile:e.onChooseFile})},zk=e=>{if(e===Wu.WS)return{handleWebsocketConnectionEvent:Uk,handleWebsocketClientDisconnectionEvent:Gk,handleWebsocketMessage:Fk,handleWebsocketClientCommand:Bk,getRemoteInvoke:()=>Pk}},qk=(e=[])=>{let t;const n=new Promise((n=>{const r=()=>{if(xv.getAllServices().every((e=>"running"===e.status))&&e.every((e=>"running"===xv.getMatchingService(e.name,e.version)?.status)))return n();t=setTimeout(r,100)};r()}));return n.abort=()=>{t&&clearTimeout(t)},n};let Kk;const Jk=Ml("run"),Zk=Yu(),Xk=1e3,Qk=_(process.argv.slice(2)),eE=e=>"number"==typeof e?{type:me.Number,value:e}:"string"==typeof e?{type:me.String,value:e}:"boolean"==typeof e?{type:me.Boolean,value:e}:Array.isArray(e)?{type:me.Array,value:e}:e;global.ImageData=J;const tE=e=>e&&"string"==typeof e.format&&e.data&&e.data instanceof ArrayBuffer;ke({createCanvas:(e,t)=>X(e,t),loadImage:async e=>{let t=e;if(tE(e)){const n=e;t=Buffer.from(n.data)}const n=await Z(t),r=X(n.width,n.height).getContext("2d");r.drawImage(n,0,0,n.width,n.height);return r.getImageData(0,0,n.width,n.height)}});const nE=(e,t)=>"*"===e?ao.onAnyGlobalVariableChange(t):ao.onGlobalVariableChange(e,t),rE=(e,t,n)=>ao.setGlobalVariable({name:e,value:t,disableChangeNotifications:n?.disableChangeNotifications||!1,disableDefineNotifications:n?.disableDefineNotifications||!1,doNotOverrideExisting:n?.doNotOverrideExisting||!1}),iE=e=>{ao.deleteGlobalVariable({name:e})},oE=()=>ao.getAllVariables(),sE=e=>ao.getGlobalVariable(e),aE=e=>Wi(e),cE=e=>async()=>{throw new Error(`${e} not implemented`)},lE={createImageDataLike:(e,t,n,r="srgb")=>{let i;return i=e instanceof Uint8ClampedArray?e:new Uint8ClampedArray(e),{data:i,width:t,height:n,colorSpace:r,_kemuType:me.ImageData}},loadImageFile:async e=>{const t=await Z(e),n=X(t.width,t.height).getContext("2d");n.drawImage(t,0,0,t.width,t.height);return n.getImageData(0,0,t.width,t.height)},encodeImageData:async(e,t="jpeg",n)=>{const r=X(e.width,e.height);let i;return r.getContext("2d").putImageData(e,0,0),i="png"===t?await r.encode(t):await r.encode(t,n),i}};var uE={start:async r=>{r=r||{};const i=r?.recipePath||Qk.recipePath||process.env.KEMU_EDGE_RECIPE_PATH||process.cwd();if(!i)throw new Error("`recipePath` not provided. Please specify it in the config object, via a command line argument [--recipePath] or as an environment variable [KEMU_EDGE_RECIPE_PATH].");const{parsed:o}=await e({path:z(q(i),".env")}),s=r.apiKey||process.env.KEMU_API_KEY;if(!s)throw new Error("Missing API key. Please provide it via config.apiKey or KEMU_API_KEY environment variable.");const a=i.endsWith(".json")||i.endsWith(".kemu"),c=a?K(i):i,l=a?i:z(c,"recipe.kemu"),u=(e=>{try{return JSON.parse(e||"")}catch(e){return null}})(await t(q(l),"utf-8"));if(!u)throw new Error("Failed to parse recipe file");if(!u.author?.id)throw new Error("Missing required author ID in recipe file.");const{serviceUrl:d,apiKey:h,environment:f}=((e,t)=>{const n=qc(e,t),r=Buffer.from(n,"base64").toString("utf8"),[i,o,s]=r.split("<@>");if(!o||!i||!s)throw new Error("Invalid API key.");return{serviceUrl:o,apiKey:i,environment:s}})(u,s);await oc();const p={id:u.uuid||String(Date.now()),version:1,author:u.author.id};(e=>{fo=e})(console);const g=zk(_e.WS),m=(e,t)=>{if(t)g?.handleWebsocketMessage({send:v,transmission:{rawMessage:e,sourceServiceId:t.sourceServiceId,targetServiceId:t.targetServiceId},json:t.msg?.json});else{const t=e instanceof Buffer?e.toString():e;g?.handleWebsocketClientCommand(Xk,t)}},y=(bl={instanceServiceId:Xk,sendBuf:m,sendCmd:m,triggerOnCommand:(...e)=>wl(...e),triggerOnConnected:()=>Sl(),triggerOnDisconnected:()=>_l(),triggerOnMessageReceived:(...e)=>Il(...e)},bl);const v=(e,t)=>{if(t)y.triggerOnMessageReceived({send:m,transmission:{rawMessage:e,sourceServiceId:t.sourceServiceId,targetServiceId:t.targetServiceId},json:t.msg.json});else{const t=e instanceof Buffer?e.toString():e;y.triggerOnCommand(t)}},b=zu(),w=g.getRemoteInvoke();b.disableServiceEncoding(0,!0),w.disableServiceEncoding(Xk,!0);const S=Object.values(u.blocks[pe].gates).filter((e=>e.type===Ke.hubService&&e.state.service&&!0!==e.state.service?.webOnly)),_=S.map((e=>{const t=e.state.service;return{name:t.name,version:t.version}})),I=z(c,"services"),x=await n(I).then((()=>!0)).catch((()=>!1));if(_.length>0&&!x)throw new Error("Services directory not found but required services are defined in the recipe. Please make sure there is a `services` directory in the recipe root and add the services you want to use to it.");await Hk({globalApiKey:h,serviceUrl:d,recipeRootPath:c,servicesInstallPath:x?z(c,"services"):null,noDefaultServices:!0,environment:f,ws:{disabled:!0},secrets:{recipeSecrets:{getRecipeDecryptedSecretsFn:async()=>({...o}),getRecipeSecretMappingsFn:cE("getRecipeSecretMappingsFn"),addRecipeSecretFn:cE("addRecipeSecretFn"),deleteRecipeSecretFn:cE("deleteRecipeSecretFn")}},ipc:{appSpace:"kemu-runner.",id:p.id}}),Jk("Waiting for services to run"),await qk(_),Jk("All services are running"),Bc(Zk),Yc(),aa((e=>{Jk("Global processing state changed: ",e)})),u.globalVariables&&(u.globalVariables=await zc(u.globalVariables));const k=await Lc(u,"runner",p.version,p.author,mr.Desktop);return Kk=k,Hu(k),await Gu({apiKey:h,id:u.author.id}),new Promise(((e,t)=>{var n;Vu("acknowledged",(async()=>{await Zk.getServices();const{failed:n,sendToInputWidget:r,invokeRecipeLoadedWidgets:i}=await Uc(k);if(n.length>0){const e=`Some widgets failed to initialize: ${n.join(", ")}`;return t(e)}await i().catch((e=>{console.error("Error invoking recipe loaded widgets: ",e)})),Jk("Recipe started"),e({sendToInputWidgetAndWaitForOutput:(e,t)=>{const n=eE(t);return r({inputName:e,data:n,waitForOutputChild:!0})},sendToInputWidget:(e,t)=>{const n=eE(t);return r({inputName:e,data:n,waitForOutputChild:!1})},globalVariables:{onChange:nE,setValue:rE,getValue:sE,delete:iE,getAll:oE},status:{onChange:aE},edgeFunctions:{register:Ga.registerFunctionHandler,unregister:Ga.unregisterFunctionHandler,clearAll:Ga.clearAllHandlers}})})),y.triggerOnConnected(),y.triggerOnCommand((n=Xk,`${be.SocketAcknowledge}${n}`))}))},terminate:async()=>{Kk&&await Fc(Kk)}};export{me as DataType,uE as default,tE as isBinaryFile,lE as utils};
12
+ Object.defineProperty(e,"__esModule",{value:!0}),e.randomBytes=e.wrapXOFConstructorWithOpts=e.wrapConstructorWithOpts=e.wrapConstructor=e.checkOpts=e.Hash=e.concatBytes=e.toBytes=e.utf8ToBytes=e.asyncLoop=e.nextTick=e.hexToBytes=e.bytesToHex=e.byteSwap32=e.byteSwapIfBE=e.byteSwap=e.isLE=e.rotl=e.rotr=e.createView=e.u32=e.u8=e.isBytes=void 0;const t=mx,n=PI;e.isBytes=function(e){return e instanceof Uint8Array||null!=e&&"object"==typeof e&&"Uint8Array"===e.constructor.name},e.u8=e=>new Uint8Array(e.buffer,e.byteOffset,e.byteLength),e.u32=e=>new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4)),e.createView=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),e.rotr=(e,t)=>e<<32-t|e>>>t,e.rotl=(e,t)=>e<<t|e>>>32-t>>>0,e.isLE=68===new Uint8Array(new Uint32Array([287454020]).buffer)[0],e.byteSwap=e=>e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255,e.byteSwapIfBE=e.isLE?e=>e:t=>(0,e.byteSwap)(t),e.byteSwap32=function(t){for(let n=0;n<t.length;n++)t[n]=(0,e.byteSwap)(t[n])};const r=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));e.bytesToHex=function(e){(0,n.bytes)(e);let t="";for(let n=0;n<e.length;n++)t+=r[e[n]];return t};const i=48,o=57,s=65,a=70,c=97,l=102;function u(e){return e>=i&&e<=o?e-i:e>=s&&e<=a?e-(s-10):e>=c&&e<=l?e-(c-10):void 0}function d(e){if("string"!=typeof e)throw new Error("utf8ToBytes expected string, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))}function h(e){return"string"==typeof e&&(e=d(e)),(0,n.bytes)(e),e}e.hexToBytes=function(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);const t=e.length,n=t/2;if(t%2)throw new Error("padded hex string expected, got unpadded hex of length "+t);const r=new Uint8Array(n);for(let t=0,i=0;t<n;t++,i+=2){const n=u(e.charCodeAt(i)),o=u(e.charCodeAt(i+1));if(void 0===n||void 0===o){const t=e[i]+e[i+1];throw new Error('hex string expected, got non-hex character "'+t+'" at index '+i)}r[t]=16*n+o}return r},e.nextTick=async()=>{},e.asyncLoop=async function(t,n,r){let i=Date.now();for(let o=0;o<t;o++){r(o);const t=Date.now()-i;t>=0&&t<n||(await(0,e.nextTick)(),i+=t)}},e.utf8ToBytes=d,e.toBytes=h,e.concatBytes=function(...e){let t=0;for(let r=0;r<e.length;r++){const i=e[r];(0,n.bytes)(i),t+=i.length}const r=new Uint8Array(t);for(let t=0,n=0;t<e.length;t++){const i=e[t];r.set(i,n),n+=i.length}return r},e.Hash=class{clone(){return this._cloneInto()}};const f={}.toString;e.checkOpts=function(e,t){if(void 0!==t&&"[object Object]"!==f.call(t))throw new Error("Options should be object or undefined");return Object.assign(e,t)},e.wrapConstructor=function(e){const t=t=>e().update(h(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t},e.wrapConstructorWithOpts=function(e){const t=(t,n)=>e(n).update(h(t)).digest(),n=e({});return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=t=>e(t),t},e.wrapXOFConstructorWithOpts=function(e){const t=(t,n)=>e(n).update(h(t)).digest(),n=e({});return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=t=>e(t),t},e.randomBytes=function(e=32){if(t.crypto&&"function"==typeof t.crypto.getRandomValues)return t.crypto.getRandomValues(new Uint8Array(e));throw new Error("crypto.getRandomValues must be defined")}}(gx),Object.defineProperty(MI,"__esModule",{value:!0}),MI.shake256=MI.shake128=MI.keccak_512=MI.keccak_384=MI.keccak_256=MI.keccak_224=MI.sha3_512=MI.sha3_384=MI.sha3_256=MI.sha3_224=MI.Keccak=MI.keccakP=void 0;const yx=PI,vx=GI,bx=gx,wx=[],Sx=[],_x=[],Ix=BigInt(0),xx=BigInt(1),kx=BigInt(2),Ex=BigInt(7),Cx=BigInt(256),$x=BigInt(113);for(let e=0,t=xx,n=1,r=0;e<24;e++){[n,r]=[r,(2*n+3*r)%5],wx.push(2*(5*r+n)),Sx.push((e+1)*(e+2)/2%64);let i=Ix;for(let e=0;e<7;e++)t=(t<<xx^(t>>Ex)*$x)%Cx,t&kx&&(i^=xx<<(xx<<BigInt(e))-xx);_x.push(i)}const[Ox,Nx]=(0,vx.split)(_x,!0),Tx=(e,t,n)=>n>32?(0,vx.rotlBH)(e,t,n):(0,vx.rotlSH)(e,t,n),Ax=(e,t,n)=>n>32?(0,vx.rotlBL)(e,t,n):(0,vx.rotlSL)(e,t,n);function Mx(e,t=24){const n=new Uint32Array(10);for(let r=24-t;r<24;r++){for(let t=0;t<10;t++)n[t]=e[t]^e[t+10]^e[t+20]^e[t+30]^e[t+40];for(let t=0;t<10;t+=2){const r=(t+8)%10,i=(t+2)%10,o=n[i],s=n[i+1],a=Tx(o,s,1)^n[r],c=Ax(o,s,1)^n[r+1];for(let n=0;n<50;n+=10)e[t+n]^=a,e[t+n+1]^=c}let t=e[2],i=e[3];for(let n=0;n<24;n++){const r=Sx[n],o=Tx(t,i,r),s=Ax(t,i,r),a=wx[n];t=e[a],i=e[a+1],e[a]=o,e[a+1]=s}for(let t=0;t<50;t+=10){for(let r=0;r<10;r++)n[r]=e[t+r];for(let r=0;r<10;r++)e[t+r]^=~n[(r+2)%10]&n[(r+4)%10]}e[0]^=Ox[r],e[1]^=Nx[r]}n.fill(0)}MI.keccakP=Mx;class Px extends bx.Hash{constructor(e,t,n,r=!1,i=24){if(super(),this.blockLen=e,this.suffix=t,this.outputLen=n,this.enableXOF=r,this.rounds=i,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,(0,yx.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,bx.u32)(this.state)}keccak(){bx.isLE||(0,bx.byteSwap32)(this.state32),Mx(this.state32,this.rounds),bx.isLE||(0,bx.byteSwap32)(this.state32),this.posOut=0,this.pos=0}update(e){(0,yx.exists)(this);const{blockLen:t,state:n}=this,r=(e=(0,bx.toBytes)(e)).length;for(let i=0;i<r;){const o=Math.min(t-this.pos,r-i);for(let t=0;t<o;t++)n[this.pos++]^=e[i++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:n,blockLen:r}=this;e[n]^=t,128&t&&n===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){(0,yx.exists)(this,!1),(0,yx.bytes)(e),this.finish();const t=this.state,{blockLen:n}=this;for(let r=0,i=e.length;r<i;){this.posOut>=n&&this.keccak();const o=Math.min(n-this.posOut,i-r);e.set(t.subarray(this.posOut,this.posOut+o),r),this.posOut+=o,r+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return(0,yx.number)(e),this.xofInto(new Uint8Array(e))}digestInto(e){if((0,yx.output)(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:t,suffix:n,outputLen:r,rounds:i,enableXOF:o}=this;return e||(e=new Px(t,n,r,o,i)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=n,e.outputLen=r,e.enableXOF=o,e.destroyed=this.destroyed,e}}MI.Keccak=Px;const Dx=(e,t,n)=>(0,bx.wrapConstructor)((()=>new Px(t,e,n)));MI.sha3_224=Dx(6,144,28),MI.sha3_256=Dx(6,136,32),MI.sha3_384=Dx(6,104,48),MI.sha3_512=Dx(6,72,64),MI.keccak_224=Dx(1,144,28),MI.keccak_256=Dx(1,136,32),MI.keccak_384=Dx(1,104,48),MI.keccak_512=Dx(1,72,64);const jx=(e,t,n)=>(0,bx.wrapXOFConstructorWithOpts)(((r={})=>new Px(t,e,void 0===r.dkLen?n:r.dkLen,!0)));MI.shake128=jx(31,168,16),MI.shake256=jx(31,136,32);const{sha3_512:Rx}=MI,Lx=(e=4,t=Math.random)=>{let n="";for(;n.length<e;)n+=Math.floor(36*t()).toString(36);return n};function Fx(e){let t=0n;for(const n of e.values())t=(t<<8n)+BigInt(n);return t}const Ux=(e="")=>Fx(Rx(e)).toString(36).slice(1),Bx=Array.from({length:26},((e,t)=>String.fromCharCode(t+97))),Wx=({globalObj:e=(void 0!==id?id:"undefined"!=typeof window?window:{}),random:t=Math.random}={})=>{const n=Object.keys(e).toString(),r=n.length?n+Lx(32,t):Lx(32,t);return Ux(r).substring(0,32)},Gx=e=>()=>e++,Vx=({random:e=Math.random,counter:t=Gx(Math.floor(476782367*e())),length:n=24,fingerprint:r=Wx({random:e})}={})=>function(){const i=(e=>Bx[Math.floor(e()*Bx.length)])(e),o=Date.now().toString(36),s=t().toString(36),a=Lx(n,e);return`${i+Ux(`${o+a+s+r}`).substring(1,n)}`},Yx=Vx();AI.getConstants=()=>({defaultLength:24,bigLength:32}),AI.init=Vx,AI.createId=Yx,AI.bufToBigInt=Fx,AI.createCounter=Gx,AI.createFingerprint=Wx,AI.isCuid=(e,{minLength:t=2,maxLength:n=32}={})=>{const r=e.length,i=/^[0-9a-z]+$/;try{if("string"==typeof e&&r>=t&&r<=n&&i.test(e))return!0}finally{}return!1};const{createId:Hx,init:zx,getConstants:qx,isCuid:Kx}=AI;var Jx=Hx;const Zx=_d("getUniqueId"),Xx=({reply:e,sourceServiceId:t})=>(Zx(`Generating unique id for service "${t}"`),e({success:[Jx()]})),Qx=_d("getActiveServices"),ek=async({transport:e,sourceServiceId:t,reply:n})=>{if(Qx(`Received GetServices request from ${e} [${t}]`),e===Uu.WS){let e=_v.getActiveServices();const r=SI(t);if(!r)return n({error:"Client not found",errCode:"CLIENT_NOT_FOUND"});let i=[];if(r.transport===Uu.WS){if(!r?.extraInfo.user?.wsApiKey)return n({error:"Client does not have an API key",errCode:"CLIENT_NO_API_KEY"});const t=e.filter(_v.isInternalKemuService),o=e.filter((e=>e.devMode&&_v.isNotInternalKemuService(e))),s=e.filter((e=>_v.isOfficialKemuService(e)&&_v.isNotInternalKemuService(e)&&_v.isNotDevService(e))).sort(((e,t)=>e.name.localeCompare(t.name))),a=e.filter((e=>_v.isNotDevService(e)&&_v.isNotInternalKemuService(e)&&!_v.isOfficialKemuService(e))),c=await(async e=>{const{features:t}=await hI(e);return t})(r.extraInfo.user?.wsApiKey),l=c?.hub_services??0,u=s.slice(0,-1!==l?l:s.length);-1!==l&&(i=s.slice(l).map((e=>({name:e.name,version:e.version,svgIcon:e.svgIcon,color:e.color,description:e.description,title:e.title,shortTitle:e.shortTitle})))),e=[...t,...o,...u,...a]}const o=_v.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:_v.isInternalKemuService(e),svgIcon:e.svgIcon,color:e.color,shortTitle:e.shortTitle})));n({success:[{available:e.map((e=>{const{widgetUIContents:t,...n}=e;return{...n}})),failed:o,installed:i}]})}};let tk="runtime",nk=null;const rk=()=>tk,ik=_d("getSystemInfo"),ok=async({reply:e})=>{ik("Received GetSystemInfo request"),e({success:[await(async()=>({platformArch:zu(),isDesktopHub:"desktop"===rk(),isRuntimeHub:"runtime"===rk(),hubVersion:Gy,...nk?{updateAvailable:nk}:{}}))()]})},sk=_d("removeService"),ak=async({args:e,sourceServiceId:t,reply:n})=>{const r=e[0],i=r.serviceName,o=r.version;if(!i)return n({error:"No service name provided"});if(!o)return n({error:"No service version provided"});const s=_v.getAllServiceVersions(i),a=s.find((e=>e.info.version===o));if(!a)return n({error:"Service not found"});sk(`Removing ${s.length} service(s) with name: ${i}`);const c=a.info.publicationId;let l;if(await _v.uninstallService(a.info.name,a.info.version),c){const e=SI(t);if(!e)return n({error:"Client not found",errCode:"CLIENT_NOT_FOUND"});const r=e.extraInfo.user?.wsApiKey;if(!r)return n({error:"Client does not have an API key",errCode:"CLIENT_NO_API_KEY"});sk(`Updating license details for "${c}"`);const i=await(async e=>{const{data:t,error:n}=await uI(`${lI()}/v1/organization/validate/uninstall_hub_service`,e,{"Content-Type":"application/json"});if(n)throw new Error(n);return t})({apiKey:r,hubService:{id:c}}).catch((e=>(sk(`Error updating license details for "${c}": ${e}`),{error:e.message,remaining:void 0})));l=i?.remaining}n({success:[{remaining:l,service:{name:i,version:o}}]})},ck=_d("getDecryptedEdgeApiKey"),lk=({reply:e})=>(ck("Getting decrypted edge API key"),e({success:[aI().globalApiKey]})),uk=({reply:e})=>{ck("Getting hub config");const t=aI();return e({success:[{kemuApiKey:t.globalApiKey,environment:t.environment}]})};let dk,hk,fk,pk,gk;const mk=e=>e.transport===Uu.IPC&&(e.reply({error:"Transport is not allowed to call this function"}),!0);var yk=async e=>{const t=e.args,n=t[0].recipeUuid,r=t[0].secretNames;if(!r||!n)return e.reply({error:"Invalid request parameters"});if(!dk)return e.reply({error:"Get recipe secrets function not set"});const i=await dk({...t[0]}),o={};for(const e of r)o[e]=e in i?i[e]:null;const s=[{secrets:o}];e.reply({success:s})},vk=async e=>{const t=e.args,n=t[0].recipeUuid,r=t[0].secretsMap;if(mk(e))return;if(!hk)return e.reply({error:"Add recipe secret mapping function not set"});if(!r||!n)return e.reply({error:"Invalid request parameters"});const i=[{secrets:await hk({recipeUuid:n,secretsMap:r})}];e.reply({success:i})},bk=async e=>{const t=e.args,n=t[0].recipeUuid,r=t[0].secretName;if(mk(e))return;if(!fk)return e.reply({error:"Delete recipe secret mapping function not set"});if(!r||!n)return e.reply({error:"Invalid request parameters"});const i=[{secrets:await fk({recipeUuid:n,secretName:r})}];e.reply({success:i})},wk=async e=>{const t=e.args[0].recipeUuid;if(!pk)return e.reply({error:"Get recipe secret mappings function not set"});if(!t)return e.reply({error:"Invalid request parameters"});const n=[{secrets:await pk({recipeUuid:t})}];e.reply({success:n})},Sk=async e=>{const t=e.args,n=t[0].hubServiceName,r=t[0].secrets;return gk?n&&r?Array.isArray(r)?(await gk({hubServiceName:n,secrets:r}),void e.reply({success:[]})):e.reply({error:'Expected "secrets" to be an array'}):e.reply({error:"Invalid request parameters"}):e.reply({error:"Add service secret function not set"})};let _k,Ik,xk;const kk=e=>e.transport===Uu.IPC&&(e.reply({error:"You are not allowed to manage secrets using this transport"}),!0);var Ek=async e=>{if(e.args,kk(e))return;if(!xk)return e.reply({error:"Get hub secrets function not set"});const t=[{contexts:await xk()}];e.reply({success:t})},Ck=async e=>{const t=e.args;if(kk(e))return;if(!_k)return e.reply({error:"Add hub secret function not set"});const n=[{contexts:await _k(t[0])}];e.reply({success:n})},$k=async e=>{const t=e.args;if(kk(e))return;if(!Ik)return e.reply({error:"Delete hub secret function not set"});const n=[{contexts:await Ik(t[0])}];e.reply({success:n})};const Ok=S(W(import.meta.url));let Nk=null;const Tk=_d("hub"),Ak=new function(){const e={};let t,n=console.log;const r={};let i="hub";const o={},s=e=>!o[e],a=(e,t,n,r,i,o)=>{let a=ib?new ArrayBuffer(0):Buffer.alloc(0);const c={json:{functionName:e,args:o.success?o.success:[o],messageId:t,type:o.success?"response":"error"}};return s(r)&&(a=Rb.encode(c,n,r)),i(a,{msg:c,sourceServiceId:n,targetServiceId:r})};return{setLogger:e=>{n=e},processMessage:(i,o,s,c)=>{if(!c)return!1;const l=c;if(e[l.messageId]){const t=e[l.messageId];return t&&(clearTimeout(t.timer),t.fulfilled||(t.fulfilled=!0,"response"===l.type?t.resolve(l.args):"error"===l.type&&t.reject(l.args[0])),delete e[l.messageId]),!0}if("execute"!==l.type&&n&&n(`No pending execution found for message id "${l.messageId}"`),"execute"===l.type){const e=r[l.functionName];if(e){const r=e=>{a(l.functionName,l.messageId,s.targetServiceId,s.sourceServiceId,o,e)};if(t&&!t({args:l.args,functionName:l.functionName,transport:i,messageId:l.messageId,sourceServiceId:s.sourceServiceId,reply:r,send:o}))return n&&n(`Function "${l.functionName}" not allowed to be invoked by client [${s.sourceServiceId}]`),r({error:"Function not allowed",errCode:"FNC_NOT_ALLOWED"}),!0;e({transport:i,args:l.args,reply:r,messageId:l.messageId,sourceServiceId:s.sourceServiceId,send:o})}else{const e=`Function "${l.functionName}" not found.`;n&&n(e),a(l.functionName,l.messageId,s.targetServiceId,s.sourceServiceId,o,{error:e,errCode:"FNC_NOT_FOUND"})}return!0}return!1},execute:async(t,r,o,a,c,l)=>{if(!o){const e="No send buffer function provided.";throw n&&n(e),e}Lb+=1;const u=`${i}-${Lb}-exec-${t.substring(0,10)}`,d={messageId:u,functionName:t,send:o,sourceServiceId:a,targetServiceId:c,args:r||[],fulfilled:!1,resolve:()=>{},reject:()=>{}};d.promise=new Promise(((e,t)=>{d.resolve=e,d.reject=t}));let h=ib?new ArrayBuffer(0):Buffer.alloc(0);const f={json:{functionName:t,args:r,messageId:u,type:"execute"}};s(c)&&(h=Rb.encode(f,a,c)),e[u]=d,n&&n(`Calling remote function "${t}" with message id "${u}"`);const p="true"===process.env.NO_INVOKE_TIMEOUT;return l?.async?(d.fulfilled=!0,d.resolve([void 0]),delete e[u]):0===l?.timeout||p||(d.timer=setTimeout((()=>{n&&n(`Remote function ${u} timed out`);const r=e[u];r&&!r.fulfilled&&(r.fulfilled=!0,d.reject(`Function ${t} Timed out`)),delete e[u]}),l?.timeout||3e4)),o(h,{sourceServiceId:a,targetServiceId:c,msg:f}),d.promise},sendResponse:a,registerFunction:(e,t)=>{r[e]=t},registerFunctionsMiddleware:e=>{t=e},unregisterAllFunctions:()=>{Object.keys(r).forEach((e=>{delete r[e]}))},getTransportSendFunction:t=>{const n=e[t];return n?n.send:null},setServiceName:e=>{i=e},getPendingExecutions:()=>e,rejectAllPending:t=>{Object.keys(e).forEach((n=>{const r=e[n];r&&!r.fulfilled&&(clearTimeout(r.timer),r.fulfilled=!0,r.reject(t),delete e[n])}))},broadcast:(e,t,r,o)=>{Lb+=1;const a=`${i}-${Lb}-multicast-${e.substring(0,10)}`;let c=ib?new ArrayBuffer(0):Buffer.alloc(0);const l={json:{functionName:e,args:t,messageId:a,type:"execute"}};let u=s(r[0].serviceId);u&&(c=Rb.encode(l,o,r[0].serviceId));for(let t=0;t<r.length;t++)try{const i=r[t];n&&n(`Broadcasting function "${e}" with message id "${a}" to client [${i.serviceId}]`),0!==t&&(u=s(i.serviceId),u&&(c=Rb.patchEncodedHeader(c,{toServiceId:i.serviceId}))),i.sendFn(c,{msg:l,sourceServiceId:o,targetServiceId:i.serviceId})}catch(e){n&&n(`Error broadcasting to client at index ${t}`)}},disableServiceEncoding:(e,t)=>{o[e]=t}}}("hub");yI=Ak,Ak.setLogger(Tk);const Mk={[Lu.RebootToInstallUpdate]:null,[Lu.GetFileContentFromCacheId]:null,[Lu.SaveRecipeToFile]:null},Pk=(e,t)=>{const{transmission:n}=t;if(0!==n.targetServiceId){const r=SI(n.targetServiceId);if(!r)return Tk(`Service [${e}] ${n.sourceServiceId} is sending data to an unknown service ["${n.targetServiceId}"]`),!0;r.transport,Uu.IPC;const i=t.json?.messageId;return Tk(`Forwarding message from ${n.sourceServiceId} to ${n.targetServiceId}, msgId: ${i}`),r.send(n.rawMessage,{sourceServiceId:n.sourceServiceId,targetServiceId:n.targetServiceId,msg:{json:t.json}}),!0}return!1},Dk=({sourceServiceId:e,args:t})=>{const n=_v.getServiceBySessionId(e);if(n){const r=_I(n.info.name,n.info.version),i=_I(n.info.name,"*");if(!r.length&&!i.length)return;const o=[...r,...i],s={...t[0],source:{serviceName:n.info.name,serviceVersion:n.info.version,sessionId:e}};Ak.broadcast(Lu.BroadcastEvent,[s],o,0)}},jk=async({args:e,reply:t})=>{const n=e[0];if(!n)return Tk("Invalid config for SendToRecipe"),t({error:"Invalid config for SendToRecipe"});const r=(i=n.recipePoolId,Object.values(vI).find((e=>e.extraInfo.recipe?.poolId===i))||null);var i;if(!r)return Tk(`No client found for recipe pool id ${n.recipePoolId}`),t({error:`No client found for recipe pool id "${n.recipePoolId}"`});try{const e=Ak.execute(Lu.SendToRecipe,[n],r.send,0,r.serviceSessionId,{async:!n.waitForResponse,timeout:n.timeout});n.waitForResponse?t({success:await e}):t({success:[]})}catch(e){return Tk(`Error sending to recipe ${n.recipePoolId}: ${e?.message||e}`),t({error:e?.message||"There was an error sending to the recipe"})}},Rk=e=>{const{send:t,transmission:n,json:r}=e;Tk(`Raw message Id received from WS: ${r?.messageId}`),Pk(Uu.WS,e)||Ak.processMessage(Uu.WS,t,n,r)},Lk=e=>{const t=(n=e,`${Ru.SocketAcknowledge}${n}`);var n;U_(e,t)},Fk=(e,t)=>{Tk(`Received unknown command [${t}] from service ${e}`)},Uk=async e=>{const{args:t,sourceServiceId:n,send:r,reply:i}=e,o=n,s=t[0],a=s?.user?.apiKey||aI().globalApiKey;if(!a)return Tk(`Received ACK from WS service ${n} but no API key was provided`),i({error:"No API key was provided",errCode:"MISSING_API_KEY"});s.user?.id&&nv.setGlobalUserId(s.user?.id),await xI({serviceSessionId:n,transport:Uu.WS,send:r,terminateFn:()=>{W_(n)},extraInfo:{websocketId:o,recipe:s.recipe,user:{wsApiKey:a,userEmail:s.user?.email,userId:s.user?.id}}}),i({success:[]})},Bk=e=>{Tk(`WS Client ${e} disconnected`),EI(e)},Wk=e=>1===e.sourceServiceId?e.functionName===Lu.GetFileContentFromCacheId:e.functionName===Lu.SocketAckResponse||e.functionName===Lu.ServiceManifest||e.functionName===Lu.SubscribeToService||(!!SI(e.sourceServiceId)||(e.reply({error:`Session id "${e.sourceServiceId}" not found. Please acknowledge the session first.`}),!1)),Gk=async({sourceServiceId:e,args:t,transport:n,send:r})=>{if(n!==Uu.IPC){var i;Tk(`Received manifest from non IPC service ${e}.`)}else{const n=t[0];if(n.devMode){const t=_v.getMatchingDevService(n.name,n.version,"stopped");if(t){Tk(`Found matching previous service ${t.info.name} (${t.info.version}). Reactivating previous client with session id ${t.info.sessionId}`);const o=SI(t.info.sessionId);if(!o)return void Tk(`Could not find previous client instance for ${t.info.name} (${t.info.version}). Aborting manifest injection`);o.send=r,vI[i=e]?delete vI[i]:mI(`Could not find source client with session id ${i}`),Pb(e,t.info.sessionId);const s=await qy(n,n.path);t.info={...t.info,...s},Tk(`Updating manifest for dev service ${t.info.sessionId}`),_v.setServiceManifest(t.info.sessionId,s,"running"),Tk(`Asking service ${e} to assume previous session id ${t.info.sessionId}`),Mb(t.info.sessionId,(e=>`${Ru.AssumeSession}${e}`)(t.info.sessionId)),(e=>{const t=vI[e];t?t.isDevClient?(t.disconnected=!1,t.transport===Uu.IPC&&(II(),kI(e))):mI(`Client with session id ${e} is not a dev client`):mI(`Could not find source client with session id ${e}`)})(t.info.sessionId)}else{_v.addDevService(e,n,"running");const t=SI(e);t?t.isDevClient=!0:xI({serviceSessionId:e,transport:Uu.IPC,send:r,extraInfo:{ipcSocketId:e},isDevClient:!0})}return}Tk(`Received manifest from non dev service ${e} [${n.name}@(${n.version})]. Ignoring...`)}};var Vk=async e=>{var t;Tk("Starting Kemu Hub..."),t=e.desktopMode?"desktop":"runtime",tk=t;const n=e?.ipc?.appSpace||"kemu.",r=e?.ipc?.id||"widgets";if(!e.serviceUrl)throw new Error("Missing service url, please set the `apiUrl` option.");e.errorTracker&&nv.setTracker(e.errorTracker),(e=>{sI={...sI,...e}})({serviceUrl:e.serviceUrl,globalApiKey:e.globalApiKey,environment:e.environment}),Ak.registerFunctionsMiddleware(Wk),e.secrets?.serviceSecrets&&(e=>{gk=e})(e.secrets.serviceSecrets.addServiceSecretFn),e.secrets?.recipeSecrets&&((e=>{dk=e})(e.secrets.recipeSecrets.getRecipeDecryptedSecretsFn),(e=>{hk=e})(e.secrets.recipeSecrets.addRecipeSecretFn),(e=>{fk=e})(e.secrets.recipeSecrets.deleteRecipeSecretFn),(e=>{pk=e})(e.secrets.recipeSecrets.getRecipeSecretMappingsFn)),e.secrets?.hubSecrets&&((e=>{xk=e})(e.secrets.hubSecrets.getHubSecretsFn),(e=>{_k=e})(e.secrets.hubSecrets.addHubSecretsFn),(e=>{Ik=e})(e.secrets.hubSecrets.deleteHubSecretFn)),Ak.registerFunction(Lu.GetServiceContents,oI),Ak.registerFunction(Lu.GetServices,ek),Ak.registerFunction(Lu.GetSystemInfo,ok),Ak.registerFunction(Lu.ShowSecretsConfigScreen,(async({args:t,reply:n})=>{const[{name:r,version:i}]=t;e?.onShowSecretsScreen?(await e.onShowSecretsScreen(r,i),n({success:[]})):n({error:"This hub does not support showing secrets configuration screens",errCode:"GUI_NOT_SUPPORTED"})})),Ak.registerFunction(Lu.UnsubscribeFromService,(({transport:e,reply:t,args:n,sourceServiceId:r})=>{if(e===Uu.WS){const[e]=n,i=SI(r);if(!i)return t({error:`Session id "${r}" not found`});Tk(`Service ${r} unsubscribing from "${e.targetService.serviceName} (${e.targetService.version})"`),t({success:[]}),i?.removeSubscription({serviceName:e.targetService.serviceName,version:e.targetService.version})}})),Ak.registerFunction(Lu.SubscribeToService,(({transport:e,reply:t,args:n,sourceServiceId:r})=>{if(e===Uu.WS){const[e]=n,i=SI(r),o=e.targetService;if(!i)return t({error:`Session id "${r}" not found`});if(Tk(`Service ${r} subscribing to "${o.serviceName} (${o.version})"`),"hub"===o.serviceName)return i.addSubscription(o),void t({success:[]});if(!i.addSubscription(o))return Tk(`Service ${r} already subscribed to "${o.serviceName} (${o.version})", ignoring request.`),t({success:[]});const s=_v.getMatchingService(o.serviceName,o.version);if(!s)return Tk(`Service ${o.serviceName} ${o.version} not active yet`),t({success:[]});if(!s.info.eventEmitter)return Tk(`Service ${o.serviceName} ${o.version} does not have an event emitter, removing subscription`),i.removeSubscription(o),t({error:`Service "${o.serviceName} (${o.version})" does not produce events`});const a=SI(s.info.sessionId);return a?.extraInfo.ipcSocketId&&(Tk(`Sending Broadcast START command to service ${s.info.sessionId}`),Mb(a?.extraInfo.ipcSocketId,Ru.BroadcastStart)),t({success:[]})}})),Ak.registerFunction("stopService",V_),Ak.registerFunction("removeService",H_),Ak.registerFunction("launchService",q_),Ak.registerFunction("getMatchingServices",J_),Ak.registerFunction("getSecretsValues",Q_),Ak.registerFunction(Lu.GetMappedSecrets,rI),Ak.registerFunction(Lu.BroadcastEvent,Dk),Ak.registerFunction(Lu.ServiceManifest,Gk),Ak.registerFunction(Lu.ChooseDirectoryDialog,NI),Ak.registerFunction(Lu.ChooseFileDialog,TI),Ak.registerFunction(Lu.GetUniqueId,Xx),Ak.registerFunction(Lu.SendToRecipe,jk),Ak.registerFunction(Lu.GetDecryptedEdgeApiKey,lk),Ak.registerFunction(Lu.GetHubConfig,uk),Ak.registerFunction(Lu.SocketAckResponse,Uk),Ak.registerFunction(Lu.UninstallService,ak),Ak.registerFunction(Lu.GetRecipeDecryptedSecretsValues,yk),Ak.registerFunction(Lu.GetRecipeSecretMappings,wk),Ak.registerFunction(Lu.AddRecipeSecretMapping,vk),Ak.registerFunction(Lu.DeleteRecipeSecretMapping,bk),Ak.registerFunction(Lu.GetHubSecrets,Ek),Ak.registerFunction(Lu.AddHubSecrets,Ck),Ak.registerFunction(Lu.DeleteHubSecret,$k),Ak.registerFunction(Lu.AddServiceSecret,Sk),Object.entries(Mk).forEach((([e,t])=>{t?Ak.registerFunction(e,t):(Tk(`Skipping registration of "${e}" because it's not implemented`),Ak.registerFunction(e,(({reply:t})=>{t({error:`This hub does not support "${e}"`,errCode:"FUNCTION_NOT_SUPPORTED"})})))})),(e=>{Ob=e})((e=>{const{send:t,transmission:n,json:r}=e;Tk(`Raw message Id received from IPC: ${r?.messageId}`),Pk(Uu.IPC,e)||Ak.processMessage(Uu.IPC,t,n,r)})),B_(Rk),R_(Lk),F_(Fk),L_(Bk),(e=>{$b=e})($I),(e=>{Eb=e})((e=>{const t=(e=>`${Ru.IpcAcknowledge}${e}`)(e);Mb(e,t)})),(e=>{Cb=e})((e=>{Tk(`IPC socket [${e}] disconnected`);const t=SI(e);if(t){Tk(`Found matching service for disconnected socket. SessionId: ${t.serviceSessionId}`);const e=_v.getServiceBySessionId(t.serviceSessionId);_v.setServiceStatus(t.serviceSessionId,"stopped"),e?.devMode?(t.disconnected=!0,II()):EI(t.serviceSessionId)}})),await(e=>(e?.ipcId&&(tb.config.id=e.ipcId),e?.ipcAppSpace&&(tb.config.appspace=e.ipcAppSpace),new Promise((e=>{tb.serve((()=>{kb.info("IPC Server Initiated"),tb.server.on("data",((e,t)=>{const n=Nb[t.id];n?(kb.data(`IPC Socket [${t.id}] data ${e.byteLength} bytes`),Tb(e,n.activeMessage,(e=>n.activeMessage=e),(e=>{if(!e.complete)return;const n=e=>{t.write(e)};if(e.command)return kb.data(`Received command from client [${t.id}]: ${e.command}`),void($b&&$b(t.id,e.command,n));e.klMessage&&Ob&&Ob({send:n,transmission:{sourceServiceId:e.sourceServiceId??-1,targetServiceId:e.targetServiceId??-1,rawMessage:e.rawMessage},json:e.klMessage.json})}))):kb.data(`Received data from unknown client [${t.id}]. Ignoring.`)})),tb.server.on("connect",(e=>{const t=Fy();kb.info(`New client connected. Registered as "${t}"`),e.id=t,Nb[t]={socket:e,activeMessage:null,disconnectHandler:()=>Ab(t)},e.on("close",Nb[t].disconnectHandler),Eb&&Eb(t)})),tb.server.on("disconnect",(e=>{Ab(e.id)})),tb.server.on("error",(e=>{console.log(`IPC Server Error: ${e}`)})),e()})),tb.server.start()}))))({ipcAppSpace:n,ipcId:r}),e?.ws?.disabled||await j_(e?.ws?.port||5368);const i=e?.defaultServicesPath||b.resolve(Ok,"defaultServices");Nk=i;const o=process.env.DEV_SESSION_ID;_v.setHubIpcConfig({recipePath:e?.recipeRootPath,appSpace:n,id:r}),_v.setEnableServiceLogsConfig(!!e?.enableServiceLogs),e?.servicesInstallPath&&(e=>{Jy=e})(e.servicesInstallPath),e?.testServicesInstallPath&&(e=>{Zy=e})(e.testServicesInstallPath);const s=Xy(),a=Qy(),c=async({requiredSecrets:e})=>{const t=Object.keys(e).reduce(((e,t)=>({...e,[t]:process.env[t]})),{});return t.__KEMU_USER_SERVICES_PATH=s,t.__KEMU_USER_TEST_SERVICES_PATH=a,t.__KEMU_SERVICE_URL=aI().serviceUrl,t.__KEMU_ENVIRONMENT=aI().environment,t};e?.getServiceSecretsFn?(_v.setGetSecretsFunction(e.getServiceSecretsFn),eI(e.getServiceSecretsFn)):(_v.setGetSecretsFunction(c),eI(c)),(e=>{nI=e})(e?.getMappedSecretsFn?e.getMappedSecretsFn:async e=>e.reduce(((e,t)=>({...e,[t.name]:[]})),{})),_v.setSpawnNodeFunction(e?.spawnFn?e.spawnFn:({args:e,options:t})=>{const n={...process.env};return V("node",e||[],{...t,env:{...n,...t?.env}})}),e?.noDefaultServices||await _v.loadServices(i,{fixedSession:o?parseInt(o):void 0,singleServiceName:process.env.DEV_SINGLE_SERVICE_NAME,internalServices:!0,enableLogs:!0}),null!==e?.servicesInstallPath&&(await Ky(s)||await h(s,{recursive:!0}),await _v.loadServices(s,{internalServices:!1,singleServiceName:process.env.DEV_SINGLE_SERVICE_NAME,enableLogs:!!e?.enableServiceLogs}));const l=process.env.DEV_NO_SPAWN_LIST?.split(",");await _v.launchServices({noSpawningList:l||[]}),Tk("Kemu Hub started"),(e?.onChooseDirectory||e?.onChooseFile)&&(e=>{OI=e})({chooseDirectory:e.onChooseDirectory,chooseFile:e.onChooseFile})},Yk=e=>{if(e===Uu.WS)return{handleWebsocketConnectionEvent:Lk,handleWebsocketClientDisconnectionEvent:Bk,handleWebsocketMessage:Rk,handleWebsocketClientCommand:Fk,getRemoteInvoke:()=>Ak}},Hk=(e=[])=>{let t;const n=new Promise((n=>{const r=()=>{if(_v.getAllServices().every((e=>"running"===e.status))&&e.every((e=>"running"===_v.getMatchingService(e.name,e.version)?.status)))return n();t=setTimeout(r,100)};r()}));return n.abort=()=>{t&&clearTimeout(t)},n};let zk;const qk=Al("run"),Kk=Gu(),Jk=1e3,Zk=v(process.argv.slice(2)),Xk=e=>"number"==typeof e?{type:pe.Number,value:e}:"string"==typeof e?{type:pe.String,value:e}:"boolean"==typeof e?{type:pe.Boolean,value:e}:Array.isArray(e)?{type:pe.Array,value:e}:e;global.ImageData=q;const Qk=e=>e&&"string"==typeof e.format&&e.data&&e.data instanceof ArrayBuffer;Ie({createCanvas:(e,t)=>J(e,t),loadImage:async e=>{let t=e;if(Qk(e)){const n=e;t=Buffer.from(n.data)}const n=await K(t),r=J(n.width,n.height).getContext("2d");r.drawImage(n,0,0,n.width,n.height);return r.getImageData(0,0,n.width,n.height)}});const eE=(e,t)=>"*"===e?ao.onAnyGlobalVariableChange(t):ao.onGlobalVariableChange(e,t),tE=(e,t,n)=>ao.setGlobalVariable({name:e,value:t,disableChangeNotifications:n?.disableChangeNotifications||!1,disableDefineNotifications:n?.disableDefineNotifications||!1,doNotOverrideExisting:n?.doNotOverrideExisting||!1}),nE=e=>{ao.deleteGlobalVariable({name:e})},rE=()=>ao.getAllVariables(),iE=e=>ao.getGlobalVariable(e),oE=e=>Wi(e),sE=e=>async()=>{throw new Error(`${e} not implemented`)},aE={createImageDataLike:(e,t,n,r="srgb")=>{let i;return i=e instanceof Uint8ClampedArray?e:new Uint8ClampedArray(e),{data:i,width:t,height:n,colorSpace:r,_kemuType:pe.ImageData}},loadImageFile:async e=>{const t=await K(e),n=J(t.width,t.height).getContext("2d");n.drawImage(t,0,0,t.width,t.height);return n.getImageData(0,0,t.width,t.height)},encodeImageData:async(e,t="jpeg",n)=>{const r=J(e.width,e.height);let i;return r.getContext("2d").putImageData(e,0,0),i="png"===t?await r.encode(t):await r.encode(t,n),i}};var cE={start:async r=>{r=r||{};const i=r?.recipePath||Zk.recipePath||process.env.KEMU_EDGE_RECIPE_PATH||process.cwd();if(!i)throw new Error("`recipePath` not provided. Please specify it in the config object, via a command line argument [--recipePath] or as an environment variable [KEMU_EDGE_RECIPE_PATH].");const{parsed:o,error:s}=await e({path:Y(H(i),".env")});s&&console.warn(`Failed to load .env file: ${s.message}. This is not an error, it just means that the .env file is not present or is not readable.`);const a=r.apiKey||process.env.KEMU_API_KEY,c=process.env.KEMU_CONFIG;if(!a)throw new Error("Missing API key. Please provide it via config.apiKey or KEMU_API_KEY environment variable.");if(r.envConfig){const{serviceUrl:e,environment:t}=r.envConfig;if(!e||!t)throw new Error("Missing server URL or environment in config.envConfig")}else if(!c)throw new Error("Missing server URL or environment in config.envConfig");const l=i.endsWith(".json")||i.endsWith(".kemu"),u=l?z(i):i,d=l?i:Y(u,"recipe.kemu"),h=(e=>{try{return JSON.parse(e||"")}catch(e){return null}})(await t(H(d),"utf-8"));if(!h)throw new Error("Failed to parse recipe file");if(!h.author?.id)throw new Error("Missing required author ID in recipe file.");const{serviceUrl:f,environment:p}=r.envConfig||(e=>{const t=Buffer.from(e,"base64").toString("utf8"),[n,r]=t.split("<@>");if(!n||!r)throw new Error("Invalid configuration.");return{serviceUrl:n,environment:r}})(c);await oc();const g={id:h.uuid||String(Date.now()),version:1,author:h.author.id};(e=>{fo=e})(console);const m=Yk(we.WS),y=(e,t)=>{if(t)m?.handleWebsocketMessage({send:b,transmission:{rawMessage:e,sourceServiceId:t.sourceServiceId,targetServiceId:t.targetServiceId},json:t.msg?.json});else{const t=e instanceof Buffer?e.toString():e;m?.handleWebsocketClientCommand(Jk,t)}},v=(vl={instanceServiceId:Jk,sendBuf:y,sendCmd:y,triggerOnCommand:(...e)=>bl(...e),triggerOnConnected:()=>wl(),triggerOnDisconnected:()=>Sl(),triggerOnMessageReceived:(...e)=>_l(...e)},vl);const b=(e,t)=>{if(t)v.triggerOnMessageReceived({send:y,transmission:{rawMessage:e,sourceServiceId:t.sourceServiceId,targetServiceId:t.targetServiceId},json:t.msg.json});else{const t=e instanceof Buffer?e.toString():e;v.triggerOnCommand(t)}},w=Yu(),S=m.getRemoteInvoke();w.disableServiceEncoding(0,!0),S.disableServiceEncoding(Jk,!0);const _=Object.values(h.blocks[he].gates).filter((e=>e.type===ze.hubService&&e.state.service&&!0!==e.state.service?.webOnly)),I=_.map((e=>{const t=e.state.service;return{name:t.name,version:t.version}})),x=Y(u,"services"),k=await n(x).then((()=>!0)).catch((()=>!1));if(I.length>0&&!k)throw new Error("Services directory not found but required services are defined in the recipe. Please make sure there is a `services` directory in the recipe root and add the services you want to use to it.");await Vk({globalApiKey:a,serviceUrl:f,recipeRootPath:u,servicesInstallPath:k?Y(u,"services"):null,noDefaultServices:!0,environment:p,ws:{disabled:!0},secrets:{recipeSecrets:{getRecipeDecryptedSecretsFn:async()=>({...o}),getRecipeSecretMappingsFn:sE("getRecipeSecretMappingsFn"),addRecipeSecretFn:sE("addRecipeSecretFn"),deleteRecipeSecretFn:sE("deleteRecipeSecretFn")}},ipc:{appSpace:"kemu-runner.",id:g.id}}),qk("Waiting for services to run"),await Hk(I),qk("All services are running"),Bc(Kk),Yc(),aa((e=>{qk("Global processing state changed: ",e)})),h.globalVariables&&(h.globalVariables=await zc(h.globalVariables));const E=await Lc(h,"runner",g.version,g.author,mr.Desktop);return zk=E,Vu(E),await Bu({id:h.author.id}),new Promise(((e,t)=>{var n;Wu("acknowledged",(async()=>{await Kk.getServices();const{failed:n,sendToInputWidget:r,invokeRecipeLoadedWidgets:i}=await Uc(E);if(n.length>0){const e=`Some widgets failed to initialize: ${n.join(", ")}`;return t(e)}await i().catch((e=>{console.error("Error invoking recipe loaded widgets: ",e)})),qk("Recipe started"),e({sendToInputWidgetAndWaitForOutput:(e,t)=>{const n=Xk(t);return r({inputName:e,data:n,waitForOutputChild:!0})},sendToInputWidget:(e,t)=>{const n=Xk(t);return r({inputName:e,data:n,waitForOutputChild:!1})},globalVariables:{onChange:eE,setValue:tE,getValue:iE,delete:nE,getAll:rE},status:{onChange:oE},edgeFunctions:{register:Ga.registerFunctionHandler,unregister:Ga.unregisterFunctionHandler,clearAll:Ga.clearAllHandlers}})})),v.triggerOnConnected(),v.triggerOnCommand((n=Jk,`${ye.SocketAcknowledge}${n}`))}))},terminate:async()=>{zk&&await Fc(zk)}};export{pe as DataType,cE as default,Qk as isBinaryFile,aE as utils};