@kemu-io/edge-runtime 1.3.1 → 1.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +3 -3
- package/runner.d.ts +13 -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"jsonp";import s from"crypto-js";import o from"emittery";import"axios";import a from"jszip";import c from"util";import l from"mustache";import{z as u}from"zod";import d,{scryptSync as h,createDecipheriv as f,createHash as p}from"crypto";import{satisfies as g}from"compare-versions";import m from"debug";import y,{mkdir as v,access as b,constants as w,readdir as S,rm as _,readFile as I}from"fs/promises";import x from"minimist";import k,{join as E,dirname as C,resolve as $}from"path";import"node-ipc";import*as O from"fs";import M,{promises as N}from"fs";import T from"tty";import A,{homedir as D,platform as P}from"os";import j from"stream";import L from"buffer";import R from"events";import F from"zlib";import U from"string_decoder";import B from"http";import W from"https";import Y from"net";import G from"tls";import H from"dgram";import V,{fileURLToPath as z}from"url";import q from"node:os";import{spawn as K}from"child_process";import{join as J,resolve as Z,dirname as X}from"node:path";import{ImageData as Q,loadImage as ee,createCanvas as te}from"@napi-rs/canvas";var ne;!function(e){e.STARTING="STARTING",e.PENDING="PENDING",e.RUNNING="RUNNING",e.PAUSED="PAUSED",e.DRAINING="DRAINING",e.STOPPED="STOPPED",e.ERROR="ERROR"}(ne=ne||(ne={}));const re="undefined"!=typeof window&&void 0!==window.document&&void 0!==typeof window.document.createElement,ie="object"==typeof self&&self.constructor&&"DedicatedWorkerGlobalScope"===self.constructor.name,se="undefined"!=typeof process&&null!=process.versions&&null!=process.versions.node,oe={};let ae=0,ce="";const le=e=>oe[e]?oe[e]:null,ue=(e,t)=>{const n=le(e);if(!n)return n;return n.blocks[t]||null},de=(e,t,n)=>{const r=ue(e,t);if(!r)return r;return r.gates[n]},he=(e,t)=>{let n=r(4);for(;oe[n];)n=r(4);const i=(s=e,JSON.parse(JSON.stringify(s)));var s;return i.logs="",i.addLog=e=>{i.logs+=`${(()=>{const e=Date.now();if(e!==ae){const t=new Date;ae=e,ce=t.toJSON()}return ce})()}:: ${e}\n`},i.dbInfo={...t},oe[n]=i,n},fe="interrupt_port",pe="main.js",ge="state.json",me="{#}",ye="UI:",ve="default";var be,we,Se,_e,Ie,xe,ke,Ee;let Ce;!function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(be||(be={})),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"}(we||(we={})),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"}(Se||(Se={})),function(e){e.Javascript="js",e.Python="py",e.Executable="exe"}(_e||(_e={})),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:"}(Ie||(Ie={})),function(e){e.GetServices="getServices",e.SubscribeToService="subscribeToService",e.UnsubscribeFromService="unsubscribeFromService",e.GetServiceContents="getServiceContents",e.SocketAckResponse="socketAckResponse",e.ShowSecretsConfigScreen="showSecretsConfigScreen",e.GetMappedSecrets="getMappedSecrets",e.GetSecretContexts="getSecretContexts",e.OnParentEvent="onParentEvent",e.GetDefaultState="getDefaultState",e.BroadcastEvent="broadcastEvent",e.HubBroadcastEvent="hubBroadcastEvent",e.ServiceManifest="serviceManifest",e.GetState="getState",e.SetState="setState",e.SetOutputs="setOutputs",e.UIEvent="uiEvent",e.GetSystemInfo="getSystemInfo",e.InitializeInstance="initializeInstance",e.TerminateInstance="terminateInstance",e.UninstallService="uninstallService",e.ChooseDirectoryDialog="chooseDirectoryDialog",e.ChooseFileDialog="chooseFileDialog",e.GetUniqueId="getUniqueId",e.RebootToInstallUpdate="rebootToInstallUpdate",e.GetFileContentFromCacheId="getFileContentFromCacheId",e.GetDecryptedEdgeApiKey="getDecryptedEdgeApiKey",e.GetHubConfig="getHubConfig"}(xe||(xe={})),function(e){e.SetDependencyPath="setDependencyPath",e.GetDependencyPath="getDependencyPath"}(ke||(ke={})),function(e){e.IPC="ipc",e.WS="ws"}(Ee||(Ee={}));const $e=()=>{if(!Ce)throw new Error("CanvasManager not set");return Ce},Oe=e=>{Ce=e},Me=(e,t)=>$e().createCanvas(e,t),Ne=e=>re?e.getContext("2d",{willReadFrequently:!0}):e.getContext("2d"),Te=e=>$e().loadImage(e),Ae="-",De=`inner${Ae}`,Pe=`outer${Ae}`,je=`${Pe}input${Ae}`,Le=`${Pe}output${Ae}`,Re=`${De}input${Ae}`,Fe=`${De}output${Ae}`,Ue=e=>(new TextEncoder).encode(e),Be=e=>e===fe,We=e=>e&&void 0!==e.width&&void 0!==e.height&&void 0!==e.data&&e.data.constructor&&"Uint8ClampedArray"===e.data.constructor.name,Ye=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,Ge=e=>e&&"number"==typeof e.x&&"number"==typeof e.y,He=e=>"number"==typeof e?we.Number:"string"==typeof e?we.String:"boolean"==typeof e?we.Boolean:Array.isArray(e)?we.Array:We(e)?we.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?we.AudioBuffer:e&&void 0!==e.byteLength?we.ArrayBuffer:Ye(e)?we.Rect:e&&void 0!==e.x&&void 0!==e.y&&"number"==typeof e.x&&"number"==typeof e.y?we.Point:(e=>e&&"string"==typeof e.format&&e.data&&e.data instanceof ArrayBuffer)(e)?we.BinaryFile:we.JsonObj,Ve=e=>{const t={};let n;n=Array.isArray(e)?e[0]:e;for(const e in n){const r=He(n[e]);t[e]=r}return t},ze=(e,t,n)=>"inner"===e?"input"===t?`${Re}${n}`:`${Fe}${n}`:"input"===t?`${je}${n}`:`${Le}${n}`,qe=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]}},Ke=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 Te(e.data)}};var Je,Ze;!function(e){e.Action="action",e.CustomInput="customInput"}(Je=Je||(Je={})),function(e){e.input="input",e.counter="counter",e.play="play",e.elapsed="elapsed",e.ifGate="ifGate",e.skipEvent="skipEvent",e.between="between",e.map="map",e.parser="parser",e.slider="slider",e.suspend="suspend",e.display="display",e.json="json",e.arrayItem="arrayItem",e.extractImage="extractImage",e.imageConvolution="imageConvolution",e.firstEvent="firstEvent",e.pixelDraw="pixelDraw",e.randomBetween="randomBetween",e.arrayCombine="arrayCombine",e.clock="clock",e.multiplication="multiplication",e.object="object",e.widgetGroup="widgetGroup",e.script="script",e.base64ToImageData="base64ToImageData",e.jsonParse="jsonParse",e.text="text",e.imageCrop="imageCrop",e.imageResize="imageResize",e.value="value",e.imageWarp="imageWarp",e.widgetBundle="widgetBundle",e.sequence="sequence",e.variable="variable",e.hubService="hubService",e.imageFilter="imageFilter",e.recipeLoad="recipeLoad",e.note="note",e.stringify="stringify",e.templateString="templateString",e.expressionEval="expressionEval",e.rescue="rescue",e.objectCombine="objectCombine",e.loop="loop"}(Ze=Ze||(Ze={}));const Xe={};let Qe;const et=async e=>{const t=Xe[e],n={name:fe,type:we.Boolean};if(t){const r={name:t.portName},i=t.data||{type:we.Boolean,value:!0};Qe?(await Qe(!0,t.targetWidgetId,t.thingId,t.recipePoolId,n.name,r,{...i,timestamp:Date.now()},[n]),"timeout"===t.type&&tt(e)):console.warn("Interrupt service has not been initialized")}},tt=e=>{const t=Xe[e];return!!t&&(t.timerRef&&("interval"===t.type?clearInterval(t.timerRef):"timeout"===t.type&&clearTimeout(t.timerRef)),delete Xe[e],!0)};var nt={interruptHandler:et,createInterrupt:(e,t,n,i,s,o,a,c)=>{if(c&&Xe[c])throw new Error("The given interrupt id already exists");const l=c||r().replace(/_/g,"-");if("interval"===e&&!o.interval)throw new Error(`Invalid interval. Expected a number greater than 0, but got '${o.interval}'`);if("timeout"===e&&!o.timeout)throw new Error(`Invalid timeout. Expected a number greater than 0, but got '${o.timeout}'`);if(Xe[l]={data:a,portName:s,recipePoolId:t,targetWidgetId:i,thingId:n,type:e},"interval"===e)Xe[l].timerRef=setInterval((async()=>await et(l)),o.interval);else{if("timeout"!==e)throw new Error(`Invalid interrupt type '${e}'`);Xe[l].timerRef=setTimeout((async()=>await et(l)),o.timeout)}return l},destroyInterrupt:tt,destroyAllInterrupts:()=>{Object.keys(Xe).forEach(tt)},setInvokeChildGateCb:e=>{Qe=e}};const rt=[10001,"Invalid `sourcePort` parameter"],it=[10002,"The gate [%s] does not exist. Have you called `loadWidgets` yet?"],st=[10110,"No storage medium has been loaded, call `loadMedium()` first"],ot=(e,...t)=>JSON.stringify({code:e[0],message:t[0]?c.format(e[1],...t):e[1].replace(/ \[%s\]/g,"")}),at=()=>({inputName:"",dataType:we.Anything}),ct="output",lt={processEvent:async(e,t)=>{const n=t.getState(),r={...at(),...n};if(e.type===r.dataType||r.dataType===we.Anything)return t.nextWidget(ct,{type:e.type,value:e.value});console.error(`Invalid data type: ${e.type} for input: ${r.inputName}. Expected: ${r.dataType}`)},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(ot(rt));const i={currentValue:0,increment:1,...r.getState()};let s=i.increment,o=i.currentValue;const a=await r.getParentAtPort(ut.increment);if(t.name===ut.increment)return void(n.data.type===we.Number&&r.setState({...i,increment:Number(n.data.value)}));if(a){const e=a.getValue();null!==e&&(s=e)}if(t.name===ut.reset)return r.setState({...i,currentValue:0});o+=s,r.setState({currentValue:o,increment:s});const c={type:we.Number,value:o};return r.nextGate(dt,c)},getInputNames:()=>[{name:ut.in,type:we.Anything},{name:ut.reset,type:we.Anything},{name:ut.increment,type:we.Number}],getOutputNames:()=>[{name:dt,type:we.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()},s=Date.now(),o=s-(i.updatedAt||s);return t.name===ft.reset?r.setState({...i,updatedAt:s,elapsed:0}):(r.setState({updatedAt:s,elapsed:o}),r.nextGate(pt,{type:we.Number,value:o}))},getInputNames:()=>[{name:ft.in,type:we.Anything},{name:ft.reset,type:we.Anything}],getOutputNames:()=>[{name:pt,type:we.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()},s=n.data.value,o=!isNaN(Number(s)),a="string"==typeof s;if(!i.useDataPort&&(n.data.type===we.Number||n.data.type===we.String||n.data.type===we.Boolean||n.data.type===we.Anything&&o||n.data.type===we.Anything&&a)){let e=!1;return("Equal"===i.condition&&(n.data.value==i.value||n.data.type===we.Boolean&&n.data.value.toString()===i.value.toString())||"Not Equal"===i.condition&&(n.data.value!==i.value||n.data.type===we.Boolean&&n.data.value!==i.value.toString())||"Greater"===i.condition&&n.data.type===we.Number&&n.data.value>Number(i.value)||"Less"===i.condition&&n.data.type===we.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===we.Number||n.data.type===we.String||n.data.type===we.Boolean||n.data.type===we.Anything&&(o||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===we.Boolean&&i.$lastValue?.toString()===i.value.toString())||"Not Equal"===i.condition&&(i.$lastValue!==i.value||i.$lastInputDataType===we.Boolean&&i.$lastValue!==i.value.toString())||"Greater"===i.condition&&i.$lastInputDataType===we.Number&&Number(i.$lastValue)>Number(i.value)||"Less"===i.condition&&i.$lastInputDataType===we.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:we.Anything,triggerPort:!0},{name:mt.evaluation,type:[we.Number,we.String,we.Boolean]}]:[{name:"in",type:[we.Number,we.String,we.Boolean]}],getOutputNames:e=>e.$lastOutputDataType?[{name:yt,type:e.$lastOutputDataType},{name:vt,type:e.$lastOutputDataType}]:[{name:yt,type:[we.Number,we.String]},{name:vt,type:[we.Number,we.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:we.Anything},{name:wt.reset,type:we.Anything}],getOutputNames:e=>[{name:St,type:e.$$lastDetectedType??we.Anything},{name:_t,type:e.$$lastDetectedType??we.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===we.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:we.Number}],getOutputNames:()=>[{name:kt,type:we.Number},{name:Et,type:we.Number}]};const $t=Object.freeze({in:"in"}),Ot="out";var Mt={onParentEvent:async(e,t,n,r)=>{const i={clamp:!0,...r.getState()},s=Number(n.data.value);if(void 0!==i.fromMax&&void 0!==i.fromMin&&void 0!==i.toMax&&void 0!==i.toMin&&""!==i.fromMax&&""!==i.fromMin&&""!==i.toMax&&""!==i.toMin&&(n.data.type===we.Number||n.data.type===we.Anything&&!isNaN(Number(s)))){let e=((e,t,n,r,i)=>(e-t)*(i-r)/(n-t)+r)(s,Number(i.fromMin),Number(i.fromMax),Number(i.toMin),Number(i.toMax));if(isNaN(e))return;return i.clamp&&(e<Number(i.toMin)&&(e=Number(i.toMin)),e>Number(i.toMax)&&(e=Number(i.toMax))),r.nextGate(Ot,{type:we.Number,value:Number(e)})}},getInputNames:()=>[{name:$t.in,type:we.Number}],getOutputNames:()=>[{name:Ot,type:we.Number}]};const Nt=Object.freeze({in:"in"}),Tt="out";var At={onParentEvent:async(e,t,n,r)=>{const i={convertTo:"Integer",floatPlaces:2,...r.getState()};let s=n.data.value;if(n.data.type===we.Number||n.data.type===we.Anything||n.data.type===we.String){if((!isNaN(Number(s))||"string"==typeof s)&&!Array.isArray(s))return"Integer"===i.convertTo?s=parseInt(s):"Decimal"===i.convertTo?s=parseFloat(Number(s).toFixed(i.floatPlaces)):"String"===i.convertTo?s=String(s):"Abs"===i.convertTo?s=Math.abs(Number(s)):"Round"===i.convertTo&&(s=Math.round(Number(s))),r.nextGate(Tt,{type:"String"===i.convertTo?we.String:we.Number,value:s})}},getInputNames:()=>[{name:Nt.in,type:we.Number}],getOutputNames:e=>{const t="String"===e?.convertTo?we.String:we.Number;return[{name:Tt,type:t}]}};const Dt=Object.freeze({in:"in"}),Pt="out";var jt={onParentEvent:async(e,t,n,r)=>{const i={currentValue:50,min:0,max:100,...r.getState()};let s=!1;return i.currentValue<i.min&&(i.currentValue=i.min,s=!0),i.currentValue>i.max&&(i.currentValue=i.max,s=!0),s&&r.setState(i),r.nextWidget(Pt,{type:we.Number,value:i.currentValue})},getInputNames:()=>[{name:Dt.in,type:we.Anything}],getOutputNames:()=>[{name:Pt,type:we.Number}]};const Lt=Object.freeze({in:"in",reset:"reset"}),Rt="out",Ft="skipped";var Ut={onParentEvent:async(e,t,n,r)=>{const i={lastCalledAt:0,delayMs:500},s={lastCalledAt:0,delayMs:500,...r.getState()};if(t.name===Lt.reset)return r.setState({...s,lastCalledAt:0});const o=Date.now(),a=o-s.lastCalledAt;return s.lastCalledAt===i.lastCalledAt||a>=s.delayMs&&s.delayMs>0?(s.lastCalledAt=o,r.setState(s),r.nextWidget(Rt,n.data)):(n.data.type!==s.$$lastDetectedType&&(s.$$lastDetectedType=n.data.type),r.setState(s),r.nextWidget(Ft,n.data))},getInputNames:()=>[{name:Lt.in,type:we.Anything},{name:Lt.reset,type:we.Anything}],getOutputNames:e=>[{name:Rt,type:e.$$lastDetectedType??we.Anything},{name:Ft,type:e.$$lastDetectedType??we.Anything}]};const Bt="in";var Wt={onParentEvent:async()=>{},getInputNames:()=>[{name:Bt,type:[we.ImageData,we.Number]}],getOutputNames:()=>[]};const Yt=()=>({properties:[{label:"property1",name:"property1"}],detectedProperties:{}}),Gt=(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()},s=n?.data?.value,o=Array.isArray(s);if(n.data.type===we.JsonObj||n.data.type===we.Rect||n.data.type===we.Point||n.data.type===we.BinaryFile||n.data.type===we.Anything||o){let e=!1;for(const t in s){const n=He(s[t]),r=!!i.detectedProperties[t],o=i.detectedProperties[t]?.type!==n;if(!r||o){const r=n===we.JsonObj||n===we.Rect||n===we.Point||n===we.Array;i.detectedProperties[t]={type:n,...r?{shape:Ve(s[t])}:void 0},e=!0}}if(o&&void 0===i.detectedProperties.length&&(i.detectedProperties.length={type:we.Number}),e&&r.setState(i),s){const e=[];for(const t of i.properties||[]){const n=Gt(s,t.label),o=t.label.includes(".");if(void 0!==n){const s=o?He(n):void 0!==i.detectedProperties[t.label]?.type?i.detectedProperties[t.label].type:we.Anything;e.push(r.nextGate(t.name,{type:s,value:n}))}}await Promise.allSettled(e)}}},getInputNames:()=>[{name:"in",type:we.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:we.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:Yt};const Vt="output",zt="noItem";var qt={onParentEvent:async(e,t,n,r)=>{const i={index:0,...r.getState()};let s=i.index;const o=n.data.value,a="string"==typeof n.data.value,c=Array.isArray(n.data.value);if(n.data.type===we.Anything&&(c||a)||n.data.type===we.String&&a||n.data.type===we.Array&&c){s<0&&(s=o.length+s);const e=a?we.String:He(o[s]);return e!==i.$$lastDetectedType&&r.setState({...i,$$lastDetectedType:e}),void 0!==o[s]?r.nextGate(Vt,{value:o[s],type:e}):r.nextGate(zt,{value:!0,type:we.Boolean})}},getInputNames:()=>[{name:"in",type:[we.Array,we.String]}],getOutputNames:e=>[{name:Vt,type:e.$$lastDetectedType??we.Anything},{name:zt,type:we.Boolean}]};const Kt={},Jt=e=>(Kt[e]||(Kt[e]={canvasFrom:Me(320,240),canvasTo:Me(320,240)}),Kt[e]),Zt=Object.freeze({image:"image",rect:"rect"}),Xt="image";var Qt={onParentEvent:async(e,t,n,r)=>{const i=Jt(r.id),s={offset:{height:0,left:0,top:0,width:0},...r.getState()},o=[we.Anything,we.Rect,we.JsonObj];if(t.name===Zt.rect&&Ye(n.data.value)&&o.includes(n.data.type)&&(s.rect=n.data.value,r.setState({...s})),t.name===Zt.image){if(!((n.data.type===we.ImageData||n.data.type===we.Anything)&&We(n.data.value)))throw new Error("Invalid image data. Expected a valid ImageData type");i.lastImage=n.data.value}if(i.lastImage&&s.rect){const e=((e,t,n,r,i)=>{if(r&&r.getContext){const s=r.getContext("2d"),o=n.getContext("2d");if(s&&o){n.width=e.width,n.height=e.height,o.putImageData(e,0,0);const a={...i};i&&(a.height=Number(i.height),a.width=Number(i.width),a.left=Number(i.left),a.top=Number(i.top));const c={top:0,width:0,left:0,height:0,...a};return i&&(Number.isInteger(c.width)||(c.width=t.width*c.width),Number.isInteger(c.height)||(c.height=t.height*c.height),Number.isInteger(c.left)||(c.left=t.left+t.width*c.left),Number.isInteger(c.top)||(c.top=t.top+t.height*c.top)),r.width=t.width+c.width,r.height=t.height+c.height,s.drawImage(n,t.left+c.left,t.top+c.top,t.width+c.width,t.height+c.height,0,0,r.width+c.width,r.height+c.height),s.getImageData(0,0,r.width||1,r.height||1)}}return e})(i.lastImage,s.rect,i.canvasFrom,i.canvasTo,s.offset);r.setState({...s,rect:null}),i.lastImage=void 0,await r.nextWidget(Xt,{type:we.ImageData,value:e})}},getInputNames:()=>[{name:Zt.image,type:we.ImageData},{name:Zt.rect,type:[we.Rect,we.JsonObj]}],getOutputNames:()=>[{name:Xt,type:we.ImageData}],initialize:async e=>{Jt(e.widgetId)},terminate:async e=>{delete Kt[e.widgetId]}};const en=(e,t)=>{const n=Math.round(Math.sqrt(t.length)),r=Math.floor(n/2),i=e.data,s=e.width,o=e.height,a=s,c=o,l=((e,t,n)=>{if(re)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<o&&u>=0&&u<s){const r=4*(c*s+u),o=t[e*n+a];f+=i[r]*o,p+=i[r+1]*o,g+=i[r+2]*o,m+=i[r+3]*o}}u[h]=f,u[h+1]=p,u[h+2]=g,u[h+3]=m+1*(255-m)}return l},tn=[-1,0,1,-2,0,2,1,0,1],nn=Object.freeze({image:"image"}),rn="image";var sn={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),s={matrix:[...tn],...i};if(n.data.type===we.ImageData||n.data.type===we.Anything&&We(n.data.value)){const e=en(n.data.value,s.matrix);return r.nextGate(rn,{type:we.ImageData,value:e})}},getInputNames:()=>[{name:nn.image,type:we.ImageData}],getOutputNames:()=>[{name:rn,type:we.ImageData}]};const on=Object.freeze({output:"output",aborted:"aborted"}),an=()=>({inputs:2,matchingOutputs:!0,lastInputIndex:-1,delayMs:500,triggeredAt:0}),cn=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:we.Anything})));return n.push({name:"reset",type:we.Anything}),n};var ln={onParentEvent:async(e,t,n,r)=>{const i={inputs:2,matchingOutputs:!0,lastInputIndex:-1,delayMs:500,triggeredAt:0,...r.getState()};if("reset"===t.name)return r.setState({...i,triggeredAt:0});const s=Date.now(),o=s-i.triggeredAt;if(i.triggeredAt&&!(o>=i.delayMs&&i.delayMs>0)&&i.delayMs)return r.nextGate(on.aborted,n.data);{i.triggeredAt=s;const e=cn(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(on.output,n.data),r.setState(i)}},getInputNames:cn,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:we.Anything})));return e.push({name:on.aborted,type:we.Anything}),e}return[{name:on.output,type:we.Anything},{name:on.aborted,type:we.Anything}]},getDefaultState:an};const un=(e,t,n,r,i,s)=>{if(i){const o=e.measureText(i),a=o.fontBoundingBoxAscent+o.fontBoundingBoxDescent;e.fillStyle=r,e.fillRect(t,n-s,1.1*o.width,a),e.font=`${s}px Arial`,e.fillStyle="black",e.fillText(i,t,n)}},dn=(e,t,n,r,i,s,o)=>{e.fillStyle=i,e.fillRect(t,n,r,r),un(e,t,n,i,s,o)},hn=(e,t,n,r,i,s)=>{e.beginPath(),e.strokeStyle=r,e.lineWidth=n,e.rect(t.left,t.top,t.width,t.height),e.stroke();const o=n/2;un(e,t.left-o,t.top-o,r,i,s)},fn={},pn=e=>(fn[e]||(fn[e]={memCanvas:Me(320,240),lastFrame:void 0,pixels:void 0}),fn[e]),gn=Object.freeze({image:"image",pixels:"pixels"}),mn="image";var yn={onParentEvent:async(e,t,n,r)=>{const i=pn(r.id),s={fontSize:12,color:"#00ff00",size:2,...r.getState()},o=(n.data.type===we.ImageData||n.data.type===we.Anything)&&We(n.data.value);if(t.name===gn.pixels){const e=(e=>Ge(e)||Ye(e)||Array.isArray(e)&&e[0]&&(Ge(e[0])||Ye(e[0])))(n.data.value);if(!e)return;i.pixels=n.data.value}if(t.name===gn.image&&o){const e=n.data.value;i.lastFrame=e}if(i.lastFrame&&i.pixels&&i.memCanvas){const e=(e=>{const{sourceImage:t,pixels:n,memCanvas:r,size:i,color:s,labelProp:o,fontSize:a}=e;if(r){const e=Ne(r);if(e){r.width!==t.width&&(r.width=t.width),r.height!==t.height&&(r.height=t.height),e.putImageData(t,0,0);const c=Array.isArray(n)?n:[n];for(let t=0;t<c.length;t++){const n=c[t],r=o?n[o]:"";Ye(n)?hn(e,n,i,s,r,a):Ge(n)&&dn(e,n.x,n.y,i,s,r,a)}return e.getImageData(0,0,r.width,r.height)}}return t})({sourceImage:i.lastFrame,pixels:i.pixels||[],memCanvas:i.memCanvas,size:s.size,color:s.color,labelProp:s.labelProp,fontSize:s.fontSize});return i.lastFrame=void 0,i.pixels=void 0,r.setState({...s}),r.nextWidget(mn,{type:we.ImageData,value:e})}r.setState(s)},getInputNames:()=>[{name:gn.image,type:we.ImageData},{name:gn.pixels,type:[we.Rect,we.Point,we.Array,we.JsonObj]}],getOutputNames:()=>[{name:mn,type:we.ImageData}],initialize:async e=>{pn(e.widgetId)},terminate:async e=>{delete fn[e.widgetId]}};const vn=Object.freeze({in:"in"}),bn="output",wn=e=>{const t=String(e).split(".");return t.length<2?0:t[1].length};var Sn={onParentEvent:async(e,t,n,r)=>{const i={min:1,max:100,...r.getState()},s=!Number.isInteger(i.min),o=!Number.isInteger(i.max),a=s||o;let c=(l=i.min,u=i.max,Math.random()*(u-l)+l);var l,u;if(a){let e=0;if(s&&(e=wn(i.min)),o){const t=wn(i.max);t>e&&(e=t)}c=Number(c.toFixed(e))}else c=Math.floor(c);return r.nextGate(bn,{type:we.Number,value:c})},getInputNames:()=>[{name:vn.in,type:we.Anything}],getOutputNames:()=>[{name:bn,type:we.Number}]};const _n=Object.freeze({output:"output",totalItems:"totalItems"}),In=Object.freeze({trigger:"trigger",clear:"clear"}),xn=()=>({$$$time:0,totalSentItems:-1,totalSentAt:0,$$list:[],$$outputShape:{},totalInputs:1}),kn=async(e,t)=>t.nextGate(_n.totalItems,{type:we.Number,value:e});var En={onParentEvent:async(e,t,n,r)=>{const i={$$$time:0,totalSentItems:-1,totalSentAt:0,$$list:[],$$outputShape:{},totalInputs:1,...r.getState()};if(t.name===In.clear)return i.$$list=[],i.properties?.autoFilled&&delete i.properties,r.setState(i),kn(i.$$list.length,r);const s=t.name===In.trigger;if(!s)if(Array.isArray(n.data.value))n.data.type!==we.Array&&n.data.type!==we.Anything||(i.$$outputShape={...i.$$outputShape,...e?.jsonShape},i.$$list=i.$$list.concat(n.data.value),r.setState({...i}),await kn(i.$$list.length,r));else{const t=`$$primitive_${Object.keys(i.$$outputShape).length}`;n.data.type===we.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 kn(i.$$list.length,r)}if(s){Object.keys(i.$$outputShape).length&&(i.properties={autoFilled:!0,jsonShape:{...i.$$outputShape}});const e=i.$$list.length,t=[...i.$$list];return i.$$list=[],r.setState({...i}),await kn(e,r),r.nextGate(_n.output,{type:we.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:we.Anything})));return n.push({name:In.clear,type:we.Anything},{name:In.trigger,type:we.Anything}),n},getOutputNames:e=>[{name:_n.output,type:we.Array,...e.properties?{jsonShape:e.properties?.jsonShape}:void 0},{name:_n.totalItems,label:"Total Items",type:we.Number}],getDefaultState:xn};const Cn=Object.freeze({start:"start",stop:"stop"}),$n="output",On="clock_interrupt";var Mn={onParentEvent:async(e,t,n,r)=>{const i={enabled:!1,interval:1e3,intervalMode:"ms",...r.getState()};if(Be(e?.name||"")&&t.name===On)return r.nextGate($n,{type:we.Boolean,value:!0});if(t.name===Cn.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!==Cn.start||i.enabled||i.$$interruptId||(i.$$interruptId=r.registerInterrupt("interval",On,{interval:i.interval}),i.enabled=!0,r.setState(i))},getInputNames:()=>[{name:Cn.start,type:we.Anything},{name:Cn.stop,type:we.Anything}],getOutputNames:()=>[{name:$n,type:we.Boolean}],initialize:async e=>{const t=e.getState();if(t.enabled&&!t.$$interruptId){const n=e.registerInterrupt("interval",On,{interval:t.interval});e.setState({...t,$$interruptId:n})}}};const Nn=Object.freeze({in:"in"}),Tn="output",An=(e,t,n)=>"number"==typeof e?Number((e*t).toFixed(n)):e;var Dn={onParentEvent:async(e,t,n,r)=>{const i={userProperties:[],factor:2,decimalPoints:2,...r.getState()},s=n.data.type;let o=n.data.value,a=!1;return e?.jsonShape&&(i.detectedInputJson={...i.detectedInputJson,...e?.jsonShape},a=!0),i.detectedInputType||(i.detectedInputType=s,a=!0),n.data.type===we.Array&&("number"==typeof n.data.value?.[0]?o=((e,t,n)=>{const r=(e||[]).map((e=>An(e,t,n)));return r})(n.data.value,i.factor,i.decimalPoints):"object"==typeof n.data.value?.[0]&&(o=((e,t,n,r)=>{const i=(e||[]).map((e=>{const i={...e};return Object.keys(i).forEach((e=>{r?.length&&!r?.includes(e)||(i[e]=An(i[e],t,n))})),i}));return i})(n.data.value,i.factor,i.decimalPoints,i.userProperties))),n.data.type===we.Number&&(o=An(n.data.value,i.factor,i.decimalPoints)),a&&r.setState(i),r.nextGate(Tn,{type:s,value:o})},getInputNames:()=>[{name:Nn.in,type:[we.Array,we.Number]}],getOutputNames:e=>[{name:Tn,type:e.detectedInputType||we.Number,jsonShape:e.detectedInputJson}]};const Pn={},jn=Object.freeze({output:"output"}),Ln=Object.freeze({trigger:"trigger"}),Rn=e=>e===we.ArrayBuffer||e===we.AudioBuffer||e===we.BinaryFile||e===we.ImageData||e===we.ImageBitmap||e===we.Array||e===we.JsonObj,Fn=()=>({useTriggerPort:!0,properties:[{name:"x",label:"x",type:we.Number,value:10},{name:"y",label:"y",type:we.Number,value:20}]}),Un=e=>{const t={};for(let n=0;n<e.properties.length;n++)t[e.properties[n].label]=e.properties[n].type;return t},Bn=(e,t)=>{const n={};for(let r=0;r<e.properties.length;r++){let i=e.properties[r].value;const s=e.properties[r].type;Rn(s)&&(i=Pn[t][e.properties[r].name]),s===we.Number?i=Number(i):s===we.String&&(i=String(i)),n[e.properties[r].label]=i}return n};var Wn={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),s=structuredClone(i),o={...Fn(),...s};if(t.name===Ln.trigger){const e=Bn(o,r.id);return r.nextWidget(jn.output,{type:we.JsonObj,value:e})}const a=o.properties.findIndex((e=>e.name===t.name));if(-1!==a){const e=o.properties[a];let t=n.data.type===e.type;if(!t&&n.data.type===we.Anything){t=He(n.data.type)===e.type}if(t){const t=Rn(n.data.type);Pn[r.id]=Pn[r.id]||{},t?(Pn[r.id][e.name]=n.data.value,o.properties[a].value=void 0):o.properties[a].value=n.data.value,o.properties[a].$$invalidInputType=!1}else o.properties[a].$$invalidInputType=!0;if(r.setState(o),!o.useTriggerPort){const e=Bn(o,r.id);return r.nextWidget(jn.output,{type:we.JsonObj,value:e})}}},getInputNames:e=>{const t={...Fn(),...e},n=t.properties.map((e=>({name:e.name,label:e.label,type:e.type})));return t.useTriggerPort&&n.push({name:Ln.trigger,label:Ln.trigger,type:we.Anything}),n},getOutputNames:e=>[{name:jn.output,label:jn.output,type:we.JsonObj,jsonShape:Un(e)}],getDefaultState:Fn,initialize:async e=>{Pn[e.widgetId]={}},terminate:async e=>{delete Pn[e.widgetId]}};const Yn=async e=>{const t=(e,t)=>e.split(t)[1];if(e.startsWith(je)){const n=t(e,je);return ze("inner","input",n)}if(e.startsWith(Fe)){const n=t(e,Fe);return ze("outer","output",n)}return null},Gn=()=>({canvasPosition:{x:0,y:0},canvasZoom:1,inputs:[{name:"input",type:[we.Anything],index:0}],outputs:[{name:"output",type:[we.Anything],index:0}],name:"Custom Widget 1",description:"",type:"custom"}),Hn=e=>{const t={...Gn(),...e},n=t.inputs.map(((e,t)=>({name:ze("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:ze("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 Vn={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),s={...Gn(),...i},o=Hn(s,(r.recipePoolId,r.recipeType,r.thingRecipeId,r.id));for(let e=0;e<o.length;e++){const i=o[e];if(t.name===i.name&&(i.type.includes(we.Anything)||i.type.includes(n.data.type))){const e=await Yn(t.name);e&&await r.nextWidget(e,{type:n.data.type,value:n.data.value})}}},getInputNames:Hn,getOutputNames:e=>{const t={...Gn(),...e},n=t.outputs.map(((e,t)=>({name:ze("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:ze("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:Gn};const zn=(e,t,n,r,i)=>{const s=4*(t*n.width+e),o=n.data[s],a=n.data[s+1],c=n.data[s+2];return Math.abs(o-r.r)<=i&&Math.abs(a-r.g)<=i&&Math.abs(c-r.b)<=i};var qn={getPixelValueAtIndex:(e,t)=>{const n=e.data,r=n[t]||0,i=n[t+1]||0,s=n[t+2]||0;return{avr:(r+i+s)/3,r:r,g:i,b:s}},getBoundingBox:(e,t,n)=>{const r=e.width,i=e.height,s=new Set,o=Number(n.threshold||0),a=isNaN(o)?10:o,c=(n,o)=>{const c=[[n,o]];let l=n,u=n,d=o,h=o;for(;c.length>0;){const n=c.shift();if(!n)continue;const[o,f]=n;o<0||f<0||o>=r||f>=i||s.has(`${o},${f}`)||!zn(o,f,e,t,a||0)||(s.add(`${o},${f}`),l=Math.min(l,o),u=Math.max(u,o),d=Math.min(d,f),h=Math.max(h,f),c.push([o+1,f],[o-1,f],[o,f+1],[o,f-1]))}return{minX:l,maxX:u,minY:d,maxY:h}},l=[];for(let o=0;o<i;o+=4)for(let i=0;i<r;i+=4)if(!s.has(`${i},${o}`)&&zn(i,o,e,t,a)){const{minX:e,maxX:t,minY:r,maxY:s}=c(i,o),a=t-e,u=s-r;if(a>=(n.minWidth||1)&&u>=(n.minHeight||1)&&l.push({left:e,top:r,width:a,height:u}),n.maxBoxes&&l.length>=n.maxBoxes)return l}return l},copyImageData:e=>new ImageData(new Uint8ClampedArray(e.data),e.width,e.height),setPixelValueAtIndex:(e,t,n)=>{const r=e.data,i="object"==typeof n,s=i?n.r:n,o=i?n.g:n,a=i?n.b:n;r[t]=s,r[t+1]=o,r[t+2]=a,r[t+3]=255}};const Kn=e=>He(e);var Jn,Zn,Xn,Qn,er,tr,nr,rr,ir,sr,or,ar,cr;!function(e){e.Seats="seats",e.RecipeInvocations="recipe_invocations",e.HubServices="hub_services",e.RecipeExports="recipe_exports"}(Jn||(Jn={})),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"}(Zn||(Zn={})),function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(Xn||(Xn={})),function(e){e.Bundle="bundle",e.Group="group"}(Qn||(Qn={})),function(e){e.Hardware="hardware",e.Virtual="virtual"}(er||(er={})),function(e){e.Cloud="cloud",e.Web="web"}(tr||(tr={})),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"}(nr||(nr={})),function(e){e.Gateway="gateway",e.Timer="timer"}(rr||(rr={})),(ir||(ir={})).InstallInProgress="installation-in-progress",function(e){e.InstallDependencies="install-dependencies",e.GetInstalledDependencies="get-installed-dep"}(sr||(sr={})),function(e){e.Success="success",e.Error="error",e.Pending="pending"}(or||(or={})),function(e){e.NotFound="not-found",e.BadRequest="bad-request",e.Forbidden="forbidden",e.InternalError="internal-error"}(ar||(ar={})),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"}(cr||(cr={}));let lr=null;var ur=()=>{if(!lr)throw new Error("Required function is not set");return lr};class dr 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 hr extends Error{constructor(e,t){super(e),this.name="UserCodeError",t&&(this.stack=t)}}const fr=(e,t)=>`\n\t\tfunction _user_code_(){\n\t\t\t${t===Xn.Browser?"\n\t\t\tvar global = {\n\t\t\t\t__user_code: true\n\t\t\t};\n\t\t\tvar process = {};\n\t\t\tvar globalThis = global;\n\t\t\tvar require = this.___notSupportedMethod;\n\t\t\t":"\n\t\t\tvar require = this.require;\n\t\t\tvar process = this.kemuProcess;\n\t\t\t"}\n\t\t\t\n\t\t\tvar console = this.console;\n\t\t\tvar eval = () => {};\n\t\t\tvar document = {};\n\t\t\tvar navigator = {};\n\t\t\tvar window = this.window;\n\t\t\tvar alert = this.notify.info;\n\t\t\tvar DataType = this.dataTypesEnum;\n\t\t\tvar setInterval = this.setInterval;\n\t\t\tvar setTimeout = this.setTimeout;\n\t\t\tvar addEventListener = this.addEventListener;\n\t\t\tvar removeEventListener = this.removeEventListener;\n\t\t\tvar requestAnimationFrame = this.___notSupportedMethod;\n\t\t\tvar __delay = (ms) => new Promise((resolve, reject) => setTimeout(resolve, ms, reject));\n\n\t\t\tvar Kemu = {\n\t\t\t\tservices: {\n\t\t\t\t\thttp: { ...this.httpWebService },\n\t\t\t\t\tdynamoDb: { ...this.dynamoService },\n\t\t\t\t\tgoogleSheets: {\n\t\t\t\t\t\t...this.googleSheetsService,\n\t\t\t\t\t}\n\t\t\t\t},\n\n\t\t\t\timage: this.imageHelpers,\n\t\t\t\tvariable: this.variablesManager,\n\n\t\t\t\thelpers: {\n\t\t\t\t\tdecodeDataType: this.decodeDataType,\n\t\t\t\t\tcryptoJS: this.CryptoJS,\n\t\t\t\t\tjsonp: this.jsonp,\n\t\t\t\t\tdelay: __delay,\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tvar sendToPort;\n\n\t\t\t// --- User Methods Start ---\n\t\t\t${e||""};\n\t\t\t// --- User Methods End ---\n\t\t\t\n\t\t\t// Processes the user code asynchronously.\n\t\t\tconst asyncProcessEvent = async (targetPort, sourcePort, event) => {\n\t\t\t\tconst userProcessEvent = typeof processEvent === 'undefined' ? undefined : processEvent;\n\t\t\t\tif(userProcessEvent) {\n\t\t\t\t\ttry{\n\t\t\t\t\t\treturn await userProcessEvent(targetPort, sourcePort, event, sendToPort);\n\t\t\t\t\t}catch(e){\n\t\t\t\t\t\tthis.__errorTracer(e);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/** invoked the very first time the recipe is initialized */\n\t\t\tconst asyncRecipeInit = async (context) => {\n\t\t\t\ttry {\n\t\t\t\t\tif(typeof recipeInit === 'function') {\n\t\t\t\t\t\treturn recipeInit(context);\n\t\t\t\t\t}\n\t\t\t\t}catch(e){\n\t\t\t\t\tthis.__errorTracer(e);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/** invoked every time the code is about to be replaced */\n\t\t\tconst asyncOnTerminate = async (context) => {\n\t\t\t\ttry {\n\t\t\t\t\tif(typeof onTerminate === 'function') {\n\t\t\t\t\t\treturn onTerminate(context);\n\t\t\t\t\t}\n\t\t\t\t}catch(e){\n\t\t\t\t\tthis.__errorTracer(e);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/** updates the function that allows widget contexts to send data to the next widget */\n\t\t\tconst setSendToPort = (sendNextFun) => {\n\t\t\t\tsendToPort = sendNextFun;\n\t\t\t}\n\n\t\t\t/** invoked the every time the user code is compiled. */\n\t\t\tconst asyncMainEvent = async (sendNextFun) => {\n\t\t\t\ttry{\n\t\t\t\t\tsetSendToPort(sendNextFun);\n\t\t\t\t\tif(typeof main === 'function'){\n\t\t\t\t\t\treturn main();\n\t\t\t\t\t}\n\t\t\t\t}catch(e){\n\t\t\t\t\tthis.__errorTracer(e);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tasyncProcessEvent: asyncProcessEvent,\n\t\t\t\tmain: asyncMainEvent,\n\t\t\t\trecipeInit: asyncRecipeInit,\n\t\t\t\tsetSendToPortFun: setSendToPort,\n\t\t\t\tonTerminate: asyncOnTerminate,\n\t\t\t\tgetLocalContext: () => global,\n\t\t\t\tgetWidgetInputs: typeof getWidgetInputs === 'undefined' ? undefined : getWidgetInputs,\n\t\t\t\tgetWidgetOutputs: typeof getWidgetOutputs === 'undefined' ? undefined : getWidgetOutputs,\n\t\t\t};\n\t\t}\n\t\t\n\t\treturn function compiler(context){\n\t\t\treturn _user_code_.call(context)\n\t\t}\n\n\t\treturn compiler;\n\t`,pr=(e,t,n,r)=>{const o=fr(e,n),a={...t,document:{},__errorTracer:e=>{if(e instanceof dr)throw e;throw new hr(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:qn,...n===Xn.Cloud?{require:ur(),kemuProcess:process.env.KEMU_PROCESS?process.env.KEMU_PROCESS:{}}:{},jsonp:i,CryptoJS:s,decodeDataType:Kn,window:{addEventListener:t?.addEventListener,removeEventListener:t?.removeEventListener}};try{const e="browser"===(()=>{if(re)return"browser";if(se)return"node";if(ie)return"worker";throw new Error("Unsupported environment")})()?(e=>e.replace(/[//]{2}[ ]*@kemu-cloud[ \t]*\{[\s\S]*?[//]{2}[ ]*@kemu-cloud[ \t]*\}/gim,""))(o):(e=>e.replace(/[//]{2}[ ]*@kemu-browser[ \t]*\{[\s\S]*?[//]{2}[ ]*@kemu-browser[ \t]*\}/gim,""))(o),t=new Function(e);return{compiledModule:t()(a)}}catch(e){return{error:{name:"CompileError",message:e.message,stack:e.stack}}}},gr="main",mr="My Script",yr="This is a test script.",vr=`\n/**\n * Name: ${mr}\n * Description: ${yr}\n */\n\nconst getWidgetInputs = () => [\n\t{ name: 'Input 1', type: DataType.Number }\n];\n\nconst getWidgetOutputs = () => [\n\t{ name: 'Output 1', type: DataType.Number }\n]\n\nlet counter = 0;\n\nconst processEvent = async (targetPort, sourceWidget, event) => {\n\tif(targetPort.name === 'Input 1'){\n\t\treturn sendToPort('Output 1', {\n\t\t\ttype: DataType.Number,\n\t\t\tvalue: counter++,\n\t\t});\n\t}\n}\n`.trim(),br=()=>({pauseExecution:!1,autoPauseOnError:!0,$$eventListeners:{},version:2,metadata:{name:mr,description:yr},pages:{[gr]:{code:vr,language:"javascript",name:"My First Script"}}}),wr=(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 fr(t,e).split(t)[0].split("\n").length+2})(t),n.column=i.column)}return e.message&&(n.message=e.message),n},Sr=(e,t)=>{const n={...{...br(),...t.getState()},$$error:e||void 0};e&&console.error(e.message),t.setState(n)},_r=new o;let Ir,xr,kr={},Er={};const Cr=e=>{const t=de(Ir,xr,e);if(!t)throw new Error(`Widget ${e} not found in thing ${xr}`);return t},$r=(e,t)=>`${e}:${t}`,Or=e=>`${Cr(e.createdByWidgetId).id}::${e.variableName}`,Mr=e=>`${ye}${e}`;var Nr=e=>{const t=Cr(e.createdByWidgetId),n=Or({variableName:e.variableName,createdByWidgetId:e.createdByWidgetId});Er[n]={type:e.type,subscriberWidgetId:t.id,subscriberWidgetType:t.type}},Tr=e=>{const t=Or({variableName:e.variableName,createdByWidgetId:e.createdByWidgetId});delete Er[t]},Ar=async e=>{const t=Cr(e.setByWidgetId);if(!t)throw new Error(`Widget ${e.setByWidgetId} not found in thing ${xr} in recipe ${Ir}`);const n=e.variableName.startsWith(ye)?Or({variableName:e.variableName,createdByWidgetId:e.setByWidgetId}):e.variableName;kr[n]={value:e.value,type:e.type};const r={value:e.value,type:e.type,varName:e.variableName,isUIElement:e.variableName.startsWith(ye),setByWidgetType:t.type,setByWidgetId:e.setByWidgetId};await _r.emit($r(e.variableName,e.type),r),e.type!==we.Anything&&await _r.emit($r(e.variableName,we.Anything),r)},Dr=e=>{const{readerWidgetId:t,variableName:n}=e;if(!Cr(t))throw new Error(`Widget ${t} not found in thing ${xr} in recipe ${Ir}`);const r=n.startsWith(ye)?Or({variableName:e.variableName,createdByWidgetId:e.readerWidgetId}):n,i=kr[r];if(i)return{type:i.type,value:i.value}},Pr=e=>{const{widgetId:t,variableName:n,type:r}=e;if(!Cr(t))throw new Error(`Widget ${t} not found in thing ${xr} in recipe ${Ir}`);const i=$r(n,r);let s;return s=_r.on(i,(async r=>{de(Ir,xr,t)?await e.onValueChange(r):(console.warn(`Zombie widget ${t} detected, unsubscribing from variable events "${n}"`),s?.())})),s},jr=(e,t)=>{const n=$r(e,we.Anything);return _r.on(n,(async e=>{const{isUIElement:n,...r}=e;await t(r)}))},Lr=e=>{Er={},kr={},Ir=e.recipePoolId,xr=e.thingId};const Rr="setTimeout",Fr="variableChanged",Ur=e=>{const{recipePoolId:t,thingId:n,scriptWidgetId:r}=e,i=de(t,n,r);if(!i)throw new Error(`Widget "${r}" not found in recipe "${t}"`);const s=(e,t)=>{const n=Dr({readerWidgetId:r,variableName:e});if(n||t)return void 0===n?{value:t?.value??t,type:t?.type??He(t)}:{value:n.value,type:n.type}},o=(t,n,s)=>{if(!e.setState)return void console.warn("Cannot subscribe to variable changes without a setState function");const o={...br(),...e.getState()},a=Pr({variableName:t,type:we.Anything,widgetId:r,onValueChange:async e=>{n?e.setByWidgetType===Ze.widgetGroup&&e.setByWidgetId===i.groupId&&await s(e):s(e)}});delete o.$$eventListeners[t],o.$$eventListeners[t]={handler:s,abort:async()=>{a()},name:Fr},e.setState(o)};return{get:s,set:async(e,t,n)=>{await Ar({variableName:e,type:n||He(t),setByWidgetId:r,value:t})},onValueChange:(e,t)=>{o(e,!1,t)},onUIValueChange:(e,t)=>{const n=Mr(e);o(n,!0,t)},getUIValue:e=>{const r=Mr(e),o=s(r);if(o)return{value:o.value,type:o.type};const a=i.groupId;if(!a)throw new Error("You can only read UI variables from inside a widgetGroup");const c=de(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.defaultValue;if(void 0===d)throw new Error(`Field "${e}" in widgetGroup "${l.name}" has no default value`);return{value:d,type:He(d)}}}},Br="__command-compile__";let Wr;const Yr=()=>{throw new Error("Method not implemented")},Gr=(e,t,n)=>{const i=(e,...n)=>{const r={...br(),...t.getState()}.$$eventListeners[e];r&&r.handler(n)},s={};return Object.keys(we).forEach((e=>{s[e]=we[e]})),{logger:zr(),dataTypesEnum:s,notify:{success:e=>{t.getState()?.$$managedUI?.notify?.success(e)},error:e=>{t.getState()?.$$managedUI?.notify?.error(e)},info:e=>{t.getState()?.$$managedUI?.notify?.info(e)}},variablesManager:e.variablesManager?Ur({recipePoolId:n.recipePoolId,scriptWidgetId:n.widgetId,thingId:n.thingId,getState:t.getState,setState:t.setState}):{get:Yr,set:async()=>Yr(),onValueChange:Yr,onUIValueChange:Yr,getUIValue:Yr},setTimeout:(n,i,s)=>{if(e.withTimers&&t&&t.setState&&t.registerInterrupt){const e=r(),o={...br(),...t.getState()};o.$$eventListeners[e]={handler:n,rejectHandler:s,name:Rr},t.setState(o),t.registerInterrupt("timeout",e,{timeout:i},void 0,e)}},addEventListener:(e,n)=>{if(t.setState){const s=r(),o={...br(),...t.getState()};o.$$eventListeners[s]={handler:n,name:e},t.setState(o),window.addEventListener(e,i.bind(s))}else console.warn(`Cannot remove event listener '${e}' because the widget context is not available.`)},removeEventListener:(e,n)=>{if(t.setState){const r={...br(),...t.getState()},i=Object.keys(r.$$eventListeners).find((t=>r.$$eventListeners[t].name===e&&r.$$eventListeners[t].handler===n));t.setState(r),i&&removeEventListener(r.$$eventListeners[i].name,r.$$eventListeners[i].handler)}else console.warn(`Cannot remove event listener '${e}' because the widget context is not available.`)}}},Hr=(e,t,n)=>{const r={...br(),...n.getState()},i=r.pages[gr].$$compiledCode;if(i)return{compiledModule:i};{const i=Gr(e,n,t);return pr(r.pages[gr].code,i,n.recipeType)}},Vr=e=>e.map((e=>({...e,name:e.name.replace("_","")}))),zr=()=>{const e=(e,...t)=>{if(Wr)try{return Wr[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)}}},qr=async(e,t)=>{const n={...e};for(const r in e){if(e[r].name===Rr){const e=n[r]?.rejectHandler;if("function"==typeof e)try{await e("TIMER_ABORTED")}catch(e){console.log("Error in reject interrupt handler: ",e)}t.cancelInterrupt(r),delete n[r]}}return n},Kr=async e=>{const t={...e};for(const n in e){if(e[n].name===Fr){const r=e[n]?.abort;if("function"==typeof r)try{await r()}catch(e){console.log("Error in abort interrupt handler: ",e)}delete t[n]}}return t},Jr=async(e,t,n)=>{let r={...br(),...e.getState()};if(void 0!==n){r.pages[gr]?.$$compiledCode?.onTerminate&&await(r.pages[gr].$$compiledCode?.onTerminate());let t=await qr(r.$$eventListeners,e);t=await Kr(t),r.$$eventListeners=t,r.pages[gr].$$compiledCode=void 0,r.pages[gr].code=n,e.setState({...r})}const i=!r.pages[gr].$$compiledCode,{compiledModule:s,error:o}=Hr({variablesManager:!0,withTimers:!0},{recipePoolId:e.recipePoolId,thingId:e.thingRecipeId,widgetId:e.id},{getState:e.getState,setState:e.setState,recipeType:e.recipeType,registerInterrupt:e.registerInterrupt});if(o){console.log("Failed to compile user code");const t=wr(o,e.recipeType);return Sr(t,e),null}if(s){let n;r={...e.getState()},r.pages[gr].$$compiledCode=s;const o=Xr(r.pages[gr].code);o?.name===r.metadata?.name&&o?.description===r.metadata?.description||(r.metadata=o||void 0);const a=e.nextWidget||e.nextGate;if(a&&s.setSendToPortFun(a),t)try{await s.recipeInit({setState:e.setState,getState:e.getState})}catch(t){n=wr(t,e.recipeType)}if(a&&i)try{await s.main(a)}catch(t){n=wr(t,e.recipeType)}r.$$lastInputs=s.getWidgetInputs?s.getWidgetInputs():[],r.$$lastOutputs=s.getWidgetOutputs?s.getWidgetOutputs():[],e.setState(r),Sr(n,e)}};var Zr={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),s={...br(),...i};if(!s.pages[gr])return console.warn("Missing default page");if(Be(e?.name||""))return s.$$eventListeners[t.name]?(await s.$$eventListeners[t.name].handler(),s.$$eventListeners[t.name].name===Rr&&delete s.$$eventListeners[t.name],void r.setState({...s})):void console.log(`Unknown interrupt id [${t.name}] `);const o=t.name===Br;await Jr(r,!1,o?n.data.value:void 0);const a=s.pages[gr].$$compiledCode;if(e&&e.name!==Br&&a)try{await a.asyncProcessEvent(t,e,n)}catch(e){if("UserCodeError"===e.name){const t=wr(e,r.recipeType);throw Sr(t,r),t}throw e}},getInputNames:(e,t)=>{const n={...br(),...e},{compiledModule:r}=Hr({},{recipePoolId:t.recipePoolId,thingId:t.thingRecipeId,widgetId:t.widgetId},{getState:()=>n,recipeType:t.recipeType});if(r?.getWidgetInputs){const e=r.getWidgetInputs();return Vr(e)}return e.$$lastInputs||[]},getOutputNames:(e,t)=>{const n={...br(),...e},{compiledModule:r}=Hr({},{recipePoolId:t.recipePoolId,thingId:t.thingRecipeId,widgetId:t.widgetId},{getState:()=>n,recipeType:t.recipeType});if(r?.getWidgetOutputs){const e=r.getWidgetOutputs();return Vr(e)}return e.$$lastOutputs||[]},getDefaultState:br,initialize:async e=>{const t=e.getState(),n={...br(),...t};n.pages[gr].code&&await Jr({getState:e.getState,id:e.widgetId,recipePoolId:e.recipePoolId,recipeType:e.recipeType,registerInterrupt:e.registerInterrupt,setState:e.setState,nextWidget:e.nextWidget,thingRecipeId:e.thingRecipeId,cancelInterrupt:()=>!0},!0,n.pages[gr].code)},terminate:async e=>{try{const t=e.getState();t.pages[gr].$$compiledCode?.onTerminate&&await t.pages[gr].$$compiledCode.onTerminate();const n=e=>nt.destroyInterrupt(e),r=await qr(t.$$eventListeners,{cancelInterrupt:n});await Kr(r)}catch(t){console.warn(`Error terminating script widget ${e.widgetId}: `,t)}}};const Xr=e=>{const t=e.trimStart().match(/^(?:\/\*\*(?:[^*]|\*(?!\/))*\*\/|\/\*(?:[^*]|\*(?!\/))*\*\/)/);if(!t)return null;const n=t[0].replace(/^\/\*\*?/,"").replace(/\*\/$/,"").split("\n").map((e=>e.replace(/^\s*\*?\s?/,"").trim())).join("\n"),r=n.match(/Name\s*:\s*([^]*?)(?=\n\s*[A-Za-z]+\s*:|$)/i),i=n.match(/Description\s*:\s*([^]*?)(?=\n\s*[A-Za-z]+\s*:|$)/i),s={};return r&&r[1]&&(s.name=r[1].trim()),i&&i[1]&&(s.description=i[1].trim()),Object.keys(s).length>0?s:null},Qr=async(e,t,n,r)=>{e.startsWith("data:image/")||(e=`data:image/png;base64,${e}`);const i=await ei(e);return((e,t,n,r)=>{const i=r.getContext("2d");if(!i)throw new Error("Failed to get canvas context");const s=e.width,o=e.height;return r.width=t,r.height=n,i.drawImage(e,0,0,s,o,0,0,t,n),i.getImageData(0,0,t,n)})(i,n||i.naturalWidth,r||i.naturalHeight,t)},ei=e=>new Promise(((t,n)=>{const r=new Image;r.onload=()=>t(r),r.onerror=e=>n(e),r.src=e})),ti=Object.freeze({image:"image"}),ni=Object.freeze({base64:"base64"}),ri=()=>({});var ii={onParentEvent:async(e,t,n,r)=>{const i={...r.getState()};if(t.name===ni.base64){if("string"!=typeof n.data.value)return;if(n.data.type!==we.String&&n.data.type!==we.Anything)return;const e=n.data.value;re&&(i.$$memCanvas&&i.$$memCanvas.getContext||(i.$$memCanvas=Me(320,240)));try{const t=await Qr(e,i.$$memCanvas,i.resize?.width,i.resize?.height);return r.setState(i),r.nextGate(ti.image,{type:we.ImageData,value:t})}catch(e){console.log("[base64ToImageData] Error: ",e)}}},getInputNames:()=>[{name:ni.base64,type:we.String}],getOutputNames:()=>[{name:ti.image,type:we.ImageData}],getDefaultState:ri};const si=Object.freeze({object:"object",error:"error"}),oi=Object.freeze({string:"string"}),ai=()=>({outputIsArray:!1});var ci={onParentEvent:async(e,t,n,r)=>{const i={outputIsArray:!1,...r.getState()};if((n.data.type===we.String||n.data.type===we.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?we.Array:we.JsonObj,value:e})}catch(e){return r.nextGate("error",{type:we.Boolean,value:!0})}},getInputNames:()=>[{name:oi.string,type:we.String}],getOutputNames:e=>[{name:si.object,type:[we.JsonObj,we.Array],label:e.outputIsArray?"array":si.object},{name:si.error,type:we.Boolean}],getDefaultState:ai};const li=Object.freeze({string:"string",length:"length"}),ui=Object.freeze({trigger:"trigger",setText:"setText"}),di=()=>({text:"",dispatchOnSet:!1});var hi={onParentEvent:async(e,t,n,r)=>{const i={text:"",dispatchOnSet:!1,...r.getState()};if(t.name===ui.setText){if(!((n.data.type===we.String||n.data.type===we.Anything)&&"string"==typeof n.data.value))return;if("string"==typeof n.data.value&&(i.text=n.data.value,r.setState(i)),!i.dispatchOnSet)return}const s=r.nextGate(li.length,{type:we.Number,value:i.text.length}),o=r.nextGate(li.string,{type:we.String,value:i.text});await Promise.all([s,o])},getInputNames:e=>{const t=[{name:ui.setText,type:we.String}];return e.dispatchOnSet||t.push({name:ui.trigger,type:we.Anything}),t},getOutputNames:()=>[{name:li.string,type:we.String},{name:li.length,type:we.Number}],getDefaultState:di};const fi=Object.freeze({image:"image"}),pi=Object.freeze({image:"image",x:"x",y:"y",width:"width",height:"height"}),gi=()=>({showInputPorts:!1});var mi={onParentEvent:async(e,t,n,r)=>{const i={showInputPorts:!1,...r.getState()};if("number"==typeof n.data.value)return t.name===pi.x&&(i.cropX=n.data.value),t.name===pi.y&&(i.cropY=n.data.value),t.name===pi.width&&(i.cropWidth=n.data.value),t.name===pi.height&&(i.cropHeight=n.data.value),void r.setState(i);if(t.name===pi.image){if(n.data.type!==we.ImageData&&n.data.type!==we.Anything)return;if(!We(n.data.value))return;const e=n.data.value;if(i.$$memCanvas&&i.$$memCanvas.getContext||(i.$$memCanvas=Me(320,240),i.$$memCanvasContext=Ne(i.$$memCanvas),r.setState(i)),!i.$$memCanvas||!i.$$memCanvasContext)return void console.error("Failed to get canvas or context");let t=e;return i.$$memCanvas.width=e.width,i.$$memCanvas.height=e.height,(i.cropX||i.cropY||i.cropWidth||i.cropHeight)&&(t=((e,t,n,r)=>{if(!n)return e;const i=Math.max(r.x||0,0),s=Math.max(r.y||0,0),o=e.width,a=e.height,c=Math.min(Math.ceil(r.width||o),o),l=Math.min(Math.ceil(r.height||a),a);return t.width=e.width,t.height=e.height,n.putImageData(e,0,0),n.drawImage(t,i,s,c,l,0,0,c,l),n.getImageData(0,0,c,l)})(e,i.$$memCanvas,i.$$memCanvasContext,{x:i.cropX,y:i.cropY,width:i.cropWidth,height:i.cropHeight})),r.nextGate(fi.image,{type:we.ImageData,value:t})}},getInputNames:e=>{const t=[{name:pi.image,type:[we.ImageData]}];return e.showInputPorts&&(t.push({name:pi.x,type:we.Number}),t.push({name:pi.y,type:we.Number}),t.push({name:pi.width,type:we.Number}),t.push({name:pi.height,type:we.Number})),t},getOutputNames:()=>[{name:fi.image,type:we.ImageData}],getDefaultState:gi};const yi=Object.freeze({image:"image"}),vi=Object.freeze({image:"image",width:"width",height:"height"}),bi=()=>({showInputPorts:!1});var wi={onParentEvent:async(e,t,n,r)=>{const i={showInputPorts:!1,...r.getState()};if("number"==typeof n.data.value)return t.name===vi.width&&(i.width=n.data.value),t.name===vi.height&&(i.height=n.data.value),void r.setState(i);if(t.name===vi.image){if(n.data.type!==we.ImageData&&n.data.type!==we.Anything)return;if(!We(n.data.value))return;const e=n.data.value;if(i.$$memCanvas&&i.$$memCanvas.getContext||(i.$$memCanvas=Me(320,240),i.$$tempCanvas=Me(320,240),r.setState(i)),!i.$$memCanvas||!i.$$tempCanvas)return;let t=e;return(i.width||i.height)&&(t=((e,t,n,r,i)=>{if(!r&&!i)return e;r&&!i?i=r*(e.height/e.width):!r&&i&&(r=i*(e.width/e.height));const s=Math.max(1,r||e.width),o=Math.max(1,i||e.height);n.width===e.width&&n.height===e.height||(n.width=e.width,n.height=e.height),t.width=s,t.height=o;const a=Ne(t),c=Ne(n);if(!a||!c)throw new Error("Failed to get canvas context");return c.putImageData(e,0,0),a.drawImage(n,0,0,e.width,e.height,0,0,s,o),a.getImageData(0,0,s,o)})(e,i.$$memCanvas,i.$$tempCanvas,i.width,i.height)),r.nextGate(yi.image,{type:we.ImageData,value:t})}},getInputNames:e=>{const t=[{name:vi.image,type:we.ImageData}];return e.showInputPorts&&(t.push({name:vi.width,type:we.Number}),t.push({name:vi.height,type:we.Number})),t},getOutputNames:()=>[{name:yi.image,type:we.ImageData}],getDefaultState:bi};const Si=Object.freeze({value:"value"}),_i=Object.freeze({trigger:"trigger",setValue:"setValue"}),Ii=()=>({value:0,dispatchOnSet:!1});var xi={onParentEvent:async(e,t,n,r)=>{const i={value:0,dispatchOnSet:!1,...r.getState()};if(t.name===_i.setValue){const e=n.data.type===we.Number||n.data.type===we.Anything||n.data.type===we.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(Si.value,{type:we.Number,value:i.value})},getInputNames:e=>{const t=[{name:_i.setValue,type:we.Number}];return e.dispatchOnSet||t.push({name:_i.trigger,type:we.Anything}),t},getOutputNames:()=>[{name:Si.value,type:we.Number}],getDefaultState:Ii};const ki=Object.freeze({image:"image"}),Ei=Object.freeze({image:"image"}),Ci=()=>({anchors:[],vertices:[],matrix:[]}),$i={onParentEvent:async(e,t,n,r)=>{const i={anchors:[],vertices:[],matrix:[],...r.getState()},s=window,o=n.data.type===we.ImageData;if(s.Speedy&&o){const e=s.Speedy,t=n.data.value;let o,u,d,h=i.$$private?.canvas,f=i.$$private?.context,p={...i};const g=4===i.anchors.length;if(i.$$private?.pipeline)o=i.$$private?.pipeline,u=i.$$private?.source;else{o=e.Pipeline(),u=e.Image.Source();const n=e.Image.Sink();d=e.Transform.PerspectiveWarp(),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=Me(c,l),f=h.getContext("2d")),u.output().connectTo(d.input()),d.output().connectTo(n.input()),o.init(u,n,d);let r=e.Matrix(3,3,[1,0,0,0,1,0,0,0,1]);if(4===i.anchors.length){const t=e.Matrix(2,4,[(a=i.anchors)[0].x,a[0].y,a[1].x,a[1].y,a[2].x,a[2].y,a[3].x,a[3].y]),n=e.Matrix(2,4,i.vertices.reduce(((e,t)=>e.concat([t.x,t.y])),[])),s=e.Matrix.Zeros(3,3);await e.Matrix.perspective(s,t,n);const o=s.read();r=e.Matrix(3,3,o)}d.transform=r,p={...p,$$private:{...p.$$private,canvas:h,context:f,perspective:d,pipeline:o,source:u}}}let m=t;if(g){const e=await(async(e,t)=>{const n=window,r=e.$$private?.source,i=e.$$private?.pipeline;if(n.Speedy&&r&&i){const e=n.Speedy,s=await createImageBitmap(t),o=await e.load(s);return r.media=o,(await i.run()).image.source}return null})(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(ki.image,{type:we.ImageData,value:m})}var a,c,l;console.log("Environment not supported")},getInputNames:()=>[{name:Ei.image,type:we.ImageData}],getOutputNames:()=>[{name:ki.image,type:we.ImageData}],getDefaultState:Ci,terminate:async e=>{const t=e.getState();t.$$private?.pipeline.release()}},Oi=()=>({name:"Default widget bundle",description:"",inputs:[{dataType:[we.Anything],name:"input"}],outputs:[{dataType:[we.Anything],name:"output"}]});let Mi;const Ni=()=>{if(!Mi)throw new Error(ot(st));return Mi};const Ti=async e=>{const t=new a,n=await t.loadAsync(e),r={};for(const e in n.files)if(!n.files[e].dir){const t=await n.file(e);t&&(r[e]=await t.async("uint8array"))}return r},Ai={};var Di=e=>Ai[e]||null;const Pi=async(e,t,n)=>{try{const r=Ni(),i=n?r.loadBlobAsString:r.loadBlob;return await i(e,t)}catch(e){return null}},ji=async e=>{const t=pe;try{const n=await Pi(e,t,!0);if(!n)return null;return Function(n)()}catch(e){return null}},Li=async e=>{const t=ge;try{const n=await Pi(e,t,!0);if(!n)return null;return JSON.parse(n)}catch(n){return console.log(`Failed to parse the bundle's state [${e}/${t}] %j`,n),null}},Ri=(e,t)=>`${e.replace(me,"")}_${t}`,Fi=(e,t)=>`widget/${e.replace(me,"")}/v/${t}`,Ui=async(e,t)=>{const n=Ni(),[r]=await Promise.all([Ti(e),n.createLocation(t)]);for(const e in r)e.startsWith("__MACOSX")||await n.saveBlob(t,e,r[e])},Bi=(e,t)=>{const n=Ri(e,t),r=Di(n);return r?{...r}:null},Wi=(e,t,n)=>{const r=`${`widget/${e.replace(me,"")}/tmp`}/${t}`;if(n){return Ni().getCacheLocation(r)}return r};var Yi=Bi,Gi=async(e,t,n)=>{const r=Wi(t,n);await Ui(e,r);const i=ji(r),s=Li(r),o=Ni(),a=o.getCacheLocation(r),[c,l]=await Promise.all([i,s]);if(!c)return null;let u=l;if(!l){const e=Oi(),t=JSON.stringify(e);await o.saveBlob(r,ge,Ue(t)),u=e}return{cachePath:a,processor:c,storedState:Object.freeze(u)}},Hi=(e,t,n)=>{if(n.isTempStorage)return Wi(e,t,n.fullStorageRoot);const r=Ni(),i=Fi(e,t);return n.fullStorageRoot?r.getCacheLocation(i):i};const Vi=()=>Oi();var zi={onParentEvent:async(e,t,n,r)=>{const i=r.getState();return i.$$processor?.onParentEvent({sourcePort:e?.name||"",targetPort:t?.name||"",data:n.data},{getState:r.getState,recipeId:r.recipePoolId,recipeType:r.recipeType,setState:r.setState,nextWidget:r.nextGate})},getInputNames:(e,t)=>{const n={...Vi(),...e};return n.$$processor?.getInputNames?n.$$processor.getInputNames(e,t):n.inputs.map((e=>({name:e.name,type:e.dataType})))},getOutputNames:(e,t)=>{const n={...Vi(),...e};return n.$$processor?.getOutputNames?n.$$processor.getOutputNames(e,t):n.outputs.map((e=>({name:e.name,type:e.dataType})))},getDefaultState:Vi,initialize:async(e,t)=>{console.log("Widget bundle initialize",e);let n={...e.getState()},r=n.$$cacheInfo?.widgetThingId||n.collectionInfo?.widgetId||e.widgetId;const i=n.$$cacheInfo?.version.toString()||n.collectionInfo?.version.toString()||1;if(n.$$cacheInfo={...n.$$cacheInfo,version:Number(i),widgetThingId:r},!r||!i)throw new Error("Widget bundle state is missing cache id or version");console.log("Loading state from cache");const s=Yi(r,i);let o=!s;if(!n.$$processor)if(n.storageUnitId&&!s){const t=await e.getStorageData(n.storageUnitId);if(t){r=e.widgetId;const s=await Gi(t,r,i);o=!0,s&&(n={...n,$$processor:s.processor,$$cacheInfo:{...n.$$cacheInfo,widgetThingId:r,version:Number(i)}},e.setState(n))}}else if(s){o=!1;const r=n.collectionInfo?{...n.collectionInfo}:void 0;n={...n,...!t.keepCurrentState&&s.storedState?{...s.storedState,...r?{collectionInfo:r}:{}}:{},$$processor:s.processor},e.setState(n)}const a=Hi(r,i,{fullStorageRoot:!0,isTempStorage:o});console.log("Invoking bundle initialize with cache: ",a);try{await(n.$$processor?.initialize({cacheLocation:a,getState:e.getState,setState:e.setState}));const t=e.getState();e.setState({...t,$$initializationError:void 0})}catch(t){const n=e.getState();throw e.setState({...n,$$initializationError:t.message||"An error occurred initializing the widget"}),t}},terminate:async e=>{const t={...e.getState()};console.log(`Terminating widget bundle ${t.name} [${t.$$cacheInfo?.widgetThingId||""}]`);const n=t.$$processor;n&&"function"==typeof n.terminate&&await n.terminate({getState:e.getState,setState:e.setState,recipePoolId:e.recipePoolId,widgetId:e.widgetId})}};const qi=Object.freeze({event:"event"}),Ki="1",Ji="2",Zi="3";var Xi={onParentEvent:async(e,t,n,r)=>{const i={...r.getState()};r.setState({...i,$$lastEventType:n.data.type}),await r.nextGate(Ki,n.data),await r.nextGate(Ji,n.data),await r.nextGate(Zi,n.data)},getInputNames:()=>[{name:qi.event,type:we.Anything}],getOutputNames:e=>{const t={type:{...e}.$$lastEventType??we.Anything};return[{name:Ki,...t},{name:Ji,...t},{name:Zi,...t}]}};const Qi=()=>({name:"myVar",type:we.Anything,reactive:!0,defaultValue:""}),es=Object.freeze({set:"set",read:"read"}),ts="value";var ns={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),s={...Qi(),...i};if(t.name!==es.set){if(t.name===es.read){const e=Dr({variableName:s.name,readerWidgetId:r.id}),t=e?e.value:s.defaultValue;await r.nextWidget(ts,{type:s.type,value:t})}}else{if(n.data.type!==s.type&&s.type!==we.Anything)return;await Ar({variableName:s.name,value:n.data.value,setByWidgetId:r.id,type:s.type})}},getInputNames:e=>{const t={...e};return[{name:es.set,type:t.type||we.Anything},{name:es.read,type:we.Anything}]},getOutputNames:e=>{const t={...e};return[{name:ts,type:t.type||we.Anything}]},initialize:async e=>{const t=e.getState(),n={...Qi(),...t};if(n.$$abortListener)try{n.$$abortListener()}catch(t){console.warn(`Error aborting variable listener for widget ${e.widgetId}: `,t)}Nr({variableName:n.name,type:n.type,createdByWidgetId:e.widgetId});const r=Pr({variableName:n.name,type:n.type,widgetId:e.widgetId,onValueChange:async t=>{const n=e.getState();void 0!==t.value&&(n.type!==we.Anything&&t.type!==n.type||n.reactive&&await e.nextWidget(ts,{type:t.type,value:t.value}))}});e.setState({...n,$$abortListener:r})},terminate:async e=>{const t=e.getState(),n={...Qi(),...t};n.$$abortListener&&n.$$abortListener(),Tr({variableName:n.name,createdByWidgetId:e.widgetId})}};let rs;var is=e=>{rs=e},ss=()=>{if(!rs)throw new Error("Hub Connector not set");return rs};const os=e=>{const t=le(e);return t?.name||""},as=async(e,t=!1)=>{const n=ss();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 cs={onParentEvent:async(e,t,n,r)=>{const i={dynamicInputs:{},dynamicOutputs:{},customState:{},...r.getState()};if(!e)return;const s=ss();let o=i.$$$serviceId;if(!o){const e=s.getCachedServices().available.find((e=>e.name===i.service?.name&&e.version===i.service?.version));if(!e)return;o=e.sessionId,i.$$$serviceId=o,r.setState(i)}const a=i.service?.variants?.find((e=>e.id===i.variantId)),c=a?i.dynamicInputs[a.id]||a?.inputs||[]:i.service?.inputs||[];if(!c?.length)return;if(!a&&i.service?.ignoreParentEvents)return;const l=i.service?.processingTimeoutSec,u=i.service?.name&&r.eventContext?.[i.service?.name];return s.onParentEvent({recipeId:r.recipePoolId,recipeName:os(r.recipePoolId),data:n.data,targetServiceSessionId:o,currentState:i.customState,targetVariantId:i.variantId,target:{portName:t.name,widgetId:r.id,widgetType:r.type},source:e,config:{timeout:l?1e3*l:0,async:i.service?.asyncParentEvents},eventContext:u})},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=le(e.recipePoolId),r=n?.name||"",i=ss(),s=await as(t);if(s)try{return await i.initializeServiceInstance({recipeId:e.recipePoolId,sessionId:s,recipeName:r,widgetId:e.widgetId,recipeType:e.recipeType,variantId:t.variantId})}catch(t){if("FNC_NOT_FOUND"!==t?.errCode){if(!!("string"!=typeof t||!t.match('^Function ".*" not found.$')))throw t;console.warn(`Widget [${e.widgetId}] does not have an init function.`)}}else console.log(`Aborting service initialization, "${t.service?.name}" was not found in the current Hub.`)},terminate:async e=>{const t={dynamicInputs:{},dynamicOutputs:{},customState:{},...e.getState()},n=ss(),r=await as(t,!0);if(r)return n.terminateServiceInstance(r,e.widgetId,e.recipePoolId,t.variantId)}};const ls=Object.freeze({Image:"image"}),us=Object.freeze({Image:"image"}),ds=()=>({filters:[{name:"grayscale",value:"0.5",id:"d-1"}]});var hs={onParentEvent:async(e,t,n,r)=>{const i={filters:[{name:"grayscale",value:"0.5",id:"d-1"}],...r.getState()};if(t.name===ls.Image&&n.data.type===we.ImageData){if(!We(n.data.value))return void console.log("ImageFilter: Invalid image data type, aborting process");const e=n.data.value;i.$$memCanvas?.getContext||(i.$$memCanvas=Me(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(us.Image,{type:we.ImageData,value:t})}},getInputNames:()=>[{name:ls.Image,type:we.ImageData}],getOutputNames:()=>[{name:us.Image,type:we.ImageData}],getDefaultState:ds};const fs="loaded";var ps={onParentEvent:async(e,t,n,r)=>r.nextWidget(fs,{value:!0,type:we.Boolean}),getInputNames:()=>[],getOutputNames:()=>[{name:fs,type:we.Boolean,description:"Triggered when the recipe is fully loaded"}]};var gs={onParentEvent:async()=>{},getInputNames:()=>[],getOutputNames:()=>[],getDefaultState:()=>({text:"",color:"#eac43e",size:{width:300,height:200}})};var ms={onParentEvent:async(e,t,n,r)=>{try{const e=((e,t)=>{switch(t){case we.Number:case we.Boolean:case we.String:return String(e);case we.Array:case we.JsonObj:case we.Rect:case we.Point:return JSON.stringify(e,((e,t)=>"bigint"==typeof t?t.toString():t));case we.ArrayBuffer:if(e instanceof ArrayBuffer){if(se)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 we.ImageData:{if(!We(e))throw new Error("Expected ImageData");const t=e,n=Me(t.width,t.height),r=Ne(n);if(!r)throw new Error("Failed to get canvas context");r.putImageData(t,0,0);const i=n.toDataURL("image/png");if(!i)throw new Error("Failed to convert canvas to data URL");return i.split(",")[1]}default:return String(e)}})(n.data.value,n.data.type);return r.nextWidget("text",{type:we.String,value:e})}catch(e){return r.nextWidget("error",{type:we.String,value:e instanceof Error?e.message:"Failed to stringify object"})}},getInputNames:()=>[{name:"object",type:[we.Number,we.String,we.ArrayBuffer,we.Array,we.Boolean,we.JsonObj,we.Rect,we.Point,we.ImageData]}],getOutputNames:()=>[{name:"text",type:we.String},{name:"error",type:we.String}],getDefaultState:()=>({})};const ys=e=>{if(Array.isArray(e))return e.map(((e,t,n)=>null===e||"object"!=typeof e?{value:e,"@index":t,"@indexPlus1":t+1,"@isFirst":0===t,"@isLast":t===n.length-1}:{...ys(e),"@index":t,"@indexPlus1":t+1,"@isFirst":0===t,"@isLast":t===n.length-1}));if("object"==typeof e&&null!==e){const t={};for(const n in e){const r=e[n];t[n]=ys(r)}return t}return e},vs=(e,t)=>{const n=(e=>{const t=new Date;return{input:"object"==typeof e&&null!==e?ys(e):{value:e},date:{year:t.getFullYear(),month:t.getMonth()+1,day:t.getDate(),hours:t.getHours(),minutes:t.getMinutes(),seconds:t.getSeconds(),milliseconds:t.getMilliseconds(),time:t.getTime(),dayOfWeek:t.getDay(),dayName:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][t.getDay()],shortDayName:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"][t.getDay()],date:t.getDate(),fullYear:t.getFullYear(),timezoneOffset:t.getTimezoneOffset(),UTCDate:t.getUTCDate(),UTCDay:t.getUTCDay(),UTCFullYear:t.getUTCFullYear(),UTCHours:t.getUTCHours(),UTCMilliseconds:t.getUTCMilliseconds(),UTCMonth:t.getUTCMonth()+1,UTCMinutes:t.getUTCMinutes(),UTCSeconds:t.getUTCSeconds(),isoString:t.toISOString(),localeString:t.toLocaleString()}}})(t);return l.render(e,n)},bs=()=>({text:"",format:"Text"});var ws={onParentEvent:async(e,t,n,r)=>{const i={text:"",format:"Text",...r.getState()},s=vs(i.text,n.data.value);return r.nextWidget("text",{type:we.String,value:s})},getInputNames:()=>[{name:"input",type:we.Anything}],getOutputNames:()=>[{name:"text",type:we.String}],getDefaultState:bs};const Ss=()=>({expression:""});var _s={onParentEvent:async(e,t,n,r)=>{const i={expression:"",...r.getState()},s=((e,t)=>{const n=Symbol("error"),r=`\n // 'data' is an argument to this function, passed by new Function call.\n // 'SError' is also an argument, providing the error symbol.\n // 'this' inside this function (created by new Function) is the global object.\n\n\t\t// Shadow eval and Function in this non-strict scope.\n\t\tvar eval = undefined;\n\t\tvar Function = undefined;\n\n // Define the sandbox environment\n const sandboxEnvironment = {\n // Make input 'data' accessible\n data: data,\n \n // Safe console (bind methods to the original console)\n console: undefined,\n\n // Mocked/disabled globals\n process: undefined,\n document: undefined,\n navigator: undefined,\n \n require: undefined,\n // eval and Function are shadowed by var declarations above\n \n // Allowed safe globals (pointing to the real ones, accessed via 'this')\n Math: this.Math,\n Date: this.Date,\n JSON: this.JSON,\n Array: this.Array,\n Object: this.Object,\n String: this.String,\n Number: this.Number,\n Boolean: this.Boolean,\n RegExp: this.RegExp,\n // Error: this.Error, // Not Allow Error constructor\n Symbol: this.Symbol, // Allow Symbol constructor\n Map: this.Map,\n Set: this.Set,\n Promise: this.Promise, // Allow Promise if async expressions are intended\n // setTimeout, setInterval, fetch, etc., are deliberately omitted\n };\n\n // Assign the sandboxEnvironment to act as the 'global' context variables\n const global = sandboxEnvironment;\n const window = sandboxEnvironment;\n const globalThis = sandboxEnvironment;\n\n // Shadow top-level variables that might be accessed directly,\n // ensuring they use the sandboxed versions.\n const process = sandboxEnvironment.process;\n const document = sandboxEnvironment.document;\n const navigator = sandboxEnvironment.navigator;\n const console = sandboxEnvironment.console; // Use the sandboxed console for the expression\n const require = sandboxEnvironment.require;\n // 'eval' and 'Function' are already shadowed by var declarations\n\n // The expression will be evaluated in this scope.\n // 'data' is available as it's an argument to the outer function.\n // 'global.xxx' will resolve to 'sandboxEnvironment.xxx'.\n // 'process.yyy' will resolve to 'sandboxEnvironment.process.yyy'.\n \n return () => {\n "use strict"; // Apply strict mode only to the expression evaluation scope\n const abort = Symbol('abort'); // Local symbol for the expression's optional special return value\n\n let result;\n try {\n // Strict mode can add a layer of security and prevent some common errors.\n // It also changes 'this' binding within the expression if it uses 'this'.\n // If the expression uses 'this', under strict mode it would be undefined unless explicitly set.\n // For expressions not using 'this', strict mode is generally safer.\n result = (() => { return ${t}; })();\n } catch(e) {\n // Log the error using the sandboxed console\n // Use 'instanceof Error' to ensure 'e' has a message property.\n const errorMessage = e instanceof Error ? e.message : String(e);\n return {\n\t\t\t\t\terror: 'Error during expression execution: ' + errorMessage, \n\t\t\t\t\tvalue: null\n\t\t\t\t}; // Return the SError symbol passed into this function's scope\n }\n \n\t\t\t// allows ternary expressions that return 'abort' to cancel the evaluation\n if (result !== abort) {\n // Original logic: if result is strictly true, and expression wasn't literally "true", return original data.\n if (result === true && String(expression).trim() !== 'true') {\n return {value: data, error: null}; \n } else {\n return {value: result, error: null};\n }\n }\n \n // If the expression explicitly returned the 'abort' symbol\n return {value: abort, error: null}; \n }\n // End of functionBody template literal\n `;try{return new Function("data","SError",r)(e,n).call({})}catch(e){return{error:e.message,value:null}}})(n.data.value,i.expression);if("symbol"==typeof s.value)return;if(s.error)throw new Error(s.error);if(Number.isNaN(s.value))throw new Error("Expression resulted in NaN");if(void 0===s.value||null===s.value)return;const o=He(s.value);return o!==i.$$lastResultType&&r.setState({...i,$$lastResultType:o}),r.nextWidget("result",{type:o,value:s.value})},getInputNames:()=>[{name:"data",type:we.Anything}],getOutputNames:e=>[{name:"result",type:e.$$lastResultType||we.Anything}],getDefaultState:Ss};var Is={onParentEvent:async(e,t,n,r)=>{const i={...r.getState()};r.setState({...i,$$lastEventType:n.data.type});try{await r.nextWidget("event",n.data)}catch(e){const t=e;await r.nextWidget("error",{type:we.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:we.Anything}],getOutputNames:e=>[{name:"event",type:{...e}.$$lastEventType??we.Anything},{name:"error",type:we.JsonObj,jsonShape:{error:we.JsonObj,inputEvent:we.JsonObj}}]};const xs={},ks=Object.freeze({output:"output"}),Es=Object.freeze({read:"read",clear:"clear"}),Cs=()=>({$$$time:0,totalInputs:1});var $s={onParentEvent:async(e,t,n,r)=>{const i={$$$time:0,totalInputs:1,...r.getState()};if(xs[r.id]||(xs[r.id]={}),t.name===Es.clear)return xs[r.id]={},void r.setState(i);const s=t.name===Es.read;if(!(s||n.data.type!==we.JsonObj&&n.data.type!==we.Anything&&n.data.type!==we.Rect||"object"!=typeof n.data.value||null===n.data.value||Array.isArray(n.data.value))){const e=xs[r.id]||{};xs[r.id]={...e,...n.data.value}}if(s){const e={...xs[r.id]};return xs[r.id]={},r.setState({...i}),r.nextWidget(ks.output,{type:we.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:we.Anything})));return n.push({name:Es.clear,type:we.Anything},{name:Es.read,type:we.Anything,triggerPort:!0}),n},getOutputNames:()=>[{name:ks.output,type:we.JsonObj}],getDefaultState:Cs,initialize:async e=>{xs[e.widgetId]={}},terminate:async e=>{delete xs[e.widgetId]}};const Os={},Ms=Object.freeze({output:"output",index:"index",finish:"finish"}),Ns=Object.freeze({array:"array",next:"next",clear:"clear"}),Ts=()=>({autoLoop:!1,autoClear:!1,$$outputType:we.Anything,totalItems:0,currentIndex:0});const As={input:lt,counter:ht,elapsed:gt,ifGate:bt,skipEvent:It,between:Ct,map:Mt,parser:At,slider:jt,suspend:Ut,display:Wt,json:Ht,arrayItem:qt,extractImage:Qt,imageConvolution:sn,firstEvent:ln,pixelDraw:yn,randomBetween:Sn,arrayCombine:En,clock:Mn,multiplication:Dn,object:Wn,widgetGroup:Vn,script:Zr,base64ToImageData:ii,jsonParse:ci,text:hi,imageCrop:mi,imageResize:wi,value:xi,imageWarp:$i,widgetBundle:zi,sequence:Xi,variable:ns,hubService:cs,imageFilter:hs,recipeLoad:ps,note:gs,stringify:ms,templateString:ws,expressionEval:_s,rescue:Is,objectCombine:$s,loop:{onParentEvent:async(e,t,n,r)=>{const i=r.getState(),s={...Ts(),...i};if(t.name===Ns.clear)return delete Os[r.id],void r.setState({...Ts(),autoLoop:s.autoLoop,autoClear:s.autoClear});if(t.name!==Ns.array)t.name===Ns.next&&await(async e=>{const t=e.id,n=Os[t],r={...Ts(),...e.getState()};if(n&&n.index<n.list.length){const i=n.index,s=n.list[i];await e.nextWidget(Ms.index,{type:we.Number,value:i}),await e.nextWidget(Ms.output,{type:r.$$outputType,value:s}),n.index++,e.setState({...r,currentIndex:n.index}),n.index===n.list.length&&(await e.nextWidget(Ms.finish,{type:we.Boolean,value:!0}),r.autoClear?(delete Os[t],e.setState({...Ts()})):(n.index=0,e.setState({...r,currentIndex:0})))}})(r);else if((n.data.type===we.Array||n.data.type===we.Anything)&&Array.isArray(n.data.value)){const e=n.data.value,t=e[0],i=void 0!==t?He(t):we.Anything,o={list:e,index:0};Os[r.id]=o;const a={...s,$$outputType:i,totalItems:e.length,currentIndex:0};if(r.setState(a),a.autoLoop&&e.length>0){for(const t of e){const e=o.index;r.setState({...a,currentIndex:e}),await r.nextWidget(Ms.index,{type:we.Number,value:e}),await r.nextWidget(Ms.output,{type:a.$$outputType,value:t}),o.index++}await r.nextWidget(Ms.finish,{type:we.Boolean,value:!0}),a.autoClear?(delete Os[r.id],r.setState({...a,$$outputType:we.Anything,totalItems:0,currentIndex:0})):(o.index=0,r.setState({...a,currentIndex:0}))}}},getInputNames:()=>[{name:Ns.array,type:we.Array},{name:Ns.next,type:we.Anything},{name:Ns.clear,type:we.Anything}],getOutputNames:e=>{const t={...Ts(),...e};return[{name:Ms.index,type:we.Number},{name:Ms.output,type:t.$$outputType},{name:Ms.finish,type:we.Anything}]},getDefaultState:Ts,initialize:async e=>{const t={...Ts(),...e.getState()};Os[e.widgetId]={list:[],index:0},e.setState({...t,currentIndex:0,totalItems:0})},terminate:async e=>{delete Os[e.widgetId]}},play:{getInputNames:()=>[],onParentEvent:()=>Promise.resolve(),getOutputNames:()=>[{name:"out",type:we.Boolean}]}},Ds={},Ps=async()=>{if(!Object.keys(Ds).length)for(const e in As){const t=As[e];Ds[e]=Object.freeze({...t})}};var js=e=>{if(Ds[e])return Ds[e];throw new Error(ot(it,e))},Ls=Ps;const Rs=new o,Fs="invoked";let Us={},Bs={},Ws={},Ys={};const Gs=(e,t,n)=>`${e}-${t}${n?`-${n}`:""}`;var Hs=(e,t,n,r,i)=>{const s=Gs(e,t,n),o=Gs(e,t),a=Gs(e,t,"produced"),c=Ws[o],l=Date.now();Ys[o]=l,Us[s]={data:r,sourcePortName:n,...i?{target:{widgetId:i.widgetId,portName:i.portName}}:{}},Rs.emit(a,{currentTime:l,prevTime:c,...i?{targetPort:i?.portName}:{}})},Vs=(e,t,n,r,i)=>{const s=Gs(e,t,n),o=Gs(e,t),a=Gs(e,t,Fs),c=Ws[o],l=Date.now();Ws[o]=l,Bs[s]={data:r,sourcePortName:n,...i?{source:{widgetId:i.widgetId,portName:i.portName}}:{}},Rs.emit(a,{prevTime:c,currentTime:l,targetPort:n,sourceInfo:i})},zs=()=>{Us={},Bs={},Ws={},Ys={},Rs.clearListeners()};const qs={};let Ks={};const Js=new o;let Zs=!1,Xs=!1,Qs=!1,eo=null,to=null;const no="processing-state-change",ro="error-event",io={abortRequested:!1,isPaused:!1,pausePromise:null,pausePromiseResolve:null,lastPausedWidgetId:null},so=e=>(to=e,Js.emit(no,e)),oo=(e,t)=>`${e}-${t}`,ao=(e,t)=>`state-change:${oo(e,t)}`,co=e=>{const{thingId:t,widgetId:n}=e,r=oo(t,n);return qs[r]||{isProcessing:!1}},lo=()=>{io.abortRequested=!1,io.isPaused=!1},uo=e=>(io.pausePromise||(io.isPaused=!0,io.pausePromise=new Promise((e=>{io.pausePromiseResolve=e})),e&&(io.lastPausedWidgetId=e),so({isProcessing:!0,isPaused:!0,...e?{pauseTrapWidgetId:e}:{}})),io.pausePromise);var ho,fo,po=async e=>{const{thingId:t,widgetId:n}=e,r=oo(t,n),i=ao(t,n),s=co({thingId:t,widgetId:n});if(s.isProcessing)return;const o={isProcessing:!0,isPaused:!1,startTime:Date.now()};qs[r]=o,Zs||(Zs=!0,eo=null,await so({isProcessing:!0,isPaused:!1})),await Js.emit(i,{thingId:t,widgetId:n,prevState:s,newState:o})},go=async e=>{const{thingId:t,widgetId:n,error:r}=e,i=oo(t,n),s=ao(t,n),o=co({thingId:t,widgetId:n}),a={isProcessing:!1,isPaused:!1,startTime:o.startTime,endTime:Date.now(),error:r};qs[i]=a,await Js.emit(s,{thingId:t,widgetId:n,prevState:o,newState:a}),r&&(eo=r,await Js.emit(ro,r)),Zs&&0===Object.values(qs).filter((e=>e.isProcessing)).length&&(Zs=!1,Xs=!1,lo(),await so({isProcessing:!1,isPaused:!1}))},mo=()=>{Zs=!1;for(const e in qs)delete qs[e];io.abortRequested=!1,io.isPaused=!1,io.pausePromise=null,io.pausePromiseResolve=null,io.lastPausedWidgetId=null,Js.clearListeners()},yo=()=>io.abortRequested,vo=e=>{io.lastPausedWidgetId=e,io.isPaused=!0,so({isProcessing:!0,isPaused:!0,pauseTrapWidgetId:e})},bo=()=>Xs||Qs?null:io.pausePromise,wo=e=>Qs?null:Ks[e]??null,So=()=>Xs,_o=e=>uo(e);!function(e){e.ServiceCreationLog="service-creation-log"}(ho=ho||(ho={})),function(e){e.Service="service",e.ServiceUI="serviceUI"}(fo=fo||(fo={}));let Io={},xo={},ko=null;const Eo=(e,t)=>{const n=(()=>{if(null===ko)throw new Error("Recipe execution type not set, please set the execution type using `setRecipeExecutionType`");return ko===Xn.Desktop})();let r=n?xo[e]:void 0;return r||(r=(e=>{const{widgets:t,targetId:n,allowedTypes:r}=e;if(!t[n])return[];const i=new Set;Object.values(t).forEach((e=>{e.children?.forEach((e=>i.add(e.childId)))}));const s=Object.keys(t).filter((e=>!i.has(e))),o=s.length>0?s:Object.keys(t),a=[],c=(e,i,s)=>{if(s.has(e))return;s.add(e);const o=t[e],l=!r||r.includes(o.type),u=[...i];l&&u.push(e),e===n?a.push(u.join("/")):o.children?.forEach((e=>c(e.childId,u,s))),s.delete(e)};return o.forEach((e=>c(e,[],new Set))),[...new Set(a)]})({widgets:t,targetId:e,allowedTypes:[Ze.hubService]}),n&&(xo[e]=r)),r},Co=(e,t,n)=>{Eo(t,n).forEach((n=>{Io[n]={eventContext:e,widgetId:t}}))},$o=(e,t)=>{const n=t[e].state,r=n.service?.name;if(!r)return[];const i=Eo(e,t),s=new Map;for(const e of i){const n=e.split("/");let i="";for(let e=0;e<n.length-1;e++){i=0===e?n[e]:`${i}/${n[e]}`;const o=Io[i];if(o&&!s.has(o.widgetId)){const e=t[o.widgetId].state;e.service?.name===r&&s.set(o.widgetId,{path:i,data:o,pathSegments:i.split("/").length})}}}return Array.from(s.values())},Oo=()=>{Io={}},Mo=e=>{ko=e},No=()=>{Io={},xo={}};let To,Ao,Do,Po=!1,jo=0;const Lo=async e=>{const{widgetId:t,thingId:n,recipeId:r,targetPortName:i,data:s}=e,o=ue(r,n);if(!o)return;const a=o.gates[t];if(!a||a.disabled)return;const c={...s,timestamp:Date.now()},l=js(a.type),u=Wo({gateId:t,originalEvent:c,blockRecipeId:o.recipeId,blockDbId:o.id,blockVersion:o.version,recipeId:r});if(u&&l.onParentEvent){const e={name:i};return To&&await To({recipeId:r,blockId:o.recipeId,gateId:t,targetPort:e.name,data:s}),l.onParentEvent(null,e,{originalEvent:c,data:{...c}},u)}},Ro=async e=>{const{interruptDriven:t,childGateId:n,recipeId:r,sourcePortName:i,targetPort:s,data:o,sourceOutputNames:a,sourceGateId:c}=e;let{originalEvent:l,block:u}=e;if(!t&&!c)throw new Error("Missing parameter ['sourceGateId']");if(!t&&!l)throw new Error("Missing parameter ['originalEvent']");t&&(l={timestamp:Date.now(),type:we.Boolean,value:!0});const d=l;if("string"==typeof u){const e=ue(r,u);if(!e)return;u=e}const h=u.gates[n];if(!h||h.disabled)return;const f=a.findIndex((e=>e.name===i)),p=js(h.type),g=Wo({gateId:n,originalEvent:d,blockRecipeId:u.recipeId,blockDbId:u.id,blockVersion:u.version,recipeId:r});if(g&&p.onParentEvent&&-1!==f){To&&await To({recipeId:r,blockId:u.recipeId,gateId:n,targetPort:s.name,data:o,sourceGate:t?"interrupt_widget":c,sourcePort:t?fe:i});const e={name:a[f].name,type:a[f].type,...a[f].jsonShape?{jsonShape:a[f].jsonShape}:void 0};return Vs(u.recipeId,n,s.name,o,c?{widgetId:c,portName:i}:void 0),p.onParentEvent(e,s,{originalEvent:d,data:o},g)}},Fo=async e=>{const{portName:t,originalEvent:n,data:r,currentGateId:i,blockRecipeId:s,thingDbId:o,thingVersion:a,recipeId:c,eventContext:l}=e,u=le(c);if(!u)throw new Error(`Failed to find recipe "${c}" in cache`);const d=u.dbInfo.recipeType,h=de(c,s,i);if(!h)return;const f={...r,timestamp:n.timestamp},p=js(h.type);let g;g=h.type===Ze.input?p.getOutputNames(h.state,{thingRecipeId:s,thingDbId:o,thingVersion:a,id:i,recipeId:c,recipeType:d,recipePoolId:c}):await p.getOutputNames(h.state,{recipePoolId:c,recipeType:d,thingRecipeId:s,widgetId:i});if(-1!==g.findIndex((e=>e.name===t))){const e=ue(c,s);if(!e)return;Hs(s,i,t,f);let r=null;const o=h.children.length;if(h.type===Ze.hubService&&l){const t=h.state,n=t.service?.name;n&&Co(l,h.id,e.gates)}try{for(let a=0;a<o;a++){const o=e.gates[h.children[a].childId];if(o?.disabled)continue;const l=qe(h.children[a]?.sourcePort),u=qe(h.children[a]?.targetPort);if(l.portName===t&&o&&!o.disabled){if(Po&&bo()&&(vo(o.id),await bo()),wo(o.id)&&!So()&&"innerInput"!==u?.portType){const e=_o(o.id);await e}if(Po&&yo())break;const a=js(o.type);let l;const p={recipePoolId:c,recipeType:d,thingRecipeId:s,widgetId:i};l=o.type===Ze.hubService?await a.getInputNames(o.state,p):a.getInputNames(o.state,p);const m=l.find((e=>e.name===u.portName));if(m){Po&&await po({thingId:s,widgetId:o.id}),jo++;if(!await Ro({interruptDriven:!1,childGateId:o.id,block:e,recipeId:c,sourcePortName:t,targetPort:{name:m.name},data:h.returnOriginalEvent?n:f,sourceOutputNames:g,sourceGateId:h.id,originalEvent:n}).then((()=>!0)).catch((e=>{const n=o.type===Ze.hubService&&"CHILD_WIDGET_ERROR"===e.errCode;if(e instanceof dr)throw e;if(n&&e.errData){const t=e.errData;throw new dr(e.error||e.message||("string"==typeof e?e:JSON.stringify(e)),{targetWidgetId:t.targetWidgetId,targetPortName:t.targetPortName,sourcePortName:t.sourcePortName,sourceWidgetId:t.sourceWidgetId,targetWidgetType:t.targetWidgetType,sourceWidgetType:t.sourceWidgetType})}if(!r){const n="string"==typeof e?e:e.message||JSON.stringify(e);r={targetWidgetId:o.id,targetPortName:m.name,sourcePortName:t,error:n}}throw new dr(e.message||("string"==typeof e?e:JSON.stringify(e)),{stack:e.stack,targetWidgetId:o.id,targetPortName:m.name,sourcePortName:t,sourceWidgetId:h.id,targetWidgetType:o.type,sourceWidgetType:h.type})})).finally((()=>{if(jo--,Po)return go({thingId:s,widgetId:o.id,error:r})})))break}}}}catch(e){if(e instanceof dr)throw e;console.error(`Error processing next widget [${i}]: ${e}`)}finally{jo<0&&(console.warn("Active execution counter is negative, this should never happen"),jo=0),0===jo&&Oo()}}},Uo=async(e,t,n,r)=>{const i=le(r);if(!i)return null;const s=ue(r,n);if(!s)return s;const o=s.gates,a=s.gates[t],c=js(a.type),l=await c.getInputNames(a.state,{recipePoolId:r,recipeType:i.dbInfo.recipeType,thingRecipeId:n,widgetId:t}),u=l.findIndex((t=>t.name===e));if(-1!==u){const e=((e,t,n)=>{for(const r in n){const i=n[r],s=i.children.length;for(let n=0;n<s;n++){const r=i.children[n],s=qe(r.targetPort);if(r.childId===e&&s.portName===t)return i}}return null})(t,l[u].name,o);if(e){const t=js(e.type);return{getValue:()=>"function"==typeof t.getValue?t.getValue():null}}}return null},Bo=e=>{const{gateId:t,originalEvent:n,thingRecipeId:r,thingDbId:i,thingVersion:s,recipeId:o}=e;if(!le(o))throw new Error(`Failed to find recipe "${o}" in cache`);if(!de(o,r,t))throw console.warn(`Gate ${t} not found in block ${r} for recipe ${o}`),new Error(`Gate ${t} not found in block ${r} for recipe ${o}`);return async(e,a)=>Fo({portName:e,originalEvent:n||{timestamp:Date.now(),type:a.type,value:a.value},data:a,currentGateId:t,blockRecipeId:r,thingDbId:i,thingVersion:s,recipeId:o})},Wo=e=>{const{gateId:t,originalEvent:n,blockRecipeId:r,blockDbId:i,blockVersion:s,recipeId:o}=e,a=le(o);if(!a)throw new Error(`Failed to find recipe "${o}" in cache`);const c=de(o,r,t);if(!c)return console.warn(`Gate ${t} not found in block ${r} for recipe ${o}`),null;const l=Bo({gateId:t,originalEvent:n,thingRecipeId:r,thingDbId:i,thingVersion:s,recipeId:o}),u=c.type===Ze.hubService,d=u?$o(t,a.blocks[r].gates):[],h=d.reduce(((e,t)=>e.pathSegments>t.pathSegments?e:t),d[0]),f={id:t,type:c.type,recipePoolId:o,thingRecipeId:r,recipeType:a.dbInfo.recipeType,returnOriginalEvent:!!c.returnOriginalEvent,registerInterrupt:(e,n,i,s,a)=>nt.createInterrupt(e,o,r,t,n,i,s,a),cancelInterrupt:e=>nt.destroyInterrupt(e),nextWidget:l,nextGate:l,getParentAtPort:e=>Uo(e,t,r,o),getState:()=>Object.freeze({...c.state,...c.type===Ze.input&&{customInputs:[]}}),setState:e=>{if("object"!=typeof e)return void console.warn(`Invalid state type [${typeof e}]. Expected an 'object'`);const n={...e,...c.type===Ze.input&&!e.customInputs&&{customInputs:[]}},i={...c.state};c.state=n,Ao&&Ao({blockId:r,gateId:t,prevState:i,newState:{...n},recipeId:o})},...u&&h&&{eventContext:h.data.eventContext}};return f};nt.setInvokeChildGateCb((async(e,t,n,r,i,s,o,a,c,l)=>Ro({interruptDriven:e,childGateId:t,block:n,recipeId:r,sourcePortName:i,targetPort:s,data:o,sourceOutputNames:a,sourceGateId:c,originalEvent:l})));const Yo=(e,t,n,r,i)=>{const s=de(e,n,r);if(!s)return console.warn(`Gate ${r} not found in block ${n} for recipe ${e}`),null;const o=(t,i,s,o)=>nt.createInterrupt(t,e,n,r,i,s,o),a=()=>Object.freeze({...s.state,...s.type===Ze.input&&{customInputs:[]}}),c=e=>{if("object"!=typeof e)return void console.warn(`Invalid state type [${typeof e}]. Expected an 'object'`);const t={...e,...s.type===Ze.input&&!e.customInputs&&{customInputs:[]}};s.state=t},l=async t=>{const r=((e,t,n)=>{const r=le(e);if(!r)throw new Error(`Recipe [${e} does not exist]`);if(!r.storage)return null;const i=ue(e,t);if(!i)throw new Error(`The Thing "${t}" does not exist in recipe ${e}`);if(!(i.storageUnits||[]).includes(n))throw new Error(`The Thing "${t}" has no access to storage unit "${n}"`);return r.storage[n]||null})(e,n,t);return r};if(i){return{getState:a,setState:c,registerInterrupt:o,getStorageData:l,nextWidget:Bo({gateId:r,thingRecipeId:n,thingDbId:s.id,thingVersion:"default",recipeId:e}),recipePoolId:e,recipeType:t,thingRecipeId:n,widgetId:r}}return{getState:a,setState:c,recipePoolId:e,widgetId:r}},Go=new o,Ho="invoked",Vo="state",zo=()=>{nt.destroyAllInterrupts()},qo=async(e,t,n)=>{const r=le(e),i=de(e,t,n);if(i&&r){const s=js(i.type);if(s&&"function"==typeof s.terminate){const i=((e,t,n,r)=>Yo(e,t,n,r))(e,r.dbInfo.recipeType,t,n);if(i)try{await s.terminate(i)}catch(e){console.warn(`Error terminating widget "${n}" in thing "${t}". Failing silently: `,e)}}}},Ko=async e=>{const{recipePoolId:t,thingRecipeId:n,widgetRecipeId:r,options:i}=e,s=le(t),o=de(t,n,r);if(o&&s){const e=js(o.type);if(e&&"function"==typeof e.initialize){const a=((e,t,n,r)=>Yo(e,t,n,r,!0))(t,s.dbInfo.recipeType,n,r);if(a){const t=e.initialize;try{(e=>{if(e.type===Ze.script){const t=e.state;if((t.version||0)<2){const n=Object.keys(e.variablesListener||{});for(const t of n)if(e.variablesListener){const n=Mr(t);e.variablesListener[n]=e.variablesListener[t],delete e.variablesListener[t],delete e.variables}t.version=2}}})(o),await t(a,i||{})}catch(e){throw console.warn(`Error initializing widget "${r}" in thing "${n}": `,e),e}}}}},Jo=(e,t)=>{const n=le(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},Zo=(e,t="",n="")=>`block:${t}:gate:${n||""}:${e}`,Xo=e=>{Go.emit(Zo(Vo),e),Go.emit(Zo(Vo,e.blockId,e.gateId),e)};To=async e=>{await Go.emit(Zo(Ho),e),await Go.emit(Zo(Ho,e.blockId,e.gateId),e)},(e=>{Ao=e})(Xo);var Qo=async(e,t,n,r,i)=>{const s=he(e,{id:t,authorId:r,version:n,recipeType:i});zs(),No(),Mo(i);const o=le(s);return o&&(o.startedAt=Date.now(),o.retryAttempts=0,o.execCounter=0,o.status=ne.STARTING,o.addLog("recipe registered")),s},ea=async e=>{const t=le(e);if(!t)return null;t.addLog("terminating recipe"),zo(),mo();for(const n in t.blocks){const r=t.blocks[n];for(const t in r.gates)await qo(e,n,t)}(e=>{!!oe[e]&&delete oe[e]})(e)},ta=async(e,t)=>{const n=le(e),r=[],i=[];if(n){Lr({recipePoolId:e,thingId:ve});for(const s in n.blocks){const o=n.blocks[s];if(!t||!Array.isArray(t)||t.includes(s))for(const t in o.gates)try{if(n.dbInfo?.recipeType===Xn.Desktop){const e=o.gates[t];if(e.type===Ze.hubService){const r=e.state;if(r?.service?.webOnly){n?.addLog(`skipping initialization of web-only widget "${t}"`);continue}}e.type===Ze.recipeLoad&&i.push(e)}await Ko({recipePoolId:e,thingRecipeId:s,widgetRecipeId:t,options:{keepCurrentState:!0}})}catch(e){r.push({widgetId:t,error:e.message})}}}return{failed:r,sendToInputWidget:(t,n,r=ve)=>(async(e,t,n,r)=>{const i=le(n),s=ue(n,r),o=Date.now();if(s&&i)for(const i in s.gates){const a=s.gates[i];if(a.type===Ze.input&&!a.disabled){const c=a.state.inputName||"";if(c===e){const e=js(a.type),l={...t,timestamp:o},u=Wo({gateId:i,originalEvent:l,blockRecipeId:r,blockDbId:s.id,blockVersion:s.version,recipeId:n});if(u&&e.processEvent){const s={...u,getState:u.getState};To&&await To({recipeId:n,blockId:r,gateId:i,targetPort:ct,data:t}),Do?await Do(r,n,c,t):await e.processEvent(l,s)}}}}})(t,n,e,r),invokeRecipeLoadedWidgets:async()=>{for(const t of i)await Lo({widgetId:t.id,thingId:ve,recipeId:e,targetPortName:fs,data:{type:we.Boolean,value:!0}})}}},na=e=>{is(e)},ra=(e,t,n,r=!1)=>{const i=Jo(t,e);if(i){const{widget:s,thing:o}=i,a={...s.state};s.state=n,r&&Xo({blockId:o.recipeId,gateId:t,recipeId:e,newState:{...n},prevState:a})}},ia=(e,t)=>{const n=Jo(t,e);return n?n.widget.state:null},sa=async e=>{const{recipePoolId:t,currentGateId:n,sourcePortName:r,originalEvent:i,data:s,eventContext:o}=e,a=Jo(n,t);if(a)return Fo({portName:r,originalEvent:i,data:s,currentGateId:n,blockRecipeId:a.thing.recipeId,thingDbId:a.thing.id,thingVersion:a.thing.version,recipeId:t,eventContext:o})};const oa=u.enum(["Read","Modify","Comment"]),aa=u.object({email:u.email(),name:u.string(),accessMode:oa});var ca;!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.CloudRecipeStorage="cloud_recipe_storage",e.InBrowserRecipeExecution="in_browser_recipe_execution",e.EventLoggerLogsRetention="event_logger_logs_retention",e.AgenticExecutions="agentic_executions"}(ca||(ca={}));const la=u.enum(["active","inactive"]),ua=u.enum(["Owner","Admin","Member"]),da=u.object({apiKey:u.string(),createdAt:u.string(),createdBy:u.string()}),ha=u.object({country:u.string(),city:u.string(),address1:u.string(),address2:u.string(),postCode:u.string()}),fa=u.object({id:u.string(),name:u.string(),groups:u.array(u.string()),logo:u.string().optional(),industry:u.string().optional(),accountOwner:u.string(),stripeCustomerId:u.string(),stripeSubscription:u.custom(),apiKeys:u.array(da).optional(),domain:u.string().optional(),createdAt:u.string(),updatedAt:u.string(),accountState:u.custom(),location:ha.optional()}),pa=u.object({id:u.string(),firstName:u.string(),lastName:u.string(),email:u.email().optional(),loginId:u.string().optional(),role:ua,groups:u.array(u.string()).optional().default([]),status:la,lastSeenAt:u.string().optional(),createdAt:u.string()});var ga,ma,ya,va;fa.pick({id:!0,name:!0,stripeSubscription:!0,stripeCustomerId:!0}),u.object({member:u.object({firstName:u.string().optional(),lastName:u.string().optional(),email:u.string().optional(),role:ua.optional(),groups:u.array(u.string()).optional(),status:la})}),pa.omit({id:!0,createdAt:!0,lastSeenAt:!0}),u.object({name:u.string(),location:ha.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"}(ga||(ga={})),function(e){e.Hardware="hardware",e.Virtual="virtual"}(ma||(ma={})),function(e){e.Cloud="cloud",e.Web="web"}(ya||(ya={})),function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(va||(va={}));const ba=u.object({name:u.string(),category:u.string(),id:u.string(),type:u.enum(ya),version:u.string()}),wa=u.object({version:u.number(),contents:u.string(),contentsLength:u.number(),createdAt:u.string()}),Sa=u.object({id:u.string(),name:u.string(),version:u.number(),dataSources:u.array(u.object({host:u.string().optional(),stream:u.string(),blocks:u.array(u.string())})).optional(),protocolVersion:u.string(),linkedTutorial:u.string().optional(),blocks:u.array(ba),widgets:u.array(u.object({type:u.string(),name:u.string(),thingId:u.string()})).optional(),contents:u.string(),storage:u.string().optional(),history:u.array(wa).optional(),cloud:u.object({environment:u.enum(ga),enabled:u.boolean()}).optional()}),_a=u.object({recipeId:u.string(),version:u.number()});Sa.extend({userId:u.string(),author:u.object({name:u.string(),id:u.string()}),copiedFrom:_a.optional(),updatedAt:u.string(),createdAt:u.string(),preview:u.string(),isPublic:u.boolean(),isDefault:u.boolean(),meta:u.object({contentsLength:u.number(),storageLength:u.number(),storageChecksum:u.string().optional()}),sharedWith:u.array(aa),publicSharedId:u.string().optional(),marketplacePublication:u.string().optional()});const Ia=Sa.omit({id:!0,version:!0,contents:!0,storage:!0});var xa,ka,Ea,Ca,$a,Oa,Ma,Na;u.object({rawContents:u.string(),recipe:Ia.extend({contentLength:u.number(),copiedFrom:_a.optional()}),storageSize:u.number().optional(),storageChecksum:u.string().optional()}),u.object({message:u.string(),recipeId:u.string(),version:u.number()}),function(e){e.Bundle="bundle",e.Group="group"}(xa||(xa={})),function(e){e.Gateway="gateway",e.Timer="timer"}(ka||(ka={})),function(e){e.InstallInProgress="installation-in-progress"}(Ea||(Ea={})),function(e){e.InstallDependencies="install-dependencies",e.GetInstalledDependencies="get-installed-dep"}(Ca||(Ca={})),function(e){e.Success="success",e.Error="error",e.Pending="pending"}($a||($a={})),function(e){e.NotFound="not-found",e.BadRequest="bad-request",e.Forbidden="forbidden",e.InternalError="internal-error"}(Oa||(Oa={})),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"}(Ma||(Ma={})),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"}(Na||(Na={}));const Ta=(e,t)=>((e,t,n)=>{const r=Buffer.from(n,"base64"),i=r.subarray(0,16),s=r.subarray(16).toString("base64"),o=h(e,t,32),a=f("aes-256-cbc",o,i);let c=a.update(s,"base64","utf8");return c+=a.final("utf8"),c})(e.id||"recipe.kemu","kemu",t),Aa=e=>{try{return JSON.parse(e)}catch(e){return null}},Da="undefined"!=typeof window,Pa={protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8},ja={protocolPrefix:4,txtLength:4},La=Object.values(Pa).reduce(((e,t)=>e+t),0),Ra=Object.values(ja).reduce(((e,t)=>e+t),0),Fa=["width","height","colorSpace"],Ua=(e,t)=>{const n={},r=[];let i=0,s=Array.isArray(e)?[]:{};const o=(e,s)=>{const a=(e=>{const t="undefined"!=typeof Buffer&&e instanceof Buffer,n=e instanceof ArrayBuffer,r=e instanceof Uint8ClampedArray,i=e instanceof Uint8Array,s=e instanceof Int8Array;return t?"Buffer":n?"ArrayBuffer":r?"Uint8ClampedArray":i?"Uint8Array":s?"Int8Array":null})(e);if(!a){if(Array.isArray(e)){const t=[];for(let n=0;n<e.length;n++)t[n]=o(e[n],`${s}[${n}]`);return t}if("object"==typeof e){const t={},n=(e=>{const t=e instanceof Int16Array,n=e instanceof Uint16Array,r=e instanceof Int32Array,i=e instanceof Uint32Array,s=e instanceof Float32Array,o=e instanceof Float64Array,a=e instanceof BigInt64Array,c=e instanceof BigUint64Array;return t?"Int16Array":n?"Uint16Array":r?"Int32Array":i?"Uint32Array":s?"Float32Array":o?"Float64Array":a?"BigInt64Array":c?"BigUint64Array":null})(e);if(n)throw new Error(`Unsupported binary type [${n}] at path "${s}"`);for(const n in e)Object.hasOwn(e,n)||Fa.includes(n)||console.warn(`Allowing inherited property: ${n} from path: ${s}`),t[n]=o(e[n],`${s.length?`${s}.`:""}${n}`);return t}return e}n[s]={index:i,length:e.byteLength,binaryType:a},"Buffer"===t?r.push(Buffer.from(e)):"ArrayBuffer"===a?r.push(e):r.push(e.buffer),i+=e.byteLength};s=o(e,"");let a=null;if(r.length>1)if("ArrayBuffer"===t){const e=r.reduce(((e,t)=>e+t.byteLength),0),t=new Uint8Array(e);let n=0;for(let e=0;e<r.length;e++)t.set(new Uint8Array(r[e]),n),n+=r[e].byteLength;a=t.buffer}else{a=Buffer.concat(r)}else 1===r.length&&(a=r[0]);return a?{map:n,combinedData:a,sourceCopy:s}:null},Ba=(e,t,n)=>{const r=t.match(/(\[\d+\])|([^[\].]+)/g)||[];let i=e;for(let e=0;e<r.length;e++){let t=r[e];const s=t.startsWith("[")&&t.endsWith("]"),o=e===r.length-1;if(s){t=t.slice(1,-1);const s=parseInt(t,10);if(!Array.isArray(i))throw new Error(`Expected an array at key "${r.slice(0,e).join(".")}" but found an object.`);o?i[s]=n:(i[s]||(i[s]=r[e+1].startsWith("[")?[]:{}),i=i[s])}else o?i[t]=n:(i[t]||(i[t]=r[e+1].startsWith("[")?[]:{}),i=i[t])}return e},Wa=(e,t,n)=>{const r="undefined"!=typeof Buffer,i=t instanceof Uint8Array;for(const s in n)if(Object.hasOwn(n,s)){const{index:o,length:a,binaryType:c}=n[s];let l=null;if(r&&t instanceof Buffer)switch(c){case"Buffer":l=t.subarray(o,o+a);break;case"ArrayBuffer":l=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(o,o+a);break;case"Uint8Array":l=new Uint8Array(t.subarray(o,o+a));break;case"Uint8ClampedArray":l=new Uint8ClampedArray(t.subarray(o,o+a));break;case"Int8Array":l=new Int8Array(t.subarray(o,o+a))}else if(t instanceof ArrayBuffer||t instanceof Uint8Array)switch(c){case"Buffer":if(r){l=Buffer.from(t.slice(o,o+a));break}case"ArrayBuffer":l=i?t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(o,o+a):t.slice(o,o+a);break;case"Uint8Array":l=i?t.slice(o,o+a):new Uint8Array(t.slice(o,o+a));break;case"Uint8ClampedArray":l=new Uint8ClampedArray(t.slice(o,o+a));break;case"Int8Array":l=new Int8Array(t.slice(o,o+a))}l&&Ba(e,s,l)}return e},Ya=e=>m(e),Ga="KMSG",Ha="KCMD",Va=Ya("klProtocol");var za={encode:(e,t,n)=>{const r={json:e.json},i=Ua(r.json,"Buffer"),s=i?.combinedData;i&&(r.jsonBinaryMap=i.map,r.json=i.sourceCopy);const o=s?s.byteLength:0,a=JSON.stringify(r),c=Buffer.from(a),l=c.byteLength,u=Pa.protocolPrefix+Pa.protocolVersion+Pa.jsonLength+Pa.binaryLength+Pa.fromServiceId+Pa.toServiceId+Pa.sentAt+l+o,d=Buffer.alloc(u),h=Date.now();let f=0;return d.write(Ga,f),f+=Pa.protocolPrefix,d.writeUInt8(1,f),f+=Pa.protocolVersion,d.writeUInt32LE(l,f),f+=Pa.jsonLength,d.writeUInt32LE(o,f),f+=Pa.binaryLength,d.writeUInt32LE(t,f),f+=Pa.fromServiceId,d.writeUInt32LE(n,f),f+=Pa.toServiceId,d.writeBigInt64LE(BigInt(h),f),f+=Pa.sentAt,c.copy(d,f),f+=l,s&&o&&s.copy(d,f),d},decodeHeader:e=>{let t=0;const n=e.toString("utf-8",t,Pa.protocolPrefix);if(t+=Pa.protocolPrefix,n!==Ga)return null;if(e.byteLength<La)return Va(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const r=e.readUInt8(t);t+=Pa.protocolVersion;const i=e.readUInt32LE(t);t+=Pa.jsonLength;const s=e.readUInt32LE(t);t+=Pa.binaryLength;const o=e.readUInt32LE(t);t+=Pa.fromServiceId;const a=e.readUInt32LE(t);t+=Pa.toServiceId;const c=e.readBigInt64LE(t);t+=Pa.sentAt;const l=i+s,u=e.subarray(t,t+l),d=e.subarray(0,La);let h=null;return e.byteLength-La-i-s>0&&(h=e.subarray(La+i+s)),{header:{protocolVersion:r,jsonLength:i,binaryLength:s,fromServiceId:o,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=Aa(n);if(!i?.json)return Va("Invalid JSON in KL message"),null;i.jsonBinaryMap&&r.byteLength&&Wa(i.json,r,i.jsonBinaryMap);const s=Buffer.concat([e.headerPackage,t]);let o=s,a=null;const c=La+e.jsonLength+e.binaryLength;return s.byteLength>c&&(a=s.subarray(c),o=s.subarray(0,c)),{message:{json:i.json,rawMessage:o},remaining:a}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<La)return Va("Invalid Header Size"),e;let n=0;return n+=Pa.protocolPrefix,n+=Pa.protocolVersion,n+=Pa.jsonLength,n+=Pa.binaryLength,void 0!==t.fromServiceId&&e.writeUInt32LE(t.fromServiceId,n),n+=Pa.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=Ra+r,s=Buffer.alloc(i);return s.write(Ha,t),t+=ja.protocolPrefix,s.writeUint32LE(r,t),t+=ja.txtLength,n.copy(s,t),s},decodeCommand:e=>{let t=0;if(e.byteLength<Ra)return{command:null};const n=e.toString("utf-8",t,ja.protocolPrefix);if(t+=ja.protocolPrefix,n!==Ha)return{command:null};const r=e.readUInt32LE(t);t+=ja.txtLength;const i=e.toString("utf-8",t,t+r),s=e.byteLength-Ra-r;let o=null;s>0&&(o=e.subarray(Ra+r));let a=0;return s<0&&(a=Math.abs(s)),{command:i,remainingData:o,missing:a}}};const qa="KMSG",Ka="KCMD",Ja=Ya("klProtocol"),Za=new TextEncoder;var Xa={encode:(e,t,n)=>{const r={json:e.json},i=Ua(e.json,"ArrayBuffer"),s=i?.combinedData;i&&(r.jsonBinaryMap=i.map,r.json=i.sourceCopy);const o=s?s.byteLength:0,a=JSON.stringify(r),c=Za.encode(a),l=c.byteLength,u=new ArrayBuffer(Pa.protocolPrefix+Pa.protocolVersion+Pa.jsonLength+Pa.binaryLength+Pa.fromServiceId+Pa.toServiceId+Pa.sentAt+l+o),d=new DataView(u),h=new Uint8Array(u),f=Date.now();let p=0;for(let e=0;e<4;++e)h[p++]=qa.charCodeAt(e);return d.setUint8(p,1),p+=Pa.protocolVersion,d.setUint32(p,l,!0),p+=Pa.jsonLength,d.setUint32(p,o,!0),p+=Pa.binaryLength,d.setUint32(p,t,!0),p+=Pa.fromServiceId,d.setUint32(p,n,!0),p+=Pa.toServiceId,d.setBigInt64(p,BigInt(f),!0),p+=Pa.sentAt,h.set(c,p),p+=l,s&&o&&h.set(new Uint8Array(s),p),u},decodeHeader:e=>{const t=new DataView(e);let n=0,r="";for(let e=0;e<Pa.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==qa)return null;if(e.byteLength<La)return Ja.log(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const i=t.getUint8(n);n+=Pa.protocolVersion;const s=t.getUint32(n,!0);n+=Pa.jsonLength;const o=t.getUint32(n,!0);n+=Pa.binaryLength;const a=t.getUint32(n,!0);n+=Pa.fromServiceId;const c=t.getUint32(n,!0);n+=Pa.toServiceId;const l=t.getBigInt64(n,!0);n+=Pa.sentAt;const u=s+o,d=e.slice(n,n+u),h=new Uint8Array(e,0,La);let f=null;if(e.byteLength-La-s-o>0){f=new Uint8Array(e,La+s+o).slice().buffer}return{header:{protocolVersion:i,jsonLength:s,binaryLength:o,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 s=(new TextDecoder).decode(n.subarray(0,e.jsonLength)),o=n.subarray(e.jsonLength,e.jsonLength+e.binaryLength),a=Aa(s);if(!a?.json)return Ja.log("Invalid JSON in KL message"),null;a.jsonBinaryMap&&o.byteLength&&Wa(a.json,o,a.jsonBinaryMap);const c=new Uint8Array(e.headerPackage.byteLength+n.byteLength);c.set(new Uint8Array(e.headerPackage),0),c.set(n,e.headerPackage.byteLength);let l=c,u=null;const d=La+e.jsonLength+e.binaryLength;return c.byteLength>d&&(u=c.subarray(d),l=c.subarray(0,d)),{message:{json:a.json,...o.length?{binaryData:o.buffer}:{},rawMessage:l.buffer},remaining:u?.buffer??null}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<La)return Ja("Invalid Header Size"),e;let n=0;n+=Pa.protocolPrefix,n+=Pa.protocolVersion,n+=Pa.jsonLength,n+=Pa.binaryLength;const r=new DataView(e);return void 0!==t.fromServiceId&&r.setUint32(n,t.fromServiceId,!0),n+=Pa.fromServiceId,void 0!==t.toServiceId&&r.setUint32(n,t.toServiceId,!0),e},encodeCommand:e=>{let t=0;const n=Za.encode(e),r=n.byteLength,i=new ArrayBuffer(Ra+r),s=new DataView(i),o=new Uint8Array(i);for(let e=0;e<4;++e)o[t++]=Ka.charCodeAt(e);return s.setUint32(t,r,!0),t+=ja.txtLength,o.set(n,t),i},decodeCommand:e=>{const t=new DataView(e);let n=0;if(e.byteLength<Ra)return{command:null};let r="";for(let e=0;e<ja.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==Ka)return{command:null};const i=t.getUint32(n,!0);n+=ja.txtLength;const s=e.byteLength-Ra-i,o=new Uint8Array(e,n,Math.min(i,e.byteLength-Ra)),a=(new TextDecoder).decode(o);let c=null;s>0&&(c=e.slice(Ra+i));let l=0;return s<0&&(l=Math.abs(s)),{command:a,remainingData:c,missing:l}}};let Qa=za;Da&&(Qa=Xa);var ec,tc=Qa;!function(e){e.FunctionNotFound="FNC_NOT_FOUND",e.ParentEventCallbackError="PARENT_EVENT_CALLBACK_ERROR"}(ec||(ec={}));let nc=Math.ceil(Date.now()/1e3);let rc,ic,sc,oc,ac,cc=!1;var lc=()=>{cc=!0},uc=(e,t)=>{if(!rc)throw new Error("Memory connection not set.");rc.sendBuf(e,t)},dc=e=>ic=e,hc=e=>ac=e,fc=e=>sc=e,pc=e=>oc=e;const gc=async(e,t=2)=>{const n=async(e,r)=>{if(Array.isArray(e))for(let i=0;i<e.length;i++){const s=e[i];if(s&&"object"==typeof s)if(Array.isArray(s))await n(s,r+1);else{const o=s._kemuType;void 0!==o?o===we.ImageData&&(e[i]=await Ke(s)):r<t&&await n(s,r+1)}}else if("object"==typeof e&&null!==e){const i=Object.keys(e);for(const s of i){const i=e[s];if(i&&"object"==typeof i){const o=i._kemuType;void 0!==o?o===we.ImageData&&(e[s]=await Ke(i)):r<t&&await n(i,r+1)}}}};return await n(e,1),e};Ya("klTransmissionManager"),Ya("ipcClient"),Ya("kemuWidgetService"),x(process.argv.slice(2));const mc=e=>m(`runner:${e}`),yc=mc("connectionManager"),vc=mc("remoteInvoke"),bc=new function(e){const t={};let n=console.log;const r={};let i=e||String(Date.now());const s={},o=e=>!s[e],a=(e,t,n,r,i,s)=>{let a=Da?new ArrayBuffer(0):Buffer.alloc(0);const c={json:{functionName:e,args:s.success?s.success:[s],messageId:t,type:s.success?"response":"error"}};return o(r)&&(a=tc.encode(c,n,r)),i(a,{msg:c,sourceServiceId:n,targetServiceId:r})};return{setLogger:e=>{n=e},processMessage:(e,i,s,o)=>{if(!o)return!1;const c=o;if(t[c.messageId]){const e=t[c.messageId];return e&&(clearTimeout(e.timer),e.fulfilled||(e.fulfilled=!0,"response"===c.type?e.resolve(c.args):"error"===c.type&&e.reject(c.args[0])),delete t[c.messageId]),!0}if("execute"!==c.type&&n&&n(`No pending execution found for message id "${c.messageId}"`),"execute"===c.type){const t=r[c.functionName];if(t){const n=e=>{a(c.functionName,c.messageId,s.targetServiceId,s.sourceServiceId,i,e)};t({transport:e,args:c.args,reply:n,messageId:c.messageId,sourceServiceId:s.sourceServiceId,send:i})}else{const e=`Function "${c.functionName}" not found.`;n&&n(e),a(c.functionName,c.messageId,s.targetServiceId,s.sourceServiceId,i,{error:e,errCode:"FNC_NOT_FOUND"})}return!0}return!1},execute:async(e,r,s,a,c,l)=>{if(!s){const e="No send buffer function provided.";throw n&&n(e),e}nc+=1;const u=`${i}-${nc}-exec-${e.substring(0,10)}`,d={messageId:u,functionName:e,send:s,sourceServiceId:a,targetServiceId:c,args:r||[],fulfilled:!1,resolve:()=>{},reject:()=>{}};d.promise=new Promise(((e,t)=>{d.resolve=e,d.reject=t}));let h=Da?new ArrayBuffer(0):Buffer.alloc(0);const f={json:{functionName:e,args:r,messageId:u,type:"execute"}};o(c)&&(h=tc.encode(f,a,c)),t[u]=d,n&&n(`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((()=>{n&&n(`Remote function ${u} timed out`);const r=t[u];r&&!r.fulfilled&&(r.fulfilled=!0,d.reject(`Function ${e} Timed out`)),delete t[u]}),l?.timeout||3e4)),s(h,{sourceServiceId:a,targetServiceId:c,msg:f}),d.promise},sendResponse:a,registerFunction:(e,t)=>{r[e]=t},getTransportSendFunction:e=>{const n=t[e];return n?n.send:null},setServiceName:e=>{i=e},getPendingExecutions:()=>t,rejectAllPending:e=>{Object.keys(t).forEach((n=>{const r=t[n];r&&!r.fulfilled&&(clearTimeout(r.timer),r.fulfilled=!0,r.reject(e),delete t[n])}))},broadcast:(e,t,r,s)=>{nc+=1;const a=`${i}-${nc}-multicast-${e.substring(0,10)}`;let c=Da?new ArrayBuffer(0):Buffer.alloc(0);const l={json:{functionName:e,args:t,messageId:a,type:"execute"}};let u=o(r[0].serviceId);u&&(c=tc.encode(l,s,r[0].serviceId));for(let t=0;t<r.length;t++)try{const i=r[t];n&&n(`Broadcasting function "${e}" with message id "${a}" to client [${i.serviceId}]`),0!==t&&(u=o(i.serviceId),u&&(c=tc.patchEncodedHeader(c,{toServiceId:i.serviceId}))),i.sendFn(c,{msg:l,sourceServiceId:s,targetServiceId:i.serviceId})}catch(e){n&&n(`Error broadcasting to client at index ${t}`)}},disableServiceEncoding:(e,t)=>{s[e]=t}}}("kweb");bc.setLogger(vc);const wc=new o,Sc=new o;let _c,Ic=null,xc=null,kc=null,Ec=null;const Cc={},$c=()=>{if(!kc)throw new Error("API key is required to interact with the hub");return kc},Oc=(e,t,n)=>{const r=`${e}_${t}`,i={contents:n,lastRequestedAt:Date.now(),contentsChecksum:""};return Cc[r]=i,i},Mc=(e,t)=>Cc[`${e}_${t}`]||null,Nc=async(e,t)=>{if(!Ic)return yc("Hub Link has not been acknowledged. Cannot get services."),null;const n=[{serviceName:e,version:t}];return(await bc.execute(xe.GetServiceContents,n,Ac,Ic,0))[0]},Tc=async(e,t,n=!1)=>{if(!e||!t)return null;const r=Mc(e,t);if(!r||n){const n=r||Oc(e,t);try{const r=await Nc(e,t);return r&&(n.contents=r.uiContent,n.contentsChecksum=r.uiContentsChecksum||""),n.contents||null}catch(n){yc(`Failed to fetch service contents for ${e} v${t}`,n)}}return r?.contents||null},Ac=uc,Dc=()=>{yc("Disconnected from the server"),Ic=null,Ec=null,bc.rejectAllPending("Disconnected from the server"),wc.emit("disconnected")},Pc=()=>{yc("Connected to the server"),wc.emit("connected")},jc=()=>xc,Lc=(e,t,n,r)=>`${e}_${t}_${n}_${r}`,Rc=async()=>{const e=jc();if(e){const t=le(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{yc(`Re-issuing subscription for service ${t.service.name} (${t.service.version})`),n[r]=!0,await Qc({listener:{recipeId:e},targetService:{serviceName:t.service.name,version:t.service.version}})}catch(e){yc(`Failed to re-issue subscription for service ${t.service.name} (${t.service.version})`,e)}}}}}}}},Fc=async e=>{if(!e)return void yc("Hub sent ACK request without service id");const t={apiKey:$c(),ackSessionId:e};await bc.execute(xe.SocketAckResponse,[t],Ac,e,0),yc("Hub Link acknowledged"),Ic=e,wc.emit("acknowledged"),Rc()},Uc=async e=>{const t=e.args[0],n=Lc("broadcast",`hub_${t.type}`,(0).toString(),"");await Sc.emit(n,t)},Bc=async e=>{const t=e.args[0];for(const e of t.outputs||[])e.type===we.ImageData&&We(e.value)&&(e.value=await Ke(e.value));const n=jc();if(n){const r=le(n);if(r){const i=async e=>{const n=Lc("broadcast",t.source.serviceName,t.source.serviceVersion,e);try{await Sc.emit(n,t)}catch(t){yc(`Failed to emit broadcast event for target ${e}`,t)}};await i("app");for(const s in r.blocks){const o=r.blocks[s];for(const r in o.gates){const s=o.gates[r];if(s.disabled)continue;const a=s.state;if(s.type===Ze.hubService&&a.service?.name===t.source.serviceName&&a.service?.version===t.source.serviceVersion&&a.variantId===t.variantId){await i(r);const s=a?.service?.name&&t.eventContext?{[a.service.name]:t.eventContext}:void 0;for(const i of t.outputs||[])if(null!==i.value&&void 0!==i.value){const t={type:i.type,value:i.value,timestamp:Date.now()};yc(`Sending data to output ${i.name} requested by messageId ${e.messageId}`),await sa({recipePoolId:n,currentGateId:r,sourcePortName:i.name,originalEvent:t,data:t,eventContext:s})}}}}}}},Wc=async e=>{const t=e.args[0],{finalState:n,recipeId:r,widgetId:i}=t,s=ia(r,i);let o=s;if(n&&o&&s&&(o={...s,customState:n},ra(r,i,o,!0)),o?.service)try{const e=Lc("setOutputs",o.service.name,o.service.version,i);await Sc.emit(e,t.outputs)}catch(e){yc(`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===we.ImageData){if(!We(n.value)){yc(`Invalid ImageData value received for output ${n.name}. Expected an ImageData-like object`);continue}n.value=await Ke(n.value)}else n.type!==we.JsonObj&&n.type!==we.Array||await gc(n.value);const s={type:n.type,value:n.value,timestamp:Date.now()};yc(`Sending data to output ${n.name} requested by messageId ${e.messageId}`);const c=o?.service?.name&&t.eventContext?{[o.service.name]:t.eventContext}:void 0;try{await sa({recipePoolId:r,currentGateId:i,sourcePortName:n.name,originalEvent:s,data:s,eventContext:c})}catch(e){yc(`Failed to trigger next global widget for output ${n.name}`,e),a=e;break}}if(a){const t=a instanceof dr,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:[]})},Yc=async e=>{const t=e.args[0],{newState:n,recipeId:r,widgetId:i}=t,s=ia(r,i);if(s){const t={...s,customState:{...s.customState,...n}};return ra(r,i,t,!0),e.reply({success:[]})}},Gc=async({args:e,reply:t})=>{const n=e[0],{recipeId:r,widgetId:i,path:s,key:o}=n;yc(`Received request to set a dependency path for "${o}" on widget "${i}" in recipe "${r}"`);const a=ia(r,i);if(a){const e={...a};e.dependencies=e.dependencies||{},e.dependencies[o]={path:s},ra(r,i,e,!0)}return t({success:[]})},Hc=async({args:e,reply:t})=>{const n=e[0],{recipeId:r,widgetId:i,key:s}=n;yc(`Received request to get a dependency path for "${s}" on widget "${i}" in recipe "${r}"`);const o=ia(r,i);if(o){const e=o.dependencies?.[s]?.path;return yc(`Returning dependency path for "${s}" on widget "${i}": "${e}"`),t({success:[e||null]})}return t({error:"Widget not found",errCode:"WIDGET_NOT_FOUND"})},Vc=async()=>{if(yc(`Requesting services on ${(new Date).toISOString()}`),!Ic)return yc("Hub Link has not been acknowledged. Cannot get services."),{available:[],installed:[],failed:[]};const[e]=await bc.execute(xe.GetServices,[],Ac,Ic,0);_c=e;for(const t of e.available){if(t.internal)continue;const e=Mc(t.name,t.version);if(!e||e?.contentsChecksum!==t.uiContentChecksum)try{const n=e||Oc(t.name,t.version);yc(`Service ${t.name} v${t.version} contents have changed, fetching new contents`);const r=await Nc(t.name,t.version);r&&(n.contents=r.uiContent,n.contentsChecksum=t.uiContentChecksum||"")}catch(e){yc(`Failed to update service contents for ${t.name} v${t.version}`,e)}}return e},zc=()=>_c||{available:[],installed:[],failed:[]},qc=()=>!!_c,Kc=async e=>{const{targetServiceSessionId:t}=e;if(!Ic)return void yc("No target service session id provided");yc(`Forwarding "onParentEvent" to service ${t}`);const n=await bc.execute(xe.OnParentEvent,[e],Ac,Ic,t,e.config).catch((e=>{throw yc(`Error invoking onParentEvent callback: ${e}`),e.errCode===ec.ParentEventCallbackError?e.error:e}));return n},Jc=async e=>{if(!Ic)return yc("Hub Link has not been acknowledged. Cannot get services."),{};const[t]=await bc.execute(xe.GetDefaultState,[],Ac,Ic,e);return t},Zc=async(e,t,n,r)=>{if(!Ic)return yc("Hub Link has not been acknowledged. Cannot get services."),null;const[i]=await bc.execute(xe.UIEvent,[t,n],Ac,Ic,e,r);return i},Xc=(e,t)=>{const n=()=>{t()};return wc.on(e,n),()=>wc.off(e,n)},Qc=async e=>{if(Ic)return bc.execute(xe.SubscribeToService,[e],Ac,Ic,0);yc("Hub Link has not been acknowledged. Cannot subscribe to services.")},el=async e=>{if(Ic)return bc.execute(xe.UnsubscribeFromService,[e],Ac,Ic,0);yc("Hub Link has not been acknowledged. Cannot subscribe to services.")},tl=(e,t,n,r)=>{const i=Lc("broadcast",t,n,e);return Sc.on(i,r)},nl=(e,t,n,r)=>{const i=Lc("setOutputs",t,n,e);return Sc.on(i,r)},rl=async(e,t,n)=>Ic?bc.execute(e,t,Ac,Ic,0,n):(yc("Hub Link has not been acknowledged. Cannot execute function."),null),il=async e=>{if(!Ic)return void yc("Hub Link has not been acknowledged. Cannot execute function.");const t=ia(e.recipeId,e.widgetId);if(!t)throw new Error("Widget or recipe pool not found. Cannot initialize service instance.");const n=Object.keys(t.dependencies||{}).reduce(((e,n)=>(e[n]=t.dependencies?.[n]?.path||null,e)),{}),r=[{currentState:t.customState,recipeId:e.recipeId,widgetId:e.widgetId,variantId:e.variantId,recipeType:e.recipeType,recipeName:e.recipeName,currentDependencies:n}],[i]=await bc.execute(xe.InitializeInstance,r,Ac,Ic,e.sessionId);if(i){const t=ia(e.recipeId,e.widgetId);if(t){const n={...t,customState:i};ra(e.recipeId,e.widgetId,n,!0)}}},sl=async(e,t,n,r)=>{if(!Ic)return void yc("Hub Link has not been acknowledged. Cannot execute function.");const i=ia(n,t);if(!i)throw new Error("Widget or recipe pool not found. Cannot initialize service instance.");const s=[{currentState:i.customState,recipeId:n,widgetId:t,variantId:r}];await bc.execute(xe.TerminateInstance,s,Ac,Ic,e)},ol=async(e,t,n="^",r)=>{const i=["^","~",">=",">","<=","<","="];if(!i.includes(n))throw new Error(`Invalid compare mode "${n}". Must be one of ${i.join(", ")}`);const s=qc(),o=r||!s?await Vc():zc();for(const r of o.available)if(r.name===e){if(r.version===t)return r;if(g(r.version,`${n}${t}`))return r}return null},al=async()=>{if(!Ic)return yc("Hub Link has not been acknowledged. Cannot get services."),null;if(Ec)return Ec;const[e]=await bc.execute(xe.GetSystemInfo,[],Ac,Ic,0).catch((e=>(yc("Failed to get system info",e),[null])));return Ec=e,e};var cl,ll,ul,dl,hl,fl,pl,gl,ml=async e=>{fc(Pc),pc(Dc),kc=e,hc((({json:e,transmission:t})=>{bc.processMessage("websocket",Ac,t,e)})),bc.registerFunction(xe.SetState,Yc),bc.registerFunction(xe.SetOutputs,Wc),bc.registerFunction(xe.BroadcastEvent,Bc),bc.registerFunction(xe.HubBroadcastEvent,Uc),bc.registerFunction(ke.SetDependencyPath,Gc),bc.registerFunction(ke.GetDependencyPath,Hc),dc((e=>{((e,t)=>{const n=Ie.SocketAcknowledge,r=Ie.IpcAcknowledge,i=e.startsWith(n);if(e===r)return t&&t(),0;if(i){const s=e.split(i?n:r),o=parseInt(s[1]);return t&&t(o),o}})(e,Fc),((e,t)=>{e===Ie.ServicesListChanged&&(t&&t())})(e,(()=>{yc("Services list changed"),wc.emit("services-changed")}))})),await lc()},yl=(e,t)=>{wc.on(e,t)},vl=()=>({getServices:Vc,getServiceContents:Tc,onParentEvent:Kc,onCommand:Xc,getDefaultState:Jc,getCachedServices:zc,areServicesCached:qc,subscribeToServiceEvents:Qc,unsubscribeFromServiceEvents:el,callProcessorHandler:Zc,onBroadcastEvent:tl,onSetOutputsEvent:nl,executeHubFunction:rl,initializeServiceInstance:il,terminateServiceInstance:sl,getCompatibleService:ol,getHubSystemInfo:al}),bl=e=>{xc=e},wl=()=>bc;!function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(cl||(cl={})),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"}(ll||(ll={})),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"}(ul||(ul={})),function(e){e.Javascript="js",e.Python="py",e.Executable="exe"}(dl||(dl={})),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:"}(hl||(hl={})),function(e){e.GetServices="getServices",e.SubscribeToService="subscribeToService",e.UnsubscribeFromService="unsubscribeFromService",e.GetServiceContents="getServiceContents",e.SocketAckResponse="socketAckResponse",e.ShowSecretsConfigScreen="showSecretsConfigScreen",e.GetMappedSecrets="getMappedSecrets",e.GetSecretContexts="getSecretContexts",e.OnParentEvent="onParentEvent",e.GetDefaultState="getDefaultState",e.BroadcastEvent="broadcastEvent",e.HubBroadcastEvent="hubBroadcastEvent",e.ServiceManifest="serviceManifest",e.GetState="getState",e.SetState="setState",e.SetOutputs="setOutputs",e.UIEvent="uiEvent",e.GetSystemInfo="getSystemInfo",e.InitializeInstance="initializeInstance",e.TerminateInstance="terminateInstance",e.UninstallService="uninstallService",e.ChooseDirectoryDialog="chooseDirectoryDialog",e.ChooseFileDialog="chooseFileDialog",e.GetUniqueId="getUniqueId",e.RebootToInstallUpdate="rebootToInstallUpdate",e.GetFileContentFromCacheId="getFileContentFromCacheId",e.GetDecryptedEdgeApiKey="getDecryptedEdgeApiKey",e.GetHubConfig="getHubConfig"}(fl||(fl={})),function(e){e.SetDependencyPath="setDependencyPath",e.GetDependencyPath="getDependencyPath"}(pl||(pl={})),function(e){e.IPC="ipc",e.WS="ws"}(gl||(gl={}));const Sl=e=>{try{return JSON.parse(e)}catch(e){return null}},_l=()=>{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=O.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}`)}},Il=/^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i,xl=e=>{if("string"!=typeof e)throw new TypeError("Invalid argument expected string");const t=e.match(Il);if(!t)throw new Error(`Invalid argument not valid semver ('${e}' received)`);return t.shift(),t},kl=e=>"*"===e||"x"===e||"X"===e,El=e=>{const t=parseInt(e,10);return isNaN(t)?e:t},Cl=(e,t)=>{if(kl(e)||kl(t))return 0;const[n,r]=((e,t)=>typeof e!=typeof t?[String(e),String(t)]:[e,t])(El(e),El(t));return n>r?1:n<r?-1:0},$l=(e,t)=>{for(let n=0;n<Math.max(e.length,t.length);n++){const r=Cl(e[n]||"0",t[n]||"0");if(0!==r)return r}return 0},Ol=(e,t,n)=>{Tl(n);const r=((e,t)=>{const n=xl(e),r=xl(t),i=n.pop(),s=r.pop(),o=$l(n,r);return 0!==o?o:i&&s?$l(i.split("."),s.split(".")):i||s?i?-1:1:0})(e,t);return Ml[n].includes(r)},Ml={">":[1],">=":[0,1],"=":[0],"<=":[-1,0],"<":[-1],"!=":[-1,1]},Nl=Object.keys(Ml),Tl=e=>{if(-1===Nl.indexOf(e))throw new Error(`Invalid operator, expected one of ${Nl.join("|")}`)};var Al="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Dl(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Pl,jl,Ll,Rl,Fl,Ul={exports:{}},Bl={exports:{}};function Wl(){if(jl)return Pl;jl=1;var e=1e3,t=60*e,n=60*t,r=24*n,i=7*r;function s(e,t,n,r){var i=t>=1.5*n;return Math.round(e/n)+" "+r+(i?"s":"")}return Pl=function(o,a){a=a||{};var c=typeof o;if("string"===c&&o.length>0)return function(s){if(!((s=String(s)).length>100)){var o=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(s);if(o){var a=parseFloat(o[1]);switch((o[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}}}}(o);if("number"===c&&isFinite(o))return a.long?function(i){var o=Math.abs(i);return o>=r?s(i,o,r,"day"):o>=n?s(i,o,n,"hour"):o>=t?s(i,o,t,"minute"):o>=e?s(i,o,e,"second"):i+" ms"}(o):function(i){var s=Math.abs(i);return s>=r?Math.round(i/r)+"d":s>=n?Math.round(i/n)+"h":s>=t?Math.round(i/t)+"m":s>=e?Math.round(i/e)+"s":i+"ms"}(o);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(o))}}function Yl(){return Rl||(Rl=1,Ll=function(e){function t(e){let r,i,s,o=null;function a(...e){if(!a.enabled)return;const n=a,i=Number(new Date),s=i-(r||i);n.diff=s,n.prev=r,n.curr=i,r=i,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((r,i)=>{if("%%"===r)return"%";o++;const s=t.formatters[i];if("function"==typeof s){const t=e[o];r=s.call(n,t),e.splice(o,1),o--}return r})),t.formatArgs.call(n,e),(n.log||t.log).apply(n,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=n,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(i!==t.namespaces&&(i=t.namespaces,s=t.enabled(e)),s),set:e=>{o=e}}),"function"==typeof t.init&&t.init(a),a}function n(e,n){const r=t(this.namespace+(void 0===n?":":n)+e);return r.log=this.log,r}function r(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){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=Wl(),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}),Ll}var Gl,Hl,Vl,zl,ql,Kl={exports:{}};"undefined"==typeof process||"renderer"===process.type||!0===process.browser||process.__nwjs?Ul.exports=(Fl||(Fl=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=Yl()(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(Bl,Bl.exports)),Bl.exports):Ul.exports=(ql||(ql=1,function(e,t){const n=T,r=c;t.init=function(e){e.inspectOpts={};const n=Object.keys(t.inspectOpts);for(let r=0;r<n.length;r++)e.inspectOpts[n[r]]=t.inspectOpts[n[r]]},t.log=function(...e){return process.stderr.write(r.formatWithOptions(t.inspectOpts,...e)+"\n")},t.formatArgs=function(n){const{namespace:r,useColors:i}=this;if(i){const t=this.color,i="[3"+(t<8?t:"8;5;"+t),s=` ${i};1m${r} [0m`;n[0]=s+n[0].split("\n").join("\n"+s),n.push(i+"m+"+e.exports.humanize(this.diff)+"[0m")}else n[0]=(t.inspectOpts.hideDate?"":(new Date).toISOString()+" ")+r+" "+n[0]},t.save=function(e){e?process.env.DEBUG=e:delete process.env.DEBUG},t.load=function(){return process.env.DEBUG},t.useColors=function(){return"colors"in t.inspectOpts?Boolean(t.inspectOpts.colors):n.isatty(process.stderr.fd)},t.destroy=r.deprecate((()=>{}),"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),t.colors=[6,2,3,4,5,1];try{const e=function(){if(zl)return Vl;zl=1;const e=A,t=T,n=Hl?Gl:(Hl=1,Gl=(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 s(e){return 0!==e&&{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function o(t,s){if(0===i)return 0;if(n("color=16m")||n("color=full")||n("color=truecolor"))return 3;if(n("color=256"))return 2;if(t&&!s&&void 0===i)return 0;const o=i||0;if("dumb"===r.TERM)return o;if("win32"===process.platform){const t=e.release().split(".");return Number(t[0])>=10&&Number(t[2])>=10586?Number(t[2])>=14931?3:2:1}if("CI"in r)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some((e=>e in r))||"codeship"===r.CI_NAME?1:o;if("TEAMCITY_VERSION"in r)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(r.TEAMCITY_VERSION)?1:0;if("truecolor"===r.COLORTERM)return 3;if("TERM_PROGRAM"in r){const e=parseInt((r.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(r.TERM_PROGRAM){case"iTerm.app":return e>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(r.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(r.TERM)||"COLORTERM"in r?1:o}return n("no-color")||n("no-colors")||n("color=false")||n("color=never")?i=0:(n("color")||n("colors")||n("color=true")||n("color=always"))&&(i=1),"FORCE_COLOR"in r&&(i="true"===r.FORCE_COLOR?1:"false"===r.FORCE_COLOR?0:0===r.FORCE_COLOR.length?1:Math.min(parseInt(r.FORCE_COLOR,10),3)),Vl={supportsColor:function(e){return s(o(e,e&&e.isTTY))},stdout:s(o(!0,t.isatty(1))),stderr:s(o(!0,t.isatty(2)))},Vl}();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=Yl()(t);const{formatters:i}=e.exports;i.o=function(e){return this.inspectOpts.colors=this.useColors,r.inspect(e,this.inspectOpts).split("\n").map((e=>e.trim())).join(" ")},i.O=function(e){return this.inspectOpts.colors=this.useColors,r.inspect(e,this.inspectOpts)}}(Kl,Kl.exports)),Kl.exports);var Jl=Dl(Ul.exports);const Zl=e=>Jl(e);var Xl={},Ql={};class eu 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,eu)}}var tu,nu,ru,iu,su,ou=e=>{if(e.length>2)throw new eu(e);function t(e={}){this.options=e}function n(e){return new t(e)}return t.prototype.transform=e,n.Format=t,n},au={exports:{}},cu={exports:{}},lu={exports:{}},uu={exports:{}};function du(){if(su)return iu;su=1;var e=A,t=ru?nu:(ru=1,nu=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 s=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 s=r?1:0;if("win32"===process.platform){var o=e.release().split(".");return Number(process.versions.node.split(".")[0])>=8&&Number(o[0])>=10&&Number(o[2])>=10586?Number(o[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:s;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,s)}(i);return function(e){return 0!==e&&{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}(s)}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)),iu={supportsColor:i,stdout:i(process.stdout),stderr:i(process.stderr)}}var hu,fu,pu,gu,mu,yu,vu,bu,wu={exports:{}},Su={exports:{}},_u={exports:{}},Iu={exports:{}},xu={exports:{}},ku={exports:{}};function Eu(){return vu||(vu=1,function(){var e={};lu.exports=e,e.themes={};var t=c,n=e.styles=(tu||(tu=1,function(){var e={};uu.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"}))}()),uu.exports),r=Object.defineProperties,i=new RegExp(/[\r\n]+/g);e.supportsColor=du().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 o(e){var t=function e(){return d.apply(e,arguments)};return t._styles=e,t.__proto__=u,t}var a,l=(a={},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"),a[e]={get:function(){return o(this._styles.concat(e))}}})),a),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 s=-1!=r.indexOf("\n"),o=this._styles,a=o.length;a--;){var c=n[o[a]];r=c.open+r.replace(c.closeRe,c.open)+c.close,s&&(r=r.replace(i,(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 s in t[n])i=e[t[n][s]](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=(hu||(hu=1,wu.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}),wu.exports),e.zalgo=(fu||(fu=1,Su.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 s(e){var t=!1;return r.filter((function(n){t=n===e})),t}return function(e,t){var r,o,a="";for(o 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(!s(o)){switch(a+=e[o],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)}),Su.exports),e.maps={},e.maps.america=(pu||(pu=1,_u.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)}}}),_u.exports)(e),e.maps.zebra=(gu||(gu=1,Iu.exports=function(e){return function(t,n){return n%2==0?t:e.inverse(t)}}),Iu.exports)(e),e.maps.rainbow=(mu||(mu=1,xu.exports=function(e){var t=["red","yellow","green","blue","magenta"];return function(n,r){return" "===n?n:e[t[r++%t.length]](n)}}),xu.exports)(e),e.maps.random=(yu||(yu=1,ku.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)}}),ku.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 o([t])}}})),e}())}()),lu.exports}function Cu(){return bu||(bu=1,function(e){var t=Eu();e.exports=t}(cu)),cu.exports}var $u,Ou,Mu={},Nu={},Tu={};function Au(){if(Ou)return au.exports;Ou=1;const e=Cu(),{LEVEL:t,MESSAGE:n}=Mu;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,s=i.allColors[t].length;n<s;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 au.exports=e=>new i(e),au.exports.Colorizer=au.exports.Format=i,au.exports}Tu.levels={emerg:0,alert:1,crit:2,error:3,warning:4,notice:5,info:6,debug:7},Tu.colors={emerg:"red",alert:"yellow",crit:"red",error:"red",warning:"red",notice:"yellow",info:"green",debug:"blue"},$u=Nu,Object.defineProperty($u,"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($u,"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($u,"syslog",{value:Tu}),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:Nu})}(Mu);const{Colorizer:Du}=Au();var Pu,ju,Lu,Ru,Fu,Uu,Bu={exports:{}},Wu={exports:{}};function Yu(){if(Fu)return Wu.exports;Fu=1;const{configs:e,LEVEL:t,MESSAGE:n}=Mu;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 Wu.exports=e=>new r(e),Wu.exports.Padder=Wu.exports.Format=r,Wu.exports}var Gu,Hu,Vu,zu,qu,Ku,Ju,Zu,Xu,Qu,ed,td,nd,rd,id={exports:{}},sd={exports:{}};function od(){return Hu||(Hu=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 s(e){return e.length<5e3&&!i.test(e)?`"${e}"`:JSON.stringify(e)}function o(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 s=1;s<n;s++)i+=`${t}"${s}":${r}${e[s]}`;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 s(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 s=g(String(i),v,l,u,m,y);return e+=void 0!==s?s:"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=o(i,h)),l.push(v);for(let n=0;n<_;n++){const r=i[n],o=g(r,v,l,u,m,y);void 0!==o&&(e+=`${S}${s(r)}:${w}${o}`,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,o,a,c,l){switch("object"==typeof n&&null!==n&&"function"==typeof n.toJSON&&(n=n.toJSON(e)),typeof n){case"string":return s(n);case"object":{if(null===n)return"null";if(-1!==o.indexOf(n))return r;const e=l;let t="",i=",";if(Array.isArray(n)){if(0===n.length)return"[]";if(f<o.length+1)return'"[Array]"';o.push(n),""!==c&&(t+=`\n${l+=c}`,i=`,\n${l}`);const r=Math.min(n.length,p);let s=0;for(;s<r-1;s++){const e=m(String(s),n[s],o,a,c,l);t+=void 0!==e?e:"null",t+=i}const u=m(String(s),n[s],o,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}`),o.pop(),`[${t}]`}o.push(n);let u="";""!==c&&(i=`,\n${l+=c}`,u=" ");let h="";for(const e of a){const r=m(e,n[e],o,a,c,l);void 0!==r&&(t+=`${h}${s(e)}:${u}${r}`,h=i)}return""!==c&&h.length>1&&(t=`\n${l}${t}\n${e}`),o.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 s(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 s=0;for(;s<i-1;s++){const t=y(String(s),n[s],u,g,m);e+=void 0!==t?t:"null",e+=r}const o=y(String(s),n[s],u,g,m);return e+=void 0!==o?o:"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=o(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}${s(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 s(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=o(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}${s(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,[])}}}(sd,sd.exports)),sd.exports}function ad(){if(zu)return Vu;zu=1;const e=ou,{MESSAGE:t}=Mu,n=od();function r(e,t){return"bigint"==typeof t?t.toString():t}return Vu=e(((e,i)=>{const s=n.configure(i);return e[t]=s(e,i.replacer||r,i.space),e}))}var cd,ld,ud,dd,hd,fd={exports:{}},pd=/d{1,4}|M{1,4}|YY(?:YY)?|S{1,3}|Do|ZZ|Z|([HhMsDm])\1?|[aA]|"[^"]*"|'[^']*'/g,gd="\\d\\d?",md="\\d\\d",yd="[^\\s]+",vd=/\[([^]*?)\]/gm;function bd(e,t){for(var n=[],r=0,i=e.length;r<i;r++)n.push(e[r].substr(0,t));return n}var wd=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 Sd(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 s=i[r];for(var o in s)e[o]=s[o]}return e}var _d=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],Id=["January","February","March","April","May","June","July","August","September","October","November","December"],xd=bd(Id,3),kd={dayNamesShort:bd(_d,3),dayNames:_d,monthNamesShort:xd,monthNames:Id,amPm:["am","pm"],DoFn:function(e){return e+["th","st","nd","rd"][e%10>3?0:(e-e%10!=10?1:0)*e%10]}},Ed=Sd({},kd),Cd=function(e){return Ed=Sd(Ed,e)},$d=function(e){return e.replace(/[|\\{()[^$+*?.-]/g,"\\$&")},Od=function(e,t){for(void 0===t&&(t=2),e=String(e);e.length<t;)e="0"+e;return e},Md={D:function(e){return String(e.getDate())},DD:function(e){return Od(e.getDate())},Do:function(e,t){return t.DoFn(e.getDate())},d:function(e){return String(e.getDay())},dd:function(e){return Od(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 Od(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 Od(String(e.getFullYear()),4).substr(2)},YYYY:function(e){return Od(e.getFullYear(),4)},h:function(e){return String(e.getHours()%12||12)},hh:function(e){return Od(e.getHours()%12||12)},H:function(e){return String(e.getHours())},HH:function(e){return Od(e.getHours())},m:function(e){return String(e.getMinutes())},mm:function(e){return Od(e.getMinutes())},s:function(e){return String(e.getSeconds())},ss:function(e){return Od(e.getSeconds())},S:function(e){return String(Math.round(e.getMilliseconds()/100))},SS:function(e){return Od(Math.round(e.getMilliseconds()/10),2)},SSS:function(e){return Od(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?"-":"+")+Od(100*Math.floor(Math.abs(t)/60)+Math.abs(t)%60,4)},Z:function(e){var t=e.getTimezoneOffset();return(t>0?"-":"+")+Od(Math.floor(Math.abs(t)/60),2)+":"+Od(Math.abs(t)%60,2)}},Nd=function(e){return+e-1},Td=[null,gd],Ad=[null,yd],Dd=["isPm",yd,function(e,t){var n=e.toLowerCase();return n===t.amPm[0]?0:n===t.amPm[1]?1:null}],Pd=["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}],jd={D:["day",gd],DD:["day",md],Do:["day",gd+yd,function(e){return parseInt(e,10)}],M:["month",gd,Nd],MM:["month",md,Nd],YY:["year",md,function(e){var t=+(""+(new Date).getFullYear()).substr(0,2);return+(""+(+e>68?t-1:t)+e)}],h:["hour",gd,void 0,"isPm"],hh:["hour",md,void 0,"isPm"],H:["hour",gd],HH:["hour",md],m:["minute",gd],mm:["minute",md],s:["second",gd],ss:["second",md],YYYY:["year","\\d{4}"],S:["millisecond","\\d",function(e){return 100*+e}],SS:["millisecond",md,function(e){return 10*+e}],SSS:["millisecond","\\d{3}"],d:Td,dd:Td,ddd:Ad,dddd:Ad,MMM:["month",yd,wd("monthNamesShort")],MMMM:["month",yd,wd("monthNames")],a:Dd,A:Dd,ZZ:Pd,Z:Pd},Ld={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"},Rd=function(e){return Sd(Ld,e)},Fd=function(e,t,n){if(void 0===t&&(t=Ld.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=Ld[t]||t).replace(vd,(function(e,t){return r.push(t),"@@@"}));var i=Sd(Sd({},Ed),n);return(t=t.replace(pd,(function(t){return Md[t](e,i)}))).replace(/@@@/g,(function(){return r.shift()}))};function Ud(e,t,n){if(void 0===n&&(n={}),"string"!=typeof t)throw new Error("Invalid format in fecha parse");if(t=Ld[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=[],s=[],o=t.replace(vd,(function(e,t){return s.push($d(t)),"@@@"})),a={},c={};o=$d(o).replace(pd,(function(e){var t=jd[e],n=t[0],r=t[1],s=t[3];if(a[n])throw new Error("Invalid format. "+n+" specified twice in format");return a[n]=!0,s&&(c[s]=!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")})),o=o.replace(/@@@/g,(function(){return s.shift()}));var l=e.match(new RegExp(o,"i"));if(!l)return null;for(var u,d=Sd(Sd({},Ed),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 Bd,Wd,Yd,Gd,Hd={format:Fd,parse:Ud,defaultI18n:kd,setGlobalDateI18n:Cd,setGlobalDateMasks:Rd},Vd=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:Sd,default:Hd,defaultI18n:kd,format:Fd,parse:Ud,setGlobalDateI18n:Cd,setGlobalDateMasks:Rd}));const zd=Ql.format=ou;function qd(e,t){Object.defineProperty(zd,e,{get:()=>t(),configurable:!0})}Ql.levels=e=>(Du.addColors(e.colors||e),e),qd("align",(function(){return ju?Pu:(ju=1,Pu=ou((e=>(e.message=`\t${e.message}`,e))))})),qd("errors",(function(){return function(){if(Ru)return Lu;Ru=1;const e=ou,{LEVEL:t,MESSAGE:n}=Mu;return Lu=e(((e,{stack:r,cause:i})=>{if(e instanceof Error){const s=Object.assign({},e,{level:e.level,[t]:e[t]||e.level,message:e.message,[n]:e[n]||e.message});return r&&(s.stack=e.stack),i&&(s.cause=e.cause),s}if(!(e.message instanceof Error))return e;const s=e.message;return Object.assign(e,s),e.message=s.message,e[n]=s.message,r&&(e.stack=s.stack),i&&(e.cause=s.cause),e}))}()})),qd("cli",(function(){return function(){if(Uu)return Bu.exports;Uu=1;const{Colorizer:e}=Au(),{Padder:t}=Yu(),{configs:n,MESSAGE:r}=Mu;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 Bu.exports=e=>new i(e),Bu.exports.Format=i,Bu.exports}()})),qd("combine",(function(){return function(){if(Gu)return id.exports;Gu=1;const e=ou;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 id.exports=(...n)=>{const r=e(t(n)),i=r();return i.Format=r.Format,i},id.exports.cascade=t,id.exports}()})),qd("colorize",(function(){return Au()})),qd("json",(function(){return ad()})),qd("label",(function(){return Ku?qu:(Ku=1,qu=ou(((e,t)=>t.message?(e.message=`[${t.label}] ${e.message}`,e):(e.label=t.label,e))))})),qd("logstash",(function(){return function(){if(Zu)return Ju;Zu=1;const e=ou,{MESSAGE:t}=Mu,n=od();return Ju=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}))}()})),qd("metadata",(function(){return Qu?Xu:(Qu=1,Xu=ou(((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})))})),qd("ms",(function(){return function(){if(td)return ed;td=1;const e=ou,t=Wl();return ed=e((e=>{const n=+new Date;return this.diff=n-(this.prevTime||n),this.prevTime=n,e.ms=`+${t(this.diff)}`,e}))}()})),qd("padLevels",(function(){return Yu()})),qd("prettyPrint",(function(){return function(){if(rd)return nd;rd=1;const e=c.inspect,t=ou,{LEVEL:n,MESSAGE:r,SPLAT:i}=Mu;return nd=t(((t,s={})=>{const o=Object.assign({},t);return delete o[n],delete o[r],delete o[i],t[r]=e(o,!1,s.depth||null,s.colorize),t}))}()})),qd("printf",(function(){return function(){if(cd)return fd.exports;cd=1;const{MESSAGE:e}=Mu;class t{constructor(e){this.template=e}transform(t){return t[e]=this.template(t),t}}return fd.exports=e=>new t(e),fd.exports.Printf=fd.exports.Format=t,fd.exports}()})),qd("simple",(function(){return function(){if(ud)return ld;ud=1;const e=ou,{MESSAGE:t}=Mu,n=od();return ld=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}))}()})),qd("splat",(function(){return function(){if(hd)return dd;hd=1;const e=c,{SPLAT:t}=Mu,n=/%[scdjifoO%]/g,r=/%%/g;class i{constructor(e){this.options=e}_splat(n,i){const s=n.message,o=n[t]||n.splat||[],a=s.match(r),c=a&&a.length||0,l=i.length-c-o.length,u=l<0?o.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(s,...o),n}transform(e){const r=e.message,i=e[t]||e.splat;if(!i||!i.length)return e;const s=r&&r.match&&r.match(n);if(!s&&(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 s?this._splat(e,s):e}}return dd=e=>new i(e)}()})),qd("timestamp",(function(){return function(){if(Wd)return Bd;Wd=1;const e=Vd;return Bd=ou(((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)))}()})),qd("uncolorize",(function(){return function(){if(Gd)return Yd;Gd=1;const e=Cu(),t=ou,{MESSAGE:n}=Mu;return Yd=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 Kd={};!function(e){const{format:t}=c;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})}))}}}(Kd);var Jd,Zd,Xd,Qd,eh,th,nh={},rh={exports:{}},ih={exports:{}};function sh(){return Qd?Xd:(Qd=1,Xd=j)}function oh(){if(th)return eh;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 th=1,eh={destroy:function(r,i){var s=this,o=this._readableState&&this._readableState.destroyed,a=this._writableState&&this._writableState.destroyed;return o||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?s._writableState?s._writableState.errorEmitted?process.nextTick(t,s):(s._writableState.errorEmitted=!0,process.nextTick(e,s,n)):process.nextTick(e,s,n):i?(process.nextTick(t,s),i(n)):process.nextTick(t,s)})),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)}},eh}var ah,ch,lh,uh={};function dh(){if(ah)return uh;ah=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 s;let o;if("string"==typeof t&&(s="not ",t.substr(0,4)===s)?(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"))o=`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";o=`The "${e}" ${r} ${i} ${n(t,"type")}`}return o+=". Received type "+typeof r,o}),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"),uh.codes=e,uh}function hh(){if(lh)return ch;lh=1;var e=dh().codes.ERR_INVALID_OPT_VALUE;return ch={getHighWaterMark:function(t,n,r,i){var s=function(e,t,n){return null!=e.highWaterMark?e.highWaterMark:t?e[n]:null}(n,i,r);if(null!=s){if(!isFinite(s)||Math.floor(s)!==s||s<0)throw new e(i?r:"highWaterMark",s);return Math.floor(s)}return t.objectMode?16:16384}}}var fh,ph,gh,mh,yh={exports:{}},vh={exports:{}};function bh(){if(ph)return yh.exports;ph=1;try{var e=require("util");if("function"!=typeof e.inherits)throw"";yh.exports=e.inherits}catch(e){yh.exports=(fh||(fh=1,"function"==typeof Object.create?vh.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:vh.exports=function(e,t){if(t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}}),vh.exports)}return yh.exports}function wh(){if(mh)return gh;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)}mh=1;var i=L.Buffer,s=c.inspect,o=s&&s.custom||"inspect";function a(e,t,n){i.prototype.copy.call(e,t,n)}return gh=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 i.alloc(0);for(var t=i.allocUnsafe(e>>>0),n=this.head,r=0;n;)a(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,s=e>i.length?i.length:e;if(s===i.length?r+=i:r+=i.slice(0,e),0==(e-=s)){s===i.length?(++n,t.next?this.head=t.next:this.head=this.tail=null):(this.head=t,t.data=i.slice(s));break}++n}return this.length-=n,r}},{key:"_getBuffer",value:function(e){var t=i.allocUnsafe(e),n=this.head,r=1;for(n.data.copy(t),e-=n.data.length;n=n.next;){var s=n.data,o=e>s.length?s.length:e;if(s.copy(t,t.length-e,0,o),0==(e-=o)){o===s.length?(++r,n.next?this.head=n.next:this.head=this.tail=null):(this.head=n,n.data=s.slice(o));break}++r}return this.length-=r,t}},{key:o,value:function(e,n){return s(this,t(t({},n),{},{depth:0,customInspect:!1}))}}]),e}()}var Sh,_h,Ih,xh,kh,Eh,Ch,$h,Oh,Mh,Nh,Th,Ah,Dh,Ph={},jh={exports:{}};function Lh(){if(_h)return Ph;_h=1;var e=(Sh||(Sh=1,function(e,t){var n=L,r=n.Buffer;function i(e,t){for(var n in e)t[n]=e[n]}function s(e,t,n){return r(e,t,n)}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?e.exports=n:(i(n,t),t.Buffer=s),s.prototype=Object.create(r.prototype),i(r,s),s.from=function(e,t,n){if("number"==typeof e)throw new TypeError("Argument must not be a number");return r(e,t,n)},s.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},s.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return r(e)},s.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n.SlowBuffer(e)}}(jh,jh.exports)),jh.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=s,this.end=o,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 s(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 o(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 Ph.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 s=r(t[i]);return s>=0?(s>0&&(e.lastNeed=s-1),s):--i<n||-2===s?0:(s=r(t[i]))>=0?(s>0&&(e.lastNeed=s-2),s):--i<n||-2===s?0:(s=r(t[i]))>=0?(s>0&&(2===s?s=0:e.lastNeed=s-3),s):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},Ph}function Rh(){if(xh)return Ih;xh=1;var e=dh().codes.ERR_STREAM_PREMATURE_CLOSE;function t(){}return Ih=function n(r,i,s){if("function"==typeof i)return n(r,null,i);i||(i={}),s=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)}}}(s||t);var o=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,o||s.call(r)},d=r._readableState&&r._readableState.endEmitted,h=function(){o=!1,d=!0,a||s.call(r)},f=function(e){s.call(r,e)},p=function(){var t;return o&&!d?(r._readableState&&r._readableState.ended||(t=new e),s.call(r,t)):a&&!l?(r._writableState&&r._writableState.ended||(t=new e),s.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)}},Ih}function Fh(){if(Mh)return Oh;var e;Mh=1,Oh=_,_.ReadableState=S,R.EventEmitter;var t,n=function(e,t){return e.listeners(t).length},r=sh(),i=L.Buffer,s=(void 0!==Al?Al:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{}).Uint8Array||function(){},o=c;t=o&&o.debuglog?o.debuglog("stream"):function(){};var a,l,u,d=wh(),h=oh(),f=hh().getHighWaterMark,p=dh().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;bh()(_,r);var b=h.errorOrDestroy,w=["error","close","destroy","pause","resume"];function S(t,n,r){e=e||Uh(),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&&(a||(a=Lh().StringDecoder),this.decoder=new a(t.encoding),this.encoding=t.encoding)}function _(t){if(e=e||Uh(),!(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,o,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,i.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)===i.prototype||(n=function(e){return i.from(e)}(n)),o)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 o||(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=i.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){a||(a=Lh().StringDecoder);var t=new a(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,D(e)}function O(e,t){t.readingMore||(t.readingMore=!0,process.nextTick(M,e,t))}function M(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 N(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 T(e){t("readable nexttick read 0"),e.read(0)}function A(e,n){t("resume",n.reading),n.reading||e.read(0),n.resumeScheduled=!1,e.emit("resume"),D(e),n.flowing&&!n.reading&&e.read(0)}function D(e){var n=e._readableState;for(t("flow",n.flowing);n.flowing&&null!==e.read(););}function P(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 j(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?j(this):C(this),null;if(0===(e=E(e,n))&&n.ended)return 0===n.length&&j(this),null;var i,s=n.needReadable;return t("need readable",s),(0===n.length||n.length-e<n.highWaterMark)&&t("length less than watermark",s=!0),n.ended||n.reading?t("reading or ended",s=!1):s&&(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?P(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&&j(this)),null!==i&&this.emit("data",i),i},_.prototype._read=function(){b(this,new y("_read()"))},_.prototype.pipe=function(e,r){var i=this,s=this._readableState;switch(s.pipesCount){case 0:s.pipes=e;break;case 1:s.pipes=[s.pipes,e];break;default:s.pipes.push(e)}s.pipesCount+=1,t("pipe count=%d opts=%j",s.pipesCount,r);var o=r&&!1===r.end||e===process.stdout||e===process.stderr?p:a;function a(){t("onend"),e.end()}s.endEmitted?process.nextTick(o):i.once("end",o),e.on("unpipe",(function n(r,o){t("onunpipe"),r===i&&o&&!1===o.hasUnpiped&&(o.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,!s.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,D(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===s.pipesCount&&s.pipes===e||s.pipesCount>1&&-1!==U(s.pipes,e))&&!l&&(t("false write response, pause",s.awaitDrain),s.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),s.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 s=0;s<i;s++)r[s].emit("unpipe",this,{hasUnpiped:!1});return this}var o=U(t.pipes,e);return-1===o||(t.pipes.splice(o,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),s=this._readableState;return"data"===e?(s.readableListening=this.listenerCount("readable")>0,!1!==s.flowing&&this.resume()):"readable"===e&&(s.endEmitted||s.readableListening||(s.readableListening=s.needReadable=!0,s.flowing=!1,s.emittedReadable=!1,t("on readable",s.length,s.reading),s.length?C(this):s.reading||process.nextTick(T,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(N,this),n},_.prototype.removeAllListeners=function(e){var t=r.prototype.removeAllListeners.apply(this,arguments);return"readable"!==e&&void 0!==e||process.nextTick(N,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(A,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 s 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(s){t("wrapped data"),r.decoder&&(s=r.decoder.write(s)),r.objectMode&&null==s||(r.objectMode||s&&s.length)&&(n.push(s)||(i=!0,e.pause()))})),e)void 0===this[s]&&"function"==typeof e[s]&&(this[s]=function(t){return function(){return e[t].apply(e,arguments)}}(s));for(var o=0;o<w.length;o++)e.on(w[o],this.emit.bind(this,w[o]));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(Eh)return kh;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}Eh=1;var n=Rh(),r=Symbol("lastResolve"),i=Symbol("lastReject"),s=Symbol("error"),o=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[s];if(null!==t)return Promise.reject(t);if(this[o])return Promise.resolve(u(void 0,!0));if(this[l].destroyed)return new Promise((function(t,n){process.nextTick((function(){e[s]?n(e[s]):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[o]?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 kh=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,s,{value:null,writable:!0}),t(d,o,{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[s]=e)}var n=f[r];null!==n&&(f[a]=null,f[r]=null,f[i]=null,n(u(void 0,!0))),f[o]=!0})),e.on("readable",h.bind(null,f)),f},kh}()),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=P,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($h)return Ch;function e(e,t,n,r,i,s,o){try{var a=e[s](o),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}$h=1;var r=dh().codes.ERR_INVALID_ARG_TYPE;return Ch=function(i,s,o){var a;if(s&&"function"==typeof s.next)a=s;else if(s&&s[Symbol.asyncIterator])a=s[Symbol.asyncIterator]();else{if(!s||!s[Symbol.iterator])throw new r("iterable",["Iterable"],s);a=s[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},o)),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,s){var o=t.apply(n,r);function a(t){e(o,i,s,a,c,"next",t)}function c(t){e(o,i,s,a,c,"throw",t)}a(void 0)}))},d.apply(this,arguments)}return c._read=function(){l||(l=!0,u())},c},Ch}()),u(_,e,t)}),Oh}function Uh(){if(Th)return Nh;Th=1;var e=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t};Nh=o;var t=Fh(),n=Bh();bh()(o,t);for(var r=e(n.prototype),i=0;i<r.length;i++){var s=r[i];o.prototype[s]||(o.prototype[s]=n.prototype[s])}function o(e){if(!(this instanceof o))return new o(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(o.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(o.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(o.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(o.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)}}),Nh}function Bh(){if(Dh)return Ah;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;Dh=1,Ah=_,_.WritableState=S;var n,r={deprecate:Zd?Jd:(Zd=1,Jd=c.deprecate)},i=sh(),s=L.Buffer,o=(void 0!==Al?Al:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{}).Uint8Array||function(){},a=oh(),l=hh().getHighWaterMark,u=dh().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=a.errorOrDestroy;function w(){}function S(n,r,i){t=t||Uh(),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 s=!1===n.decodeStrings;this.decodeStrings=!s,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 s=E(n)||e.destroyed;s||n.corked||n.bufferProcessing||!n.bufferedRequest||k(e,n),r?process.nextTick(x,e,n,s,i):x(e,n,s,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||Uh());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)),i.call(this)}function I(e,t,n,r,i,s,o){t.writelen=r,t.writecb=o,t.writing=!0,t.sync=!0,t.destroyed?t.onwrite(new g("write")):n?e._writev(i,t.onwrite):e._write(i,s,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,s=new Array(i),o=n.corkedRequestsFree;o.entry=r;for(var a=0,c=!0;r;)s[a]=r,r.isBuf||(c=!1),r=r.next,a+=1;s.allBuffers=c,I(t,n,!0,n.length,s,"",o.finish),n.pendingcb++,n.lastBufferedRequest=null,o.next?(n.corkedRequestsFree=o.next,o.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 bh()(_,i),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,a=!1,c=!i.objectMode&&(r=e,s.isBuffer(r)||r instanceof o);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++,a=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)),a},_.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=a.destroy,_.prototype._undestroy=a.undestroy,_.prototype._destroy=function(e,t){t(e)},Ah}const Wh=c,Yh=Bh(),{LEVEL:Gh}=Mu,Hh=ih.exports=function(e={}){Yh.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())}))};Wh.inherits(Hh,Yh),Hh.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[Gh]]){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)},Hh.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)},Hh.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[Gh]])||!this.handleExceptions&&!0===t.exception)},Hh.prototype._nop=function(){};var Vh=ih.exports,zh={exports:{}};const qh=c,{LEVEL:Kh}=Mu,Jh=Vh,Zh=zh.exports=function(e={}){if(Jh.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))};qh.inherits(Zh,Jh),Zh.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[Kh]])&&this.transport.log(e[Kh],e.message,e,this._nop),n(null)},Zh.prototype._writev=function(e,t){for(let t=0;t<e.length;t++)this._accept(e[t])&&(this.transport.log(e[t].chunk[Kh],e[t].chunk.message,e[t].chunk,this._nop),e[t].callback());return t(null)},Zh.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"))},Zh.prototype.close=function(){this.transport.close&&this.transport.close(),this.transport.__winstonError&&(this.transport.removeListener("error",this.transport.__winstonError),this.transport.__winstonError=null)};var Xh=zh.exports;rh.exports=Vh,rh.exports.LegacyTransportStream=Xh;var Qh,ef,tf=rh.exports,nf={exports:{}},rf={exports:{}},sf={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}(sf,sf.exports);var of=sf.exports,af={},cf={exports:{}},lf={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}(lf,lf.exports);var uf=lf.exports,df={};Object.defineProperty(df,"__esModule",{value:!0}),df.fallback=vf,df.wrap=bf;var hf,ff,pf,gf=df.hasQueueMicrotask="function"==typeof queueMicrotask&&queueMicrotask,mf=df.hasSetImmediate="function"==typeof setImmediate&&setImmediate,yf=df.hasNextTick="object"==typeof process&&"function"==typeof process.nextTick;function vf(e){setTimeout(e,0)}function bf(e){return(t,...n)=>e((()=>t(...n)))}function wf(){if(pf)return af;pf=1,Object.defineProperty(af,"__esModule",{value:!0}),af.isAsyncIterable=af.isAsyncGenerator=af.isAsync=void 0;var e,t=(ff||(ff=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 o(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 o(r,n);n(null,r)}))};var n=s(uf),r=s(df),i=wf();function s(e){return e&&e.__esModule?e:{default:e}}function o(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}(cf,cf.exports)),cf.exports),n=(e=t)&&e.__esModule?e:{default:e};function r(e){return"AsyncFunction"===e[Symbol.toStringTag]}return af.default=function(e){if("function"!=typeof e)throw new Error("expected a function");return r(e)?(0,n.default)(e):e},af.isAsync=r,af.isAsyncGenerator=function(e){return"AsyncGenerator"===e[Symbol.toStringTag]},af.isAsyncIterable=function(e){return"function"==typeof e[Symbol.asyncIterator]},af}hf=gf?queueMicrotask:mf?setImmediate:yf?process.nextTick:vf,df.default=bf(hf);var Sf={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}(Sf,Sf.exports);var _f,If=Sf.exports,xf={exports:{}},kf={exports:{}},Ef={exports:{}},Cf={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}(Cf,Cf.exports);var $f=Cf.exports,Of={exports:{}},Mf={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}(Mf,Mf.exports);var Nf=Mf.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,s,o,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):[],s=-1,o=i.length,function e(){var n=i[++s];return"__proto__"===n?e():s<o?{value:t[n],key:n}:null})};var n=i(of),r=i(Nf);function i(e){return e&&e.__esModule?e:{default:e}}e.exports=t.default}(Of,Of.exports);var Tf=Of.exports,Af={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}(Af,Af.exports);var Df=Af.exports,Pf={exports:{}},jf={exports:{}};!function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default={},e.exports=t.default}(jf,jf.exports);var Lf=jf.exports;!function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t,n,i){let s=!1,o=!1,a=!1,c=0,l=0;function u(){c>=t||a||s||(a=!0,e.next().then((({value:e,done:t})=>{if(!o&&!s){if(a=!1,t)return s=!0,void(c<=0&&i(null));c++,n(e,l,d),l++,u()}})).catch(h))}function d(e,t){if(c-=1,!o)return e?h(e):!1===e?(s=!0,void(o=!0)):t===r.default||s&&c<=0?(s=!0,i(null)):void u()}function h(e){o||(a=!1,s=!0,i(e))}u()};var n,r=(n=Lf)&&n.__esModule?n:{default:n};e.exports=t.default}(Pf,Pf.exports);var Rf=Pf.exports;!function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var n=c($f),r=c(Tf),i=c(Df),s=wf(),o=c(Rf),a=c(Lf);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,s.isAsyncGenerator)(t))return(0,o.default)(t,e,c,l);if((0,s.isAsyncIterable)(t))return(0,o.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}(Ef,Ef.exports);var Ff=Ef.exports;!function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var n=s(Ff),r=s(wf()),i=s(If);function s(e){return e&&e.__esModule?e:{default:e}}t.default=(0,i.default)((function(e,t,i,s){return(0,n.default)(t)(e,(0,r.default)(i),s)}),4),e.exports=t.default}(kf,kf.exports);var Uf,Bf,Wf=kf.exports;var Yf,Gf,Hf,Vf,zf,qf,Kf={exports:{}};function Jf(){if(Gf)return Yf;Gf=1,Yf=a;var e=dh().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,s=Uh();function o(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 s=this._readableState;s.reading=!1,(s.needReadable||s.length<s.highWaterMark)&&this._read(s.highWaterMark)}function a(e){if(!(this instanceof a))return new a(e);s.call(this,e),this._transformState={afterTransform:o.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 bh()(a,s),a.prototype.push=function(e,t){return this._transformState.needTransform=!1,s.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){s.prototype._destroy.call(this,e,(function(e){t(e)}))},Yf}!function(e,t){var n=j;"disable"===process.env.READABLE_STREAM&&n?(e.exports=n.Readable,Object.assign(e.exports,n),e.exports.Stream=n):((t=e.exports=Fh()).Stream=n||t,t.Readable=t,t.Writable=Bh(),t.Duplex=Uh(),t.Transform=Jf(),t.PassThrough=function(){if(Vf)return Hf;Vf=1,Hf=t;var e=Jf();function t(n){if(!(this instanceof t))return new t(n);e.call(this,n)}return bh()(t,e),t.prototype._transform=function(e,t,n){n(null,e)},Hf}(),t.finished=Rh(),t.pipeline=function(){if(qf)return zf;var e;qf=1;var t=dh().codes,n=t.ERR_MISSING_ARGS,r=t.ERR_STREAM_DESTROYED;function i(e){if(e)throw e}function s(e){e()}function o(e,t){return e.pipe(t)}return zf=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,s){s=function(e){var t=!1;return function(){t||(t=!0,e.apply(void 0,arguments))}}(s);var o=!1;t.on("close",(function(){o=!0})),void 0===e&&(e=Rh()),e(t,{readable:n,writable:i},(function(e){if(e)return s(e);o=!0,s()}));var a=!1;return function(e){if(!o&&!a)return a=!0,function(e){return e.setHeader&&"function"==typeof e.abort}(t)?t.abort():"function"==typeof t.destroy?t.destroy():void s(e||new r("pipe"))}}(t,i,n>0,(function(e){l||(l=e),e&&d.forEach(s),i||(d.forEach(s),u(l))}))}));return a.reduce(o)},zf}())}(Kf,Kf.exports);var Zf,Xf,Qf,ep,tp=Kf.exports,np={exports:{}};function rp(){if(Xf)return Zf;Xf=1;var e=[],t=[],n=function(){};function r(t){return!~e.indexOf(t)&&(e.push(t),!0)}function i(e){n=e}function s(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 o(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=o,e.set=i,e.use=r,l((function(){return!1}),e)}function d(e){return e.enabled=!0,e.modify=o,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 Zf=function(e){return e.introduce=l,e.enabled=s,e.process=c,e.modify=o,e.write=a,e.nope=u,e.yep=d,e.set=i,e.use=r,e}}var ip,sp,op,ap,cp,lp,up={exports:{}},dp={exports:{}};function hp(){if(lp)return up.exports;lp=1;var e=sp?ip:(sp=1,ip={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(cp)return dp.exports;cp=1;var e=ap?op:(ap=1,op=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=dp.exports=function(r){for(var i=[],s=0,o=r.length;s<o;s++){var a=r[s];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))}},dp.exports}(),n=Object.hasOwnProperty,r=Object.create(null);for(var i in e)n.call(e,i)&&(r[e[i]]=i);var s=up.exports={to:{},get:{}};function o(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 s.get=function(e){var t,n;switch(e.substring(0,3).toLowerCase()){case"hsl":t=s.get.hsl(e),n="hsl";break;case"hwb":t=s.get.hwb(e),n="hwb";break;default:t=s.get.rgb(e),n="rgb"}return t?{model:n,value:t}:null},s.get.rgb=function(t){if(!t)return null;var r,i,s,a=[0,0,0,1];if(r=t.match(/^#([a-f0-9]{6})([a-f0-9]{2})?$/i)){for(s=r[2],r=r[1],i=0;i<3;i++){var c=2*i;a[i]=parseInt(r.slice(c,c+2),16)}s&&(a[3]=parseInt(s,16)/255)}else if(r=t.match(/^#([a-f0-9]{3,4})$/i)){for(s=(r=r[1])[3],i=0;i<3;i++)a[i]=parseInt(r[i]+r[i],16);s&&(a[3]=parseInt(s+s,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]=o(a[i],0,255);return a[3]=o(a[3],0,1),a},s.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,o(parseFloat(t[2]),0,100),o(parseFloat(t[3]),0,100),o(isNaN(n)?1:n,0,1)]}return null},s.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,o(parseFloat(t[2]),0,100),o(parseFloat(t[3]),0,100),o(isNaN(n)?1:n,0,1)]}return null},s.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])):"")},s.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]+")"},s.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]+")"},s.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]+")"},s.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+")"},s.to.keyword=function(e){return r[e.slice(0,3)]},up.exports}var fp,pp,gp,mp,yp,vp,bp,wp,Sp,_p,Ip,xp,kp,Ep,Cp,$p,Op,Mp,Np,Tp,Ap,Dp,Pp,jp,Lp,Rp,Fp,Up={exports:{}};function Bp(){if(gp)return Up.exports;gp=1;var e=pp?fp:(pp=1,fp={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=Up.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 s=r[i].channels,o=r[i].labels;delete r[i].channels,delete r[i].labels,Object.defineProperty(r[i],"channels",{value:s}),Object.defineProperty(r[i],"labels",{value:o})}return r.rgb.hsl=function(e){var t,n,r=e[0]/255,i=e[1]/255,s=e[2]/255,o=Math.min(r,i,s),a=Math.max(r,i,s),c=a-o;return a===o?t=0:r===a?t=(i-s)/c:i===a?t=2+(s-r)/c:s===a&&(t=4+(r-i)/c),(t=Math.min(60*t,360))<0&&(t+=360),n=(o+a)/2,[t,100*(a===o?0:n<=.5?c/(a+o):c/(2-a-o)),100*n]},r.rgb.hsv=function(e){var t,n,r,i,s,o=e[0]/255,a=e[1]/255,c=e[2]/255,l=Math.max(o,a,c),u=l-Math.min(o,a,c),d=function(e){return(l-e)/6/u+.5};return 0===u?i=s=0:(s=u/l,t=d(o),n=d(a),r=d(c),o===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*s,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,s,o,a=1/0;for(var c in e)if(e.hasOwnProperty(c)){var l=(s=n,o=e[c],Math.pow(s[0]-o[0],2)+Math.pow(s[1]-o[1],2)+Math.pow(s[2]-o[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],s=t[2];return i/=100,s/=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-(s=s>.008856?Math.pow(s,1/3):7.787*s+16/116))]},r.hsl.rgb=function(e){var t,n,r,i,s,o=e[0]/360,a=e[1]/100,c=e[2]/100;if(0===a)return[s=255*c,s,s];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=o+1/3*-(l-1))<0&&r++,r>1&&r--,s=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*s;return i},r.hsl.hsv=function(e){var t=e[0],n=e[1]/100,r=e[2]/100,i=n,s=Math.max(r,.01);return n*=(r*=2)<=1?r:2-r,i*=s<=1?s:2-s,[t,100*(0===r?2*i/(s+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,s=t-Math.floor(t),o=255*r*(1-n),a=255*r*(1-n*s),c=255*r*(1-n*(1-s));switch(r*=255,i){case 0:return[r,c,o];case 1:return[a,r,o];case 2:return[o,r,c];case 3:return[o,a,r];case 4:return[c,o,r];case 5:return[r,o,a]}},r.hsv.hsl=function(e){var t,n,r,i=e[0],s=e[1]/100,o=e[2]/100,a=Math.max(o,.01);return r=(2-s)*o,n=s*a,[i,100*(n=(n/=(t=(2-s)*a)<=1?t:2-t)||0),100*(r/=2)]},r.hwb.rgb=function(e){var t,n,r,i,s,o,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:s=n,o=i,a=l;break;case 1:s=i,o=n,a=l;break;case 2:s=l,o=n,a=i;break;case 3:s=l,o=i,a=n;break;case 4:s=i,o=l,a=n;break;case 5:s=n,o=l,a=i}return[255*s,255*o,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,s=e[1]/100,o=e[2]/100;return n=-.9689*i+1.8758*s+.0415*o,r=.0557*i+-.204*s+1.057*o,t=(t=3.2406*i+-1.5372*s+-.4986*o)>.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 s=Math.pow(n,3),o=Math.pow(t,3),a=Math.pow(r,3);return n=s>.008856?s:(n-16/116)/7.787,t=o>.008856?o:(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],s=1 in arguments?arguments[1]:r.rgb.hsv(e)[2];if(0===(s=Math.round(s/50)))return 30;var o=30+(Math.round(i/255)<<2|Math.round(n/255)<<1|Math.round(t/255));return 2===s&&(o+=60),o},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,s=Math.max(Math.max(n,r),i),o=Math.min(Math.min(n,r),i),a=s-o;return t=a<=0?0:s===n?(r-i)/a%6:s===r?2+(i-n)/a:4+(n-r)/a+4,t/=6,[360*(t%=1),100*a,100*(a<1?o/(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,s=[0,0,0],o=t%1*6,a=o%1,c=1-a;switch(Math.floor(o)){case 0:s[0]=1,s[1]=a,s[2]=0;break;case 1:s[0]=c,s[1]=1,s[2]=0;break;case 2:s[0]=0,s[1]=1,s[2]=a;break;case 3:s[0]=0,s[1]=c,s[2]=1;break;case 4:s[0]=a,s[1]=0,s[2]=1;break;default:s[0]=1,s[1]=0,s[2]=c}return i=(1-n)*r,[255*(n*s[0]+i),255*(n*s[1]+i),255*(n*s[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]},Up.exports}function Wp(){if(bp)return vp;bp=1;var e=Bp(),t=function(){if(yp)return mp;yp=1;var e=Bp();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(),s=Object.keys(e[i]),o=s.length,a=0;a<o;a++){var c=s[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],s=e[r[t].parent][t],o=r[t].parent;r[o].parent;)i.unshift(r[o].parent),s=n(e[r[o].parent][o],s),o=r[o].parent;return s.conversion=i,s}return mp=function(e){for(var n=t(e),i={},s=Object.keys(n),o=s.length,a=0;a<o;a++){var c=s[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)}))})),vp=n}function Yp(){if(kp)return xp;kp=1;var e=function(){if(Sp)return wp;Sp=1;var e=hp(),t=Wp(),n=[].slice,r=["keyword","gray","hex"],i={};Object.keys(t).forEach((function(e){i[n.call(t[e].labels).sort().join("")]=e}));var s={};function o(a,c){if(!(this instanceof o))return new o(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 o)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(s[this.model])for(d=t[this.model].channels,u=0;u<d;u++){var v=s[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){(s[e]||(s[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 o.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 o(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 o(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 o(e):t[this.model].keyword(this.color)},hex:function(t){return arguments.length?new o(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 o.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,s=2*i-1,a=n.alpha()-r.alpha(),c=((s*a==-1?s:(s+a)/(1+s*a))+1)/2,l=1-c;return o.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;o.prototype[e]=function(){if(this.model===e)return new o(this);if(arguments.length)return new o(arguments,e);var n,r="number"==typeof arguments[i]?i:this.valpha;return new o((n=t[this.model][e].raw(this.color),Array.isArray(n)?n:[n]).concat(r),e)},o[e]=function(t){return"number"==typeof t&&(t=l(n.call(arguments),i)),new o(t,e)}}})),wp=o}(),t=(Ip||(Ip=1,_p=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}),_p);return xp=function(n,r){var i=n.split(r||":"),s=t(i[0]);if(!i.length)return s;for(var o=0,a=i.length-1;o<a;o++)s=e(s).mix(e(t(i[o+1]))).saturate(1).hex();return s},xp}function Gp(){if(Pp)return Dp;Pp=1;var e=function(){if(Ap)return Tp;Ap=1;var e=(Np||(Np=1,Mp=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}),Mp);return Tp=function(t){return function(n){try{return e(n,t())}catch(e){}return!1}}}();return Dp=e((function(){return process.env.DEBUG||process.env.DIAGNOSTICS}))}"production"===process.env.NODE_ENV?np.exports=function(){if(ep)return Qf;ep=1;var e=rp()((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 Qf=e}():np.exports=function(){if(Fp)return Rp;Fp=1;var e=rp(),t=T.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(Op)return $p;Op=1;var e=Yp(),t=function(){if(Cp)return Ep;function e(t,n){return n?new e(t).style(n):this instanceof e?void(this.text=t):new e(t)}return Cp=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,s=n/255*5;return this.ansi(r,i,s)},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()},Ep=e}();return $p=function(n,r){var i=r.namespace,s=!1!==r.colors?t(i+":",e(i)):i+":";return n[0]=s+" "+n[0],n}}()),n.use(Gp()),n.set(Lp?jp:(Lp=1,jp=function(e,t){try{Function.prototype.apply.call(console.log,console,t)}catch(e){}})),Rp=n}();var Hp,Vp,zp,qp,Kp,Jp,Zp=np.exports;function Xp(){if(qp)return zp;qp=1;const e=M,t=k,n=(Bf||(Bf=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t){return(0,r.default)(s.default,e,t)};var n=(_f||(_f=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var n=s(of),r=s(wf()),i=s(If);function s(e){return e&&e.__esModule?e:{default:e}}t.default=(0,i.default)(((e,t,i)=>{var s=(0,n.default)(t)?[]:{};e(t,((e,t,n)=>{(0,r.default)(e)(((e,...r)=>{r.length<2&&([r]=r),s[t]=r,n(e)}))}),(e=>i(e,s)))}),3),e.exports=t.default}(rf,rf.exports)),rf.exports),r=o(n),i=(Uf||(Uf=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var n=i(Wf),r=i(If);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}(xf,xf.exports)),xf.exports),s=o(i);function o(e){return e&&e.__esModule?e:{default:e}}e.exports=t.default}(nf,nf.exports)),nf.exports),r=F,{MESSAGE:i}=Mu,{Stream:s,PassThrough:o}=tp,a=tf,c=Zp("winston:file"),l=A,u=function(){if(Vp)return Hp;Vp=1;const e=M,{StringDecoder:t}=U,{Stream:n}=tp;function r(){}return Hp=(i,s)=>{const o=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 s?s(t):c.emit("error",t),void c.destroy();!function t(){if(!c.destroyed)return e.read(n,o,0,o.length,u,((e,n)=>{if(e)return s?s(e):c.emit("error",e),void c.destroy();if(!n)return l&&((null==i.start||d>i.start)&&(s?s(null,l):c.emit("line",l)),d++,l=""),setTimeout(t,1e3);let r=a.write(o.slice(0,n));s||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)&&(s?s(null,r[f]):c.emit("line",r[f])),d++;return l=r[h],u+=n,t()}));e.close(n,r)}()})),s?c.destroy:c},Hp}();return zp=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 o,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 s=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 s?t():(this._drain=!0,this._stream.once("drain",(()=>{this._drain=!1,t()}))),c("written",s,this._drain),this.finishIfEnding(),s}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 s="",o=[],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&&o.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&&o.length>=n.rows&&o.shift(),o.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,o)})),c.on("data",(e=>{const t=(e=(s+e).split(/\n+/)).length-1;let r=0;for(;r<t;r++)(!n.start||a>=n.start)&&l(e[r]),a++;s=e[t]})),c.on("close",(()=>{s&&l(s,!0),"desc"===n.order&&(o=o.reverse()),r&&r(null,o)}))}stream(e={}){const n=t.join(this.dirname,this.filename),r=new s,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 o,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),s=[];this.zippedArchive&&s.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)),s.push(function(e){this.tailable?this._checkMaxFilesTailable(r,i,e):(this._created+=1,this._checkMaxFilesIncrementing(r,i,e))}.bind(this)),n(s,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 s=this._created-this.maxFiles,o=`${r}${0!==s?s:""}${n}${this.zippedArchive?".gz":""}`,a=t.join(this.dirname,o);e.unlink(a,i)}_checkMaxFilesTailable(r,i,s){const o=[];if(!this.maxFiles)return;const a=this.zippedArchive?".gz":"";for(let n=this.maxFiles-1;n>1;n--)o.push(function(n,s){let o=`${i}${n-1}${r}${a}`;const c=t.join(this.dirname,o);e.exists(c,(l=>{if(!l)return s(null);o=`${i}${n}${r}${a}`,e.rename(c,t.join(this.dirname,o),s)}))}.bind(this,n));n(o,(()=>{e.rename(t.join(this.dirname,`${i}${r}${a}`),t.join(this.dirname,`${i}1${r}${a}`),s)}))}_compressFile(t,n,i){e.access(t,e.F_OK,(s=>{if(s)return i();var o=r.createGzip(),a=e.createReadStream(t),c=e.createWriteStream(n);c.on("finish",(()=>{e.unlink(t,i)})),a.pipe(o).pipe(c)}))}_createLogDirIfNotExist(t){e.existsSync(t)||e.mkdirSync(t,{recursive:!0})}},zp}const Qp=e=>null!==e&&"object"==typeof e&&"function"==typeof e.pipe;Qp.writable=e=>Qp(e)&&!1!==e.writable&&"function"==typeof e._write&&"object"==typeof e._writableState,Qp.readable=e=>Qp(e)&&!1!==e.readable&&"function"==typeof e._read&&"object"==typeof e._readableState,Qp.duplex=e=>Qp.writable(e)&&Qp.readable(e),Qp.transform=e=>Qp.duplex(e)&&"function"==typeof e._transform;var eg,tg,ng=Qp;!function(e){Object.defineProperty(e,"Console",{configurable:!0,enumerable:!0,get:()=>function(){if(ef)return Qh;ef=1;const e=A,{LEVEL:t,MESSAGE:n}=Mu,r=tf;return Qh=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:()=>Xp()}),Object.defineProperty(e,"Http",{configurable:!0,enumerable:!0,get:()=>function(){if(Jp)return Kp;Jp=1;const e=B,t=W,{Stream:n}=tp,r=tf,{configure:i}=od();return Kp=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 s="";const o=this._request(e,i,r);return t.destroy=()=>o.destroy(),o.on("data",(e=>{const n=(e=(s+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)}s=e[n]})),o.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,s,o){const a=Object.assign({},this.headers);s&&s.bearer&&(a.Authorization=`Bearer ${s.bearer}`);const c=(this.ssl?t:e).request({...this.options,method:"POST",host:this.host,port:this.port,path:`/${o.replace(/^\//,"")}`,headers:a,auth:s&&s.username&&s.password?`${s.username}:${s.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"))}},Kp}()}),Object.defineProperty(e,"Stream",{configurable:!0,enumerable:!0,get:()=>function(){if(tg)return eg;tg=1;const e=ng,{MESSAGE:t}=Mu,n=A,r=tf;return eg=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()}}}()})}(nh);var rg={};const ig=Ql,{configs:sg}=Mu;rg.cli=ig.levels(sg.cli),rg.npm=ig.levels(sg.npm),rg.syslog=ig.levels(sg.syslog),rg.addColors=ig.levels;var og={exports:{}},ag={exports:{}};!function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var n=l(of),r=l(Lf),i=l(Wf),s=l($f),o=l(Df),a=l(wf()),c=l(If);function l(e){return e&&e.__esModule?e:{default:e}}function u(e,t,n){n=(0,s.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,o.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}(ag,ag.exports);var cg=ag.exports,lg={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}(lg,lg.exports);var ug=lg.exports;!function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var n=o(cg),r=o(ug),i=o(wf()),s=o(If);function o(e){return e&&e.__esModule?e:{default:e}}t.default=(0,s.default)((function(e,t,s){return(0,n.default)(e,(0,r.default)((0,i.default)(t)),s)}),3),e.exports=t.default}(og,og.exports);var dg=og.exports,hg=Object.prototype.toString,fg=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=hg.call(e).slice(8,-1);return(t="Function"===n?t.substring(t.indexOf("(")+1,t.indexOf(")")):n)||"anonymous"}(e),r},pg={};!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 s=r.stack;return Error.prepareStackTrace=i,Error.stackTraceLimit=n,s},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,s=null,o=null,a=null,c="native"===n[5];if(n[1]){var l=(s=n[1]).lastIndexOf(".");if("."==s[l-1]&&l--,l>0){r=s.substr(0,l),i=s.substr(l+1);var u=r.indexOf(".Module");u>0&&(s=s.substr(u+1),r=r.substr(0,u))}o=null}i&&(o=r,a=i),"<anonymous>"===i&&(a=null,s=null);var d={fileName:n[2]||null,lineNumber:parseInt(n[3],10)||null,functionName:s,typeName:o,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)}}(pg);const{Writable:gg}=tp,mg=A,yg=dg,vg=Zp("winston:exception"),bg=fg,wg=pg,Sg=class extends gg{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 _g=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:mg.loadavg(),uptime:mg.uptime()}}getTrace(e){return(e?wg.parse(e):wg.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 Sg(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 s(){vg("doExit",i),vg("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(s);yg(n,((e,t)=>{const n=bg(t),r=e.transport||e;function i(e){return()=>{vg(e),n()}}r._ending=!0,r.once("finish",i("finished")),r.once("error",i("error"))}),(()=>i&&s())),this.logger.log(t),i&&(r=setTimeout(s,3e3))}_getExceptionHandlers(){return this.logger.transports.filter((e=>(e.transport||e).handleExceptions))}};const{Writable:Ig}=tp,xg=A,kg=dg,Eg=Zp("winston:rejection"),Cg=fg,$g=pg,Og=class extends Ig{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 Mg,Ng,Tg,Ag,Dg=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:xg.loadavg(),uptime:xg.uptime()}}getTrace(e){return(e?$g.parse(e):$g.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 Og(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 s(){Eg("doExit",i),Eg("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(s);kg(n,((e,t)=>{const n=Cg(t),r=e.transport||e;function i(e){return()=>{Eg(e),n()}}r._ending=!0,r.once("finish",i("finished")),r.once("error",i("error"))}),(()=>i&&s())),this.logger.log(t),i&&(r=setTimeout(s,3e3))}_getRejectionHandlers(){return this.logger.transports.filter((e=>(e.transport||e).handleRejections))}};function Pg(){if(Ag)return Tg;Ag=1;const{Stream:e,Transform:t}=tp,n=dg,{LEVEL:r,SPLAT:i}=Mu,s=ng,o=_g,a=Dg,c=Xh,l=(Ng||(Ng=1,Mg=class{constructor(e){const t=Pg();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)}}),Mg),{warn:u}=Kd,d=rg,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:s=!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||ad()(),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 o(this),this.rejections=new a(this),this.profilers={},this.exitOnError=s,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[s]=n;if("object"==typeof s&&null!==s&&!(t&&t.match&&t.match(h))){const o=Object.assign({},this.defaultMeta,s,{[r]:e,[i]:n,level:e,message:t});return s.message&&(o.message=`${o.message} ${s.message}`),s.stack&&(o.stack=s.stack),s.cause&&(o.cause=s.cause),this.write(o),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=!s(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(!s(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)}}),Tg=f}const{LEVEL:jg}=Mu,Lg=rg,Rg=Pg(),Fg=Zp("winston:create-logger");var Ug=function(e={}){e.levels=e.levels||Lg.npm.levels;class t extends Rg{constructor(e){super(e)}}const n=new t(e);return Object.keys(e.levels).forEach((function(e){Fg('Define prototype method for "%s"',e),"log"!==e?(t.prototype[e]=function(...t){const r=this||n;if(1===t.length){const[i]=t,s=i&&i.message&&i||{message:i};return s.level=s[jg]=e,r._addDefaultMeta(s),r.write(s),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 Bg=Ug;var Wg=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=Bg(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=Ql,{warn:n}=Kd;e.version="3.17.0",e.transports=nh,e.config=rg,e.addColors=t.levels,e.format=t.format,e.createLogger=Ug,e.Logger=Pg(),e.ExceptionHandler=_g,e.RejectionHandler=Dg,e.Container=Wg,e.Transport=tf,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"])}(Xl);var Yg=Dl(Xl),Gg={exports:{}};!function(e,t){var n=d;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=o(e,t))}(t=Gg.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 s=["buffer","hex","binary","base64"];function o(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===s.indexOf(n.encoding)&&"passthrough"!==n.algorithm)throw new Error('Encoding "'+n.encoding+'" not supported. supported values: '+s.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,s=Object.prototype.toString.call(t),o=/\[object (.*)\]/i.exec(s);if(o=(o=o?o[1]:"unknown:["+s+"]").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"===o||"function"===o||"asyncfunction"===o){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["_"+o]){if(e.ignoreUnknown)return r("["+o+"]");throw new Error('Unknown object type "'+o+'"')}this["_"+o](t)},_array:function(t,i){i=void 0!==i?i:!1!==e.unorderedArrays;var s=this;if(r("array:"+t.length+":"),!i||t.length<=1)return t.forEach((function(e){return s.dispatch(e)}));var o=[],a=t.map((function(t){var r=new l,i=n.slice();return c(e,r,i).dispatch(t),o=o.concat(i.slice(n.length)),r.read().toString()}));return n=n.concat(o),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=o(e,t),n).dispatch(e)}}(0,Gg.exports);var Hg,Vg,zg,qg={exports:{}};function Kg(){return Hg||(Hg=1,(e=qg).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 s(e){return null!=e&&"[object Object]"===Object.prototype.toString.call(e)}function o(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(o(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)o(t,n)&&(e[n]=t[n]);return o(t,"toString")&&(e.toString=t.toString),o(t,"valueOf")&&(e.valueOf=t.valueOf),e}function f(e,t,n,r){return Pt(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,s=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),s>0)for(n=0;n<s;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,s,a,c=[],l=arguments.length;for(s=0;s<l;s++){if(i="","object"==typeof arguments[s]){for(a in i+="\n["+s+"] ",arguments[0])o(arguments[0],a)&&(i+=a+": "+arguments[0][a]+", ");i=i.slice(0,-2)}else i=arguments[s];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)o(t,n)&&(s(e[n])&&s(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)o(e,n)&&!o(t,n)&&s(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)o(e,t)&&n.push(t);return n};function M(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 N=/(\[[^\[]*\])|(\\)?([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,T=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,A={},D={};function P(e,t,n,r){var i=r;"string"==typeof r&&(i=function(){return this[r]()}),e&&(D[e]=i),t&&(D[t[0]]=function(){return M(i.apply(this,arguments),t[1],t[2])}),n&&(D[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 L(e,t){return e.isValid()?(t=R(t,e.localeData()),A[t]=A[t]||function(e){var t,n,r=e.match(N);for(t=0,n=r.length;t<n;t++)D[r[t]]?r[t]=D[r[t]]:r[t]=j(r[t]);return function(t){var i,s="";for(i=0;i<n;i++)s+=C(r[i])?r[i].call(t,e):r[i];return s}}(t),A[t](e)):e.localeData().invalidDate()}function R(e,t){var n=5;function r(e){return t.longDateFormat(e)||e}for(T.lastIndex=0;n>=0&&T.test(e);)e=e.replace(T,r),T.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)o(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 Y,G=/\d/,H=/\d\d/,V=/\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,se=/[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,oe=/^[1-9]\d?/,ae=/^([1-9]\d|\d)/;function ce(e,t,n){Y[e]=C(t)?t:function(e){return e&&n?n:t}}function le(e,t){return o(Y,e)?Y[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}Y={};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&&o(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}P("Y",0,0,(function(){var e=this.year();return e<=9999?M(e,4):"+"+e})),P(0,["YY",2],0,(function(){return this.year()%100})),P(0,["YYYY",4],0,"year"),P(0,["YYYYY",5],0,"year"),P(0,["YYYYYY",6,!0],0,"year"),ce("Y",ne),ce("YY",K,H),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=Me("FullYear",!0);function Me(e,t){return function(n){return null!=n?(Te(this,e,n),r.updateOffset(this,t),this):Ne(this,e)}}function Ne(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 Te(e,t,n){var r,i,s,o,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}s=n,o=e.month(),a=29!==(a=e.date())||1!==o||ye(s)?a:28,i?r.setUTCFullYear(s,o,a):r.setFullYear(s,o,a)}}function Ae(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},P("M",["MM",2],"Mo",(function(){return this.month()+1})),P("MMM",0,0,(function(e){return this.localeData().monthsShort(this,e)})),P("MMMM",0,0,(function(e){return this.localeData().months(this,e)})),ce("M",K,oe),ce("MM",K,H),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 De="January_February_March_April_May_June_July_August_September_October_November_December".split("_"),Pe="Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),je=/D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/,Le=se,Re=se;function Fe(e,t,n){var r,i,s,o=e.toLocaleLowerCase();if(!this._monthsParse)for(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[],r=0;r<12;++r)s=f([2e3,r]),this._shortMonthsParse[r]=this.monthsShort(s,"").toLocaleLowerCase(),this._longMonthsParse[r]=this.months(s,"").toLocaleLowerCase();return n?"MMM"===t?-1!==(i=$e.call(this._shortMonthsParse,o))?i:null:-1!==(i=$e.call(this._longMonthsParse,o))?i:null:"MMM"===t?-1!==(i=$e.call(this._shortMonthsParse,o))||-1!==(i=$e.call(this._longMonthsParse,o))?i:null:-1!==(i=$e.call(this._longMonthsParse,o))||-1!==(i=$e.call(this._shortMonthsParse,o))?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,Ae(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):Ne(this,"Month")}function We(){function e(e,t){return t.length-e.length}var t,n,r,i,s=[],o=[],a=[];for(t=0;t<12;t++)n=f([2e3,t]),r=ue(this.monthsShort(n,"")),i=ue(this.months(n,"")),s.push(r),o.push(i),a.push(i),a.push(r);s.sort(e),o.sort(e),a.sort(e),this._monthsRegex=new RegExp("^("+a.join("|")+")","i"),this._monthsShortRegex=this._monthsRegex,this._monthsStrictRegex=new RegExp("^("+o.join("|")+")","i"),this._monthsShortStrictRegex=new RegExp("^("+s.join("|")+")","i")}function Ye(e,t,n,r,i,s,o){var a;return e<100&&e>=0?(a=new Date(e+400,t,n,r,i,s,o),isFinite(a.getFullYear())&&a.setFullYear(e)):a=new Date(e,t,n,r,i,s,o),a}function Ge(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 He(e,t,n){var r=7+t-n;return-(7+Ge(e,0,r).getUTCDay()-t)%7+r-1}function Ve(e,t,n,r,i){var s,o,a=1+7*(t-1)+(7+n-r)%7+He(e,r,i);return a<=0?o=Ce(s=e-1)+a:a>Ce(e)?(s=e+1,o=a-Ce(e)):(s=e,o=a),{year:s,dayOfYear:o}}function ze(e,t,n){var r,i,s=He(e.year(),t,n),o=Math.floor((e.dayOfYear()-s-1)/7)+1;return o<1?r=o+qe(i=e.year()-1,t,n):o>qe(e.year(),t,n)?(r=o-qe(e.year(),t,n),i=e.year()+1):(i=e.year(),r=o),{week:r,year:i}}function qe(e,t,n){var r=He(e,t,n),i=He(e+1,t,n);return(Ce(e)-r+i)/7}P("w",["ww",2],"wo","week"),P("W",["WW",2],"Wo","isoWeek"),ce("w",K,oe),ce("ww",K,H),ce("W",K,oe),ce("WW",K,H),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))}P("d",0,"do","day"),P("dd",0,0,(function(e){return this.localeData().weekdaysMin(this,e)})),P("ddd",0,0,(function(e){return this.localeData().weekdaysShort(this,e)})),P("dddd",0,0,(function(e){return this.localeData().weekdays(this,e)})),P("e",0,0,"weekday"),P("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=se,et=se,tt=se;function nt(e,t,n){var r,i,s,o=e.toLocaleLowerCase();if(!this._weekdaysParse)for(this._weekdaysParse=[],this._shortWeekdaysParse=[],this._minWeekdaysParse=[],r=0;r<7;++r)s=f([2e3,1]).day(r),this._minWeekdaysParse[r]=this.weekdaysMin(s,"").toLocaleLowerCase(),this._shortWeekdaysParse[r]=this.weekdaysShort(s,"").toLocaleLowerCase(),this._weekdaysParse[r]=this.weekdays(s,"").toLocaleLowerCase();return n?"dddd"===t?-1!==(i=$e.call(this._weekdaysParse,o))?i:null:"ddd"===t?-1!==(i=$e.call(this._shortWeekdaysParse,o))?i:null:-1!==(i=$e.call(this._minWeekdaysParse,o))?i:null:"dddd"===t?-1!==(i=$e.call(this._weekdaysParse,o))||-1!==(i=$e.call(this._shortWeekdaysParse,o))||-1!==(i=$e.call(this._minWeekdaysParse,o))?i:null:"ddd"===t?-1!==(i=$e.call(this._shortWeekdaysParse,o))||-1!==(i=$e.call(this._weekdaysParse,o))||-1!==(i=$e.call(this._minWeekdaysParse,o))?i:null:-1!==(i=$e.call(this._minWeekdaysParse,o))||-1!==(i=$e.call(this._weekdaysParse,o))||-1!==(i=$e.call(this._shortWeekdaysParse,o))?i:null}function rt(){function e(e,t){return t.length-e.length}var t,n,r,i,s,o=[],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,"")),s=ue(this.weekdays(n,"")),o.push(r),a.push(i),c.push(s),l.push(r),l.push(i),l.push(s);o.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("^("+o.join("|")+")","i")}function it(){return this.hours()%12||12}function st(e,t){P(e,0,0,(function(){return this.localeData().meridiem(this.hours(),this.minutes(),t)}))}function ot(e,t){return t._meridiemParse}P("H",["HH",2],0,"hour"),P("h",["hh",2],0,it),P("k",["kk",2],0,(function(){return this.hours()||24})),P("hmm",0,0,(function(){return""+it.apply(this)+M(this.minutes(),2)})),P("hmmss",0,0,(function(){return""+it.apply(this)+M(this.minutes(),2)+M(this.seconds(),2)})),P("Hmm",0,0,(function(){return""+this.hours()+M(this.minutes(),2)})),P("Hmmss",0,0,(function(){return""+this.hours()+M(this.minutes(),2)+M(this.seconds(),2)})),st("a",!0),st("A",!1),ce("a",ot),ce("A",ot),ce("H",K,ae),ce("h",K,oe),ce("k",K,oe),ce("HH",K,H),ce("hh",K,H),ce("kk",K,H),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=Me("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:De,monthsShort:Pe,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,s=0;s<e.length;){for(t=(i=ft(e[s]).split("-")).length,n=(n=ft(e[s+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--}s++}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]>Ae(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,s,o,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])){s=(c[2]||" ")+It[t][0];break}if(null==s)return void(e._isValid=!1)}if(!r&&null!=s)return void(e._isValid=!1);if(c[4]){if(!St.exec(c[4]))return void(e._isValid=!1);o="Z"}e._f=i+(s||"")+(o||""),At(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,s){var o=[$t(e),Pe.indexOf(t),parseInt(n,10),parseInt(r,10),parseInt(i,10)];return s&&o.push(parseInt(s,10)),o}(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=Ge.apply(null,e._a),e._d.setUTCMinutes(e._d.getUTCMinutes()-e._tzm),p(e).rfc2822=!0}else e._isValid=!1}function Mt(e,t,n){return null!=e?e:null!=t?t:n}function Nt(e){var t=new Date(r.now());return e._useUTC?[t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate()]:[t.getFullYear(),t.getMonth(),t.getDate()]}function Tt(e){var t,n,r,i,s,o=[];if(!e._d){for(r=Nt(e),e._w&&null==e._a[we]&&null==e._a[be]&&function(e){var t,n,r,i,s,o,a,c,l;null!=(t=e._w).GG||null!=t.W||null!=t.E?(s=1,o=4,n=Mt(t.GG,e._a[ve],ze(jt(),1,4).year),r=Mt(t.W,1),((i=Mt(t.E,1))<1||i>7)&&(c=!0)):(s=e._locale._week.dow,o=e._locale._week.doy,l=ze(jt(),s,o),n=Mt(t.gg,e._a[ve],l.year),r=Mt(t.w,l.week),null!=t.d?((i=t.d)<0||i>6)&&(c=!0):null!=t.e?(i=t.e+s,(t.e<0||t.e>6)&&(c=!0)):i=s),r<1||r>qe(n,s,o)?p(e)._overflowWeeks=!0:null!=c?p(e)._overflowWeekday=!0:(a=Ve(n,r,i,s,o),e._a[ve]=a.year,e._dayOfYear=a.dayOfYear)}(e),null!=e._dayOfYear&&(s=Mt(e._a[ve],r[ve]),(e._dayOfYear>Ce(s)||0===e._dayOfYear)&&(p(e)._overflowDayOfYear=!0),n=Ge(s,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]=o[t]=r[t];for(;t<7;t++)e._a[t]=o[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?Ge:Ye).apply(null,o),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 At(e){if(e._f!==r.ISO_8601)if(e._f!==r.RFC_2822){e._a=[],p(e).empty=!0;var t,n,i,s,o,a,c,l=""+e._i,u=l.length,d=0;for(c=(i=R(e._f,e._locale).match(N)||[]).length,t=0;t<c;t++)s=i[t],(n=(l.match(le(s,e))||[])[0])&&((o=l.substr(0,l.indexOf(n))).length>0&&p(e).unusedInput.push(o),l=l.slice(l.indexOf(n)+n.length),d+=n.length),D[s]?(n?p(e).empty=!1:p(e).unusedTokens.push(s),me(s,n,e)):e._strict&&!n&&p(e).unusedTokens.push(s);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])),Tt(e),vt(e)}else Ot(e);else Ct(e)}function Dt(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,s,o,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++)s=0,o=!1,t=b({},e),null!=e._useUTC&&(t._useUTC=e._useUTC),t._f=e._f[i],At(t),g(t)&&(o=!0),s+=p(t).charsLeftOver,s+=10*p(t).unusedTokens.length,p(t).score=s,a?s<r&&(r=s,n=t):(null==r||s<r||o)&&(r=s,n=t,o&&(a=!0));h(e,n||t)}(e):n?At(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)})),Tt(e)):s(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)})),Tt(e)}}(e):l(t)?e._d=new Date(t):r.createFromInputFallback(e)}(e),g(e)||(e._d=null),e))}function Pt(e,t,n,r,o){var c={};return!0!==t&&!1!==t||(r=t,t=void 0),!0!==n&&!1!==n||(r=n,n=void 0),(s(e)&&a(e)||i(e)&&0===e.length)&&(e=void 0),c._isAMomentObject=!0,c._useUTC=c._isUTC=o,c._l=n,c._i=e,c._f=t,c._strict=r,function(e){var t=new w(vt(Dt(e)));return t._nextDay&&(t.add(1,"d"),t._nextDay=void 0),t}(c)}function jt(e,t,n,r){return Pt(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 Lt=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()})),Rt=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(o(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,s=t.week||t.isoWeek||0,o=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=+o+7*s,this._months=+i+3*r+12*n,this._data={},this._locale=yt(),this._bubble()}function Yt(e){return e instanceof Wt}function Gt(e){return e<0?-1*Math.round(-1*e):Math.round(e)}function Ht(e,t){P(e,0,0,(function(){var e=this.utcOffset(),n="+";return e<0&&(e=-e,n="-"),n+M(~~(e/60),2)+t+M(~~e%60,2)}))}Ht("Z",":"),Ht("ZZ",""),ce("Z",ie),ce("ZZ",ie),pe(["Z","ZZ"],(function(e,t,n){n._useUTC=!0,n._tzm=zt(ie,e)}));var Vt=/([\+\-]|\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(Vt)||["-",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,s=e,a=null;return Yt(e)?s={ms:e._milliseconds,d:e._days,M:e._months}:l(e)||!isNaN(+e)?(s={},t?s[t]=+e:s.milliseconds=+e):(a=Zt.exec(e))?(n="-"===a[1]?-1:1,s={y:0,d:he(a[we])*n,h:he(a[Se])*n,m:he(a[_e])*n,s:he(a[Ie])*n,ms:he(Gt(1e3*a[xe]))*n}):(a=Xt.exec(e))?(n="-"===a[1]?-1:1,s={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==s?s={}:"object"==typeof s&&("from"in s||"to"in s)&&(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(s.from),jt(s.to)),(s={}).ms=i.milliseconds,s.M=i.months),r=new Wt(s),Yt(e)&&o(e,"_locale")&&(r._locale=e._locale),Yt(e)&&o(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 s=t._milliseconds,o=Gt(t._days),a=Gt(t._months);e.isValid()&&(i=null==i||i,a&&Ue(e,Ne(e,"Month")+a*n),o&&Te(e,"Date",Ne(e,"Date")+o*n),s&&e._d.setTime(e._d.valueOf()+s*n),i&&r.updateOffset(e,o||a))}Qt.fn=Wt.prototype,Qt.invalid=function(){return Qt(NaN)};var sn=nn(1,"add"),on=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=s(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||o(e,n);return r&&i}(e)||null==e}function ln(e){var t,n=s(e)&&!a(e),r=!1,i=["sameDay","nextDay","lastDay","nextWeek","lastWeek","sameElse"];for(t=0;t<i.length;t+=1)r=r||o(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,s=[],o=[],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),o.push(n),s.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("^("+o.join("|")+")","i"),this._erasAbbrRegex=new RegExp("^("+s.join("|")+")","i"),this._erasNarrowRegex=new RegExp("^("+a.join("|")+")","i")}function In(e,t){P(0,[e,e.length],0,t)}function xn(e,t,n,r,i){var s;return null==e?ze(this,r,i).year:(t>(s=qe(e,r,i))&&(t=s),kn.call(this,e,t,n,r,i))}function kn(e,t,n,r,i){var s=Ve(e,t,n,r,i),o=Ge(s.year,0,s.dayOfYear);return this.year(o.getUTCFullYear()),this.month(o.getUTCMonth()),this.date(o.getUTCDate()),this}P("N",0,0,"eraAbbr"),P("NN",0,0,"eraAbbr"),P("NNN",0,0,"eraAbbr"),P("NNNN",0,0,"eraName"),P("NNNNN",0,0,"eraNarrow"),P("y",["y",1],"yo","eraYear"),P("y",["yy",2],0,"eraYear"),P("y",["yyy",3],0,"eraYear"),P("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)})),P(0,["gg",2],0,(function(){return this.weekYear()%100})),P(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,H),ce("gg",K,H),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)})),P("Q",0,"Qo","quarter"),ce("Q",G),pe("Q",(function(e,t){t[be]=3*(he(e)-1)})),P("D",["DD",2],"Do","date"),ce("D",K,oe),ce("DD",K,H),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=Me("Date",!0);P("DDD",["DDDD",3],"DDDo","dayOfYear"),ce("DDD",X),ce("DDDD",V),pe(["DDD","DDDD"],(function(e,t,n){n._dayOfYear=he(e)})),P("m",["mm",2],0,"minute"),ce("m",K,ae),ce("mm",K,H),pe(["m","mm"],_e);var Cn=Me("Minutes",!1);P("s",["ss",2],0,"second"),ce("s",K,ae),ce("ss",K,H),pe(["s","ss"],Ie);var $n,On,Mn=Me("Seconds",!1);for(P("S",0,0,(function(){return~~(this.millisecond()/100)})),P(0,["SS",2],0,(function(){return~~(this.millisecond()/10)})),P(0,["SSS",3],0,"millisecond"),P(0,["SSSS",4],0,(function(){return 10*this.millisecond()})),P(0,["SSSSS",5],0,(function(){return 100*this.millisecond()})),P(0,["SSSSSS",6],0,(function(){return 1e3*this.millisecond()})),P(0,["SSSSSSS",7],0,(function(){return 1e4*this.millisecond()})),P(0,["SSSSSSSS",8],0,(function(){return 1e5*this.millisecond()})),P(0,["SSSSSSSSS",9],0,(function(){return 1e6*this.millisecond()})),ce("S",X,G),ce("SS",X,H),ce("SSS",X,V),$n="SSSS";$n.length<=9;$n+="S")ce($n,te);function Nn(e,t){t[xe]=he(1e3*("0."+e))}for($n="S";$n.length<=9;$n+="S")pe($n,Nn);On=Me("Milliseconds",!1),P("z",0,0,"zoneAbbr"),P("zz",0,0,"zoneName");var Tn=w.prototype;function An(e){return e}Tn.add=sn,Tn.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"),s=r.calendarFormat(this,i)||"sameElse",o=t&&(C(t[s])?t[s].call(this,n):t[s]);return this.format(o||this.localeData().calendar(s,this,jt(n)))},Tn.clone=function(){return new w(this)},Tn.diff=function(e,t,n){var r,i,s;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":s=un(this,r)/12;break;case"month":s=un(this,r);break;case"quarter":s=un(this,r)/3;break;case"second":s=(this-r)/1e3;break;case"minute":s=(this-r)/6e4;break;case"hour":s=(this-r)/36e5;break;case"day":s=(this-r-i)/864e5;break;case"week":s=(this-r-i)/6048e5;break;default:s=this-r}return n?s:de(s)},Tn.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},Tn.format=function(e){e||(e=this.isUtc()?r.defaultFormatUtc:r.defaultFormat);var t=L(this,e);return this.localeData().postformat(t)},Tn.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()},Tn.fromNow=function(e){return this.from(jt(),e)},Tn.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()},Tn.toNow=function(e){return this.to(jt(),e)},Tn.get=function(e){return C(this[e=U(e)])?this[e]():this},Tn.invalidAt=function(){return p(this).overflow},Tn.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())},Tn.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())},Tn.isBetween=function(e,t,n,r){var i=S(e)?e:jt(e),s=S(t)?t:jt(t);return!!(this.isValid()&&i.isValid()&&s.isValid())&&("("===(r=r||"()")[0]?this.isAfter(i,n):!this.isBefore(i,n))&&(")"===r[1]?this.isBefore(s,n):!this.isAfter(s,n))},Tn.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()))},Tn.isSameOrAfter=function(e,t){return this.isSame(e,t)||this.isAfter(e,t)},Tn.isSameOrBefore=function(e,t){return this.isSame(e,t)||this.isBefore(e,t)},Tn.isValid=function(){return g(this)},Tn.lang=hn,Tn.locale=dn,Tn.localeData=fn,Tn.max=Rt,Tn.min=Lt,Tn.parsingFlags=function(){return h({},p(this))},Tn.set=function(e,t){if("object"==typeof e){var n,r=function(e){var t,n=[];for(t in e)o(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},Tn.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},Tn.subtract=on,Tn.toArray=function(){var e=this;return[e.year(),e.month(),e.date(),e.hour(),e.minute(),e.second(),e.millisecond()]},Tn.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()}},Tn.toDate=function(){return new Date(this.valueOf())},Tn.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?L(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",L(n,"Z")):L(n,t?"YYYY-MM-DD[T]HH:mm:ss.SSS[Z]":"YYYY-MM-DD[T]HH:mm:ss.SSSZ")},Tn.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&&(Tn[Symbol.for("nodejs.util.inspect.custom")]=function(){return"Moment<"+this.format()+">"}),Tn.toJSON=function(){return this.isValid()?this.toISOString():null},Tn.toString=function(){return this.clone().locale("en").format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ")},Tn.unix=function(){return Math.floor(this.valueOf()/1e3)},Tn.valueOf=function(){return this._d.valueOf()-6e4*(this._offset||0)},Tn.creationData=function(){return{input:this._i,format:this._f,locale:this._locale,isUTC:this._isUTC,strict:this._strict}},Tn.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""},Tn.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""},Tn.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""},Tn.eraYear=function(){var e,t,n,i,s=this.localeData().eras();for(e=0,t=s.length;e<t;++e)if(n=s[e].since<=s[e].until?1:-1,i=this.clone().startOf("day").valueOf(),s[e].since<=i&&i<=s[e].until||s[e].until<=i&&i<=s[e].since)return(this.year()-r(s[e].since).year())*n+s[e].offset;return this.year()},Tn.year=Oe,Tn.isLeapYear=function(){return ye(this.year())},Tn.weekYear=function(e){return xn.call(this,e,this.week(),this.weekday()+this.localeData()._week.dow,this.localeData()._week.dow,this.localeData()._week.doy)},Tn.isoWeekYear=function(e){return xn.call(this,e,this.isoWeek(),this.isoWeekday(),1,4)},Tn.quarter=Tn.quarters=function(e){return null==e?Math.ceil((this.month()+1)/3):this.month(3*(e-1)+this.month()%3)},Tn.month=Be,Tn.daysInMonth=function(){return Ae(this.year(),this.month())},Tn.week=Tn.weeks=function(e){var t=this.localeData().week(this);return null==e?t:this.add(7*(e-t),"d")},Tn.isoWeek=Tn.isoWeeks=function(e){var t=ze(this,1,4).week;return null==e?t:this.add(7*(e-t),"d")},Tn.weeksInYear=function(){var e=this.localeData()._week;return qe(this.year(),e.dow,e.doy)},Tn.weeksInWeekYear=function(){var e=this.localeData()._week;return qe(this.weekYear(),e.dow,e.doy)},Tn.isoWeeksInYear=function(){return qe(this.year(),1,4)},Tn.isoWeeksInISOWeekYear=function(){return qe(this.isoWeekYear(),1,4)},Tn.date=En,Tn.day=Tn.days=function(e){if(!this.isValid())return null!=e?this:NaN;var t=Ne(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},Tn.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")},Tn.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},Tn.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")},Tn.hour=Tn.hours=at,Tn.minute=Tn.minutes=Cn,Tn.second=Tn.seconds=Mn,Tn.millisecond=Tn.milliseconds=On,Tn.utcOffset=function(e,t,n){var i,s=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"),s!==e&&(!t||this._changeInProgress?rn(this,Qt(e-s,"m"),1,!1):this._changeInProgress||(this._changeInProgress=!0,r.updateOffset(this,!0),this._changeInProgress=null)),this}return this._isUTC?s:Kt(this)},Tn.utc=function(e){return this.utcOffset(0,e)},Tn.local=function(e){return this._isUTC&&(this.utcOffset(0,e),this._isUTC=!1,e&&this.subtract(Kt(this),"m")),this},Tn.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},Tn.hasAlignedHourOffset=function(e){return!!this.isValid()&&(e=e?jt(e).utcOffset():0,(this.utcOffset()-e)%60==0)},Tn.isDST=function(){return this.utcOffset()>this.clone().month(0).utcOffset()||this.utcOffset()>this.clone().month(5).utcOffset()},Tn.isLocal=function(){return!!this.isValid()&&!this._isUTC},Tn.isUtcOffset=function(){return!!this.isValid()&&this._isUTC},Tn.isUtc=Jt,Tn.isUTC=Jt,Tn.zoneAbbr=function(){return this._isUTC?"UTC":""},Tn.zoneName=function(){return this._isUTC?"Coordinated Universal Time":""},Tn.dates=I("dates accessor is deprecated. Use date instead.",En),Tn.months=I("months accessor is deprecated. Use month instead",Be),Tn.years=I("years accessor is deprecated. Use year instead",Oe),Tn.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()})),Tn.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=Dt(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),s=0;for(n=0;n<r;n++)he(e[n])!==he(t[n])&&s++;return s+i}(t._a,e.toArray())>0):this._isDSTShifted=!1,this._isDSTShifted}));var Dn=O.prototype;function Pn(e,t,n,r){var i=yt(),s=f().set(r,t);return i[n](s,e)}function jn(e,t,n){if(l(e)&&(t=e,e=void 0),e=e||"",null!=t)return Pn(e,t,n,"month");var r,i=[];for(r=0;r<12;r++)i[r]=Pn(e,r,n,"month");return i}function Ln(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,s=yt(),o=e?s._week.dow:0,a=[];if(null!=n)return Pn(t,(n+o)%7,r,"day");for(i=0;i<7;i++)a[i]=Pn(t,(i+o)%7,r,"day");return a}Dn.calendar=function(e,t,n){var r=this._calendar[e]||this._calendar.sameElse;return C(r)?r.call(t,n):r},Dn.longDateFormat=function(e){var t=this._longDateFormat[e],n=this._longDateFormat[e.toUpperCase()];return t||!n?t:(this._longDateFormat[e]=n.match(N).map((function(e){return"MMMM"===e||"MM"===e||"DD"===e||"dddd"===e?e.slice(1):e})).join(""),this._longDateFormat[e])},Dn.invalidDate=function(){return this._invalidDate},Dn.ordinal=function(e){return this._ordinal.replace("%d",e)},Dn.preparse=An,Dn.postformat=An,Dn.relativeTime=function(e,t,n,r){var i=this._relativeTime[n];return C(i)?i(e,t,n,r):i.replace(/%d/i,e)},Dn.pastFuture=function(e,t){var n=this._relativeTime[e>0?"future":"past"];return C(n)?n(t):n.replace(/%s/i,t)},Dn.set=function(e){var t,n;for(n in e)o(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)},Dn.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},Dn.erasParse=function(e,t,n){var r,i,s,o,a,c=this.eras();for(e=e.toUpperCase(),r=0,i=c.length;r<i;++r)if(s=c[r].name.toUpperCase(),o=c[r].abbr.toUpperCase(),a=c[r].narrow.toUpperCase(),n)switch(t){case"N":case"NN":case"NNN":if(o===e)return c[r];break;case"NNNN":if(s===e)return c[r];break;case"NNNNN":if(a===e)return c[r]}else if([s,o,a].indexOf(e)>=0)return c[r]},Dn.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},Dn.erasAbbrRegex=function(e){return o(this,"_erasAbbrRegex")||_n.call(this),e?this._erasAbbrRegex:this._erasRegex},Dn.erasNameRegex=function(e){return o(this,"_erasNameRegex")||_n.call(this),e?this._erasNameRegex:this._erasRegex},Dn.erasNarrowRegex=function(e){return o(this,"_erasNarrowRegex")||_n.call(this),e?this._erasNarrowRegex:this._erasRegex},Dn.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},Dn.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},Dn.monthsParse=function(e,t,n){var r,i,s;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]||(s="^"+this.months(i,"")+"|^"+this.monthsShort(i,""),this._monthsParse[r]=new RegExp(s.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}},Dn.monthsRegex=function(e){return this._monthsParseExact?(o(this,"_monthsRegex")||We.call(this),e?this._monthsStrictRegex:this._monthsRegex):(o(this,"_monthsRegex")||(this._monthsRegex=Re),this._monthsStrictRegex&&e?this._monthsStrictRegex:this._monthsRegex)},Dn.monthsShortRegex=function(e){return this._monthsParseExact?(o(this,"_monthsRegex")||We.call(this),e?this._monthsShortStrictRegex:this._monthsShortRegex):(o(this,"_monthsShortRegex")||(this._monthsShortRegex=Le),this._monthsShortStrictRegex&&e?this._monthsShortStrictRegex:this._monthsShortRegex)},Dn.week=function(e){return ze(e,this._week.dow,this._week.doy).week},Dn.firstDayOfYear=function(){return this._week.doy},Dn.firstDayOfWeek=function(){return this._week.dow},Dn.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},Dn.weekdaysMin=function(e){return!0===e?Ke(this._weekdaysMin,this._week.dow):e?this._weekdaysMin[e.day()]:this._weekdaysMin},Dn.weekdaysShort=function(e){return!0===e?Ke(this._weekdaysShort,this._week.dow):e?this._weekdaysShort[e.day()]:this._weekdaysShort},Dn.weekdaysParse=function(e,t,n){var r,i,s;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]||(s="^"+this.weekdays(i,"")+"|^"+this.weekdaysShort(i,"")+"|^"+this.weekdaysMin(i,""),this._weekdaysParse[r]=new RegExp(s.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}},Dn.weekdaysRegex=function(e){return this._weekdaysParseExact?(o(this,"_weekdaysRegex")||rt.call(this),e?this._weekdaysStrictRegex:this._weekdaysRegex):(o(this,"_weekdaysRegex")||(this._weekdaysRegex=Qe),this._weekdaysStrictRegex&&e?this._weekdaysStrictRegex:this._weekdaysRegex)},Dn.weekdaysShortRegex=function(e){return this._weekdaysParseExact?(o(this,"_weekdaysRegex")||rt.call(this),e?this._weekdaysShortStrictRegex:this._weekdaysShortRegex):(o(this,"_weekdaysShortRegex")||(this._weekdaysShortRegex=et),this._weekdaysShortStrictRegex&&e?this._weekdaysShortStrictRegex:this._weekdaysShortRegex)},Dn.weekdaysMinRegex=function(e){return this._weekdaysParseExact?(o(this,"_weekdaysRegex")||rt.call(this),e?this._weekdaysMinStrictRegex:this._weekdaysMinRegex):(o(this,"_weekdaysMinRegex")||(this._weekdaysMinRegex=tt),this._weekdaysMinStrictRegex&&e?this._weekdaysMinStrictRegex:this._weekdaysMinRegex)},Dn.isPM=function(e){return"p"===(e+"").toLowerCase().charAt(0)},Dn.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 Rn=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 Yn(e){return function(){return this.as(e)}}var Gn=Yn("ms"),Hn=Yn("s"),Vn=Yn("m"),zn=Yn("h"),qn=Yn("d"),Kn=Yn("w"),Jn=Yn("M"),Zn=Yn("Q"),Xn=Yn("y"),Qn=Gn;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"),sr=er("days"),or=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,s,o,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?"-":"",s=hr(this._months)!==hr(d)?"-":"",o=hr(this._days)!==hr(d)?"-":"",a=hr(this._milliseconds)!==hr(d)?"-":"",i+"P"+(n?s+n+"Y":"")+(u?s+u+"M":"")+(l?o+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=Rn(this._milliseconds),this._days=Rn(this._days),this._months=Rn(this._months),e.milliseconds=Rn(e.milliseconds),e.seconds=Rn(e.seconds),e.minutes=Rn(e.minutes),e.hours=Rn(e.hours),e.months=Rn(e.months),e.years=Rn(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=Gn,pr.asSeconds=Hn,pr.asMinutes=Vn,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,s=this._milliseconds,o=this._days,a=this._months,c=this._data;return s>=0&&o>=0&&a>=0||s<=0&&o<=0&&a<=0||(s+=864e5*Un(Wn(a)+o),o=0,a=0),c.milliseconds=s%1e3,e=de(s/1e3),c.seconds=e%60,t=de(e/60),c.minutes=t%60,n=de(t/60),c.hours=n%24,o+=de(n/24),a+=i=de(Bn(o)),o-=Un(Wn(i)),r=de(a/12),a%=12,c.days=o,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=sr,pr.weeks=function(){return de(this.days()/7)},pr.months=or,pr.years=ar,pr.humanize=function(e,t){if(!this.isValid())return this.localeData().invalidDate();var n,r,i=!1,s=lr;return"object"==typeof e&&(t=e,e=!1),"boolean"==typeof e&&(i=e),"object"==typeof t&&(s=Object.assign({},lr,t),null!=t.s&&null==t.ss&&(s.ss=t.s-1)),r=function(e,t,n,r){var i=Qt(e).abs(),s=cr(i.as("s")),o=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=s<=n.ss&&["s",s]||s<n.s&&["ss",s]||o<=1&&["m"]||o<n.m&&["mm",o]||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,s,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,P("X",0,0,"unix"),P("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 s from"jsonp";import o from"crypto-js";import{z as a}from"zod";import c from"emittery";import l from"mustache";import u,{scryptSync as d,createDecipheriv as h,createHash as f}from"crypto";import{satisfies as p}from"compare-versions";import g from"debug";import m,{mkdir as y,access as v,constants as b,readdir as w,rm as S,readFile as _}from"fs/promises";import I from"minimist";import x,{join as k,dirname as E,resolve as C}from"path";import"node-ipc";import*as O from"fs";import $ from"fs";import N from"tty";import M,{homedir as A,platform as T}from"os";import P from"stream";import D from"buffer";import j from"events";import R from"zlib";import L from"string_decoder";import F from"http";import U from"https";import B from"net";import W from"tls";import Y from"dgram";import G,{fileURLToPath as H}from"url";import V from"node:os";import{spawn as z}from"child_process";import{join as q,resolve as K,dirname as J}from"node:path";import{ImageData as Z,loadImage as X,createCanvas as Q}from"@napi-rs/canvas";var ee;!function(e){e.STARTING="STARTING",e.PENDING="PENDING",e.RUNNING="RUNNING",e.PAUSED="PAUSED",e.DRAINING="DRAINING",e.STOPPED="STOPPED",e.ERROR="ERROR"}(ee||(ee={}));const te="undefined"!=typeof window&&void 0!==window.document&&void 0!==window.document.createElement,ne="object"==typeof self&&self.constructor&&"DedicatedWorkerGlobalScope"===self.constructor.name,re="undefined"!=typeof process&&null!=process.versions&&null!=process.versions.node,ie={};let se=0,oe="";const ae=e=>ie[e]?ie[e]:null,ce=(e,t)=>{const n=ae(e);if(!n)return n;return n.blocks[t]||null},le=e=>{const{recipeId:t,widgetId:n}=e,r=ae(t);if(!r)return null;for(const e in r.blocks){const t=r.blocks[e].gates[n];if(t)return t}return null},ue=(e,t,n)=>{const r=ce(e,t);if(!r)return r;return r.gates[n]},de=(e,t)=>{let n=r(4);for(;ie[n];)n=r(4);const i=(s=e,JSON.parse(JSON.stringify(s)));var s;return i.logs="",i.addLog=e=>{i.logs+=`${(()=>{const e=Date.now();if(e!==se){const t=new Date;se=e,oe=t.toJSON()}return oe})()}:: ${e}\n`},i.dbInfo={...t},ie[n]=i,n},he=e=>{const t=ae(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}},fe="interrupt_port",pe="UI:",ge="default";var me,ye,ve,be,we,Se,_e,Ie;let xe;!function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(me||(me={})),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"}(ye||(ye={})),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"}(ve||(ve={})),function(e){e.Javascript="js",e.Python="py",e.Executable="exe"}(be||(be={})),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:"}(we||(we={})),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"}(Se||(Se={})),function(e){e.SetDependencyPath="setDependencyPath",e.GetDependencyPath="getDependencyPath"}(_e||(_e={})),function(e){e.IPC="ipc",e.WS="ws"}(Ie||(Ie={}));const ke=()=>{if(!xe)throw new Error("CanvasManager not set");return xe},Ee=e=>{xe=e},Ce=(e,t)=>ke().createCanvas(e,t),Oe=e=>te?e.getContext("2d",{willReadFrequently:!0}):e.getContext("2d"),$e=e=>ke().loadImage(e),Ne="-",Me=`inner${Ne}`,Ae=`outer${Ne}`,Te=`${Ae}input${Ne}`,Pe=`${Ae}output${Ne}`,De=`${Me}input${Ne}`,je=`${Me}output${Ne}`,Re=e=>e===fe,Le=e=>e&&void 0!==e.width&&void 0!==e.height&&void 0!==e.data&&e.data.constructor&&"Uint8ClampedArray"===e.data.constructor.name,Fe=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,Ue=e=>e&&"number"==typeof e.x&&"number"==typeof e.y,Be=e=>"number"==typeof e?ye.Number:"string"==typeof e?ye.String:"boolean"==typeof e?ye.Boolean:Array.isArray(e)?ye.Array:Le(e)?ye.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?ye.AudioBuffer:e&&void 0!==e.byteLength?ye.ArrayBuffer:Fe(e)?ye.Rect:e&&void 0!==e.x&&void 0!==e.y&&"number"==typeof e.x&&"number"==typeof e.y?ye.Point:(e=>e&&"string"==typeof e.format&&e.data&&e.data instanceof ArrayBuffer)(e)?ye.BinaryFile:ye.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},Ye=(e,t,n)=>"inner"===e?"input"===t?`${De}${n}`:`${je}${n}`:"input"===t?`${Te}${n}`:`${Pe}${n}`,Ge=e=>{const t=(e||"")?.split("_");if(t.length<3)throw new Error(`Unknown child identifier format [${e}]`);const n=t[0];return{portType:t[1],widgetId:n,portName:t[2]}},He=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)}};var Ve,ze;!function(e){e.Action="action",e.CustomInput="customInput"}(Ve||(Ve={})),function(e){e.input="input",e.counter="counter",e.play="play",e.elapsed="elapsed",e.ifGate="ifGate",e.skipEvent="skipEvent",e.between="between",e.map="map",e.parser="parser",e.slider="slider",e.suspend="suspend",e.display="display",e.json="json",e.arrayItem="arrayItem",e.extractImage="extractImage",e.imageConvolution="imageConvolution",e.firstEvent="firstEvent",e.pixelDraw="pixelDraw",e.randomBetween="randomBetween",e.arrayCombine="arrayCombine",e.clock="clock",e.multiplication="multiplication",e.object="object",e.widgetGroup="widgetGroup",e.script="script",e.base64ToImageData="base64ToImageData",e.jsonParse="jsonParse",e.text="text",e.imageCrop="imageCrop",e.imageResize="imageResize",e.value="value",e.imageWarp="imageWarp",e.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"}(ze||(ze={}));const qe={};let Ke,Je=()=>0;const Ze=async e=>{const t=qe[e],n={name:fe,type:ye.Boolean};if(t){const r={name:t.portName},i=t.data||{type:ye.Boolean,value:!0};if(!Je)throw new Error("consumeEventCounter is not set");const s=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:s}),"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:s,sourceWidgetId:o,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:s,sourceWidgetId:o,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 st=(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},ot=(e,t)=>{const n=it[e];n&&(delete it[e],n.resolve(t))};const at=()=>({inputName:"",dataType:ye.Anything}),ct="output",lt={processEvent:async(e,t)=>{const n=t.getState(),r={...at(),...n};if(e.type!==r.dataType&&r.dataType!==ye.Anything)return void console.error(`Invalid data type: ${e.type} for input: ${r.inputName}. Expected: ${r.dataType}`);const i=t.waitForOutputChild,s=i?st(t.id,e):void 0,o=i?{eventKey:s?.eventKey}:void 0;if(await t.nextWidget(ct,{type:e.type,value:e.value},o).catch((e=>{console.log("[INPUT] error resolving event: ",e),s?.reject(e)})),s){return await s.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 s=i.increment,o=i.currentValue;const a=await r.getParentAtPort(ut.increment);if(t.name===ut.increment)return void(n.data.type===ye.Number&&r.setState({...i,increment:Number(n.data.value)}));if(a){const e=a.getValue();null!==e&&(s=e)}if(t.name===ut.reset)return r.setState({...i,currentValue:0});o+=s,r.setState({currentValue:o,increment:s});const c={type:ye.Number,value:o};return r.nextGate(dt,c)},getInputNames:()=>[{name:ut.in,type:ye.Anything},{name:ut.reset,type:ye.Anything},{name:ut.increment,type:ye.Number}],getOutputNames:()=>[{name:dt,type:ye.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()},s=Date.now(),o=s-(i.updatedAt||s);return t.name===ft.reset?r.setState({...i,updatedAt:s,elapsed:0}):(r.setState({updatedAt:s,elapsed:o}),r.nextGate(pt,{type:ye.Number,value:o}))},getInputNames:()=>[{name:ft.in,type:ye.Anything},{name:ft.reset,type:ye.Anything}],getOutputNames:()=>[{name:pt,type:ye.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()},s=n.data.value,o=!isNaN(Number(s)),a="string"==typeof s;if(!i.useDataPort&&(n.data.type===ye.Number||n.data.type===ye.String||n.data.type===ye.Boolean||n.data.type===ye.Anything&&o||n.data.type===ye.Anything&&a)){let e=!1;return("Equal"===i.condition&&(n.data.value==i.value||n.data.type===ye.Boolean&&n.data.value.toString()===i.value.toString())||"Not Equal"===i.condition&&(n.data.value!==i.value||n.data.type===ye.Boolean&&n.data.value!==i.value.toString())||"Greater"===i.condition&&n.data.type===ye.Number&&n.data.value>Number(i.value)||"Less"===i.condition&&n.data.type===ye.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===ye.Number||n.data.type===ye.String||n.data.type===ye.Boolean||n.data.type===ye.Anything&&(o||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===ye.Boolean&&i.$lastValue?.toString()===i.value.toString())||"Not Equal"===i.condition&&(i.$lastValue!==i.value||i.$lastInputDataType===ye.Boolean&&i.$lastValue!==i.value.toString())||"Greater"===i.condition&&i.$lastInputDataType===ye.Number&&Number(i.$lastValue)>Number(i.value)||"Less"===i.condition&&i.$lastInputDataType===ye.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:ye.Anything,triggerPort:!0},{name:mt.evaluation,type:[ye.Number,ye.String,ye.Boolean]}]:[{name:"in",type:[ye.Number,ye.String,ye.Boolean]}],getOutputNames:e=>e.$lastOutputDataType?[{name:yt,type:e.$lastOutputDataType},{name:vt,type:e.$lastOutputDataType}]:[{name:yt,type:[ye.Number,ye.String]},{name:vt,type:[ye.Number,ye.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:ye.Anything},{name:wt.reset,type:ye.Anything}],getOutputNames:e=>[{name:St,type:e.$$lastDetectedType??ye.Anything},{name:_t,type:e.$$lastDetectedType??ye.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===ye.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:ye.Number}],getOutputNames:()=>[{name:kt,type:ye.Number},{name:Et,type:ye.Number}]};const Ot=Object.freeze({in:"in"}),$t="out";var Nt={onParentEvent:async(e,t,n,r)=>{const i={clamp:!0,...r.getState()},s=Number(n.data.value);if(void 0!==i.fromMax&&void 0!==i.fromMin&&void 0!==i.toMax&&void 0!==i.toMin&&""!==i.fromMax&&""!==i.fromMin&&""!==i.toMax&&""!==i.toMin&&(n.data.type===ye.Number||n.data.type===ye.Anything&&!isNaN(Number(s)))){let e=((e,t,n,r,i)=>(e-t)*(i-r)/(n-t)+r)(s,Number(i.fromMin),Number(i.fromMax),Number(i.toMin),Number(i.toMax));if(isNaN(e))return;return i.clamp&&(e<Number(i.toMin)&&(e=Number(i.toMin)),e>Number(i.toMax)&&(e=Number(i.toMax))),r.nextGate($t,{type:ye.Number,value:Number(e)})}},getInputNames:()=>[{name:Ot.in,type:ye.Number}],getOutputNames:()=>[{name:$t,type:ye.Number}]};const Mt=Object.freeze({in:"in"}),At="out";var Tt={onParentEvent:async(e,t,n,r)=>{const i={convertTo:"Integer",floatPlaces:2,...r.getState()};let s=n.data.value;if(n.data.type===ye.Number||n.data.type===ye.Anything||n.data.type===ye.String){if((!isNaN(Number(s))||"string"==typeof s)&&!Array.isArray(s))return"Integer"===i.convertTo?s=parseInt(s):"Decimal"===i.convertTo?s=parseFloat(Number(s).toFixed(i.floatPlaces)):"String"===i.convertTo?s=String(s):"Abs"===i.convertTo?s=Math.abs(Number(s)):"Round"===i.convertTo&&(s=Math.round(Number(s))),r.nextGate(At,{type:"String"===i.convertTo?ye.String:ye.Number,value:s})}},getInputNames:()=>[{name:Mt.in,type:ye.Number}],getOutputNames:e=>{const t="String"===e?.convertTo?ye.String:ye.Number;return[{name:At,type:t}]}};const Pt=Object.freeze({in:"in"}),Dt="out";var jt={onParentEvent:async(e,t,n,r)=>{const i={currentValue:50,min:0,max:100,...r.getState()};let s=!1;return i.currentValue<i.min&&(i.currentValue=i.min,s=!0),i.currentValue>i.max&&(i.currentValue=i.max,s=!0),s&&r.setState(i),r.nextWidget(Dt,{type:ye.Number,value:i.currentValue})},getInputNames:()=>[{name:Pt.in,type:ye.Anything}],getOutputNames:()=>[{name:Dt,type:ye.Number}]};const Rt=Object.freeze({in:"in",reset:"reset"}),Lt="out",Ft="skipped";var Ut={onParentEvent:async(e,t,n,r)=>{const i={lastCalledAt:0,delayMs:500},s={lastCalledAt:0,delayMs:500,...r.getState()};if(t.name===Rt.reset)return r.setState({...s,lastCalledAt:0});const o=Date.now(),a=o-s.lastCalledAt;return s.lastCalledAt===i.lastCalledAt||a>=s.delayMs&&s.delayMs>0?(s.lastCalledAt=o,r.setState(s),r.nextWidget(Lt,n.data)):(n.data.type!==s.$$lastDetectedType&&(s.$$lastDetectedType=n.data.type),r.setState(s),r.nextWidget(Ft,n.data))},getInputNames:()=>[{name:Rt.in,type:ye.Anything},{name:Rt.reset,type:ye.Anything}],getOutputNames:e=>[{name:Lt,type:e.$$lastDetectedType??ye.Anything},{name:Ft,type:e.$$lastDetectedType??ye.Anything}]};const Bt="in";var Wt={onParentEvent:async()=>{},getInputNames:()=>[{name:Bt,type:[ye.ImageData,ye.Number]}],getOutputNames:()=>[]};const Yt=()=>({properties:[{label:"property1",name:"property1"}],detectedProperties:{}}),Gt=(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()},s=n?.data?.value,o=Array.isArray(s);if(n.data.type===ye.JsonObj||n.data.type===ye.Rect||n.data.type===ye.Point||n.data.type===ye.BinaryFile||n.data.type===ye.Anything||o){let e=!1;for(const t in s){const n=Be(s[t]),r=!!i.detectedProperties[t],o=i.detectedProperties[t]?.type!==n;if(!r||o){const r=n===ye.JsonObj||n===ye.Rect||n===ye.Point||n===ye.Array;i.detectedProperties[t]={type:n,...r?{shape:We(s[t])}:void 0},e=!0}}if(o&&void 0===i.detectedProperties.length&&(i.detectedProperties.length={type:ye.Number}),e&&r.setState(i),s){const e=[];for(const t of i.properties||[]){const n=Gt(s,t.label),o=t.label.includes(".");if(void 0!==n){const s=o?Be(n):void 0!==i.detectedProperties[t.label]?.type?i.detectedProperties[t.label].type:ye.Anything;e.push(r.nextGate(t.name,{type:s,value:n}))}}await Promise.allSettled(e)}}},getInputNames:()=>[{name:"in",type:ye.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:ye.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:Yt};const Vt="output",zt="noItem";var qt={onParentEvent:async(e,t,n,r)=>{const i={index:0,...r.getState()};let s=i.index;const o=n.data.value,a="string"==typeof n.data.value,c=Array.isArray(n.data.value);if(n.data.type===ye.Anything&&(c||a)||n.data.type===ye.String&&a||n.data.type===ye.Array&&c){s<0&&(s=o.length+s);const e=a?ye.String:Be(o[s]);return e!==i.$$lastDetectedType&&r.setState({...i,$$lastDetectedType:e}),void 0!==o[s]?r.nextGate(Vt,{value:o[s],type:e}):r.nextGate(zt,{value:!0,type:ye.Boolean})}},getInputNames:()=>[{name:"in",type:[ye.Array,ye.String]}],getOutputNames:e=>[{name:Vt,type:e.$$lastDetectedType??ye.Anything},{name:zt,type:ye.Boolean}]};const Kt={},Jt=e=>(Kt[e]||(Kt[e]={canvasFrom:Ce(320,240),canvasTo:Ce(320,240)}),Kt[e]),Zt=Object.freeze({image:"image",rect:"rect"}),Xt="image";var Qt={onParentEvent:async(e,t,n,r)=>{const i=Jt(r.id),s={offset:{height:0,left:0,top:0,width:0},...r.getState()},o=[ye.Anything,ye.Rect,ye.JsonObj];if(t.name===Zt.rect&&Fe(n.data.value)&&o.includes(n.data.type)&&(s.rect=n.data.value,r.setState({...s})),t.name===Zt.image){if(!((n.data.type===ye.ImageData||n.data.type===ye.Anything)&&Le(n.data.value)))throw new Error("Invalid image data. Expected a valid ImageData type");i.lastImage=n.data.value}if(i.lastImage&&s.rect){const e=((e,t,n,r,i)=>{if(r&&r.getContext){const s=r.getContext("2d"),o=n.getContext("2d");if(s&&o){n.width=e.width,n.height=e.height,o.putImageData(e,0,0);const a={...i};i&&(a.height=Number(i.height),a.width=Number(i.width),a.left=Number(i.left),a.top=Number(i.top));const c={top:0,width:0,left:0,height:0,...a};return i&&(Number.isInteger(c.width)||(c.width=t.width*c.width),Number.isInteger(c.height)||(c.height=t.height*c.height),Number.isInteger(c.left)||(c.left=t.left+t.width*c.left),Number.isInteger(c.top)||(c.top=t.top+t.height*c.top)),r.width=t.width+c.width,r.height=t.height+c.height,s.drawImage(n,t.left+c.left,t.top+c.top,t.width+c.width,t.height+c.height,0,0,r.width+c.width,r.height+c.height),s.getImageData(0,0,r.width||1,r.height||1)}}return e})(i.lastImage,s.rect,i.canvasFrom,i.canvasTo,s.offset);r.setState({...s,rect:null}),i.lastImage=void 0,await r.nextWidget(Xt,{type:ye.ImageData,value:e})}},getInputNames:()=>[{name:Zt.image,type:ye.ImageData},{name:Zt.rect,type:[ye.Rect,ye.JsonObj]}],getOutputNames:()=>[{name:Xt,type:ye.ImageData}],initialize:async e=>{Jt(e.widgetId)},terminate:async e=>{delete Kt[e.widgetId]}};const en=(e,t)=>{const n=Math.round(Math.sqrt(t.length)),r=Math.floor(n/2),i=e.data,s=e.width,o=e.height,a=s,c=o,l=((e,t,n)=>{if(te)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<o&&u>=0&&u<s){const r=4*(c*s+u),o=t[e*n+a];f+=i[r]*o,p+=i[r+1]*o,g+=i[r+2]*o,m+=i[r+3]*o}}u[h]=f,u[h+1]=p,u[h+2]=g,u[h+3]=m+1*(255-m)}return l},tn=[-1,0,1,-2,0,2,1,0,1],nn=Object.freeze({image:"image"}),rn="image";var sn={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),s={matrix:[...tn],...i};if(n.data.type===ye.ImageData||n.data.type===ye.Anything&&Le(n.data.value)){const e=en(n.data.value,s.matrix);return r.nextGate(rn,{type:ye.ImageData,value:e})}},getInputNames:()=>[{name:nn.image,type:ye.ImageData}],getOutputNames:()=>[{name:rn,type:ye.ImageData}]};const on=Object.freeze({output:"output",aborted:"aborted"}),an=()=>({inputs:2,matchingOutputs:!0,lastInputIndex:-1,delayMs:500,triggeredAt:0}),cn=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:ye.Anything})));return n.push({name:"reset",type:ye.Anything}),n};var ln={onParentEvent:async(e,t,n,r)=>{const i={inputs:2,matchingOutputs:!0,lastInputIndex:-1,delayMs:500,triggeredAt:0,...r.getState()};if("reset"===t.name)return r.setState({...i,triggeredAt:0});const s=Date.now(),o=s-i.triggeredAt;if(i.triggeredAt&&!(o>=i.delayMs&&i.delayMs>0)&&i.delayMs)return r.nextGate(on.aborted,n.data);{i.triggeredAt=s;const e=cn(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(on.output,n.data),r.setState(i)}},getInputNames:cn,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:ye.Anything})));return e.push({name:on.aborted,type:ye.Anything}),e}return[{name:on.output,type:ye.Anything},{name:on.aborted,type:ye.Anything}]},getDefaultState:an};const un=(e,t,n,r,i,s)=>{if(i){const o=e.measureText(i),a=o.fontBoundingBoxAscent+o.fontBoundingBoxDescent;e.fillStyle=r,e.fillRect(t,n-s,1.1*o.width,a),e.font=`${s}px Arial`,e.fillStyle="black",e.fillText(i,t,n)}},dn=(e,t,n,r,i,s,o)=>{e.fillStyle=i,e.fillRect(t,n,r,r),un(e,t,n,i,s,o)},hn=(e,t,n,r,i,s)=>{e.beginPath(),e.strokeStyle=r,e.lineWidth=n,e.rect(t.left,t.top,t.width,t.height),e.stroke();const o=n/2;un(e,t.left-o,t.top-o,r,i,s)},fn={},pn=e=>(fn[e]||(fn[e]={memCanvas:Ce(320,240),lastFrame:void 0,pixels:void 0}),fn[e]),gn=Object.freeze({image:"image",pixels:"pixels"}),mn="image";var yn={onParentEvent:async(e,t,n,r)=>{const i=pn(r.id),s={fontSize:12,color:"#00ff00",size:2,...r.getState()},o=(n.data.type===ye.ImageData||n.data.type===ye.Anything)&&Le(n.data.value);if(t.name===gn.pixels){const e=(e=>Ue(e)||Fe(e)||Array.isArray(e)&&e[0]&&(Ue(e[0])||Fe(e[0])))(n.data.value);if(!e)return;i.pixels=n.data.value}if(t.name===gn.image&&o){const e=n.data.value;i.lastFrame=e}if(i.lastFrame&&i.pixels&&i.memCanvas){const e=(e=>{const{sourceImage:t,pixels:n,memCanvas:r,size:i,color:s,labelProp:o,fontSize:a}=e;if(r){const e=Oe(r);if(e){r.width!==t.width&&(r.width=t.width),r.height!==t.height&&(r.height=t.height),e.putImageData(t,0,0);const c=Array.isArray(n)?n:[n];for(let t=0;t<c.length;t++){const n=c[t],r=o?n[o]:"";Fe(n)?hn(e,n,i,s,r,a):Ue(n)&&dn(e,n.x,n.y,i,s,r,a)}return e.getImageData(0,0,r.width,r.height)}}return t})({sourceImage:i.lastFrame,pixels:i.pixels||[],memCanvas:i.memCanvas,size:s.size,color:s.color,labelProp:s.labelProp,fontSize:s.fontSize});return i.lastFrame=void 0,i.pixels=void 0,r.setState({...s}),r.nextWidget(mn,{type:ye.ImageData,value:e})}r.setState(s)},getInputNames:()=>[{name:gn.image,type:ye.ImageData},{name:gn.pixels,type:[ye.Rect,ye.Point,ye.Array,ye.JsonObj]}],getOutputNames:()=>[{name:mn,type:ye.ImageData}],initialize:async e=>{pn(e.widgetId)},terminate:async e=>{delete fn[e.widgetId]}};const vn=Object.freeze({in:"in"}),bn="output",wn=e=>{const t=String(e).split(".");return t.length<2?0:t[1].length};var Sn={onParentEvent:async(e,t,n,r)=>{const i={min:1,max:100,...r.getState()},s=!Number.isInteger(i.min),o=!Number.isInteger(i.max),a=s||o;let c=(l=i.min,u=i.max,Math.random()*(u-l)+l);var l,u;if(a){let e=0;if(s&&(e=wn(i.min)),o){const t=wn(i.max);t>e&&(e=t)}c=Number(c.toFixed(e))}else c=Math.floor(c);return r.nextGate(bn,{type:ye.Number,value:c})},getInputNames:()=>[{name:vn.in,type:ye.Anything}],getOutputNames:()=>[{name:bn,type:ye.Number}]};const _n=Object.freeze({output:"output",totalItems:"totalItems"}),In=Object.freeze({trigger:"trigger",clear:"clear"}),xn=()=>({$$$time:0,totalSentItems:-1,totalSentAt:0,$$list:[],$$outputShape:{},totalInputs:1}),kn=async(e,t)=>t.nextGate(_n.totalItems,{type:ye.Number,value:e});var En={onParentEvent:async(e,t,n,r)=>{const i={$$$time:0,totalSentItems:-1,totalSentAt:0,$$list:[],$$outputShape:{},totalInputs:1,...r.getState()};if(t.name===In.clear)return i.$$list=[],i.properties?.autoFilled&&delete i.properties,r.setState(i),kn(i.$$list.length,r);const s=t.name===In.trigger;if(!s)if(Array.isArray(n.data.value))n.data.type!==ye.Array&&n.data.type!==ye.Anything||(i.$$outputShape={...i.$$outputShape,...e?.jsonShape},i.$$list=i.$$list.concat(n.data.value),r.setState({...i}),await kn(i.$$list.length,r));else{const t=`$$primitive_${Object.keys(i.$$outputShape).length}`;n.data.type===ye.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 kn(i.$$list.length,r)}if(s){Object.keys(i.$$outputShape).length&&(i.properties={autoFilled:!0,jsonShape:{...i.$$outputShape}});const e=i.$$list.length,t=[...i.$$list];return i.$$list=[],r.setState({...i}),await kn(e,r),r.nextGate(_n.output,{type:ye.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:ye.Anything})));return n.push({name:In.clear,type:ye.Anything},{name:In.trigger,type:ye.Anything}),n},getOutputNames:e=>[{name:_n.output,type:ye.Array,...e.properties?{jsonShape:e.properties?.jsonShape}:void 0},{name:_n.totalItems,label:"Total Items",type:ye.Number}],getDefaultState:xn};const Cn=Object.freeze({start:"start",stop:"stop"}),On="output",$n="clock_interrupt";var Nn={onParentEvent:async(e,t,n,r)=>{const i={enabled:!1,interval:1e3,intervalMode:"ms",...r.getState()};if(Re(e?.name||"")&&t.name===$n)return r.nextGate(On,{type:ye.Boolean,value:!0});if(t.name===Cn.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!==Cn.start||i.enabled||i.$$interruptId||(i.$$interruptId=r.registerInterrupt({type:"interval",sourceWidgetId:r.id,customTargetPortName:$n,config:{interval:i.interval}}),i.enabled=!0,r.setState(i))},getInputNames:()=>[{name:Cn.start,type:ye.Anything},{name:Cn.stop,type:ye.Anything}],getOutputNames:()=>[{name:On,type:ye.Boolean}],initialize:async e=>{const t=e.getState();if(t.enabled&&!t.$$interruptId){const n=e.registerInterrupt({type:"interval",sourceWidgetId:e.widgetId,customTargetPortName:$n,config:{interval:t.interval}});e.setState({...t,$$interruptId:n})}}};const Mn=Object.freeze({in:"in"}),An="output",Tn=(e,t,n)=>"number"==typeof e?Number((e*t).toFixed(n)):e;var Pn={onParentEvent:async(e,t,n,r)=>{const i={userProperties:[],factor:2,decimalPoints:2,...r.getState()},s=n.data.type;let o=n.data.value,a=!1;return e?.jsonShape&&(i.detectedInputJson={...i.detectedInputJson,...e?.jsonShape},a=!0),i.detectedInputType||(i.detectedInputType=s,a=!0),n.data.type===ye.Array&&("number"==typeof n.data.value?.[0]?o=((e,t,n)=>{const r=(e||[]).map((e=>Tn(e,t,n)));return r})(n.data.value,i.factor,i.decimalPoints):"object"==typeof n.data.value?.[0]&&(o=((e,t,n,r)=>{const i=(e||[]).map((e=>{const i={...e};return Object.keys(i).forEach((e=>{r?.length&&!r?.includes(e)||(i[e]=Tn(i[e],t,n))})),i}));return i})(n.data.value,i.factor,i.decimalPoints,i.userProperties))),n.data.type===ye.Number&&(o=Tn(n.data.value,i.factor,i.decimalPoints)),a&&r.setState(i),r.nextGate(An,{type:s,value:o})},getInputNames:()=>[{name:Mn.in,type:[ye.Array,ye.Number]}],getOutputNames:e=>[{name:An,type:e.detectedInputType||ye.Number,jsonShape:e.detectedInputJson}]};const Dn={},jn=Object.freeze({output:"output"}),Rn=Object.freeze({trigger:"trigger"}),Ln=e=>e===ye.ArrayBuffer||e===ye.AudioBuffer||e===ye.BinaryFile||e===ye.ImageData||e===ye.ImageBitmap||e===ye.Array||e===ye.JsonObj,Fn=()=>({useTriggerPort:!0,properties:[{name:"x",label:"x",type:ye.Number,value:10},{name:"y",label:"y",type:ye.Number,value:20}]}),Un=e=>{const t={};for(let n=0;n<e.properties.length;n++)t[e.properties[n].label]=e.properties[n].type;return t},Bn=(e,t)=>{const n={};for(let r=0;r<e.properties.length;r++){let i=e.properties[r].value;const s=e.properties[r].type;Ln(s)&&(i=Dn[t][e.properties[r].name]),s===ye.Number?i=Number(i):s===ye.String&&(i=String(i)),n[e.properties[r].label]=i}return n};var Wn={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),s=structuredClone(i),o={...Fn(),...s};if(t.name===Rn.trigger){const e=Bn(o,r.id);return r.nextWidget(jn.output,{type:ye.JsonObj,value:e})}const a=o.properties.findIndex((e=>e.name===t.name));if(-1!==a){const e=o.properties[a];let t=n.data.type===e.type;if(!t&&n.data.type===ye.Anything){t=Be(n.data.type)===e.type}if(t){const t=Ln(n.data.type);Dn[r.id]=Dn[r.id]||{},t?(Dn[r.id][e.name]=n.data.value,o.properties[a].value=void 0):o.properties[a].value=n.data.value,o.properties[a].$$invalidInputType=!1}else o.properties[a].$$invalidInputType=!0;if(r.setState(o),!o.useTriggerPort){const e=Bn(o,r.id);return r.nextWidget(jn.output,{type:ye.JsonObj,value:e})}}},getInputNames:e=>{const t={...Fn(),...e},n=t.properties.map((e=>({name:e.name,label:e.label,type:e.type})));return t.useTriggerPort&&n.push({name:Rn.trigger,label:Rn.trigger,type:ye.Anything}),n},getOutputNames:e=>[{name:jn.output,label:jn.output,type:ye.JsonObj,jsonShape:Un(e)}],getDefaultState:Fn,initialize:async e=>{Dn[e.widgetId]={}},terminate:async e=>{delete Dn[e.widgetId]}};const Yn=async e=>{const t=(e,t)=>e.split(t)[1];if(e.startsWith(Te)){const n=t(e,Te);return Ye("inner","input",n)}if(e.startsWith(je)){const n=t(e,je);return Ye("outer","output",n)}return null},Gn=()=>({canvasPosition:{x:0,y:0},canvasZoom:1,inputs:[{name:"input",type:[ye.Anything],index:0}],outputs:[{name:"output",type:[ye.Anything],index:0}],name:"Custom Widget 1",description:"",type:"custom"}),Hn=e=>{const t={...Gn(),...e},n=t.inputs.map(((e,t)=>({name:Ye("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:Ye("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 Vn={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),s={...Gn(),...i},o=Hn(s,(r.recipePoolId,r.recipeType,r.thingRecipeId,r.id));for(let e=0;e<o.length;e++){const i=o[e];if(t.name===i.name&&(i.type.includes(ye.Anything)||i.type.includes(n.data.type))){const e=await Yn(t.name);e&&await r.nextWidget(e,{type:n.data.type,value:n.data.value})}}},getInputNames:Hn,getOutputNames:e=>{const t={...Gn(),...e},n=t.outputs.map(((e,t)=>({name:Ye("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:Ye("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:Gn};const zn=(e,t,n,r,i)=>{const s=4*(t*n.width+e),o=n.data[s],a=n.data[s+1],c=n.data[s+2];return Math.abs(o-r.r)<=i&&Math.abs(a-r.g)<=i&&Math.abs(c-r.b)<=i};var qn={image:{getPixelValueAtIndex:(e,t)=>{const n=e.data,r=n[t]||0,i=n[t+1]||0,s=n[t+2]||0;return{avr:(r+i+s)/3,r:r,g:i,b:s}},getBoundingBox:(e,t,n)=>{const r=e.width,i=e.height,s=new Set,o=Number(n.threshold||0),a=isNaN(o)?10:o,c=(n,o)=>{const c=[[n,o]];let l=n,u=n,d=o,h=o;for(;c.length>0;){const n=c.shift();if(!n)continue;const[o,f]=n;o<0||f<0||o>=r||f>=i||s.has(`${o},${f}`)||!zn(o,f,e,t,a||0)||(s.add(`${o},${f}`),l=Math.min(l,o),u=Math.max(u,o),d=Math.min(d,f),h=Math.max(h,f),c.push([o+1,f],[o-1,f],[o,f+1],[o,f-1]))}return{minX:l,maxX:u,minY:d,maxY:h}},l=[];for(let o=0;o<i;o+=4)for(let i=0;i<r;i+=4)if(!s.has(`${i},${o}`)&&zn(i,o,e,t,a)){const{minX:e,maxX:t,minY:r,maxY:s}=c(i,o),a=t-e,u=s-r;if(a>=(n.minWidth||1)&&u>=(n.minHeight||1)&&l.push({left:e,top:r,width:a,height:u}),n.maxBoxes&&l.length>=n.maxBoxes)return l}return l},copyImageData:e=>new ImageData(new Uint8ClampedArray(e.data),e.width,e.height),setPixelValueAtIndex:(e,t,n)=>{const r=e.data,i="object"==typeof n,s=i?n.r:n,o=i?n.g:n,a=i?n.b:n;r[t]=s,r[t+1]=o,r[t+2]=a,r[t+3]=255}}};const Kn=e=>Be(e),Jn=a.enum(["Read","Modify","Comment"]),Zn=a.object({email:a.email(),name:a.string(),accessMode:Jn});var Xn;!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"}(Xn||(Xn={}));const Qn=a.enum(["active","inactive"]),er=a.enum(["Owner","Admin","Member"]),tr=a.object({apiKey:a.string(),createdAt:a.string(),createdBy:a.string()}),nr=a.object({country:a.string(),city:a.string(),address1:a.string(),address2:a.string(),postCode:a.string()}),rr=a.object({id:a.string(),name:a.string(),groups:a.array(a.string()),logo:a.string().optional(),industry:a.string().optional(),accountOwner:a.string(),stripeCustomerId:a.string(),stripeSubscription:a.custom(),apiKeys:a.array(tr).optional(),domain:a.string().optional(),createdAt:a.string(),updatedAt:a.string(),accountState:a.custom(),location:nr.optional()}),ir=a.object({id:a.string(),firstName:a.string(),lastName:a.string(),email:a.email().optional(),loginId:a.string().optional(),role:er,groups:a.array(a.string()).optional().default([]),status:Qn,lastSeenAt:a.string().optional(),createdAt:a.string()});var sr,or,ar,cr;rr.pick({id:!0,name:!0,stripeSubscription:!0,stripeCustomerId:!0}),a.object({member:a.object({firstName:a.string().optional(),lastName:a.string().optional(),email:a.string().optional(),role:er.optional(),groups:a.array(a.string()).optional(),status:Qn})}),ir.omit({id:!0,createdAt:!0,lastSeenAt:!0}),a.object({name:a.string(),location:nr.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"}(sr||(sr={})),function(e){e.Hardware="hardware",e.Virtual="virtual"}(or||(or={})),function(e){e.Cloud="cloud",e.Web="web"}(ar||(ar={})),function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(cr||(cr={}));const lr=a.object({name:a.string(),category:a.string(),id:a.string(),type:a.enum(ar),version:a.string()}),ur=a.object({version:a.number(),contents:a.string(),contentsLength:a.number(),createdAt:a.string(),comments:a.string().optional()}),dr=a.object({id:a.string(),name:a.string(),uuid:a.string().optional(),version:a.number(),dataSources:a.array(a.object({host:a.string().optional(),stream:a.string(),blocks:a.array(a.string())})).optional(),protocolVersion:a.string(),linkedTutorial:a.string().optional(),blocks:a.array(lr),widgets:a.array(a.object({type:a.string(),name:a.string(),thingId:a.string()})).optional(),contents:a.string(),storage:a.string().optional(),history:a.array(ur).optional(),cloud:a.object({environment:a.enum(sr),enabled:a.boolean()}).optional()}),hr=a.object({recipeId:a.string(),version:a.number()});dr.extend({userId:a.string(),author:a.object({name:a.string(),id:a.string()}),copiedFrom:hr.optional(),updatedAt:a.string(),createdAt:a.string(),preview:a.string(),isPublic:a.boolean(),isDefault:a.boolean(),meta:a.object({contentsLength:a.number(),storageLength:a.number(),storageChecksum:a.string().optional()}),sharedWith:a.array(Zn),publicSharedId:a.string().optional(),marketplacePublication:a.string().optional()});const fr=dr.omit({id:!0,version:!0,contents:!0,storage:!0});var pr,gr,mr,yr,vr,br,wr,Sr;a.object({rawContents:a.string(),recipe:fr.extend({contentLength:a.number(),copiedFrom:hr.optional()}),storageSize:a.number().optional(),storageChecksum:a.string().optional(),comments:a.string().optional(),currentVersion:a.number().optional()}),a.object({message:a.string(),recipeId:a.string(),version:a.number(),versionHistory:a.array(ur)}),function(e){e.Bundle="bundle",e.Group="group"}(pr||(pr={})),function(e){e.Gateway="gateway",e.Timer="timer"}(gr||(gr={})),function(e){e.InstallInProgress="installation-in-progress"}(mr||(mr={})),function(e){e.InstallDependencies="install-dependencies",e.GetInstalledDependencies="get-installed-dep"}(yr||(yr={})),function(e){e.Success="success",e.Error="error",e.Pending="pending"}(vr||(vr={})),function(e){e.NotFound="not-found",e.BadRequest="bad-request",e.Forbidden="forbidden",e.InternalError="internal-error"}(br||(br={})),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"}(wr||(wr={})),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"}(Sr||(Sr={}));const _r=a.object({id:a.string(),name:a.string(),organizationId:a.string()}),Ir=a.object({version:a.number(),contents:a.string(),contentsLength:a.number(),createdAt:a.string(),title:a.string(),shortDescription:a.string(),comments:a.string().optional()}),xr=a.object({id:a.string(),title:a.string(),author:_r,shortDescription:a.string(),authorId:a.string(),category:a.string(),tags:a.array(a.string()),createdAt:a.string(),downloads:a.number().default(0),updatedAt:a.string(),iconSvg:a.string(),contents:a.string(),descriptionMarkdown:a.string(),githubUrl:a.string().optional(),visibility:a.enum(["public","private","organization"]),version:a.number(),history:a.array(Ir).default([]),deletedAt:a.string().optional()}),kr=xr.extend({rating:a.object({average:a.number(),total:a.number()}).optional()});a.object({id:a.string(),author:a.object({id:a.string(),name:a.string()}).optional(),description:a.string(),createdAt:a.string(),updatedAt:a.string(),snippetId:a.string(),deletedAt:a.string().optional(),isAbuseReport:a.boolean().optional(),reportReason:a.enum(["spam","inappropriate","not-working","security","other"]).optional()}),a.object({query:a.string().optional(),category:a.string().optional(),featured:a.boolean().optional(),recommended:a.boolean().optional(),sortBy:a.enum(["most_recent","most_liked","alphabetical"]).optional(),visibility:a.enum(["public","private","organization"]).optional(),page:a.number().optional(),limit:a.number().optional()}),a.object({snippets:a.array(kr),total:a.number(),page:a.number(),limit:a.number(),hasMore:a.boolean()}),a.object({snippetId:a.string(),rating:a.number(),off:a.boolean().optional()}),a.object({average:a.number(),total:a.number()}),a.object({success:a.boolean(),error:a.string().optional()}),a.object({snippet:a.lazy((()=>a.object({title:a.string(),shortDescription:a.string(),category:a.string(),tags:a.array(a.string()),iconSvg:a.string(),contents:a.string(),descriptionMarkdown:a.string(),githubUrl:a.string().optional(),visibility:a.enum(["public","private","organization"]),deletedAt:a.string().optional()})))}),a.object({snippet:a.lazy((()=>a.object({title:a.string(),shortDescription:a.string(),category:a.string(),tags:a.array(a.string()),iconSvg:a.string(),contents:a.string(),descriptionMarkdown:a.string(),githubUrl:a.string().optional(),visibility:a.enum(["public","private","organization"])})))}),a.object({snippet:xr}),a.object({snippet:xr}),a.object({snippetId:a.string(),version:a.number()}),a.object({snippet:xr});let Er=null;var Cr=()=>{if(!Er)throw new Error("Required function is not set");return Er};class Or 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 $r extends Error{constructor(e,t){super(e),this.name="UserCodeError",t&&(this.stack=t)}}const Nr=(e,t)=>`\n\t\tfunction _user_code_(){\n\t\t\t${t===cr.Browser?"\n\t\t\tvar global = {\n\t\t\t\t__user_code: true\n\t\t\t};\n\t\t\tvar process = {};\n\t\t\tvar globalThis = global;\n\t\t\tvar require = this.___notSupportedMethod;\n\t\t\t":"\n\t\t\tvar require = this.require;\n\t\t\tvar process = this.kemuProcess;\n\t\t\t"}\n\t\t\t\n\t\t\tvar console = this.console;\n\t\t\tvar eval = () => {};\n\t\t\tvar document = {};\n\t\t\tvar navigator = {};\n\t\t\tvar window = this.window;\n\t\t\tvar alert = this.notify.info;\n\t\t\tvar DataType = this.dataTypesEnum;\n\t\t\tvar setInterval = this.setInterval;\n\t\t\tvar setTimeout = this.setTimeout;\n\t\t\tvar addEventListener = this.addEventListener;\n\t\t\tvar removeEventListener = this.removeEventListener;\n\t\t\tvar requestAnimationFrame = this.___notSupportedMethod;\n\t\t\tvar __delay = (ms) => new Promise((resolve, reject) => setTimeout(resolve, ms, reject));\n\n\t\t\tvar Kemu = {\n\t\t\t\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\n\t\t\t\thelpers: {\n\t\t\t\t\tdecodeDataType: this.decodeDataType,\n\t\t\t\t\tcryptoJS: this.CryptoJS,\n\t\t\t\t\tjsonp: this.jsonp,\n\t\t\t\t\thttp: this.http,\n\t\t\t\t\tdelay: __delay,\n\t\t\t\t}\n\t\t\t};\n\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\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`,Mr=(e,t,n,r)=>{const i=Nr(e,n),a={...t,document:{},__errorTracer:e=>{if(e instanceof Or)throw e;throw new $r(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:qn.image,...n===cr.Cloud?{require:Cr(),kemuProcess:process.env.KEMU_PROCESS?process.env.KEMU_PROCESS:{}}:{},jsonp:s,CryptoJS:o,decodeDataType:Kn,window:{addEventListener:t?.addEventListener,removeEventListener:t?.removeEventListener}};try{const e="browser"===(()=>{if(te)return"browser";if(re)return"node";if(ne)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()(a)}}catch(e){return{error:{name:"CompileError",message:e.message,stack:e.stack}}}},Ar="main",Tr="My Script",Pr="This is a test script.",Dr=`\n/**\n * Name: ${Tr}\n * Description: ${Pr}\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(),jr=()=>({pauseExecution:!1,autoPauseOnError:!0,$$eventListeners:{},version:2,metadata:{name:Tr,description:Pr},pages:{[Ar]:{code:Dr,language:"javascript",name:"My First Script"}}}),Rr=(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 Nr(t,e).split(t)[0].split("\n").length+2})(t),n.column=i.column)}return e.message&&(n.message=e.message),n},Lr=(e,t)=>{const n={...{...jr(),...t.getState()},$$error:e||void 0};e&&console.error(e.message),t.setState(n)},Fr=new c;let Ur,Br,Wr={},Yr={};const Gr=e=>{const t=ue(Ur,Br,e);if(!t)throw new Error(`Widget ${e} not found in thing ${Br}`);return t},Hr=(e,t)=>`${e}:${t}`,Vr=e=>`${Gr(e.createdByWidgetId).id}::${e.variableName}`,zr=e=>`${pe}${e}`;var qr=e=>{const t=Gr(e.createdByWidgetId),n=Vr({variableName:e.variableName,createdByWidgetId:e.createdByWidgetId});Yr[n]={type:e.type,subscriberWidgetId:t.id,subscriberWidgetType:t.type}},Kr=e=>{const t=Vr({variableName:e.variableName,createdByWidgetId:e.createdByWidgetId});delete Yr[t]},Jr=async e=>{const t=Gr(e.setByWidgetId);if(!t)throw new Error(`Widget ${e.setByWidgetId} not found in thing ${Br} in recipe ${Ur}`);const n=e.variableName.startsWith(pe)?Vr({variableName:e.variableName,createdByWidgetId:e.setByWidgetId}):e.variableName;Wr[n]={value:e.value,type:e.type};const r={value:e.value,type:e.type,varName:e.variableName,isUIElement:e.variableName.startsWith(pe),setByWidgetType:t.type,setByWidgetId:e.setByWidgetId};await Fr.emit(Hr(e.variableName,e.type),r),e.type!==ye.Anything&&await Fr.emit(Hr(e.variableName,ye.Anything),r)},Zr=e=>{const{readerWidgetId:t,variableName:n}=e;if(!Gr(t))throw new Error(`Widget ${t} not found in thing ${Br} in recipe ${Ur}`);const r=n.startsWith(pe)?Vr({variableName:e.variableName,createdByWidgetId:e.readerWidgetId}):n,i=Wr[r];if(i)return{type:i.type,value:i.value}},Xr=e=>{const{widgetId:t,variableName:n,type:r}=e;if(!Gr(t))throw new Error(`Widget ${t} not found in thing ${Br} in recipe ${Ur}`);const i=Hr(n,r);let s;return s=Fr.on(i,(async r=>{ue(Ur,Br,t)?await e.onValueChange(r):(console.warn(`Zombie widget ${t} detected, unsubscribing from variable events "${n}"`),s?.())})),s},Qr=(e,t)=>{const n=Hr(e,ye.Anything);return Fr.on(n,(async e=>{const{isUIElement:n,...r}=e;await t(r)}))},ei=e=>{Yr={},Wr={},Ur=e.recipePoolId,Br=e.thingId};const ti="setTimeout",ni="variableChanged",ri=e=>{const{recipePoolId:t,thingId:n,scriptWidgetId:r}=e,i=ue(t,n,r);if(!i)throw new Error(`Widget "${r}" not found in recipe "${t}"`);const s=(e,t)=>{const n=Zr({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}},o=(t,n,s)=>{if(!e.setState)return void console.warn("Cannot subscribe to variable changes without a setState function");const o={...jr(),...e.getState()},a=Xr({variableName:t,type:ye.Anything,widgetId:r,onValueChange:async e=>{n?e.setByWidgetType===ze.widgetGroup&&e.setByWidgetId===i.groupId&&await s(e):s(e)}});delete o.$$eventListeners[t],o.$$eventListeners[t]={handler:s,abort:async()=>{a()},name:ni},e.setState(o)};return{get:s,set:async(e,t,n)=>{await Jr({variableName:e,type:n||Be(t),setByWidgetId:r,value:t})},onValueChange:(e,t)=>{o(e,!1,t)},onUIValueChange:(e,t)=>{const n=zr(e);o(n,!0,t)},getUIValue:e=>{const r=zr(e),o=s(r);if(o)return{value:o.value,type:o.type};const a=i.groupId;if(!a)throw new Error("You can only read UI variables from inside a widgetGroup");const c=ue(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.defaultValue;if(void 0===d)throw new Error(`Field "${e}" in widgetGroup "${l.name}" has no default value`);return{value:d,type:Be(d)}}}};let ii;var si=e=>{ii=e},oi=()=>{if(!ii)throw new Error("Hub Connector not set");return ii};const ai=new c,ci="invoked";let li={},ui={},di={},hi={};const fi=(e,t,n)=>`${e}-${t}${n?`-${n}`:""}`;var pi=e=>{const{data:t,thingId:n,widgetId:r,sourcePortName:i,recipeId:s,target:o,sourceOutputNames:a,currentPath:c,eventId:l}=e,u=fi(n,r,i),d=fi(n,r),h=fi(n,r,"produced"),f=di[d],p=Date.now();hi[d]=p,li[u]={data:t,recipeId:s,currentPath:c,eventId:l,source:{widgetId:r,portName:i},sourceOutputNames:a,...o?{target:{widgetId:o.widgetId,portName:o.portName}}:{}},ai.emit(h,{currentTime:p,prevTime:f,...o?{targetPort:o?.portName}:{}})},gi=e=>{const{thingId:t,widgetId:n,targetPortName:r,data:i,source:s,originalEvent:o,recipeId:a,sourceOutputNames:c,currentPath:l,eventId:u}=e,d=fi(t,n,r),h=fi(t,n),f=fi(t,n,ci),p=di[h],g=Date.now();di[h]=g,ui[d]={data:i,recipeId:a,originalEvent:o,sourceOutputNames:c,currentPath:l,eventId:u,target:{widgetId:n,portName:r},...s?{source:{widgetId:s.widgetId,portName:s.portName}}:{}},ai.emit(f,{prevTime:p,currentTime:g,targetPort:r,sourceInfo:s})},mi=()=>{li={},ui={},di={},hi={},ai.clearListeners()};const yi=e=>{const{recipePoolId:t,widgetId:n,secrets:r,clearExistingSecrets:i}=e,s=le({recipeId:t,widgetId:n});if(!s)throw new Error(`Widget [${n}] not found in recipe [${t}]`);i&&(s.secrets={});for(const e of r)s.secrets={...s.secrets,[e.name]:e}},vi=e=>{const{recipePoolId:t,widgetId:n}=e,r=le({recipeId:t,widgetId:n});if(!r)throw new Error(`Widget [${n}] not found in recipe [${t}]`);delete r.secrets},bi={},wi="value",Si=async e=>{const{recipeUuid:t,secretNames:n,serviceName:r}=e,i=oi(),s=[{recipeUuid:t,secretNames:n,serviceName:r}];let o={};try{const e=await i.executeHubFunction(Se.GetRecipeDecryptedSecretsValues,s);e&&(o=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 o},_i=e=>{const t=ae(e);if(!t)throw new Error(`Recipe [${e} does not exist]`);return{uuid:t.uuid,recipeType:t.dbInfo?.recipeType}};var Ii={onParentEvent:async(e,t,n,r)=>{const i={name:"",...r.getState()};if(!i.name||!e)return;const{uuid:s}=_i(r.recipePoolId);if(!s)throw new Error(`Recipe [${s}] does not have a valid id]`);const o=r.recipeType===me.Desktop,a=bi[r.id]?.[i.name];let c=a;if(!a||a&&!o){const e=await Si({recipeUuid:s,secretNames:[i.name]});c=e?.[i.name],null!=c&&o&&(bi[r.id]||(bi[r.id]={}),bi[r.id][i.name]=c)}if(null==c)throw new Error(`Secret "${i.name}" not mapped to this recipe`);r.nextWidget(wi,{type:ye.String,value:c})},getOutputNames:()=>[{name:wi,type:ye.String}],getInputNames:()=>[{name:"read",type:ye.Anything}],terminate:async e=>{bi[e.widgetId]={},vi({recipePoolId:e.recipePoolId,widgetId:e.widgetId})},initialize:async e=>{const t={name:"",...e.getState()};t.name&&(bi[e.widgetId]={},yi({recipePoolId:e.recipePoolId,widgetId:e.widgetId,secrets:[{name:t.name}]}))}};const xi={},ki=e=>{const{recipePoolId:t,thingId:n,scriptWidgetId:r}=e,i=ae(t),s=i?.dbInfo.recipeType,o=_i(t).uuid,a=ue(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=s===me.Desktop,n={};let i=[];for(const t of e){const e=xi[r]?.[t];null==e&&i.push(t)}if(t||(i=e),i.length>0){const t=await Si({recipeUuid:o,secretNames:i});for(const i of e){const e=t?.[i],s=xi[r]?.[i];n[i]=void 0!==e?e:void 0!==s?s:null}xi[r]={...xi[r],...n}}else for(const t of e)n[t]=xi[r]?.[t]||null;return n}},unregisteredSecrets:()=>{a&&(a.secrets={})}}},Ei=new c;let Ci={};const Oi="statusValueChanged",$i="keyRemovedFromWidget",Ni=()=>{Ci={}},Mi=()=>{Ei.clearListeners()},Ai=e=>{Ei.emit(Oi,e)};var Ti=e=>{const{name:t,value:n,sourceWidget:r,widgetId:i,widgetType:s}=e;Ci[i]=Ci[i]||[];const o=Ci[i].find((e=>e.name===t&&e.widgetType===s&&e.widgetId===i));o?o.data=n:Ci[i].push({name:t,data:n,sourceWidget:r,widgetId:i,widgetType:s});let a=n;null===n&&(a={type:ye.Anything,value:""}),Ai({name:t,value:a,sourceWidget:r,statusWidgetId:i,widgetType:s})},Pi=()=>{Ni(),Mi()},Di=e=>{const t=()=>{const e=[];for(const t in Ci)for(const n of Ci[t])e.push(n.name);return e},n=t();delete Ci[e];(e=>{Ei.emit($i,e)})({before:n,after:t()})};const ji=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},Ti({name:e,sourceWidget:t,widgetId:t,value:r,widgetType:ze.script})}},clearStatusValues:()=>{Di(t)}}},Ri="kemu.io.scriptHttp",Li=e=>{const{recipePoolId:t,widgetId:n,httpConfig:r}=e,i=oi();let s;const o=(e=>e.find((e=>e.name===Ri&&e.internal))||null)(i.getCachedServices().available);if(!o)throw new Error("HTTP service not found");const a={listener:{recipeId:t},targetService:{serviceName:Ri,version:"1.0.0"}};i.subscribeToServiceEvents(a);const c=i.onBroadcastEvent(n,Ri,"1.0.0",(e=>{const t=e.outputs?.find((e=>"stream"===e.name));if(t){const e=t.value;s=e.requestId,r.onStream&&r.onStream(e)}})),l=he(t),u={currentState:{},recipe:l,recipeType:l.type,widgetId:n,recipeId:t},d=(e,t)=>i.callProcessorHandler(o.sessionId,u,e,t,{timeout:0});return{promise:d("send",r),abort:async()=>{c(),s&&await d("abort",{requestId:s})}}},Fi="__command-compile__",Ui={};let Bi;const Wi=()=>{throw new Error("Method not implemented")},Yi=e=>{const{features:t,widgetContext:n,widgetEnvInfo:i}=e,s=(e,...t)=>{const r={...jr(),...n.getState()}.$$eventListeners[e];r&&r.handler(t)},o={};Object.keys(ye).forEach((e=>{o[e]=ye[e]}));const a=ki({recipePoolId:i.recipePoolId,thingId:i.thingId,scriptWidgetId:i.widgetId}),c=ji({scriptWidgetId:i.widgetId});a.unregisteredSecrets(),c.clearStatusValues(),Ui[i.widgetId]?.abortHttp?.().catch((e=>{console.warn("Error aborting old HTTP instance: ",e)}));return{logger:Vi(),dataTypesEnum:o,recipePoolId:i.recipePoolId,widgetId:i.widgetId,http:e=>{const{promise:t,abort:n}=Li({httpConfig:e,recipePoolId:i.recipePoolId,widgetId:i.widgetId});Ui[i.widgetId]={abortHttp:n};return t.abort=async()=>{delete Ui[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?ri({recipePoolId:i.recipePoolId,scriptWidgetId:i.widgetId,thingId:i.thingId,getState:n.getState,setState:n.setState}):{get:Wi,set:async()=>Wi(),onValueChange:Wi,onUIValueChange:Wi,getUIValue:Wi},statusManager:c.statusManager,secretsManager:a.secretsManager,setTimeout:(e,s,o)=>{if(t.withTimers&&n&&n.setState&&n.registerInterrupt){const t=r(),a={...jr(),...n.getState()};a.$$eventListeners[t]={handler:e,rejectHandler:o,name:ti},n.setState(a),n.registerInterrupt({type:"timeout",customTargetPortName:t,sourceWidgetId:i.widgetId,config:{timeout:s},customId:t})}},addEventListener:(e,t)=>{if(n.setState){const i=r(),o={...jr(),...n.getState()};o.$$eventListeners[i]={handler:t,name:e},n.setState(o),window.addEventListener(e,s.bind(i))}else console.warn(`Cannot remove event listener '${e}' because the widget context is not available.`)},removeEventListener:(e,t)=>{if(n.setState){const r={...jr(),...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.`)}}},Gi=(e,t,n)=>{const r={...jr(),...n.getState()},i=r.pages[Ar].$$compiledCode;if(i)return{compiledModule:i};{const i=Yi({features:e,widgetContext:n,widgetEnvInfo:t});return Mr(r.pages[Ar].code,i,n.recipeType)}},Hi=e=>e.map((e=>({...e,name:e.name.replace("_","")}))),Vi=()=>{const e=(e,...t)=>{if(Bi)try{return Bi[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)}}},zi=async(e,t)=>{const n={...e};for(const r in e){if(e[r].name===ti){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},qi=async e=>{const t={...e};for(const n in e){if(e[n].name===ni){const r=e[n]?.abort;if("function"==typeof r)try{await r()}catch(e){console.log("Error in abort interrupt handler: ",e)}delete t[n]}}return t},Ki=async(e,t,n)=>{let r={...jr(),...e.getState()};if(void 0!==n){r.pages[Ar]?.$$compiledCode?.onTerminate&&await(r.pages[Ar].$$compiledCode?.onTerminate());let t=await zi(r.$$eventListeners,e);t=await qi(t),r.$$eventListeners=t,r.pages[Ar].$$compiledCode=void 0,r.pages[Ar].code=n,e.setState({...r})}const i=!r.pages[Ar].$$compiledCode,{compiledModule:s,error:o}=Gi({variablesManager:!0,withTimers:!0},{recipePoolId:e.recipePoolId,thingId:e.thingRecipeId,widgetId:e.id},{getState:e.getState,setState:e.setState,recipeType:e.recipeType,registerInterrupt:e.registerInterrupt});if(o){console.log("Failed to compile user code");const t=Rr(o,e.recipeType);return Lr(t,e),null}if(s){let n;r={...e.getState()},r.pages[Ar].$$compiledCode=s;const o=Ji(r.pages[Ar].code);o?.name===r.metadata?.name&&o?.description===r.metadata?.description||(r.metadata=o||void 0);const a=e.nextWidget||e.nextGate;if(a&&s.setSendToPortFun(a),e.invokeNextWidget&&s.setSetOutputFn(e.invokeNextWidget),t)try{await s.recipeInit({setState:e.setState,getState:e.getState})}catch(t){n=Rr(t,e.recipeType)}if(a&&i)try{await s.main()}catch(t){n=Rr(t,e.recipeType)}r.$$lastInputs=s.getWidgetInputs?s.getWidgetInputs():[],r.$$lastOutputs=s.getWidgetOutputs?s.getWidgetOutputs():[],e.setState(r),Lr(n,e)}},Ji=e=>{const t=e.trimStart().match(/^(?:\/\*\*(?:[^*]|\*(?!\/))*\*\/|\/\*(?:[^*]|\*(?!\/))*\*\/)/);if(!t)return null;const n=t[0].replace(/^\/\*\*?/,"").replace(/\*\/$/,"").split("\n").map((e=>e.replace(/^\s*\*?\s?/,"").trim())).join("\n"),r=n.match(/Name\s*:\s*([^]*?)(?=\n\s*[A-Za-z]+\s*:|$)/i),i=n.match(/Description\s*:\s*([^]*?)(?=\n\s*[A-Za-z]+\s*:|$)/i),s={};return r&&r[1]&&(s.name=r[1].trim()),i&&i[1]&&(s.description=i[1].trim()),Object.keys(s).length>0?s:null};var Zi={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),s={...jr(),...i};if(!s.pages[Ar])return console.warn("Missing default page");if(Re(e?.name||""))return s.$$eventListeners[t.name]?(await s.$$eventListeners[t.name].handler(),s.$$eventListeners[t.name].name===ti&&delete s.$$eventListeners[t.name],void r.setState({...s})):void console.log(`Unknown interrupt id [${t.name}] `);const o=t.name===Fi;await Ki(r,!1,o?n.data.value:void 0);const a=s.pages[Ar].$$compiledCode;if(e&&e.name!==Fi&&a)try{await a.asyncProcessEvent(t,e,{...n,executionContext:{currentPath:r.currentPath,eventId:r.eventId}})}catch(e){if("UserCodeError"===e.name){const t=Rr(e,r.recipeType);throw Lr(t,r),t}throw e}},getInputNames:(e,t)=>{const n={...jr(),...e},{compiledModule:r}=Gi({},{recipePoolId:t.recipePoolId,thingId:t.thingRecipeId,widgetId:t.widgetId},{getState:()=>n,recipeType:t.recipeType});if(r?.getWidgetInputs){const e=r.getWidgetInputs();return Hi(e)}return e.$$lastInputs||[]},getOutputNames:(e,t)=>{const n={...jr(),...e},{compiledModule:r}=Gi({},{recipePoolId:t.recipePoolId,thingId:t.thingRecipeId,widgetId:t.widgetId},{getState:()=>n,recipeType:t.recipeType});if(r?.getWidgetOutputs){const e=r.getWidgetOutputs();return Hi(e)}return e.$$lastOutputs||[]},getDefaultState:jr,initialize:async e=>{const t=e.getState(),n={...jr(),...t};n.pages[Ar].code&&await Ki({getState:e.getState,id:e.widgetId,recipePoolId:e.recipePoolId,recipeType:e.recipeType,registerInterrupt:e.registerInterrupt,setState:e.setState,nextWidget:e.nextWidget,thingRecipeId:e.thingRecipeId,cancelInterrupt:()=>!0},!0,n.pages[Ar].code)},terminate:async e=>{try{const t=e.getState();t.pages[Ar].$$compiledCode?.onTerminate&&await t.pages[Ar].$$compiledCode.onTerminate();const n=e=>Qe.destroyInterrupt(e),r=await zi(t.$$eventListeners,{cancelInterrupt:n});await qi(r);const i=ji({scriptWidgetId:e.widgetId});ki({recipePoolId:e.recipePoolId,thingId:e.thingRecipeId,scriptWidgetId:e.widgetId}).unregisteredSecrets(),i.clearStatusValues();for(const e of Object.values(Ui))e.abortHttp?.().catch((e=>{console.warn("Error aborting old HTTP instance: ",e)}))}catch(t){console.warn(`Error terminating script widget ${e.widgetId}: `,t)}}};const Xi=async(e,t,n,r)=>{e.startsWith("data:image/")||(e=`data:image/png;base64,${e}`);const i=await Qi(e);return((e,t,n,r)=>{const i=r.getContext("2d");if(!i)throw new Error("Failed to get canvas context");const s=e.width,o=e.height;return r.width=t,r.height=n,i.drawImage(e,0,0,s,o,0,0,t,n),i.getImageData(0,0,t,n)})(i,n||i.naturalWidth,r||i.naturalHeight,t)},Qi=e=>new Promise(((t,n)=>{const r=new Image;r.onload=()=>t(r),r.onerror=e=>n(e),r.src=e})),es=Object.freeze({image:"image"}),ts=Object.freeze({base64:"base64"}),ns=()=>({});var rs={onParentEvent:async(e,t,n,r)=>{const i={...r.getState()};if(t.name===ts.base64){if("string"!=typeof n.data.value)return;if(n.data.type!==ye.String&&n.data.type!==ye.Anything)return;const e=n.data.value;te&&(i.$$memCanvas&&i.$$memCanvas.getContext||(i.$$memCanvas=Ce(320,240)));try{const t=await Xi(e,i.$$memCanvas,i.resize?.width,i.resize?.height);return r.setState(i),r.nextGate(es.image,{type:ye.ImageData,value:t})}catch(e){console.log("[base64ToImageData] Error: ",e)}}},getInputNames:()=>[{name:ts.base64,type:ye.String}],getOutputNames:()=>[{name:es.image,type:ye.ImageData}],getDefaultState:ns};const is=Object.freeze({object:"object",error:"error"}),ss=Object.freeze({string:"string"}),os=()=>({outputIsArray:!1});var as={onParentEvent:async(e,t,n,r)=>{const i={outputIsArray:!1,...r.getState()};if((n.data.type===ye.String||n.data.type===ye.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?ye.Array:ye.JsonObj,value:e})}catch(e){return r.nextGate("error",{type:ye.Boolean,value:!0})}},getInputNames:()=>[{name:ss.string,type:ye.String}],getOutputNames:e=>[{name:is.object,type:[ye.JsonObj,ye.Array],label:e.outputIsArray?"array":is.object},{name:is.error,type:ye.Boolean}],getDefaultState:os};const cs=Object.freeze({string:"string",length:"length"}),ls=Object.freeze({trigger:"trigger",setText:"setText"}),us=()=>({text:"",dispatchOnSet:!1});var ds={onParentEvent:async(e,t,n,r)=>{const i={text:"",dispatchOnSet:!1,...r.getState()};if(t.name===ls.setText){if(!((n.data.type===ye.String||n.data.type===ye.Anything)&&"string"==typeof n.data.value))return;if("string"==typeof n.data.value&&(i.text=n.data.value,r.setState(i)),!i.dispatchOnSet)return}const s=r.nextGate(cs.length,{type:ye.Number,value:i.text.length}),o=r.nextGate(cs.string,{type:ye.String,value:i.text});await Promise.all([s,o])},getInputNames:e=>{const t=[{name:ls.setText,type:ye.String}];return e.dispatchOnSet||t.push({name:ls.trigger,type:ye.Anything}),t},getOutputNames:()=>[{name:cs.string,type:ye.String},{name:cs.length,type:ye.Number}],getDefaultState:us};const hs=Object.freeze({image:"image"}),fs=Object.freeze({image:"image",x:"x",y:"y",width:"width",height:"height"}),ps=()=>({showInputPorts:!1});var gs={onParentEvent:async(e,t,n,r)=>{const i={showInputPorts:!1,...r.getState()};if("number"==typeof n.data.value)return t.name===fs.x&&(i.cropX=n.data.value),t.name===fs.y&&(i.cropY=n.data.value),t.name===fs.width&&(i.cropWidth=n.data.value),t.name===fs.height&&(i.cropHeight=n.data.value),void r.setState(i);if(t.name===fs.image){if(n.data.type!==ye.ImageData&&n.data.type!==ye.Anything)return;if(!Le(n.data.value))return;const e=n.data.value;if(i.$$memCanvas&&i.$$memCanvas.getContext||(i.$$memCanvas=Ce(320,240),i.$$memCanvasContext=Oe(i.$$memCanvas),r.setState(i)),!i.$$memCanvas||!i.$$memCanvasContext)return void console.error("Failed to get canvas or context");let t=e;return i.$$memCanvas.width=e.width,i.$$memCanvas.height=e.height,(i.cropX||i.cropY||i.cropWidth||i.cropHeight)&&(t=((e,t,n,r)=>{if(!n)return e;const i=Math.max(r.x||0,0),s=Math.max(r.y||0,0),o=e.width,a=e.height,c=Math.min(Math.ceil(r.width||o),o),l=Math.min(Math.ceil(r.height||a),a);return t.width=e.width,t.height=e.height,n.putImageData(e,0,0),n.drawImage(t,i,s,c,l,0,0,c,l),n.getImageData(0,0,c,l)})(e,i.$$memCanvas,i.$$memCanvasContext,{x:i.cropX,y:i.cropY,width:i.cropWidth,height:i.cropHeight})),r.nextGate(hs.image,{type:ye.ImageData,value:t})}},getInputNames:e=>{const t=[{name:fs.image,type:[ye.ImageData]}];return e.showInputPorts&&(t.push({name:fs.x,type:ye.Number}),t.push({name:fs.y,type:ye.Number}),t.push({name:fs.width,type:ye.Number}),t.push({name:fs.height,type:ye.Number})),t},getOutputNames:()=>[{name:hs.image,type:ye.ImageData}],getDefaultState:ps};const ms=Object.freeze({image:"image"}),ys=Object.freeze({image:"image",width:"width",height:"height"}),vs=()=>({showInputPorts:!1});var bs={onParentEvent:async(e,t,n,r)=>{const i={showInputPorts:!1,...r.getState()};if("number"==typeof n.data.value)return t.name===ys.width&&(i.width=n.data.value),t.name===ys.height&&(i.height=n.data.value),void r.setState(i);if(t.name===ys.image){if(n.data.type!==ye.ImageData&&n.data.type!==ye.Anything)return;if(!Le(n.data.value))return;const e=n.data.value;if(i.$$memCanvas&&i.$$memCanvas.getContext||(i.$$memCanvas=Ce(320,240),i.$$tempCanvas=Ce(320,240),r.setState(i)),!i.$$memCanvas||!i.$$tempCanvas)return;let t=e;return(i.width||i.height)&&(t=((e,t,n,r,i)=>{if(!r&&!i)return e;r&&!i?i=r*(e.height/e.width):!r&&i&&(r=i*(e.width/e.height));const s=Math.max(1,r||e.width),o=Math.max(1,i||e.height);n.width===e.width&&n.height===e.height||(n.width=e.width,n.height=e.height),t.width=s,t.height=o;const a=Oe(t),c=Oe(n);if(!a||!c)throw new Error("Failed to get canvas context");return c.putImageData(e,0,0),a.drawImage(n,0,0,e.width,e.height,0,0,s,o),a.getImageData(0,0,s,o)})(e,i.$$memCanvas,i.$$tempCanvas,i.width,i.height)),r.nextGate(ms.image,{type:ye.ImageData,value:t})}},getInputNames:e=>{const t=[{name:ys.image,type:ye.ImageData}];return e.showInputPorts&&(t.push({name:ys.width,type:ye.Number}),t.push({name:ys.height,type:ye.Number})),t},getOutputNames:()=>[{name:ms.image,type:ye.ImageData}],getDefaultState:vs};const ws=Object.freeze({value:"value"}),Ss=Object.freeze({trigger:"trigger",setValue:"setValue"}),_s=()=>({value:0,dispatchOnSet:!1});var Is={onParentEvent:async(e,t,n,r)=>{const i={value:0,dispatchOnSet:!1,...r.getState()};if(t.name===Ss.setValue){const e=n.data.type===ye.Number||n.data.type===ye.Anything||n.data.type===ye.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(ws.value,{type:ye.Number,value:i.value})},getInputNames:e=>{const t=[{name:Ss.setValue,type:ye.Number}];return e.dispatchOnSet||t.push({name:Ss.trigger,type:ye.Anything}),t},getOutputNames:()=>[{name:ws.value,type:ye.Number}],getDefaultState:_s};const xs=Object.freeze({image:"image"}),ks=Object.freeze({image:"image"}),Es=()=>({anchors:[],vertices:[],matrix:[]}),Cs={onParentEvent:async(e,t,n,r)=>{const i={anchors:[],vertices:[],matrix:[],...r.getState()},s=window,o=n.data.type===ye.ImageData;if(s.Speedy&&o){const e=s.Speedy,t=n.data.value;let o,u,d,h=i.$$private?.canvas,f=i.$$private?.context,p={...i};const g=4===i.anchors.length;if(i.$$private?.pipeline)o=i.$$private?.pipeline,u=i.$$private?.source;else{o=e.Pipeline(),u=e.Image.Source();const n=e.Image.Sink();d=e.Transform.PerspectiveWarp(),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=Ce(c,l),f=h.getContext("2d")),u.output().connectTo(d.input()),d.output().connectTo(n.input()),o.init(u,n,d);let r=e.Matrix(3,3,[1,0,0,0,1,0,0,0,1]);if(4===i.anchors.length){const t=e.Matrix(2,4,[(a=i.anchors)[0].x,a[0].y,a[1].x,a[1].y,a[2].x,a[2].y,a[3].x,a[3].y]),n=e.Matrix(2,4,i.vertices.reduce(((e,t)=>e.concat([t.x,t.y])),[])),s=e.Matrix.Zeros(3,3);await e.Matrix.perspective(s,t,n);const o=s.read();r=e.Matrix(3,3,o)}d.transform=r,p={...p,$$private:{...p.$$private,canvas:h,context:f,perspective:d,pipeline:o,source:u}}}let m=t;if(g){const e=await(async(e,t)=>{const n=window,r=e.$$private?.source,i=e.$$private?.pipeline;if(n.Speedy&&r&&i){const e=n.Speedy,s=await createImageBitmap(t),o=await e.load(s);return r.media=o,(await i.run()).image.source}return null})(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(xs.image,{type:ye.ImageData,value:m})}var a,c,l;console.log("Environment not supported")},getInputNames:()=>[{name:ks.image,type:ye.ImageData}],getOutputNames:()=>[{name:xs.image,type:ye.ImageData}],getDefaultState:Es,terminate:async e=>{const t=e.getState();t.$$private?.pipeline.release()}},Os=Object.freeze({event:"event"}),$s="1",Ns="2",Ms="3";var As={onParentEvent:async(e,t,n,r)=>{const i={...r.getState()};r.setState({...i,$$lastEventType:n.data.type}),await r.nextGate($s,n.data),await r.nextGate(Ns,n.data),await r.nextGate(Ms,n.data)},getInputNames:()=>[{name:Os.event,type:ye.Anything}],getOutputNames:e=>{const t={type:{...e}.$$lastEventType??ye.Anything};return[{name:$s,...t},{name:Ns,...t},{name:Ms,...t}]}};const Ts=()=>({name:"myVar",type:ye.Anything,reactive:!0,defaultValue:""}),Ps=Object.freeze({set:"set",read:"read"}),Ds="value";var js={onParentEvent:async(e,t,n,r)=>{const i=r.getState(),s={...Ts(),...i};if(t.name!==Ps.set){if(t.name===Ps.read){const e=Zr({variableName:s.name,readerWidgetId:r.id}),t=e?e.value:s.defaultValue;await r.nextWidget(Ds,{type:s.type,value:t})}}else{if(n.data.type!==s.type&&s.type!==ye.Anything)return;await Jr({variableName:s.name,value:n.data.value,setByWidgetId:r.id,type:s.type})}},getInputNames:e=>{const t={...e};return[{name:Ps.set,type:t.type||ye.Anything},{name:Ps.read,type:ye.Anything}]},getOutputNames:e=>{const t={...e};return[{name:Ds,type:t.type||ye.Anything}]},initialize:async e=>{const t=e.getState(),n={...Ts(),...t};if(n.$$abortListener)try{n.$$abortListener()}catch(t){console.warn(`Error aborting variable listener for widget ${e.widgetId}: `,t)}qr({variableName:n.name,type:n.type,createdByWidgetId:e.widgetId});const r=Xr({variableName:n.name,type:n.type,widgetId:e.widgetId,onValueChange:async t=>{const n=e.getState();void 0!==t.value&&(n.type!==ye.Anything&&t.type!==n.type||n.reactive&&await e.nextWidget(Ds,{type:t.type,value:t.value}))}});e.setState({...n,$$abortListener:r})},terminate:async e=>{const t=e.getState(),n={...Ts(),...t};n.$$abortListener&&n.$$abortListener(),Kr({variableName:n.name,createdByWidgetId:e.widgetId})}};const Rs=async(e,t=!1)=>{const n=oi();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 Ls={onParentEvent:async(e,t,n,r)=>{const i={dynamicInputs:{},dynamicOutputs:{},customState:{},...r.getState()};if(!e)return;const s=ae(r.recipePoolId);if(!s)throw new Error(`Recipe [${r.recipePoolId}] not found`);const o=oi();let a=i.$$$serviceId;if(!a){const e=o.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=s?.name||"";return o.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:s.uuid,poolId:r.recipePoolId,name:h,type:r.recipeType,version:s.dbInfo.version,authorId:s.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=ae(e.recipePoolId),r=n?.name||"",i=oi(),s=await Rs(t);if(s)try{return await i.initializeServiceInstance({recipePoolId:e.recipePoolId,sessionId:s,recipeName:r,widgetId:e.widgetId,recipeType:e.recipeType,variantId:t.variantId})}catch(t){if("FNC_NOT_FOUND"!==t?.errCode){if(!!("string"!=typeof t||!t.match('^Function ".*" not found.$')))throw t;console.warn(`Widget [${e.widgetId}] does not have an init function.`)}}else console.log(`Aborting service initialization, "${t.service?.name}" was not found in the current Hub.`)},terminate:async e=>{const t={dynamicInputs:{},dynamicOutputs:{},customState:{},...e.getState()},n=oi(),r=await Rs(t,!0);if(r)return n.terminateServiceInstance(r,e.widgetId,e.recipePoolId,t.variantId)}};const Fs=Object.freeze({Image:"image"}),Us=Object.freeze({Image:"image"}),Bs=()=>({filters:[{name:"grayscale",value:"0.5",id:"d-1"}]});var Ws={onParentEvent:async(e,t,n,r)=>{const i={filters:[{name:"grayscale",value:"0.5",id:"d-1"}],...r.getState()};if(t.name===Fs.Image&&n.data.type===ye.ImageData){if(!Le(n.data.value))return void console.log("ImageFilter: Invalid image data type, aborting process");const e=n.data.value;i.$$memCanvas?.getContext||(i.$$memCanvas=Ce(e.width,e.height)),i.$$context?.drawImage||(i.$$context=i.$$memCanvas.getContext("2d")),i.$$memCanvas.width!==e.width&&(i.$$memCanvas.width=e.width),i.$$memCanvas.height!==e.height&&(i.$$memCanvas.height=e.height),r.setState(i),i.$$context.putImageData(e,0,0),i.filters.length?i.$$context.filter=i.filters.map((e=>{let t="";return"blur"===e.name?t="px":"hue-rotate"===e.name&&(t="deg"),`${e.name}(${parseFloat(e.value)}${t})`})).join(" "):i.$$context.filter="none",i.$$context.drawImage(i.$$memCanvas,0,0);const t=i.$$context.getImageData(0,0,e.width,e.height);return r.nextWidget(Us.Image,{type:ye.ImageData,value:t})}},getInputNames:()=>[{name:Fs.Image,type:ye.ImageData}],getOutputNames:()=>[{name:Us.Image,type:ye.ImageData}],getDefaultState:Bs};const Ys="loaded";var Gs={onParentEvent:async(e,t,n,r)=>r.nextWidget(Ys,{value:!0,type:ye.Boolean}),getInputNames:()=>[],getOutputNames:()=>[{name:Ys,type:ye.Boolean,description:"Triggered when the recipe is fully loaded"}]};var Hs={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 ye.Number:case ye.Boolean:case ye.String:return String(e);case ye.Array:case ye.JsonObj:case ye.Rect:case ye.Point:return JSON.stringify(e,((e,t)=>"bigint"==typeof t?t.toString():t));case ye.ArrayBuffer:if(e instanceof ArrayBuffer){if(re)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 ye.ImageData:{if(!Le(e))throw new Error("Expected ImageData");const t=e,n=Ce(t.width,t.height),r=Oe(n);if(!r)throw new Error("Failed to get canvas context");r.putImageData(t,0,0);const i=n.toDataURL("image/png");if(!i)throw new Error("Failed to convert canvas to data URL");return i.split(",")[1]}default:return String(e)}})(n.data.value,n.data.type);return r.nextWidget("text",{type:ye.String,value:e})}catch(e){return r.nextWidget("error",{type:ye.String,value:e instanceof Error?e.message:"Failed to stringify object"})}},getInputNames:()=>[{name:"object",type:[ye.Number,ye.String,ye.ArrayBuffer,ye.Array,ye.Boolean,ye.JsonObj,ye.Rect,ye.Point,ye.ImageData]}],getOutputNames:()=>[{name:"text",type:ye.String},{name:"error",type:ye.String}],getDefaultState:()=>({})};const zs=e=>{if(Array.isArray(e))return e.map(((e,t,n)=>null===e||"object"!=typeof e?{value:e,"@index":t,"@indexPlus1":t+1,"@isFirst":0===t,"@isLast":t===n.length-1}:{...zs(e),"@index":t,"@indexPlus1":t+1,"@isFirst":0===t,"@isLast":t===n.length-1}));if("object"==typeof e&&null!==e){const t={};for(const n in e){const r=e[n];t[n]=zs(r)}return t}return e},qs=(e,t)=>{const n=(e=>{const t=new Date;return{input:"object"==typeof e&&null!==e?zs(e):{value:e},date:{year:t.getFullYear(),month:t.getMonth()+1,day:t.getDate(),hours:t.getHours(),minutes:t.getMinutes(),seconds:t.getSeconds(),milliseconds:t.getMilliseconds(),time:t.getTime(),dayOfWeek:t.getDay(),dayName:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][t.getDay()],shortDayName:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"][t.getDay()],date:t.getDate(),fullYear:t.getFullYear(),timezoneOffset:t.getTimezoneOffset(),UTCDate:t.getUTCDate(),UTCDay:t.getUTCDay(),UTCFullYear:t.getUTCFullYear(),UTCHours:t.getUTCHours(),UTCMilliseconds:t.getUTCMilliseconds(),UTCMonth:t.getUTCMonth()+1,UTCMinutes:t.getUTCMinutes(),UTCSeconds:t.getUTCSeconds(),isoString:t.toISOString(),localeString:t.toLocaleString()}}})(t);return l.render(e,n)},Ks=()=>({text:"",format:"Text"});var Js={onParentEvent:async(e,t,n,r)=>{const i={text:"",format:"Text",...r.getState()},s=qs(i.text,n.data.value);return r.nextWidget("text",{type:ye.String,value:s})},getInputNames:()=>[{name:"input",type:ye.Anything}],getOutputNames:()=>[{name:"text",type:ye.String}],getDefaultState:Ks};const Zs=()=>({expression:""});var Xs={onParentEvent:async(e,t,n,r)=>{const i={expression:"",...r.getState()},s=((e,t)=>{const n=Symbol("error"),r=`\n // 'data' is an argument to this function, passed by new Function call.\n // 'SError' is also an argument, providing the error symbol.\n // 'expression' is also an argument, providing the expression string for validation.\n // 'this' inside this function (created by new Function) is the global object.\n\n\t\t// Shadow eval and Function in this non-strict scope.\n\t\tvar eval = undefined;\n\t\tvar Function = undefined;\n\n // Define the sandbox environment\n const sandboxEnvironment = {\n // Make input 'data' accessible\n data: data,\n \n // Safe console (bind methods to the original console)\n console: undefined,\n\n // Mocked/disabled globals\n process: undefined,\n document: undefined,\n navigator: undefined,\n \n require: undefined,\n // eval and Function are shadowed by var declarations above\n \n // Allowed safe globals (pointing to the real ones, accessed via 'this')\n Math: this.Math,\n Date: this.Date,\n JSON: this.JSON,\n Array: this.Array,\n Object: this.Object,\n String: this.String,\n Number: this.Number,\n Boolean: this.Boolean,\n RegExp: this.RegExp,\n // Error: this.Error, // Not Allow Error constructor\n Symbol: this.Symbol, // Allow Symbol constructor\n Map: this.Map,\n Set: this.Set,\n Promise: this.Promise, // Allow Promise if async expressions are intended\n // setTimeout, setInterval, fetch, etc., are deliberately omitted\n };\n\n // Assign the sandboxEnvironment to act as the 'global' context variables\n const global = sandboxEnvironment;\n const window = sandboxEnvironment;\n const globalThis = sandboxEnvironment;\n\n // Shadow top-level variables that might be accessed directly,\n // ensuring they use the sandboxed versions.\n const process = sandboxEnvironment.process;\n const document = sandboxEnvironment.document;\n const navigator = sandboxEnvironment.navigator;\n const console = sandboxEnvironment.console; // Use the sandboxed console for the expression\n const require = sandboxEnvironment.require;\n // 'eval' and 'Function' are already shadowed by var declarations\n\n // The expression will be evaluated in this scope.\n // 'data' is available as it's an argument to the outer function.\n // 'global.xxx' will resolve to 'sandboxEnvironment.xxx'.\n // 'process.yyy' will resolve to 'sandboxEnvironment.process.yyy'.\n \n return () => {\n "use strict"; // Apply strict mode only to the expression evaluation scope\n const abort = Symbol('abort'); // Local symbol for the expression's optional special return value\n\n let result;\n try {\n // Strict mode can add a layer of security and prevent some common errors.\n // It also changes 'this' binding within the expression if it uses 'this'.\n // If the expression uses 'this', under strict mode it would be undefined unless explicitly set.\n // For expressions not using 'this', strict mode is generally safer.\n result = (() => { return ${t}; })();\n } catch(e) {\n // Log the error using the sandboxed console\n // Use 'instanceof Error' to ensure 'e' has a message property.\n const errorMessage = e instanceof Error ? e.message : String(e);\n return {\n\t\t\t\t\terror: 'Error during expression execution: ' + errorMessage, \n\t\t\t\t\tvalue: null\n\t\t\t\t}; // Return the SError symbol passed into this function's scope\n }\n \n\t\t\t// allows ternary expressions that return 'abort' to cancel the evaluation\n if (result !== abort) {\n // Always return the actual result of the expression evaluation\n return {value: result, error: null};\n }\n \n // If the expression explicitly returned the 'abort' symbol\n return {value: abort, error: null}; \n }\n // End of functionBody template literal\n `;try{return new Function("data","SError","expression",r)(e,n,t).call({})}catch(e){return{error:e.message,value:null}}})(n.data.value,i.expression);if("symbol"==typeof s.value)return;if(s.error)throw new Error(s.error);if(Number.isNaN(s.value))throw new Error("Expression resulted in NaN");if(void 0===s.value||null===s.value)return;const o=Be(s.value);return o!==i.$$lastResultType&&r.setState({...i,$$lastResultType:o}),r.nextWidget("result",{type:o,value:s.value})},getInputNames:()=>[{name:"data",type:ye.Anything}],getOutputNames:e=>[{name:"result",type:e.$$lastResultType||ye.Anything}],getDefaultState:Zs};var Qs={onParentEvent:async(e,t,n,r)=>{const i={...r.getState()};r.setState({...i,$$lastEventType:n.data.type});try{await r.nextWidget("event",n.data)}catch(e){const t=e;await r.nextWidget("error",{type:ye.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:ye.Anything}],getOutputNames:e=>[{name:"event",type:{...e}.$$lastEventType??ye.Anything},{name:"error",type:ye.JsonObj,jsonShape:{error:ye.JsonObj,inputEvent:ye.JsonObj}}]};const eo={},to=Object.freeze({output:"output"}),no=Object.freeze({read:"read",clear:"clear"}),ro=()=>({$$$time:0,totalInputs:1});var io={onParentEvent:async(e,t,n,r)=>{const i={$$$time:0,totalInputs:1,...r.getState()};if(eo[r.id]||(eo[r.id]={}),t.name===no.clear)return eo[r.id]={},void r.setState(i);const s=t.name===no.read;if(!(s||n.data.type!==ye.JsonObj&&n.data.type!==ye.Anything&&n.data.type!==ye.Rect||"object"!=typeof n.data.value||null===n.data.value||Array.isArray(n.data.value))){const e=eo[r.id]||{};eo[r.id]={...e,...n.data.value}}if(s){const e={...eo[r.id]};return eo[r.id]={},r.setState({...i}),r.nextWidget(to.output,{type:ye.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:ye.Anything})));return n.push({name:no.clear,type:ye.Anything},{name:no.read,type:ye.Anything,triggerPort:!0}),n},getOutputNames:()=>[{name:to.output,type:ye.JsonObj}],getDefaultState:ro,initialize:async e=>{eo[e.widgetId]={}},terminate:async e=>{delete eo[e.widgetId]}};const so={},oo=Object.freeze({output:"output",index:"index",finish:"finish"}),ao=Object.freeze({array:"array",next:"next",clear:"clear"}),co=()=>({autoLoop:!1,autoClear:!1,$$outputType:ye.Anything,totalItems:0,currentIndex:0});const lo={input:lt,counter:ht,elapsed:gt,ifGate:bt,skipEvent:It,between:Ct,map:Nt,parser:Tt,slider:jt,suspend:Ut,display:Wt,json:Ht,arrayItem:qt,extractImage:Qt,imageConvolution:sn,firstEvent:ln,pixelDraw:yn,randomBetween:Sn,arrayCombine:En,clock:Nn,multiplication:Pn,object:Wn,widgetGroup:Vn,script:Zi,base64ToImageData:rs,jsonParse:as,text:ds,imageCrop:gs,imageResize:bs,value:Is,imageWarp:Cs,sequence:As,variable:js,hubService:Ls,imageFilter:Ws,recipeLoad:Gs,note:Hs,stringify:Vs,templateString:Js,expressionEval:Xs,rescue:Qs,objectCombine:io,loop:{onParentEvent:async(e,t,n,r)=>{const i=r.getState(),s={...co(),...i};if(t.name===ao.clear)return delete so[r.id],void r.setState({...co(),autoLoop:s.autoLoop,autoClear:s.autoClear});if(t.name!==ao.array)t.name===ao.next&&await(async e=>{const t=e.id,n=so[t],r={...co(),...e.getState()};if(n&&n.index<n.list.length){const i=n.index,s=n.list[i];await e.nextWidget(oo.index,{type:ye.Number,value:i}),await e.nextWidget(oo.output,{type:r.$$outputType,value:s}),n.index++,e.setState({...r,currentIndex:n.index}),n.index===n.list.length&&(await e.nextWidget(oo.finish,{type:ye.Boolean,value:!0}),r.autoClear?(delete so[t],e.setState({...co()})):(n.index=0,e.setState({...r,currentIndex:0})))}})(r);else if((n.data.type===ye.Array||n.data.type===ye.Anything)&&Array.isArray(n.data.value)){const e=n.data.value,t=e[0],i=void 0!==t?Be(t):ye.Anything,o={list:e,index:0};so[r.id]=o;const a={...s,$$outputType:i,totalItems:e.length,currentIndex:0};if(r.setState(a),a.autoLoop&&e.length>0){for(const t of e){const e=o.index;r.setState({...a,currentIndex:e}),await r.nextWidget(oo.index,{type:ye.Number,value:e}),await r.nextWidget(oo.output,{type:a.$$outputType,value:t}),o.index++}await r.nextWidget(oo.finish,{type:ye.Boolean,value:!0}),a.autoClear?(delete so[r.id],r.setState({...a,$$outputType:ye.Anything,totalItems:0,currentIndex:0})):(o.index=0,r.setState({...a,currentIndex:0}))}}},getInputNames:()=>[{name:ao.array,type:ye.Array},{name:ao.next,type:ye.Anything},{name:ao.clear,type:ye.Anything}],getOutputNames:e=>{const t={...co(),...e};return[{name:oo.index,type:ye.Number},{name:oo.output,type:t.$$outputType},{name:oo.finish,type:ye.Anything}]},getDefaultState:co,initialize:async e=>{const t={...co(),...e.getState()};so[e.widgetId]={list:[],index:0},e.setState({...t,currentIndex:0,totalItems:0})},terminate:async e=>{delete so[e.widgetId]}},status:{onParentEvent:async(e,t,n,r)=>{const i={name:"",...r.getState()};i.name&&e&&Ti({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:ye.Anything}],terminate:async e=>{Di(e.widgetId)},initialize:async e=>{const t={name:"",...e.getState()};Ti({name:t.name||"",sourceWidget:"",widgetType:ze.status,widgetId:e.widgetId,value:null})}},secret:Ii,output:{onParentEvent:async(e,t,n,r)=>{if(!r.eventContext)return;const i=r.eventContext;if(i?.eventKey)return ot(i.eventKey,n.data.value);console.error("No event key found in context event")},getOutputNames:()=>[],getInputNames:()=>[{name:"event",type:ye.Anything}]},play:{getInputNames:()=>[],onParentEvent:()=>Promise.resolve(),getOutputNames:()=>[{name:"out",type:ye.Boolean}]}},uo={},ho=async()=>{if(!Object.keys(uo).length)for(const e in lo){const t=lo[e];uo[e]=Object.freeze({...t})}};var fo=e=>{if(uo[e])return uo[e];throw new Error(nt(tt,e))},po=ho;const go={};let mo={};const yo=new c;let vo=!1,bo=!1,wo=!1,So=null,_o=null;const Io="processing-state-change",xo="error-event",ko={abortRequested:!1,isPaused:!1,pausePromise:null,pausePromiseResolve:null,lastPausedWidgetId:null},Eo=e=>(_o=e,yo.emit(Io,e)),Co=(e,t)=>`${e}-${t}`,Oo=(e,t)=>`state-change:${Co(e,t)}`,$o=e=>{const{thingId:t,widgetId:n}=e,r=Co(t,n);return go[r]||{isProcessing:!1}},No=()=>{ko.abortRequested=!1,ko.isPaused=!1},Mo=e=>(ko.pausePromise||(ko.isPaused=!0,ko.pausePromise=new Promise((e=>{ko.pausePromiseResolve=e})),e&&(ko.lastPausedWidgetId=e),Eo({isProcessing:!0,isPaused:!0,...e?{pauseTrapWidgetId:e}:{}})),ko.pausePromise);var Ao,To,Po=async e=>{const{thingId:t,widgetId:n}=e,r=Co(t,n),i=Oo(t,n),s=$o({thingId:t,widgetId:n});if(s.isProcessing)return;const o={isProcessing:!0,isPaused:!1,startTime:Date.now()};go[r]=o,vo||(vo=!0,So=null,await Eo({isProcessing:!0,isPaused:!1})),await yo.emit(i,{thingId:t,widgetId:n,prevState:s,newState:o})},Do=async e=>{const{thingId:t,widgetId:n,error:r}=e,i=Co(t,n),s=Oo(t,n),o=$o({thingId:t,widgetId:n}),a={isProcessing:!1,isPaused:!1,startTime:o.startTime,endTime:Date.now(),error:r};go[i]=a,await yo.emit(s,{thingId:t,widgetId:n,prevState:o,newState:a}),r&&(So=r,await yo.emit(xo,r)),vo&&0===Object.values(go).filter((e=>e.isProcessing)).length&&(vo=!1,bo=!1,No(),await Eo({isProcessing:!1,isPaused:!1}))},jo=()=>{vo=!1;for(const e in go)delete go[e];ko.abortRequested=!1,ko.isPaused=!1,ko.pausePromise=null,ko.pausePromiseResolve=null,ko.lastPausedWidgetId=null,yo.clearListeners()},Ro=()=>ko.abortRequested,Lo=e=>{ko.lastPausedWidgetId=e,ko.isPaused=!0,Eo({isProcessing:!0,isPaused:!0,pauseTrapWidgetId:e})},Fo=()=>bo||wo?null:ko.pausePromise,Uo=e=>wo?null:mo[e]??null,Bo=()=>bo,Wo=e=>Mo(e);!function(e){e.ServiceCreationLog="service-creation-log"}(Ao||(Ao={})),function(e){e.Service="service",e.ServiceUI="serviceUI"}(To||(To={}));let Yo={},Go=0,Ho=null;const Vo=(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,s=r.service?.name;return!(!i||!s||i!==s)}return e.type===ze.output&&t.type===ze.input},zo=e=>{const{widgetId:t,widgets:n,currentPath:r}=e,i=n[t];if(!i)return[];const s=new Map;for(let e=0;e<r.length;e++){const t=r.slice(0,e+1),o=t.join("/"),a=Yo[o];if(a){const c=n[a.widgetId];if(c){const n=a.path,l=r.join("/").startsWith(n);Vo(i,c)&&l&&(s.has(o)||s.set(o,{path:o,data:a,pathSegments:t.length,pathIndex:e,invocationOrder:a.invocationOrder,timestamp:a.timestamp}))}}}const o=Array.from(s.values()).sort(((e,t)=>e.pathIndex-t.pathIndex));return o},qo=e=>{const{context:t,widgetId:n,currentPath:r,executionId:i="default"}=e;if(Go++,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 s=r.join("/");Yo[s]={path:s,eventContext:t,widgetId:n,invocationOrder:Go,timestamp:Date.now(),executionId:i}},Ko=e=>{const t=zo(e);return t.length>0?t[t.length-1]:null},Jo=()=>{Yo={},Go=0},Zo=e=>{Ho=e},Xo=()=>{Yo={},Go=0};let Qo,ea,ta,na=!1,ra=0,ia=0;const sa=async e=>{const{widgetId:t,thingId:n,recipeId:r,targetPortName:i,data:s}=e,o=ce(r,n);if(!o)return;const a=o.gates[t];if(!a||a.disabled)return;const c={...s,timestamp:Date.now()},l=fo(a.type);ia+=1;const u=ua({gateId:t,originalEvent:c,blockRecipeId:o.recipeId,blockDbId:o.id,blockVersion:o.version,recipeId:r,sourceWidgetId:void 0,currentPath:[],eventId:ia});if(u&&l.onParentEvent){const e={name:i};return Qo&&await Qo({recipeId:r,blockId:o.recipeId,gateId:t,targetPort:e.name,data:s}),l.onParentEvent(null,e,{originalEvent:c,data:{...c}},u)}},oa=async e=>{const{eventContext:t,interruptDriven:n,childGateId:r,recipeId:i,sourcePortName:s,targetPort:o,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:ye.Boolean,value:!0});const p=h;if("string"==typeof f){const e=ce(i,f);if(!e)return;f=e}const g=f.gates[r];if(!g||g.disabled)return;const m=c.findIndex((e=>e.name===s)),y=fo(g.type),v=[...e.currentPath];if(l){0===v.length?v.push(`${l}:${d?.toString()}`):v.push(l)}if(t){const e=le({recipeId:i,widgetId:l});e?.type!==ze.hubService&&e?.type!==ze.input||qo({context:t,widgetId:l,currentPath:v,executionId:d?.toString()})}const b=ua({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){Qo&&await Qo({recipeId:i,blockId:f.recipeId,gateId:r,targetPort:o.name,data:a,sourceGate:n?"interrupt_widget":l,sourcePort:n?fe:s});const e={name:c[m].name,type:c[m].type,...c[m].jsonShape?{jsonShape:c[m].jsonShape}:void 0,sourceWidgetId:l};return u||gi({thingId:f.recipeId,widgetId:r,sourceOutputNames:c,targetPortName:o.name,currentPath:v,eventId:d,data:a,originalEvent:p,recipeId:i,source:l?{widgetId:l,portName:s}:void 0}),y.onParentEvent(e,o,{originalEvent:p,data:a},b)}},aa=async e=>{const{portName:t,originalEvent:n,data:r,currentGateId:i,blockRecipeId:s,thingDbId:o,thingVersion:a,recipeId:c,eventContext:l,currentPath:u}=e;let{eventId:d}=e;const h=ae(c);if(!h)throw new Error(`Failed to find recipe "${c}" in cache`);const f=h.dbInfo.recipeType,p=ue(c,s,i);if(!p)return;const g={...r,timestamp:n.timestamp},m=fo(p.type);let y;y=p.type===ze.input?m.getOutputNames(p.state,{thingRecipeId:s,thingDbId:o,thingVersion:a,id:i,recipeId:c,recipeType:f,recipePoolId:c}):await m.getOutputNames(p.state,{recipePoolId:c,recipeType:f,thingRecipeId:s,widgetId:i});if(-1!==y.findIndex((e=>e.name===t))){const e=ce(c,s);if(!e)return;null===d&&(ia+=1,d=ia),pi({thingId:s,widgetId:i,sourceOutputNames:y,sourcePortName:t,currentPath:u,data:g,recipeId:c,eventId:d});let r=null;const o=p.children.length,a=u;try{for(let u=0;u<o;u++){const o=e.gates[p.children[u].childId];if(o?.disabled)continue;const h=Ge(p.children[u]?.sourcePort),m=Ge(p.children[u]?.targetPort);if(h.portName===t&&o&&!o.disabled){if(na&&Fo()&&(Lo(o.id),await Fo()),Uo(o.id)&&!Bo()&&"innerInput"!==m?.portType){const e=Wo(o.id);await e}if(na&&Ro())break;const u=fo(o.type);let h;const v={recipePoolId:c,recipeType:f,thingRecipeId:s,widgetId:i};h=o.type===ze.hubService?await u.getInputNames(o.state,v):u.getInputNames(o.state,v);const b=h.find((e=>e.name===m.portName));if(b){na&&await Po({thingId:s,widgetId:o.id}),ra++;if(!await oa({eventContext:l,interruptDriven:!1,childGateId:o.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=o.type===ze.hubService&&"CHILD_WIDGET_ERROR"===e.errCode;if(e instanceof Or)throw e;if(n&&e.errData){const t=e.errData;throw new Or(e.error||e.message||("string"==typeof e?e:JSON.stringify(e)),{targetWidgetId:t.targetWidgetId,targetPortName:t.targetPortName,sourcePortName:t.sourcePortName,sourceWidgetId:t.sourceWidgetId,targetWidgetType:t.targetWidgetType,sourceWidgetType:t.sourceWidgetType})}if(!r){const n="string"==typeof e?e:e.message||JSON.stringify(e);r={targetWidgetId:o.id,targetPortName:b.name,sourcePortName:t,error:n}}throw new Or(e.message||("string"==typeof e?e:JSON.stringify(e)),{stack:e.stack,targetWidgetId:o.id,targetPortName:b.name,sourcePortName:t,sourceWidgetId:p.id,targetWidgetType:o.type,sourceWidgetType:p.type})})).finally((()=>{if(ra--,na)return Do({thingId:s,widgetId:o.id,error:r})})))break}}}}catch(e){if(e instanceof Or)throw e;console.error(`Error processing next widget [${i}]: ${e}`)}finally{ra<0&&(console.warn("Active execution counter is negative, this should never happen"),ra=0),0===ra&&Jo()}}},ca=async(e,t,n,r)=>{const i=ae(r);if(!i)return null;const s=ce(r,n);if(!s)return s;const o=s.gates,a=s.gates[t],c=fo(a.type),l=await c.getInputNames(a.state,{recipePoolId:r,recipeType:i.dbInfo.recipeType,thingRecipeId:n,widgetId:t}),u=l.findIndex((t=>t.name===e));if(-1!==u){const e=((e,t,n)=>{for(const r in n){const i=n[r],s=i.children.length;for(let n=0;n<s;n++){const r=i.children[n],s=Ge(r.targetPort);if(r.childId===e&&s.portName===t)return i}}return null})(t,l[u].name,o);if(e){const t=fo(e.type);return{getValue:()=>"function"==typeof t.getValue?t.getValue():null}}}return null},la=e=>{const{gateId:t,originalEvent:n,thingRecipeId:r,thingDbId:i,thingVersion:s,recipeId:o,currentPath:a,eventId:c}=e;if(!ae(o))throw new Error(`Failed to find recipe "${o}" in cache`);if(!ue(o,r,t))throw console.warn(`Gate ${t} not found in block ${r} for recipe ${o}`),new Error(`Gate ${t} not found in block ${r} for recipe ${o}`);return async e=>aa({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:s,recipeId:o,eventContext:e.eventContext,currentPath:e.executionContext?.currentPath||a,eventId:e.executionContext?.eventId||c})},ua=e=>{const{gateId:t,originalEvent:n,blockRecipeId:r,blockDbId:i,blockVersion:s,recipeId:o,currentPath:a,eventId:c}=e,l=ae(o);if(!l)throw new Error(`Failed to find recipe "${o}" in cache`);const u=ue(o,r,t);if(!u)return console.warn(`Gate ${t} not found in block ${r} for recipe ${o}`),null;const d=la({gateId:t,originalEvent:n,thingRecipeId:r,thingDbId:i,thingVersion:s,recipeId:o,currentPath:a,eventId:c}),h=Ko({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:o,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:s,sourceWidgetId:a,interruptData:c,customId:l}=e;return Qe.createInterrupt({type:n,recipePoolId:o,thingId:r,targetWidgetId:t,sourceWidgetId:a,portName:i,config:s,data:c,customId:l})},cancelInterrupt:e=>Qe.destroyInterrupt(e),invokeNextWidget:d,nextWidget:f,nextGate:f,getParentAtPort:e=>ca(e,t,r,o),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,ea&&ea({blockId:r,gateId:t,prevState:i,newState:{...n},recipeId:o})}};return p};Qe.setInvokeChildGateCb(oa),Qe.setConsumeEventCounterCb((()=>++ia));const da=(e,t,n,r,i)=>{const s=ue(e,n,r);if(!s)return console.warn(`Gate ${r} not found in block ${n} for recipe ${e}`),null;const o=t=>{const{type:i,customTargetPortName:s,config:o,data:a}=t;return Qe.createInterrupt({type:i,recipePoolId:e,thingId:n,targetWidgetId:r,sourceWidgetId:r,portName:s,config:o,data:a})},a=()=>Object.freeze({...s.state,...s.type===ze.input&&{customInputs:[]}}),c=e=>{if("object"!=typeof e)return void console.warn(`Invalid state type [${typeof e}]. Expected an 'object'`);const t={...e,...s.type===ze.input&&!e.customInputs&&{customInputs:[]}};s.state=t},l=async t=>{const r=((e,t,n)=>{const r=ae(e);if(!r)throw new Error(`Recipe [${e} does not exist]`);if(!r.storage)return null;const i=ce(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=la({gateId:r,thingRecipeId:n,thingDbId:s.id,thingVersion:"default",recipeId:e,currentPath:[],eventId:null});return{getState:a,setState:c,registerInterrupt:o,getStorageData:l,nextWidget:(e,t,n)=>i({port:e,data:t,eventContext:n}),recipePoolId:e,recipeType:t,thingRecipeId:n,widgetId:r}}return{getState:a,setState:c,recipePoolId:e,widgetId:r,thingRecipeId:n}},ha=new c,fa="invoked",pa="state",ga=()=>{Qe.destroyAllInterrupts()},ma=async(e,t,n)=>{const r=ae(e),i=ue(e,t,n);if(i&&r){const s=fo(i.type);if(s&&"function"==typeof s.terminate){const i=((e,t,n,r)=>da(e,t,n,r))(e,r.dbInfo.recipeType,t,n);if(i)try{await s.terminate(i)}catch(e){console.warn(`Error terminating widget "${n}" in thing "${t}". Failing silently: `,e)}}}},ya=async e=>{const{recipePoolId:t,thingRecipeId:n,widgetRecipeId:r,options:i}=e,s=ae(t),o=ue(t,n,r);if(o&&s){const e=fo(o.type);if(e&&"function"==typeof e.initialize){const a=((e,t,n,r)=>da(e,t,n,r,!0))(t,s.dbInfo.recipeType,n,r);if(a){const t=e.initialize;try{(e=>{if(e.type===ze.script){const t=e.state;if((t.version||0)<2){const n=Object.keys(e.variablesListener||{});for(const t of n)if(e.variablesListener){const n=zr(t);e.variablesListener[n]=e.variablesListener[t],delete e.variablesListener[t],delete e.variables}t.version=2}}})(o),await t(a,i||{})}catch(e){throw console.warn(`Error initializing widget "${r}" in thing "${n}": `,e),e}}}}},va=(e,t)=>{const n=ae(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},ba=(e,t="",n="")=>`block:${t}:gate:${n||""}:${e}`,wa=e=>{ha.emit(ba(pa),e),ha.emit(ba(pa,e.blockId,e.gateId),e)};Qo=async e=>{await ha.emit(ba(fa),e),await ha.emit(ba(fa,e.blockId,e.gateId),e)},(e=>{ea=e})(wa);var Sa=async(e,t,n,r,i)=>{const s=de(e,{id:t,authorId:r,version:n,recipeType:i});mi(),Xo(),Zo(i);const o=ae(s);return o&&(o.startedAt=Date.now(),o.retryAttempts=0,o.execCounter=0,o.status=ee.STARTING,o.addLog("recipe registered")),s},_a=async e=>{const t=ae(e);if(!t)return null;t.addLog("terminating recipe"),ga(),jo();for(const n in t.blocks){const r=t.blocks[n];for(const t in r.gates)await ma(e,n,t)}(e=>{!!ie[e]&&delete ie[e]})(e)},Ia=async(e,t)=>{const n=ae(e),r=[],i=[];if(n){Pi(),ei({recipePoolId:e,thingId:ge});for(const s in n.blocks){const o=n.blocks[s];if(!t||!Array.isArray(t)||t.includes(s))for(const t in o.gates)try{if(n.dbInfo?.recipeType===cr.Desktop){const e=o.gates[t];if(e.type===ze.hubService){const r=e.state;if(r?.service?.webOnly){n?.addLog(`skipping initialization of web-only widget "${t}"`);continue}}e.type===ze.recipeLoad&&i.push(e)}await ya({recipePoolId:e,thingRecipeId:s,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=ge,waitForOutputChild:s=!0}=t;return(async e=>{const{inputName:t,data:n,recipePoolId:r,thingId:i,waitForOutputChild:s=!0}=e,o=ae(r),a=ce(r,i),c=Date.now();if(a&&o){ia+=1;for(const e in a.gates){const o=a.gates[e];if(o.type===ze.input&&!o.disabled){const l=o.state.inputName||"";if(l===t){const t=fo(o.type),u={...n,timestamp:c},d=ua({gateId:e,originalEvent:u,blockRecipeId:i,blockDbId:a.id,blockVersion:a.version,recipeId:r,sourceWidgetId:void 0,currentPath:[],eventId:ia});if(d&&t.processEvent){const o={...d,getState:d.getState,waitForOutputChild:s};if(Qo&&await Qo({recipeId:r,blockId:i,gateId:e,targetPort:ct,data:n}),!ta)return await t.processEvent(u,o);await ta(i,r,l,n)}continue}}}}})({inputName:n,data:r,recipePoolId:e,thingId:i,waitForOutputChild:s})},invokeRecipeLoadedWidgets:async()=>{for(const t of i)await sa({widgetId:t.id,thingId:ge,recipeId:e,targetPortName:Ys,data:{type:ye.Boolean,value:!0}})}}},xa=e=>{si(e)},ka=(e,t,n,r=!1)=>{const i=va(t,e);if(i){const{widget:s,thing:o}=i,a={...s.state};s.state=n,r&&wa({blockId:o.recipeId,gateId:t,recipeId:e,newState:{...n},prevState:a})}},Ea=(e,t)=>{const n=va(t,e);return n?n.widget.state:null},Ca=async e=>{const{recipePoolId:t,currentGateId:n,sourcePortName:r,originalEvent:i,data:s,eventContext:o,currentPath:a,eventId:c}=e,l=va(n,t);if(l)return aa({portName:r,originalEvent:i,data:s,currentGateId:n,blockRecipeId:l.thing.recipeId,thingDbId:l.thing.id,thingVersion:l.thing.version,recipeId:t,eventContext:o,currentPath:a,eventId:c})},Oa=yi;const $a=(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),s=r.subarray(16).toString("base64"),o=d(e,t,32),a=h("aes-256-cbc",o,i);let c=a.update(s,"base64","utf8");return c+=a.final("utf8"),c})(e.uuid,"kemu",t)},Na=e=>{try{return JSON.parse(e)}catch(e){return null}},Ma="undefined"!=typeof window,Aa={protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8},Ta={protocolPrefix:4,txtLength:4},Pa=Object.values(Aa).reduce(((e,t)=>e+t),0),Da=Object.values(Ta).reduce(((e,t)=>e+t),0),ja=["width","height","colorSpace"],Ra=(e,t)=>{const n={},r=[];let i=0,s=Array.isArray(e)?[]:{};const o=(e,s)=>{const a=(e=>{const t="undefined"!=typeof Buffer&&e instanceof Buffer,n=e instanceof ArrayBuffer,r=e instanceof Uint8ClampedArray,i=e instanceof Uint8Array,s=e instanceof Int8Array;return t?"Buffer":n?"ArrayBuffer":r?"Uint8ClampedArray":i?"Uint8Array":s?"Int8Array":null})(e);if(!a){if(Array.isArray(e)){const t=[];for(let n=0;n<e.length;n++)t[n]=o(e[n],`${s}[${n}]`);return t}if("object"==typeof e){const t={},n=(e=>{const t=e instanceof Int16Array,n=e instanceof Uint16Array,r=e instanceof Int32Array,i=e instanceof Uint32Array,s=e instanceof Float32Array,o=e instanceof Float64Array,a=e instanceof BigInt64Array,c=e instanceof BigUint64Array;return t?"Int16Array":n?"Uint16Array":r?"Int32Array":i?"Uint32Array":s?"Float32Array":o?"Float64Array":a?"BigInt64Array":c?"BigUint64Array":null})(e);if(n)throw new Error(`Unsupported binary type [${n}] at path "${s}"`);for(const n in e)Object.hasOwn(e,n)||ja.includes(n)||console.warn(`Allowing inherited property: ${n} from path: ${s}`),t[n]=o(e[n],`${s.length?`${s}.`:""}${n}`);return t}return e}n[s]={index:i,length:e.byteLength,binaryType:a},"Buffer"===t?r.push(Buffer.from(e)):"ArrayBuffer"===a?r.push(e):r.push(e.buffer),i+=e.byteLength};s=o(e,"");let a=null;if(r.length>1)if("ArrayBuffer"===t){const e=r.reduce(((e,t)=>e+t.byteLength),0),t=new Uint8Array(e);let n=0;for(let e=0;e<r.length;e++)t.set(new Uint8Array(r[e]),n),n+=r[e].byteLength;a=t.buffer}else{a=Buffer.concat(r)}else 1===r.length&&(a=r[0]);return a?{map:n,combinedData:a,sourceCopy:s}:null},La=(e,t,n)=>{const r=t.match(/(\[\d+\])|([^[\].]+)/g)||[];let i=e;for(let e=0;e<r.length;e++){let t=r[e];const s=t.startsWith("[")&&t.endsWith("]"),o=e===r.length-1;if(s){t=t.slice(1,-1);const s=parseInt(t,10);if(!Array.isArray(i))throw new Error(`Expected an array at key "${r.slice(0,e).join(".")}" but found an object.`);o?i[s]=n:(i[s]||(i[s]=r[e+1].startsWith("[")?[]:{}),i=i[s])}else o?i[t]=n:(i[t]||(i[t]=r[e+1].startsWith("[")?[]:{}),i=i[t])}return e},Fa=(e,t,n)=>{const r="undefined"!=typeof Buffer,i=t instanceof Uint8Array;for(const s in n)if(Object.hasOwn(n,s)){const{index:o,length:a,binaryType:c}=n[s];let l=null;if(r&&t instanceof Buffer)switch(c){case"Buffer":l=t.subarray(o,o+a);break;case"ArrayBuffer":l=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(o,o+a);break;case"Uint8Array":l=new Uint8Array(t.subarray(o,o+a));break;case"Uint8ClampedArray":l=new Uint8ClampedArray(t.subarray(o,o+a));break;case"Int8Array":l=new Int8Array(t.subarray(o,o+a))}else if(t instanceof ArrayBuffer||t instanceof Uint8Array)switch(c){case"Buffer":if(r){l=Buffer.from(t.slice(o,o+a));break}case"ArrayBuffer":l=i?t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(o,o+a):t.slice(o,o+a);break;case"Uint8Array":l=i?t.slice(o,o+a):new Uint8Array(t.slice(o,o+a));break;case"Uint8ClampedArray":l=new Uint8ClampedArray(t.slice(o,o+a));break;case"Int8Array":l=new Int8Array(t.slice(o,o+a))}l&&La(e,s,l)}return e},Ua=e=>g(e),Ba="KMSG",Wa="KCMD",Ya=Ua("klProtocol");var Ga={encode:(e,t,n)=>{const r={json:e.json},i=Ra(r.json,"Buffer"),s=i?.combinedData;i&&(r.jsonBinaryMap=i.map,r.json=i.sourceCopy);const o=s?s.byteLength:0,a=JSON.stringify(r),c=Buffer.from(a),l=c.byteLength,u=Aa.protocolPrefix+Aa.protocolVersion+Aa.jsonLength+Aa.binaryLength+Aa.fromServiceId+Aa.toServiceId+Aa.sentAt+l+o,d=Buffer.alloc(u),h=Date.now();let f=0;return d.write(Ba,f),f+=Aa.protocolPrefix,d.writeUInt8(1,f),f+=Aa.protocolVersion,d.writeUInt32LE(l,f),f+=Aa.jsonLength,d.writeUInt32LE(o,f),f+=Aa.binaryLength,d.writeUInt32LE(t,f),f+=Aa.fromServiceId,d.writeUInt32LE(n,f),f+=Aa.toServiceId,d.writeBigInt64LE(BigInt(h),f),f+=Aa.sentAt,c.copy(d,f),f+=l,s&&o&&s.copy(d,f),d},decodeHeader:e=>{let t=0;const n=e.toString("utf-8",t,Aa.protocolPrefix);if(t+=Aa.protocolPrefix,n!==Ba)return null;if(e.byteLength<Pa)return Ya(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const r=e.readUInt8(t);t+=Aa.protocolVersion;const i=e.readUInt32LE(t);t+=Aa.jsonLength;const s=e.readUInt32LE(t);t+=Aa.binaryLength;const o=e.readUInt32LE(t);t+=Aa.fromServiceId;const a=e.readUInt32LE(t);t+=Aa.toServiceId;const c=e.readBigInt64LE(t);t+=Aa.sentAt;const l=i+s,u=e.subarray(t,t+l),d=e.subarray(0,Pa);let h=null;return e.byteLength-Pa-i-s>0&&(h=e.subarray(Pa+i+s)),{header:{protocolVersion:r,jsonLength:i,binaryLength:s,fromServiceId:o,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=Na(n);if(!i?.json)return Ya("Invalid JSON in KL message"),null;i.jsonBinaryMap&&r.byteLength&&Fa(i.json,r,i.jsonBinaryMap);const s=Buffer.concat([e.headerPackage,t]);let o=s,a=null;const c=Pa+e.jsonLength+e.binaryLength;return s.byteLength>c&&(a=s.subarray(c),o=s.subarray(0,c)),{message:{json:i.json,rawMessage:o},remaining:a}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<Pa)return Ya("Invalid Header Size"),e;let n=0;return n+=Aa.protocolPrefix,n+=Aa.protocolVersion,n+=Aa.jsonLength,n+=Aa.binaryLength,void 0!==t.fromServiceId&&e.writeUInt32LE(t.fromServiceId,n),n+=Aa.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=Da+r,s=Buffer.alloc(i);return s.write(Wa,t),t+=Ta.protocolPrefix,s.writeUint32LE(r,t),t+=Ta.txtLength,n.copy(s,t),s},decodeCommand:e=>{let t=0;if(e.byteLength<Da)return{command:null};const n=e.toString("utf-8",t,Ta.protocolPrefix);if(t+=Ta.protocolPrefix,n!==Wa)return{command:null};const r=e.readUInt32LE(t);t+=Ta.txtLength;const i=e.toString("utf-8",t,t+r),s=e.byteLength-Da-r;let o=null;s>0&&(o=e.subarray(Da+r));let a=0;return s<0&&(a=Math.abs(s)),{command:i,remainingData:o,missing:a}}};const Ha="KMSG",Va="KCMD",za=Ua("klProtocol"),qa=new TextEncoder;var Ka={encode:(e,t,n)=>{const r={json:e.json},i=Ra(e.json,"ArrayBuffer"),s=i?.combinedData;i&&(r.jsonBinaryMap=i.map,r.json=i.sourceCopy);const o=s?s.byteLength:0,a=JSON.stringify(r),c=qa.encode(a),l=c.byteLength,u=new ArrayBuffer(Aa.protocolPrefix+Aa.protocolVersion+Aa.jsonLength+Aa.binaryLength+Aa.fromServiceId+Aa.toServiceId+Aa.sentAt+l+o),d=new DataView(u),h=new Uint8Array(u),f=Date.now();let p=0;for(let e=0;e<4;++e)h[p++]=Ha.charCodeAt(e);return d.setUint8(p,1),p+=Aa.protocolVersion,d.setUint32(p,l,!0),p+=Aa.jsonLength,d.setUint32(p,o,!0),p+=Aa.binaryLength,d.setUint32(p,t,!0),p+=Aa.fromServiceId,d.setUint32(p,n,!0),p+=Aa.toServiceId,d.setBigInt64(p,BigInt(f),!0),p+=Aa.sentAt,h.set(c,p),p+=l,s&&o&&h.set(new Uint8Array(s),p),u},decodeHeader:e=>{const t=new DataView(e);let n=0,r="";for(let e=0;e<Aa.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==Ha)return null;if(e.byteLength<Pa)return za.log(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const i=t.getUint8(n);n+=Aa.protocolVersion;const s=t.getUint32(n,!0);n+=Aa.jsonLength;const o=t.getUint32(n,!0);n+=Aa.binaryLength;const a=t.getUint32(n,!0);n+=Aa.fromServiceId;const c=t.getUint32(n,!0);n+=Aa.toServiceId;const l=t.getBigInt64(n,!0);n+=Aa.sentAt;const u=s+o,d=e.slice(n,n+u),h=new Uint8Array(e,0,Pa);let f=null;if(e.byteLength-Pa-s-o>0){f=new Uint8Array(e,Pa+s+o).slice().buffer}return{header:{protocolVersion:i,jsonLength:s,binaryLength:o,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 s=(new TextDecoder).decode(n.subarray(0,e.jsonLength)),o=n.subarray(e.jsonLength,e.jsonLength+e.binaryLength),a=Na(s);if(!a?.json)return za.log("Invalid JSON in KL message"),null;a.jsonBinaryMap&&o.byteLength&&Fa(a.json,o,a.jsonBinaryMap);const c=new Uint8Array(e.headerPackage.byteLength+n.byteLength);c.set(new Uint8Array(e.headerPackage),0),c.set(n,e.headerPackage.byteLength);let l=c,u=null;const d=Pa+e.jsonLength+e.binaryLength;return c.byteLength>d&&(u=c.subarray(d),l=c.subarray(0,d)),{message:{json:a.json,...o.length?{binaryData:o.buffer}:{},rawMessage:l.buffer},remaining:u?.buffer??null}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<Pa)return za("Invalid Header Size"),e;let n=0;n+=Aa.protocolPrefix,n+=Aa.protocolVersion,n+=Aa.jsonLength,n+=Aa.binaryLength;const r=new DataView(e);return void 0!==t.fromServiceId&&r.setUint32(n,t.fromServiceId,!0),n+=Aa.fromServiceId,void 0!==t.toServiceId&&r.setUint32(n,t.toServiceId,!0),e},encodeCommand:e=>{let t=0;const n=qa.encode(e),r=n.byteLength,i=new ArrayBuffer(Da+r),s=new DataView(i),o=new Uint8Array(i);for(let e=0;e<4;++e)o[t++]=Va.charCodeAt(e);return s.setUint32(t,r,!0),t+=Ta.txtLength,o.set(n,t),i},decodeCommand:e=>{const t=new DataView(e);let n=0;if(e.byteLength<Da)return{command:null};let r="";for(let e=0;e<Ta.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==Va)return{command:null};const i=t.getUint32(n,!0);n+=Ta.txtLength;const s=e.byteLength-Da-i,o=new Uint8Array(e,n,Math.min(i,e.byteLength-Da)),a=(new TextDecoder).decode(o);let c=null;s>0&&(c=e.slice(Da+i));let l=0;return s<0&&(l=Math.abs(s)),{command:a,remainingData:c,missing:l}}};let Ja=Ga;Ma&&(Ja=Ka);var Za,Xa=Ja;!function(e){e.FunctionNotFound="FNC_NOT_FOUND",e.FunctionNotAllowed="FNC_NOT_ALLOWED",e.ParentEventCallbackError="PARENT_EVENT_CALLBACK_ERROR"}(Za||(Za={}));let Qa=Math.ceil(Date.now()/1e3);let ec,tc,nc,rc,ic,sc=!1;var oc=()=>{sc=!0},ac=(e,t)=>{if(!ec)throw new Error("Memory connection not set.");ec.sendBuf(e,t)},cc=e=>tc=e,lc=e=>ic=e,uc=e=>nc=e,dc=e=>rc=e;const hc=async(e,t=2)=>{const n=async(e,r)=>{if(Array.isArray(e))for(let i=0;i<e.length;i++){const s=e[i];if(s&&"object"==typeof s)if(Array.isArray(s))await n(s,r+1);else{const o=s._kemuType;void 0!==o?o===ye.ImageData&&(e[i]=await He(s)):r<t&&await n(s,r+1)}}else if("object"==typeof e&&null!==e){const i=Object.keys(e);for(const s of i){const i=e[s];if(i&&"object"==typeof i){const o=i._kemuType;void 0!==o?o===ye.ImageData&&(e[s]=await He(i)):r<t&&await n(i,r+1)}}}};return await n(e,1),e};Ua("klTransmissionManager"),Ua("ipcClient"),Ua("kemuWidgetService"),I(process.argv.slice(2));const fc=e=>g(`runner:${e}`),pc=fc("connectionManager"),gc=fc("remoteInvoke"),mc=new function(e){const t={};let n,r=console.log;const i={};let s=e||String(Date.now());const o={},a=e=>!o[e],c=(e,t,n,r,i,s)=>{let o=Ma?new ArrayBuffer(0):Buffer.alloc(0);const c={json:{functionName:e,args:s.success?s.success:[s],messageId:t,type:s.success?"response":"error"}};return a(r)&&(o=Xa.encode(c,n,r)),i(o,{msg:c,sourceServiceId:n,targetServiceId:r})};return{setLogger:e=>{r=e},processMessage:(e,s,o,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,o.targetServiceId,o.sourceServiceId,s,e)};if(!(!n||n({args:l.args,functionName:l.functionName,transport:e,messageId:l.messageId,sourceServiceId:o.sourceServiceId,reply:i,send:s})))return r&&r(`Function "${l.functionName}" not allowed to be invoked by client [${o.sourceServiceId}]`),i({error:"Function not allowed",errCode:"FNC_NOT_ALLOWED"}),!0;t({transport:e,args:l.args,reply:i,messageId:l.messageId,sourceServiceId:o.sourceServiceId,send:s})}else{const e=`Function "${l.functionName}" not found.`;r&&r(e),c(l.functionName,l.messageId,o.targetServiceId,o.sourceServiceId,s,{error:e,errCode:"FNC_NOT_FOUND"})}return!0}return!1},execute:async(e,n,i,o,c,l)=>{if(!i){const e="No send buffer function provided.";throw r&&r(e),e}Qa+=1;const u=`${s}-${Qa}-exec-${e.substring(0,10)}`,d={messageId:u,functionName:e,send:i,sourceServiceId:o,targetServiceId:c,args:n||[],fulfilled:!1,resolve:()=>{},reject:()=>{}};d.promise=new Promise(((e,t)=>{d.resolve=e,d.reject=t}));let h=Ma?new ArrayBuffer(0):Buffer.alloc(0);const f={json:{functionName:e,args:n,messageId:u,type:"execute"}};a(c)&&(h=Xa.encode(f,o,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:o,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=>{s=e},getPendingExecutions:()=>t,rejectAllPending:e=>{Object.keys(t).forEach((n=>{const r=t[n];r&&!r.fulfilled&&(clearTimeout(r.timer),r.fulfilled=!0,r.reject(e),delete t[n])}))},broadcast:(e,t,n,i)=>{Qa+=1;const o=`${s}-${Qa}-multicast-${e.substring(0,10)}`;let c=Ma?new ArrayBuffer(0):Buffer.alloc(0);const l={json:{functionName:e,args:t,messageId:o,type:"execute"}};let u=a(n[0].serviceId);u&&(c=Xa.encode(l,i,n[0].serviceId));for(let t=0;t<n.length;t++)try{const s=n[t];r&&r(`Broadcasting function "${e}" with message id "${o}" to client [${s.serviceId}]`),0!==t&&(u=a(s.serviceId),u&&(c=Xa.patchEncodedHeader(c,{toServiceId:s.serviceId}))),s.sendFn(c,{msg:l,sourceServiceId:i,targetServiceId:s.serviceId})}catch(e){r&&r(`Error broadcasting to client at index ${t}`)}},disableServiceEncoding:(e,t)=>{o[e]=t}}}("kweb");mc.setLogger(gc);const yc=new c,vc=new c;let bc,wc=null,Sc=null,_c=null,Ic=null,xc=null;const kc={},Ec=()=>{if(!_c)throw new Error("API key is required to interact with the hub");return _c},Cc=(e,t,n)=>{const r=`${e}_${t}`,i={contents:n,lastRequestedAt:Date.now(),contentsChecksum:""};return kc[r]=i,i},Oc=(e,t)=>kc[`${e}_${t}`]||null,$c=async(e,t)=>{if(!wc)return pc("Hub Link has not been acknowledged. Cannot get services."),null;const n=[{serviceName:e,version:t}];return(await mc.execute(Se.GetServiceContents,n,Mc,wc,0))[0]},Nc=async(e,t,n=!1)=>{if(!e||!t)return null;const r=Oc(e,t);if(!r||n){const n=r||Cc(e,t);try{const r=await $c(e,t);return r&&(n.contents=r.uiContent,n.contentsChecksum=r.uiContentsChecksum||""),n.contents||null}catch(n){pc(`Failed to fetch service contents for ${e} v${t}`,n)}}return r?.contents||null},Mc=ac,Ac=()=>{pc("Disconnected from the server"),wc=null,Ic=null,mc.rejectAllPending("Disconnected from the server"),yc.emit("disconnected")},Tc=()=>{pc("Connected to the server"),yc.emit("connected")},Pc=()=>Sc,Dc=(e,t,n,r)=>`${e}_${t}_${n}_${r}`,jc=async()=>{const e=Pc();if(e){const t=ae(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{pc(`Re-issuing subscription for service ${t.service.name} (${t.service.version})`),n[r]=!0,await Xc({listener:{recipeId:e},targetService:{serviceName:t.service.name,version:t.service.version}})}catch(e){pc(`Failed to re-issue subscription for service ${t.service.name} (${t.service.version})`,e)}}}}}}}},Rc=async e=>{if(!e)return void pc("Hub sent ACK request without service id");const t=Pc();if(!t)return void pc("Hub sent ACK request without recipe pool id");if(!ae(t))throw new Error("Hub sent ACK request without recipe");const n=xc?{...xc}:null,r={apiKey:n?.apiKey,recipe:he(t),user:n,ackSessionId:e};await mc.execute(Se.SocketAckResponse,[r],Mc,e,0),pc("Hub Link acknowledged"),wc=e,yc.emit("acknowledged"),await al(),jc()},Lc=async e=>{const t=e.args[0],{widgetId:n,data:r,recipePoolId:i,waitForResponse:s}=t;return console.log("🔥 handleSendToRecipe: ",r),e.reply({success:[`message received by recipe ok target widget "${n}", recipe pool id "${i}", waitForResponse "${s}"`]})},Fc=async e=>{const t=e.args[0],n=Dc("broadcast",`hub_${t.type}`,(0).toString(),"");await vc.emit(n,t)},Uc=async e=>{const t=e.args[0];for(const e of t.outputs||[])e.type===ye.ImageData&&Le(e.value)&&(e.value=await He(e.value));const n=Pc();if(n){const r=ae(n);if(r){const i=async e=>{const n=Dc("broadcast",t.source.serviceName,t.source.serviceVersion,e);try{await vc.emit(n,t)}catch(t){pc(`Failed to emit broadcast event for target ${e}`,t)}};await i("app");for(const s in r.blocks){const o=r.blocks[s];for(const r in o.gates){const s=o.gates[r];if(s.disabled)continue;const a=s.state;if(s.type!==ze.script){if(s.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 s={type:i.type,value:i.value,timestamp:Date.now()};pc(`Sending data to output ${i.name} requested by messageId ${e.messageId}`),await Ca({recipePoolId:n,currentGateId:r,sourcePortName:i.name,originalEvent:s,data:s,eventContext:t.eventContext,currentPath:t.currentPath||[],eventId:t.eventId||null})}}}else await i(r)}}}}},Bc=async e=>{const t=e.args[0],{finalState:n,recipeId:r,widgetId:i}=t,s=Ea(r,i);let o=s;if(n&&o&&s&&(o={...s,customState:n},ka(r,i,o,!0)),o?.service)try{const e=Dc("setOutputs",o.service.name,o.service.version,i);await vc.emit(e,t.outputs)}catch(e){pc(`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===ye.ImageData){if(!Le(n.value)){pc(`Invalid ImageData value received for output ${n.name}. Expected an ImageData-like object`);continue}n.value=await He(n.value)}else n.type!==ye.JsonObj&&n.type!==ye.Array||await hc(n.value);const s={type:n.type,value:n.value,timestamp:Date.now()};pc(`Sending data to output ${n.name} requested by messageId ${e.messageId}`);try{await Ca({recipePoolId:r,currentGateId:i,sourcePortName:n.name,originalEvent:s,data:s,eventContext:t.eventContext,currentPath:t.currentPath||[],eventId:t.eventId||null})}catch(e){pc(`Failed to trigger next global widget for output ${n.name}`,e),a=e;break}}if(a){const t=a instanceof Or,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:[]})},Wc=async e=>{const t=e.args[0],{newState:n,recipeId:r,widgetId:i}=t,s=Ea(r,i);if(s){const t={...s,customState:{...s.customState,...n}};return ka(r,i,t,!0),e.reply({success:[]})}},Yc=async({args:e,reply:t})=>{const n=e[0],{recipeId:r,widgetId:i,path:s,key:o}=n;pc(`Received request to set a dependency path for "${o}" on widget "${i}" in recipe "${r}"`);const a=Ea(r,i);if(a){const e={...a};e.dependencies=e.dependencies||{},e.dependencies[o]={path:s},ka(r,i,e,!0)}return t({success:[]})},Gc=async({args:e,reply:t})=>{const n=e[0],{recipeId:r,widgetId:i,key:s}=n;pc(`Received request to get a dependency path for "${s}" on widget "${i}" in recipe "${r}"`);const o=Ea(r,i);if(o){const e=o.dependencies?.[s]?.path;return pc(`Returning dependency path for "${s}" on widget "${i}": "${e}"`),t({success:[e||null]})}return t({error:"Widget not found",errCode:"WIDGET_NOT_FOUND"})},Hc=async()=>{if(pc(`Requesting services on ${(new Date).toISOString()}`),!wc)return pc("Hub Link has not been acknowledged. Cannot get services."),{available:[],installed:[],failed:[]};const[e]=await mc.execute(Se.GetServices,[],Mc,wc,0);bc=e;for(const t of e.available){if(t.internal)continue;const e=Oc(t.name,t.version);if(!e||e?.contentsChecksum!==t.uiContentChecksum)try{const n=e||Cc(t.name,t.version);pc(`Service ${t.name} v${t.version} contents have changed, fetching new contents`);const r=await $c(t.name,t.version);r&&(n.contents=r.uiContent,n.contentsChecksum=t.uiContentChecksum||"")}catch(e){pc(`Failed to update service contents for ${t.name} v${t.version}`,e)}}return e},Vc=()=>bc||{available:[],installed:[],failed:[]},zc=()=>!!bc,qc=async e=>{const{targetServiceSessionId:t}=e;if(!wc)return void pc("No target service session id provided");pc(`Forwarding "onParentEvent" to service ${t}`);const n=await mc.execute(Se.OnParentEvent,[e],Mc,wc,t,e.config).catch((e=>{throw pc(`Error invoking onParentEvent callback: ${e}`),e.errCode===Za.ParentEventCallbackError?e.error:e}));return n},Kc=async e=>{if(!wc)return pc("Hub Link has not been acknowledged. Cannot get services."),{};const[t]=await mc.execute(Se.GetDefaultState,[],Mc,wc,e);return t},Jc=async(e,t,n,r)=>{if(!wc)return pc("Hub Link has not been acknowledged. Cannot get services."),null;const[i]=await mc.execute(Se.UIEvent,[t,n],Mc,wc,e,r);return i},Zc=(e,t)=>{const n=()=>{t()};return yc.on(e,n),()=>yc.off(e,n)},Xc=async e=>{if(wc)return mc.execute(Se.SubscribeToService,[e],Mc,wc,0);pc("Hub Link has not been acknowledged. Cannot subscribe to services.")},Qc=async e=>{if(wc)return mc.execute(Se.UnsubscribeFromService,[e],Mc,wc,0);pc("Hub Link has not been acknowledged. Cannot subscribe to services.")},el=(e,t,n,r)=>{const i=Dc("broadcast",t,n,e);return vc.on(i,r)},tl=(e,t,n,r)=>{const i=Dc("setOutputs",t,n,e);return vc.on(i,r)},nl=async(e,t,n)=>wc?mc.execute(e,t,Mc,wc,0,n):(pc("Hub Link has not been acknowledged. Cannot execute function."),null),rl=async e=>{if(!wc)return void pc("Hub Link has not been acknowledged. Cannot execute function.");const t=Ea(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(!ae(e.recipePoolId))throw new Error("Recipe not found. Cannot initialize service instance.");const r=[{currentState:t.customState,recipeId:e.recipePoolId,recipe:he(e.recipePoolId),widgetId:e.widgetId,variantId:e.variantId,recipeType:e.recipeType,recipeName:e.recipeName,currentDependencies:n,kemuApiKey:Ec()}],[i,s]=await mc.execute(Se.InitializeInstance,r,Mc,wc,e.sessionId);if(s&&s.length>0){const n=s.filter((e=>e.name&&e.name.length>0)).map((e=>({name:e.name,hubServiceName:t.service?.name})));Oa({clearExistingSecrets:!0,recipePoolId:e.recipePoolId,widgetId:e.widgetId,secrets:n})}if(i){const t=Ea(e.recipePoolId,e.widgetId);if(t){const n={...t,customState:i};ka(e.recipePoolId,e.widgetId,n,!0)}}},il=async(e,t,n,r)=>{if(!wc)return void pc("Hub Link has not been acknowledged. Cannot execute function.");const i=Ea(n,t);if(!i)throw new Error("Widget or recipe pool not found. Cannot initialize service instance.");const s=ae(n);if(!s)throw new Error("Recipe not found. Cannot terminate service instance.");const o=[{currentState:i.customState,recipeId:n,recipe:{poolId:n,uuid:s.uuid,name:s.name,type:s.dbInfo.recipeType,dbId:s.dbInfo.id,version:s.dbInfo.version,authorId:s.dbInfo.authorId},widgetId:t,variantId:r}];await mc.execute(Se.TerminateInstance,o,Mc,wc,e)},sl=async(e,t,n="^",r)=>{const i=["^","~",">=",">","<=","<","="];if(!i.includes(n))throw new Error(`Invalid compare mode "${n}". Must be one of ${i.join(", ")}`);const s=zc(),o=r||!s?await Hc():Vc();for(const r of o.available)if(r.name===e){if(r.version===t)return r;if(p(r.version,`${n}${t}`))return r}return null},ol=async()=>{if(!wc)return pc("Hub Link has not been acknowledged. Cannot get services."),null;if(Ic)return Ic;const[e]=await mc.execute(Se.GetSystemInfo,[],Mc,wc,0).catch((e=>(pc("Failed to get system info",e),[null])));return Ic=e,e},al=async()=>{Ic=await ol()};var cl,ll,ul,dl,hl,fl,pl,gl,ml=async e=>{if(!e.apiKey)throw new Error("an API key is required to connect to the hub");xc=e,_c=e.apiKey,uc(Tc),dc(Ac),lc((({json:e,transmission:t})=>{mc.processMessage("websocket",Mc,t,e)})),mc.registerFunction(Se.SetState,Wc),mc.registerFunction(Se.SetOutputs,Bc),mc.registerFunction(Se.BroadcastEvent,Uc),mc.registerFunction(Se.HubBroadcastEvent,Fc),mc.registerFunction(Se.SendToRecipe,Lc),mc.registerFunction(_e.SetDependencyPath,Yc),mc.registerFunction(_e.GetDependencyPath,Gc),cc((e=>{((e,t)=>{const n=we.SocketAcknowledge,r=we.IpcAcknowledge,i=e.startsWith(n);if(e===r)return t&&t(),0;if(i){const s=e.split(i?n:r),o=parseInt(s[1]);return t&&t(o),o}})(e,Rc),((e,t)=>{e===we.ServicesListChanged&&(t&&t())})(e,(()=>{pc("Services list changed"),yc.emit("services-changed")}))})),await oc()},yl=(e,t)=>{yc.on(e,t)},vl=()=>({getServices:Hc,getServiceContents:Nc,onParentEvent:qc,onCommand:Zc,getDefaultState:Kc,getCachedServices:Vc,areServicesCached:zc,subscribeToServiceEvents:Xc,unsubscribeFromServiceEvents:Qc,callProcessorHandler:Jc,onBroadcastEvent:el,onSetOutputsEvent:tl,executeHubFunction:nl,initializeServiceInstance:rl,terminateServiceInstance:il,getCompatibleService:sl,getHubSystemInfo:ol}),bl=e=>{Sc=e},wl=()=>mc;!function(e){e.Browser="browser",e.Cloud="cloud",e.Desktop="desktop"}(cl||(cl={})),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"}(ll||(ll={})),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"}(ul||(ul={})),function(e){e.Javascript="js",e.Python="py",e.Executable="exe"}(dl||(dl={})),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:"}(hl||(hl={})),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"}(fl||(fl={})),function(e){e.SetDependencyPath="setDependencyPath",e.GetDependencyPath="getDependencyPath"}(pl||(pl={})),function(e){e.IPC="ipc",e.WS="ws"}(gl||(gl={}));const Sl=e=>{try{return JSON.parse(e)}catch(e){return null}},_l=()=>{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=O.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}`)}},Il=/^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i,xl=e=>{if("string"!=typeof e)throw new TypeError("Invalid argument expected string");const t=e.match(Il);if(!t)throw new Error(`Invalid argument not valid semver ('${e}' received)`);return t.shift(),t},kl=e=>"*"===e||"x"===e||"X"===e,El=e=>{const t=parseInt(e,10);return isNaN(t)?e:t},Cl=(e,t)=>{if(kl(e)||kl(t))return 0;const[n,r]=((e,t)=>typeof e!=typeof t?[String(e),String(t)]:[e,t])(El(e),El(t));return n>r?1:n<r?-1:0},Ol=(e,t)=>{for(let n=0;n<Math.max(e.length,t.length);n++){const r=Cl(e[n]||"0",t[n]||"0");if(0!==r)return r}return 0},$l=(e,t,n)=>{Al(n);const r=((e,t)=>{const n=xl(e),r=xl(t),i=n.pop(),s=r.pop(),o=Ol(n,r);return 0!==o?o:i&&s?Ol(i.split("."),s.split(".")):i||s?i?-1:1:0})(e,t);return Nl[n].includes(r)},Nl={">":[1],">=":[0,1],"=":[0],"<=":[-1,0],"<":[-1],"!=":[-1,1]},Ml=Object.keys(Nl),Al=e=>{if(-1===Ml.indexOf(e))throw new Error(`Invalid operator, expected one of ${Ml.join("|")}`)};var Tl="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Pl(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Dl,jl,Rl,Ll,Fl,Ul={exports:{}},Bl={exports:{}};function Wl(){if(jl)return Dl;jl=1;var e=1e3,t=60*e,n=60*t,r=24*n,i=7*r;function s(e,t,n,r){var i=t>=1.5*n;return Math.round(e/n)+" "+r+(i?"s":"")}return Dl=function(o,a){a=a||{};var c=typeof o;if("string"===c&&o.length>0)return function(s){if(!((s=String(s)).length>100)){var o=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(s);if(o){var a=parseFloat(o[1]);switch((o[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}}}}(o);if("number"===c&&isFinite(o))return a.long?function(i){var o=Math.abs(i);return o>=r?s(i,o,r,"day"):o>=n?s(i,o,n,"hour"):o>=t?s(i,o,t,"minute"):o>=e?s(i,o,e,"second"):i+" ms"}(o):function(i){var s=Math.abs(i);return s>=r?Math.round(i/r)+"d":s>=n?Math.round(i/n)+"h":s>=t?Math.round(i/t)+"m":s>=e?Math.round(i/e)+"s":i+"ms"}(o);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(o))}}function Yl(){return Ll||(Ll=1,Rl=function(e){function t(e){let r,i,s,o=null;function a(...e){if(!a.enabled)return;const n=a,i=Number(new Date),s=i-(r||i);n.diff=s,n.prev=r,n.curr=i,r=i,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((r,i)=>{if("%%"===r)return"%";o++;const s=t.formatters[i];if("function"==typeof s){const t=e[o];r=s.call(n,t),e.splice(o,1),o--}return r})),t.formatArgs.call(n,e),(n.log||t.log).apply(n,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=n,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(i!==t.namespaces&&(i=t.namespaces,s=t.enabled(e)),s),set:e=>{o=e}}),"function"==typeof t.init&&t.init(a),a}function n(e,n){const r=t(this.namespace+(void 0===n?":":n)+e);return r.log=this.log,r}function r(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){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=Wl(),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}),Rl}var Gl,Hl,Vl,zl,ql,Kl={exports:{}};"undefined"==typeof process||"renderer"===process.type||!0===process.browser||process.__nwjs?Ul.exports=(Fl||(Fl=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=Yl()(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(Bl,Bl.exports)),Bl.exports):Ul.exports=(ql||(ql=1,function(e,t){const n=N,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),s=` ${i};1m${r} [0m`;n[0]=s+n[0].split("\n").join("\n"+s),n.push(i+"m+"+e.exports.humanize(this.diff)+"[0m")}else n[0]=(t.inspectOpts.hideDate?"":(new Date).toISOString()+" ")+r+" "+n[0]},t.save=function(e){e?process.env.DEBUG=e:delete process.env.DEBUG},t.load=function(){return process.env.DEBUG},t.useColors=function(){return"colors"in t.inspectOpts?Boolean(t.inspectOpts.colors):n.isatty(process.stderr.fd)},t.destroy=r.deprecate((()=>{}),"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),t.colors=[6,2,3,4,5,1];try{const e=function(){if(zl)return Vl;zl=1;const e=M,t=N,n=Hl?Gl:(Hl=1,Gl=(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 s(e){return 0!==e&&{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function o(t,s){if(0===i)return 0;if(n("color=16m")||n("color=full")||n("color=truecolor"))return 3;if(n("color=256"))return 2;if(t&&!s&&void 0===i)return 0;const o=i||0;if("dumb"===r.TERM)return o;if("win32"===process.platform){const t=e.release().split(".");return Number(t[0])>=10&&Number(t[2])>=10586?Number(t[2])>=14931?3:2:1}if("CI"in r)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some((e=>e in r))||"codeship"===r.CI_NAME?1:o;if("TEAMCITY_VERSION"in r)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(r.TEAMCITY_VERSION)?1:0;if("truecolor"===r.COLORTERM)return 3;if("TERM_PROGRAM"in r){const e=parseInt((r.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(r.TERM_PROGRAM){case"iTerm.app":return e>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(r.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(r.TERM)||"COLORTERM"in r?1:o}return n("no-color")||n("no-colors")||n("color=false")||n("color=never")?i=0:(n("color")||n("colors")||n("color=true")||n("color=always"))&&(i=1),"FORCE_COLOR"in r&&(i="true"===r.FORCE_COLOR?1:"false"===r.FORCE_COLOR?0:0===r.FORCE_COLOR.length?1:Math.min(parseInt(r.FORCE_COLOR,10),3)),Vl={supportsColor:function(e){return s(o(e,e&&e.isTTY))},stdout:s(o(!0,t.isatty(1))),stderr:s(o(!0,t.isatty(2)))},Vl}();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=Yl()(t);const{formatters:s}=e.exports;s.o=function(e){return this.inspectOpts.colors=this.useColors,r.inspect(e,this.inspectOpts).split("\n").map((e=>e.trim())).join(" ")},s.O=function(e){return this.inspectOpts.colors=this.useColors,r.inspect(e,this.inspectOpts)}}(Kl,Kl.exports)),Kl.exports);var Jl=Pl(Ul.exports);const Zl=e=>Jl(e);var Xl={},Ql={};class eu 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,eu)}}var tu,nu,ru,iu,su,ou=e=>{if(e.length>2)throw new eu(e);function t(e={}){this.options=e}function n(e){return new t(e)}return t.prototype.transform=e,n.Format=t,n},au={exports:{}},cu={exports:{}},lu={exports:{}},uu={exports:{}};function du(){if(su)return iu;su=1;var e=M,t=ru?nu:(ru=1,nu=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 s=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 s=r?1:0;if("win32"===process.platform){var o=e.release().split(".");return Number(process.versions.node.split(".")[0])>=8&&Number(o[0])>=10&&Number(o[2])>=10586?Number(o[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:s;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,s)}(i);return function(e){return 0!==e&&{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}(s)}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)),iu={supportsColor:i,stdout:i(process.stdout),stderr:i(process.stderr)}}var hu,fu,pu,gu,mu,yu,vu,bu,wu={exports:{}},Su={exports:{}},_u={exports:{}},Iu={exports:{}},xu={exports:{}},ku={exports:{}};function Eu(){return vu||(vu=1,function(){var e={};lu.exports=e,e.themes={};var t=i,n=e.styles=(tu||(tu=1,function(){var e={};uu.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"}))}()),uu.exports),r=Object.defineProperties,s=new RegExp(/[\r\n]+/g);e.supportsColor=du().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 o=/[|\\{}()[\]^$+*?.]/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(o,"\\$&")}(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"),o=this._styles,a=o.length;a--;){var c=n[o[a]];r=c.open+r.replace(c.closeRe,c.open)+c.close,i&&(r=r.replace(s,(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 s in t[n])i=e[t[n][s]](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=(hu||(hu=1,wu.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}),wu.exports),e.zalgo=(fu||(fu=1,Su.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 s(e){var t=!1;return r.filter((function(n){t=n===e})),t}return function(e,t){var r,o,a="";for(o 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(!s(o)){switch(a+=e[o],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)}),Su.exports),e.maps={},e.maps.america=(pu||(pu=1,_u.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)}}}),_u.exports)(e),e.maps.zebra=(gu||(gu=1,Iu.exports=function(e){return function(t,n){return n%2==0?t:e.inverse(t)}}),Iu.exports)(e),e.maps.rainbow=(mu||(mu=1,xu.exports=function(e){var t=["red","yellow","green","blue","magenta"];return function(n,r){return" "===n?n:e[t[r++%t.length]](n)}}),xu.exports)(e),e.maps.random=(yu||(yu=1,ku.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)}}),ku.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}())}()),lu.exports}function Cu(){return bu||(bu=1,function(e){var t=Eu();e.exports=t}(cu)),cu.exports}var Ou,$u,Nu={},Mu={},Au={};function Tu(){if($u)return au.exports;$u=1;const e=Cu(),{LEVEL:t,MESSAGE:n}=Nu;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,s=i.allColors[t].length;n<s;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 au.exports=e=>new i(e),au.exports.Colorizer=au.exports.Format=i,au.exports}Au.levels={emerg:0,alert:1,crit:2,error:3,warning:4,notice:5,info:6,debug:7},Au.colors={emerg:"red",alert:"yellow",crit:"red",error:"red",warning:"red",notice:"yellow",info:"green",debug:"blue"},Ou=Mu,Object.defineProperty(Ou,"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(Ou,"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(Ou,"syslog",{value:Au}),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:Mu})}(Nu);const{Colorizer:Pu}=Tu();var Du,ju,Ru,Lu,Fu,Uu,Bu={exports:{}},Wu={exports:{}};function Yu(){if(Fu)return Wu.exports;Fu=1;const{configs:e,LEVEL:t,MESSAGE:n}=Nu;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 Wu.exports=e=>new r(e),Wu.exports.Padder=Wu.exports.Format=r,Wu.exports}var Gu,Hu,Vu,zu,qu,Ku,Ju,Zu,Xu,Qu,ed,td,nd,rd,id={exports:{}},sd={exports:{}};function od(){return Hu||(Hu=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 s(e){return e.length<5e3&&!i.test(e)?`"${e}"`:JSON.stringify(e)}function o(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 s=1;s<n;s++)i+=`${t}"${s}":${r}${e[s]}`;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 s(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 s=g(String(i),v,l,u,m,y);return e+=void 0!==s?s:"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=o(i,h)),l.push(v);for(let n=0;n<_;n++){const r=i[n],o=g(r,v,l,u,m,y);void 0!==o&&(e+=`${S}${s(r)}:${w}${o}`,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,o,a,c,l){switch("object"==typeof n&&null!==n&&"function"==typeof n.toJSON&&(n=n.toJSON(e)),typeof n){case"string":return s(n);case"object":{if(null===n)return"null";if(-1!==o.indexOf(n))return r;const e=l;let t="",i=",";if(Array.isArray(n)){if(0===n.length)return"[]";if(f<o.length+1)return'"[Array]"';o.push(n),""!==c&&(t+=`\n${l+=c}`,i=`,\n${l}`);const r=Math.min(n.length,p);let s=0;for(;s<r-1;s++){const e=m(String(s),n[s],o,a,c,l);t+=void 0!==e?e:"null",t+=i}const u=m(String(s),n[s],o,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}`),o.pop(),`[${t}]`}o.push(n);let u="";""!==c&&(i=`,\n${l+=c}`,u=" ");let h="";for(const e of a){const r=m(e,n[e],o,a,c,l);void 0!==r&&(t+=`${h}${s(e)}:${u}${r}`,h=i)}return""!==c&&h.length>1&&(t=`\n${l}${t}\n${e}`),o.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 s(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 s=0;for(;s<i-1;s++){const t=y(String(s),n[s],u,g,m);e+=void 0!==t?t:"null",e+=r}const o=y(String(s),n[s],u,g,m);return e+=void 0!==o?o:"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=o(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}${s(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 s(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=o(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}${s(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,[])}}}(sd,sd.exports)),sd.exports}function ad(){if(zu)return Vu;zu=1;const e=ou,{MESSAGE:t}=Nu,n=od();function r(e,t){return"bigint"==typeof t?t.toString():t}return Vu=e(((e,i)=>{const s=n.configure(i);return e[t]=s(e,i.replacer||r,i.space),e}))}var cd,ld,ud,dd,hd,fd={exports:{}},pd=/d{1,4}|M{1,4}|YY(?:YY)?|S{1,3}|Do|ZZ|Z|([HhMsDm])\1?|[aA]|"[^"]*"|'[^']*'/g,gd="\\d\\d?",md="\\d\\d",yd="[^\\s]+",vd=/\[([^]*?)\]/gm;function bd(e,t){for(var n=[],r=0,i=e.length;r<i;r++)n.push(e[r].substr(0,t));return n}var wd=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 Sd(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 s=i[r];for(var o in s)e[o]=s[o]}return e}var _d=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],Id=["January","February","March","April","May","June","July","August","September","October","November","December"],xd=bd(Id,3),kd={dayNamesShort:bd(_d,3),dayNames:_d,monthNamesShort:xd,monthNames:Id,amPm:["am","pm"],DoFn:function(e){return e+["th","st","nd","rd"][e%10>3?0:(e-e%10!=10?1:0)*e%10]}},Ed=Sd({},kd),Cd=function(e){return Ed=Sd(Ed,e)},Od=function(e){return e.replace(/[|\\{()[^$+*?.-]/g,"\\$&")},$d=function(e,t){for(void 0===t&&(t=2),e=String(e);e.length<t;)e="0"+e;return e},Nd={D:function(e){return String(e.getDate())},DD:function(e){return $d(e.getDate())},Do:function(e,t){return t.DoFn(e.getDate())},d:function(e){return String(e.getDay())},dd:function(e){return $d(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 $d(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 $d(String(e.getFullYear()),4).substr(2)},YYYY:function(e){return $d(e.getFullYear(),4)},h:function(e){return String(e.getHours()%12||12)},hh:function(e){return $d(e.getHours()%12||12)},H:function(e){return String(e.getHours())},HH:function(e){return $d(e.getHours())},m:function(e){return String(e.getMinutes())},mm:function(e){return $d(e.getMinutes())},s:function(e){return String(e.getSeconds())},ss:function(e){return $d(e.getSeconds())},S:function(e){return String(Math.round(e.getMilliseconds()/100))},SS:function(e){return $d(Math.round(e.getMilliseconds()/10),2)},SSS:function(e){return $d(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?"-":"+")+$d(100*Math.floor(Math.abs(t)/60)+Math.abs(t)%60,4)},Z:function(e){var t=e.getTimezoneOffset();return(t>0?"-":"+")+$d(Math.floor(Math.abs(t)/60),2)+":"+$d(Math.abs(t)%60,2)}},Md=function(e){return+e-1},Ad=[null,gd],Td=[null,yd],Pd=["isPm",yd,function(e,t){var n=e.toLowerCase();return n===t.amPm[0]?0:n===t.amPm[1]?1:null}],Dd=["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}],jd={D:["day",gd],DD:["day",md],Do:["day",gd+yd,function(e){return parseInt(e,10)}],M:["month",gd,Md],MM:["month",md,Md],YY:["year",md,function(e){var t=+(""+(new Date).getFullYear()).substr(0,2);return+(""+(+e>68?t-1:t)+e)}],h:["hour",gd,void 0,"isPm"],hh:["hour",md,void 0,"isPm"],H:["hour",gd],HH:["hour",md],m:["minute",gd],mm:["minute",md],s:["second",gd],ss:["second",md],YYYY:["year","\\d{4}"],S:["millisecond","\\d",function(e){return 100*+e}],SS:["millisecond",md,function(e){return 10*+e}],SSS:["millisecond","\\d{3}"],d:Ad,dd:Ad,ddd:Td,dddd:Td,MMM:["month",yd,wd("monthNamesShort")],MMMM:["month",yd,wd("monthNames")],a:Pd,A:Pd,ZZ:Dd,Z:Dd},Rd={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"},Ld=function(e){return Sd(Rd,e)},Fd=function(e,t,n){if(void 0===t&&(t=Rd.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=Rd[t]||t).replace(vd,(function(e,t){return r.push(t),"@@@"}));var i=Sd(Sd({},Ed),n);return(t=t.replace(pd,(function(t){return Nd[t](e,i)}))).replace(/@@@/g,(function(){return r.shift()}))};function Ud(e,t,n){if(void 0===n&&(n={}),"string"!=typeof t)throw new Error("Invalid format in fecha parse");if(t=Rd[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=[],s=[],o=t.replace(vd,(function(e,t){return s.push(Od(t)),"@@@"})),a={},c={};o=Od(o).replace(pd,(function(e){var t=jd[e],n=t[0],r=t[1],s=t[3];if(a[n])throw new Error("Invalid format. "+n+" specified twice in format");return a[n]=!0,s&&(c[s]=!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")})),o=o.replace(/@@@/g,(function(){return s.shift()}));var l=e.match(new RegExp(o,"i"));if(!l)return null;for(var u,d=Sd(Sd({},Ed),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 Bd,Wd,Yd,Gd,Hd={format:Fd,parse:Ud,defaultI18n:kd,setGlobalDateI18n:Cd,setGlobalDateMasks:Ld},Vd=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:Sd,default:Hd,defaultI18n:kd,format:Fd,parse:Ud,setGlobalDateI18n:Cd,setGlobalDateMasks:Ld}));const zd=Ql.format=ou;function qd(e,t){Object.defineProperty(zd,e,{get:()=>t(),configurable:!0})}Ql.levels=e=>(Pu.addColors(e.colors||e),e),qd("align",(function(){return ju?Du:(ju=1,Du=ou((e=>(e.message=`\t${e.message}`,e))))})),qd("errors",(function(){return function(){if(Lu)return Ru;Lu=1;const e=ou,{LEVEL:t,MESSAGE:n}=Nu;return Ru=e(((e,{stack:r,cause:i})=>{if(e instanceof Error){const s=Object.assign({},e,{level:e.level,[t]:e[t]||e.level,message:e.message,[n]:e[n]||e.message});return r&&(s.stack=e.stack),i&&(s.cause=e.cause),s}if(!(e.message instanceof Error))return e;const s=e.message;return Object.assign(e,s),e.message=s.message,e[n]=s.message,r&&(e.stack=s.stack),i&&(e.cause=s.cause),e}))}()})),qd("cli",(function(){return function(){if(Uu)return Bu.exports;Uu=1;const{Colorizer:e}=Tu(),{Padder:t}=Yu(),{configs:n,MESSAGE:r}=Nu;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 Bu.exports=e=>new i(e),Bu.exports.Format=i,Bu.exports}()})),qd("combine",(function(){return function(){if(Gu)return id.exports;Gu=1;const e=ou;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 id.exports=(...n)=>{const r=e(t(n)),i=r();return i.Format=r.Format,i},id.exports.cascade=t,id.exports}()})),qd("colorize",(function(){return Tu()})),qd("json",(function(){return ad()})),qd("label",(function(){return Ku?qu:(Ku=1,qu=ou(((e,t)=>t.message?(e.message=`[${t.label}] ${e.message}`,e):(e.label=t.label,e))))})),qd("logstash",(function(){return function(){if(Zu)return Ju;Zu=1;const e=ou,{MESSAGE:t}=Nu,n=od();return Ju=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}))}()})),qd("metadata",(function(){return Qu?Xu:(Qu=1,Xu=ou(((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})))})),qd("ms",(function(){return function(){if(td)return ed;td=1;const e=ou,t=Wl();return ed=e((e=>{const n=+new Date;return this.diff=n-(this.prevTime||n),this.prevTime=n,e.ms=`+${t(this.diff)}`,e}))}()})),qd("padLevels",(function(){return Yu()})),qd("prettyPrint",(function(){return function(){if(rd)return nd;rd=1;const e=i.inspect,t=ou,{LEVEL:n,MESSAGE:r,SPLAT:s}=Nu;return nd=t(((t,i={})=>{const o=Object.assign({},t);return delete o[n],delete o[r],delete o[s],t[r]=e(o,!1,i.depth||null,i.colorize),t}))}()})),qd("printf",(function(){return function(){if(cd)return fd.exports;cd=1;const{MESSAGE:e}=Nu;class t{constructor(e){this.template=e}transform(t){return t[e]=this.template(t),t}}return fd.exports=e=>new t(e),fd.exports.Printf=fd.exports.Format=t,fd.exports}()})),qd("simple",(function(){return function(){if(ud)return ld;ud=1;const e=ou,{MESSAGE:t}=Nu,n=od();return ld=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}))}()})),qd("splat",(function(){return function(){if(hd)return dd;hd=1;const e=i,{SPLAT:t}=Nu,n=/%[scdjifoO%]/g,r=/%%/g;class s{constructor(e){this.options=e}_splat(n,i){const s=n.message,o=n[t]||n.splat||[],a=s.match(r),c=a&&a.length||0,l=i.length-c-o.length,u=l<0?o.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(s,...o),n}transform(e){const r=e.message,i=e[t]||e.splat;if(!i||!i.length)return e;const s=r&&r.match&&r.match(n);if(!s&&(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 s?this._splat(e,s):e}}return dd=e=>new s(e)}()})),qd("timestamp",(function(){return function(){if(Wd)return Bd;Wd=1;const e=Vd;return Bd=ou(((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)))}()})),qd("uncolorize",(function(){return function(){if(Gd)return Yd;Gd=1;const e=Cu(),t=ou,{MESSAGE:n}=Nu;return Yd=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 Kd={};!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})}))}}}(Kd);var Jd,Zd,Xd,Qd,eh,th,nh={},rh={exports:{}},ih={exports:{}};function sh(){return Qd?Xd:(Qd=1,Xd=P)}function oh(){if(th)return eh;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 th=1,eh={destroy:function(r,i){var s=this,o=this._readableState&&this._readableState.destroyed,a=this._writableState&&this._writableState.destroyed;return o||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?s._writableState?s._writableState.errorEmitted?process.nextTick(t,s):(s._writableState.errorEmitted=!0,process.nextTick(e,s,n)):process.nextTick(e,s,n):i?(process.nextTick(t,s),i(n)):process.nextTick(t,s)})),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)}},eh}var ah,ch,lh,uh={};function dh(){if(ah)return uh;ah=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 s;let o;if("string"==typeof t&&(s="not ",t.substr(0,4)===s)?(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"))o=`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";o=`The "${e}" ${r} ${i} ${n(t,"type")}`}return o+=". Received type "+typeof r,o}),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"),uh.codes=e,uh}function hh(){if(lh)return ch;lh=1;var e=dh().codes.ERR_INVALID_OPT_VALUE;return ch={getHighWaterMark:function(t,n,r,i){var s=function(e,t,n){return null!=e.highWaterMark?e.highWaterMark:t?e[n]:null}(n,i,r);if(null!=s){if(!isFinite(s)||Math.floor(s)!==s||s<0)throw new e(i?r:"highWaterMark",s);return Math.floor(s)}return t.objectMode?16:16384}}}var fh,ph,gh,mh,yh={exports:{}},vh={exports:{}};function bh(){if(ph)return yh.exports;ph=1;try{var e=require("util");if("function"!=typeof e.inherits)throw"";yh.exports=e.inherits}catch(e){yh.exports=(fh||(fh=1,"function"==typeof Object.create?vh.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:vh.exports=function(e,t){if(t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}}),vh.exports)}return yh.exports}function wh(){if(mh)return gh;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)}mh=1;var s=D.Buffer,o=i.inspect,a=o&&o.custom||"inspect";function c(e,t,n){s.prototype.copy.call(e,t,n)}return gh=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 s.alloc(0);for(var t=s.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,s=e>i.length?i.length:e;if(s===i.length?r+=i:r+=i.slice(0,e),0==(e-=s)){s===i.length?(++n,t.next?this.head=t.next:this.head=this.tail=null):(this.head=t,t.data=i.slice(s));break}++n}return this.length-=n,r}},{key:"_getBuffer",value:function(e){var t=s.allocUnsafe(e),n=this.head,r=1;for(n.data.copy(t),e-=n.data.length;n=n.next;){var i=n.data,o=e>i.length?i.length:e;if(i.copy(t,t.length-e,0,o),0==(e-=o)){o===i.length?(++r,n.next?this.head=n.next:this.head=this.tail=null):(this.head=n,n.data=i.slice(o));break}++r}return this.length-=r,t}},{key:a,value:function(e,n){return o(this,t(t({},n),{},{depth:0,customInspect:!1}))}}]),e}()}var Sh,_h,Ih,xh,kh,Eh,Ch,Oh,$h,Nh,Mh,Ah,Th,Ph,Dh={},jh={exports:{}};function Rh(){if(_h)return Dh;_h=1;var e=(Sh||(Sh=1,function(e,t){var n=D,r=n.Buffer;function i(e,t){for(var n in e)t[n]=e[n]}function s(e,t,n){return r(e,t,n)}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?e.exports=n:(i(n,t),t.Buffer=s),s.prototype=Object.create(r.prototype),i(r,s),s.from=function(e,t,n){if("number"==typeof e)throw new TypeError("Argument must not be a number");return r(e,t,n)},s.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},s.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return r(e)},s.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n.SlowBuffer(e)}}(jh,jh.exports)),jh.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=s,this.end=o,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 s(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 o(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 Dh.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 s=r(t[i]);return s>=0?(s>0&&(e.lastNeed=s-1),s):--i<n||-2===s?0:(s=r(t[i]))>=0?(s>0&&(e.lastNeed=s-2),s):--i<n||-2===s?0:(s=r(t[i]))>=0?(s>0&&(2===s?s=0:e.lastNeed=s-3),s):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},Dh}function Lh(){if(xh)return Ih;xh=1;var e=dh().codes.ERR_STREAM_PREMATURE_CLOSE;function t(){}return Ih=function n(r,i,s){if("function"==typeof i)return n(r,null,i);i||(i={}),s=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)}}}(s||t);var o=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,o||s.call(r)},d=r._readableState&&r._readableState.endEmitted,h=function(){o=!1,d=!0,a||s.call(r)},f=function(e){s.call(r,e)},p=function(){var t;return o&&!d?(r._readableState&&r._readableState.ended||(t=new e),s.call(r,t)):a&&!l?(r._writableState&&r._writableState.ended||(t=new e),s.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)}},Ih}function Fh(){if(Nh)return $h;var e;Nh=1,$h=_,_.ReadableState=S,j.EventEmitter;var t,n=function(e,t){return e.listeners(t).length},r=sh(),s=D.Buffer,o=(void 0!==Tl?Tl:"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=wh(),h=oh(),f=hh().getHighWaterMark,p=dh().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;bh()(_,r);var b=h.errorOrDestroy,w=["error","close","destroy","pause","resume"];function S(t,n,r){e=e||Uh(),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=Rh().StringDecoder),this.decoder=new c(t.encoding),this.encoding=t.encoding)}function _(t){if(e=e||Uh(),!(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,O(e)))}}(e,l);else if(a||(c=function(e,t){var n,r;return r=t,s.isBuffer(r)||r instanceof o||"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)===s.prototype||(n=function(e){return s.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):$(e,l)):x(e,l,n,!1)}else i||(l.reading=!1,$(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)),$(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=s.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=Rh().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(O,e))}function O(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,P(e)}function $(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 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 A(e){t("readable nexttick read 0"),e.read(0)}function T(e,n){t("resume",n.reading),n.reading||e.read(0),n.resumeScheduled=!1,e.emit("resume"),P(e),n.flowing&&!n.reading&&e.read(0)}function P(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,s=n.needReadable;return t("need readable",s),(0===n.length||n.length-e<n.highWaterMark)&&t("length less than watermark",s=!0),n.ended||n.reading?t("reading or ended",s=!1):s&&(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,s=this._readableState;switch(s.pipesCount){case 0:s.pipes=e;break;case 1:s.pipes=[s.pipes,e];break;default:s.pipes.push(e)}s.pipesCount+=1,t("pipe count=%d opts=%j",s.pipesCount,r);var o=r&&!1===r.end||e===process.stdout||e===process.stderr?p:a;function a(){t("onend"),e.end()}s.endEmitted?process.nextTick(o):i.once("end",o),e.on("unpipe",(function n(r,o){t("onunpipe"),r===i&&o&&!1===o.hasUnpiped&&(o.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,!s.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,P(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===s.pipesCount&&s.pipes===e||s.pipesCount>1&&-1!==U(s.pipes,e))&&!l&&(t("false write response, pause",s.awaitDrain),s.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),s.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 s=0;s<i;s++)r[s].emit("unpipe",this,{hasUnpiped:!1});return this}var o=U(t.pipes,e);return-1===o||(t.pipes.splice(o,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),s=this._readableState;return"data"===e?(s.readableListening=this.listenerCount("readable")>0,!1!==s.flowing&&this.resume()):"readable"===e&&(s.endEmitted||s.readableListening||(s.readableListening=s.needReadable=!0,s.flowing=!1,s.emittedReadable=!1,t("on readable",s.length,s.reading),s.length?C(this):s.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(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(T,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 s 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(s){t("wrapped data"),r.decoder&&(s=r.decoder.write(s)),r.objectMode&&null==s||(r.objectMode||s&&s.length)&&(n.push(s)||(i=!0,e.pause()))})),e)void 0===this[s]&&"function"==typeof e[s]&&(this[s]=function(t){return function(){return e[t].apply(e,arguments)}}(s));for(var o=0;o<w.length;o++)e.on(w[o],this.emit.bind(this,w[o]));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(Eh)return kh;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}Eh=1;var n=Lh(),r=Symbol("lastResolve"),i=Symbol("lastReject"),s=Symbol("error"),o=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[s];if(null!==t)return Promise.reject(t);if(this[o])return Promise.resolve(u(void 0,!0));if(this[l].destroyed)return new Promise((function(t,n){process.nextTick((function(){e[s]?n(e[s]):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[o]?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 kh=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,s,{value:null,writable:!0}),t(d,o,{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[s]=e)}var n=f[r];null!==n&&(f[a]=null,f[r]=null,f[i]=null,n(u(void 0,!0))),f[o]=!0})),e.on("readable",h.bind(null,f)),f},kh}()),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(Oh)return Ch;function e(e,t,n,r,i,s,o){try{var a=e[s](o),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}Oh=1;var r=dh().codes.ERR_INVALID_ARG_TYPE;return Ch=function(i,s,o){var a;if(s&&"function"==typeof s.next)a=s;else if(s&&s[Symbol.asyncIterator])a=s[Symbol.asyncIterator]();else{if(!s||!s[Symbol.iterator])throw new r("iterable",["Iterable"],s);a=s[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},o)),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,s){var o=t.apply(n,r);function a(t){e(o,i,s,a,c,"next",t)}function c(t){e(o,i,s,a,c,"throw",t)}a(void 0)}))},d.apply(this,arguments)}return c._read=function(){l||(l=!0,u())},c},Ch}()),u(_,e,t)}),$h}function Uh(){if(Ah)return Mh;Ah=1;var e=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t};Mh=o;var t=Fh(),n=Bh();bh()(o,t);for(var r=e(n.prototype),i=0;i<r.length;i++){var s=r[i];o.prototype[s]||(o.prototype[s]=n.prototype[s])}function o(e){if(!(this instanceof o))return new o(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(o.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(o.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(o.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(o.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)}}),Mh}function Bh(){if(Ph)return Th;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;Ph=1,Th=_,_.WritableState=S;var n,r={deprecate:Zd?Jd:(Zd=1,Jd=i.deprecate)},s=sh(),o=D.Buffer,a=(void 0!==Tl?Tl:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{}).Uint8Array||function(){},c=oh(),l=hh().getHighWaterMark,u=dh().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||Uh(),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 s=!1===n.decodeStrings;this.decodeStrings=!s,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(O,e,t),e._writableState.errorEmitted=!0,b(e,r)):(i(r),e._writableState.errorEmitted=!0,b(e,r),O(e,t))}(e,n,r,t,i);else{var s=E(n)||e.destroyed;s||n.corked||n.bufferProcessing||!n.bufferedRequest||k(e,n),r?process.nextTick(x,e,n,s,i):x(e,n,s,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||Uh());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)),s.call(this)}function I(e,t,n,r,i,s,o){t.writelen=r,t.writecb=o,t.writing=!0,t.sync=!0,t.destroyed?t.onwrite(new g("write")):n?e._writev(i,t.onwrite):e._write(i,s,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(),O(e,t)}function k(t,n){n.bufferProcessing=!0;var r=n.bufferedRequest;if(t._writev&&r&&r.next){var i=n.bufferedRequestCount,s=new Array(i),o=n.corkedRequestsFree;o.entry=r;for(var a=0,c=!0;r;)s[a]=r,r.isBuf||(c=!1),r=r.next,a+=1;s.allBuffers=c,I(t,n,!0,n.length,s,"",o.finish),n.pendingcb++,n.lastBufferedRequest=null,o.next?(n.corkedRequestsFree=o.next,o.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"),O(e,t)}))}function O(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 bh()(_,s),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,s=!1,c=!i.objectMode&&(r=e,o.isBuffer(r)||r instanceof a);return c&&!o.isBuffer(e)&&(e=function(e){return o.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++,s=function(e,t,n,r,i,s){if(!n){var a=function(e,t,n){return e.objectMode||!1===e.decodeStrings||"string"!=typeof t||(t=o.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:s,next:null},u?u.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1}else I(e,t,!1,c,r,i,s);return l}(this,i,c,e,t,n)),s},_.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,O(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)},Th}const Wh=i,Yh=Bh(),{LEVEL:Gh}=Nu,Hh=ih.exports=function(e={}){Yh.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())}))};Wh.inherits(Hh,Yh),Hh.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[Gh]]){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)},Hh.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)},Hh.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[Gh]])||!this.handleExceptions&&!0===t.exception)},Hh.prototype._nop=function(){};var Vh=ih.exports,zh={exports:{}};const qh=i,{LEVEL:Kh}=Nu,Jh=Vh,Zh=zh.exports=function(e={}){if(Jh.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))};qh.inherits(Zh,Jh),Zh.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[Kh]])&&this.transport.log(e[Kh],e.message,e,this._nop),n(null)},Zh.prototype._writev=function(e,t){for(let t=0;t<e.length;t++)this._accept(e[t])&&(this.transport.log(e[t].chunk[Kh],e[t].chunk.message,e[t].chunk,this._nop),e[t].callback());return t(null)},Zh.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"))},Zh.prototype.close=function(){this.transport.close&&this.transport.close(),this.transport.__winstonError&&(this.transport.removeListener("error",this.transport.__winstonError),this.transport.__winstonError=null)};var Xh=zh.exports;rh.exports=Vh,rh.exports.LegacyTransportStream=Xh;var Qh,ef,tf=rh.exports,nf={exports:{}},rf={exports:{}},sf={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}(sf,sf.exports);var of=sf.exports,af={},cf={exports:{}},lf={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}(lf,lf.exports);var uf=lf.exports,df={};Object.defineProperty(df,"__esModule",{value:!0}),df.fallback=vf,df.wrap=bf;var hf,ff,pf,gf=df.hasQueueMicrotask="function"==typeof queueMicrotask&&queueMicrotask,mf=df.hasSetImmediate="function"==typeof setImmediate&&setImmediate,yf=df.hasNextTick="object"==typeof process&&"function"==typeof process.nextTick;function vf(e){setTimeout(e,0)}function bf(e){return(t,...n)=>e((()=>t(...n)))}function wf(){if(pf)return af;pf=1,Object.defineProperty(af,"__esModule",{value:!0}),af.isAsyncIterable=af.isAsyncGenerator=af.isAsync=void 0;var e,t=(ff||(ff=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 o(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 o(r,n);n(null,r)}))};var n=s(uf),r=s(df),i=wf();function s(e){return e&&e.__esModule?e:{default:e}}function o(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}(cf,cf.exports)),cf.exports),n=(e=t)&&e.__esModule?e:{default:e};function r(e){return"AsyncFunction"===e[Symbol.toStringTag]}return af.default=function(e){if("function"!=typeof e)throw new Error("expected a function");return r(e)?(0,n.default)(e):e},af.isAsync=r,af.isAsyncGenerator=function(e){return"AsyncGenerator"===e[Symbol.toStringTag]},af.isAsyncIterable=function(e){return"function"==typeof e[Symbol.asyncIterator]},af}hf=gf?queueMicrotask:mf?setImmediate:yf?process.nextTick:vf,df.default=bf(hf);var Sf={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}(Sf,Sf.exports);var _f,If=Sf.exports,xf={exports:{}},kf={exports:{}},Ef={exports:{}},Cf={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}(Cf,Cf.exports);var Of=Cf.exports,$f={exports:{}},Nf={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}(Nf,Nf.exports);var Mf=Nf.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,s,o,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):[],s=-1,o=i.length,function e(){var n=i[++s];return"__proto__"===n?e():s<o?{value:t[n],key:n}:null})};var n=i(of),r=i(Mf);function i(e){return e&&e.__esModule?e:{default:e}}e.exports=t.default}($f,$f.exports);var Af=$f.exports,Tf={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}(Tf,Tf.exports);var Pf=Tf.exports,Df={exports:{}},jf={exports:{}};!function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default={},e.exports=t.default}(jf,jf.exports);var Rf=jf.exports;!function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t,n,i){let s=!1,o=!1,a=!1,c=0,l=0;function u(){c>=t||a||s||(a=!0,e.next().then((({value:e,done:t})=>{if(!o&&!s){if(a=!1,t)return s=!0,void(c<=0&&i(null));c++,n(e,l,d),l++,u()}})).catch(h))}function d(e,t){if(c-=1,!o)return e?h(e):!1===e?(s=!0,void(o=!0)):t===r.default||s&&c<=0?(s=!0,i(null)):void u()}function h(e){o||(a=!1,s=!0,i(e))}u()};var n,r=(n=Rf)&&n.__esModule?n:{default:n};e.exports=t.default}(Df,Df.exports);var Lf=Df.exports;!function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var n=c(Of),r=c(Af),i=c(Pf),s=wf(),o=c(Lf),a=c(Rf);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,s.isAsyncGenerator)(t))return(0,o.default)(t,e,c,l);if((0,s.isAsyncIterable)(t))return(0,o.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}(Ef,Ef.exports);var Ff=Ef.exports;!function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var n=s(Ff),r=s(wf()),i=s(If);function s(e){return e&&e.__esModule?e:{default:e}}t.default=(0,i.default)((function(e,t,i,s){return(0,n.default)(t)(e,(0,r.default)(i),s)}),4),e.exports=t.default}(kf,kf.exports);var Uf,Bf,Wf=kf.exports;var Yf,Gf,Hf,Vf,zf,qf,Kf={exports:{}};function Jf(){if(Gf)return Yf;Gf=1,Yf=a;var e=dh().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,s=Uh();function o(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 s=this._readableState;s.reading=!1,(s.needReadable||s.length<s.highWaterMark)&&this._read(s.highWaterMark)}function a(e){if(!(this instanceof a))return new a(e);s.call(this,e),this._transformState={afterTransform:o.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 bh()(a,s),a.prototype.push=function(e,t){return this._transformState.needTransform=!1,s.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){s.prototype._destroy.call(this,e,(function(e){t(e)}))},Yf}!function(e,t){var n=P;"disable"===process.env.READABLE_STREAM&&n?(e.exports=n.Readable,Object.assign(e.exports,n),e.exports.Stream=n):((t=e.exports=Fh()).Stream=n||t,t.Readable=t,t.Writable=Bh(),t.Duplex=Uh(),t.Transform=Jf(),t.PassThrough=function(){if(Vf)return Hf;Vf=1,Hf=t;var e=Jf();function t(n){if(!(this instanceof t))return new t(n);e.call(this,n)}return bh()(t,e),t.prototype._transform=function(e,t,n){n(null,e)},Hf}(),t.finished=Lh(),t.pipeline=function(){if(qf)return zf;var e;qf=1;var t=dh().codes,n=t.ERR_MISSING_ARGS,r=t.ERR_STREAM_DESTROYED;function i(e){if(e)throw e}function s(e){e()}function o(e,t){return e.pipe(t)}return zf=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,s){s=function(e){var t=!1;return function(){t||(t=!0,e.apply(void 0,arguments))}}(s);var o=!1;t.on("close",(function(){o=!0})),void 0===e&&(e=Lh()),e(t,{readable:n,writable:i},(function(e){if(e)return s(e);o=!0,s()}));var a=!1;return function(e){if(!o&&!a)return a=!0,function(e){return e.setHeader&&"function"==typeof e.abort}(t)?t.abort():"function"==typeof t.destroy?t.destroy():void s(e||new r("pipe"))}}(t,i,n>0,(function(e){l||(l=e),e&&d.forEach(s),i||(d.forEach(s),u(l))}))}));return a.reduce(o)},zf}())}(Kf,Kf.exports);var Zf,Xf,Qf,ep,tp=Kf.exports,np={exports:{}};function rp(){if(Xf)return Zf;Xf=1;var e=[],t=[],n=function(){};function r(t){return!~e.indexOf(t)&&(e.push(t),!0)}function i(e){n=e}function s(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 o(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=o,e.set=i,e.use=r,l((function(){return!1}),e)}function d(e){return e.enabled=!0,e.modify=o,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 Zf=function(e){return e.introduce=l,e.enabled=s,e.process=c,e.modify=o,e.write=a,e.nope=u,e.yep=d,e.set=i,e.use=r,e}}var ip,sp,op,ap,cp,lp,up={exports:{}},dp={exports:{}};function hp(){if(lp)return up.exports;lp=1;var e=sp?ip:(sp=1,ip={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(cp)return dp.exports;cp=1;var e=ap?op:(ap=1,op=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=dp.exports=function(r){for(var i=[],s=0,o=r.length;s<o;s++){var a=r[s];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))}},dp.exports}(),n=Object.hasOwnProperty,r=Object.create(null);for(var i in e)n.call(e,i)&&(r[e[i]]=i);var s=up.exports={to:{},get:{}};function o(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 s.get=function(e){var t,n;switch(e.substring(0,3).toLowerCase()){case"hsl":t=s.get.hsl(e),n="hsl";break;case"hwb":t=s.get.hwb(e),n="hwb";break;default:t=s.get.rgb(e),n="rgb"}return t?{model:n,value:t}:null},s.get.rgb=function(t){if(!t)return null;var r,i,s,a=[0,0,0,1];if(r=t.match(/^#([a-f0-9]{6})([a-f0-9]{2})?$/i)){for(s=r[2],r=r[1],i=0;i<3;i++){var c=2*i;a[i]=parseInt(r.slice(c,c+2),16)}s&&(a[3]=parseInt(s,16)/255)}else if(r=t.match(/^#([a-f0-9]{3,4})$/i)){for(s=(r=r[1])[3],i=0;i<3;i++)a[i]=parseInt(r[i]+r[i],16);s&&(a[3]=parseInt(s+s,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]=o(a[i],0,255);return a[3]=o(a[3],0,1),a},s.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,o(parseFloat(t[2]),0,100),o(parseFloat(t[3]),0,100),o(isNaN(n)?1:n,0,1)]}return null},s.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,o(parseFloat(t[2]),0,100),o(parseFloat(t[3]),0,100),o(isNaN(n)?1:n,0,1)]}return null},s.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])):"")},s.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]+")"},s.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]+")"},s.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]+")"},s.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+")"},s.to.keyword=function(e){return r[e.slice(0,3)]},up.exports}var fp,pp,gp,mp,yp,vp,bp,wp,Sp,_p,Ip,xp,kp,Ep,Cp,Op,$p,Np,Mp,Ap,Tp,Pp,Dp,jp,Rp,Lp,Fp,Up={exports:{}};function Bp(){if(gp)return Up.exports;gp=1;var e=pp?fp:(pp=1,fp={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=Up.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 s=r[i].channels,o=r[i].labels;delete r[i].channels,delete r[i].labels,Object.defineProperty(r[i],"channels",{value:s}),Object.defineProperty(r[i],"labels",{value:o})}return r.rgb.hsl=function(e){var t,n,r=e[0]/255,i=e[1]/255,s=e[2]/255,o=Math.min(r,i,s),a=Math.max(r,i,s),c=a-o;return a===o?t=0:r===a?t=(i-s)/c:i===a?t=2+(s-r)/c:s===a&&(t=4+(r-i)/c),(t=Math.min(60*t,360))<0&&(t+=360),n=(o+a)/2,[t,100*(a===o?0:n<=.5?c/(a+o):c/(2-a-o)),100*n]},r.rgb.hsv=function(e){var t,n,r,i,s,o=e[0]/255,a=e[1]/255,c=e[2]/255,l=Math.max(o,a,c),u=l-Math.min(o,a,c),d=function(e){return(l-e)/6/u+.5};return 0===u?i=s=0:(s=u/l,t=d(o),n=d(a),r=d(c),o===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*s,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,s,o,a=1/0;for(var c in e)if(e.hasOwnProperty(c)){var l=(s=n,o=e[c],Math.pow(s[0]-o[0],2)+Math.pow(s[1]-o[1],2)+Math.pow(s[2]-o[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],s=t[2];return i/=100,s/=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-(s=s>.008856?Math.pow(s,1/3):7.787*s+16/116))]},r.hsl.rgb=function(e){var t,n,r,i,s,o=e[0]/360,a=e[1]/100,c=e[2]/100;if(0===a)return[s=255*c,s,s];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=o+1/3*-(l-1))<0&&r++,r>1&&r--,s=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*s;return i},r.hsl.hsv=function(e){var t=e[0],n=e[1]/100,r=e[2]/100,i=n,s=Math.max(r,.01);return n*=(r*=2)<=1?r:2-r,i*=s<=1?s:2-s,[t,100*(0===r?2*i/(s+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,s=t-Math.floor(t),o=255*r*(1-n),a=255*r*(1-n*s),c=255*r*(1-n*(1-s));switch(r*=255,i){case 0:return[r,c,o];case 1:return[a,r,o];case 2:return[o,r,c];case 3:return[o,a,r];case 4:return[c,o,r];case 5:return[r,o,a]}},r.hsv.hsl=function(e){var t,n,r,i=e[0],s=e[1]/100,o=e[2]/100,a=Math.max(o,.01);return r=(2-s)*o,n=s*a,[i,100*(n=(n/=(t=(2-s)*a)<=1?t:2-t)||0),100*(r/=2)]},r.hwb.rgb=function(e){var t,n,r,i,s,o,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:s=n,o=i,a=l;break;case 1:s=i,o=n,a=l;break;case 2:s=l,o=n,a=i;break;case 3:s=l,o=i,a=n;break;case 4:s=i,o=l,a=n;break;case 5:s=n,o=l,a=i}return[255*s,255*o,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,s=e[1]/100,o=e[2]/100;return n=-.9689*i+1.8758*s+.0415*o,r=.0557*i+-.204*s+1.057*o,t=(t=3.2406*i+-1.5372*s+-.4986*o)>.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 s=Math.pow(n,3),o=Math.pow(t,3),a=Math.pow(r,3);return n=s>.008856?s:(n-16/116)/7.787,t=o>.008856?o:(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],s=1 in arguments?arguments[1]:r.rgb.hsv(e)[2];if(0===(s=Math.round(s/50)))return 30;var o=30+(Math.round(i/255)<<2|Math.round(n/255)<<1|Math.round(t/255));return 2===s&&(o+=60),o},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,s=Math.max(Math.max(n,r),i),o=Math.min(Math.min(n,r),i),a=s-o;return t=a<=0?0:s===n?(r-i)/a%6:s===r?2+(i-n)/a:4+(n-r)/a+4,t/=6,[360*(t%=1),100*a,100*(a<1?o/(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,s=[0,0,0],o=t%1*6,a=o%1,c=1-a;switch(Math.floor(o)){case 0:s[0]=1,s[1]=a,s[2]=0;break;case 1:s[0]=c,s[1]=1,s[2]=0;break;case 2:s[0]=0,s[1]=1,s[2]=a;break;case 3:s[0]=0,s[1]=c,s[2]=1;break;case 4:s[0]=a,s[1]=0,s[2]=1;break;default:s[0]=1,s[1]=0,s[2]=c}return i=(1-n)*r,[255*(n*s[0]+i),255*(n*s[1]+i),255*(n*s[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]},Up.exports}function Wp(){if(bp)return vp;bp=1;var e=Bp(),t=function(){if(yp)return mp;yp=1;var e=Bp();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(),s=Object.keys(e[i]),o=s.length,a=0;a<o;a++){var c=s[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],s=e[r[t].parent][t],o=r[t].parent;r[o].parent;)i.unshift(r[o].parent),s=n(e[r[o].parent][o],s),o=r[o].parent;return s.conversion=i,s}return mp=function(e){for(var n=t(e),i={},s=Object.keys(n),o=s.length,a=0;a<o;a++){var c=s[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)}))})),vp=n}function Yp(){if(kp)return xp;kp=1;var e=function(){if(Sp)return wp;Sp=1;var e=hp(),t=Wp(),n=[].slice,r=["keyword","gray","hex"],i={};Object.keys(t).forEach((function(e){i[n.call(t[e].labels).sort().join("")]=e}));var s={};function o(a,c){if(!(this instanceof o))return new o(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 o)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(s[this.model])for(d=t[this.model].channels,u=0;u<d;u++){var v=s[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){(s[e]||(s[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 o.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 o(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 o(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 o(e):t[this.model].keyword(this.color)},hex:function(t){return arguments.length?new o(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 o.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,s=2*i-1,a=n.alpha()-r.alpha(),c=((s*a==-1?s:(s+a)/(1+s*a))+1)/2,l=1-c;return o.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;o.prototype[e]=function(){if(this.model===e)return new o(this);if(arguments.length)return new o(arguments,e);var n,r="number"==typeof arguments[i]?i:this.valpha;return new o((n=t[this.model][e].raw(this.color),Array.isArray(n)?n:[n]).concat(r),e)},o[e]=function(t){return"number"==typeof t&&(t=l(n.call(arguments),i)),new o(t,e)}}})),wp=o}(),t=(Ip||(Ip=1,_p=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}),_p);return xp=function(n,r){var i=n.split(r||":"),s=t(i[0]);if(!i.length)return s;for(var o=0,a=i.length-1;o<a;o++)s=e(s).mix(e(t(i[o+1]))).saturate(1).hex();return s},xp}function Gp(){if(Dp)return Pp;Dp=1;var e=function(){if(Tp)return Ap;Tp=1;var e=(Mp||(Mp=1,Np=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}),Np);return Ap=function(t){return function(n){try{return e(n,t())}catch(e){}return!1}}}();return Pp=e((function(){return process.env.DEBUG||process.env.DIAGNOSTICS}))}"production"===process.env.NODE_ENV?np.exports=function(){if(ep)return Qf;ep=1;var e=rp()((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 Qf=e}():np.exports=function(){if(Fp)return Lp;Fp=1;var e=rp(),t=N.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($p)return Op;$p=1;var e=Yp(),t=function(){if(Cp)return Ep;function e(t,n){return n?new e(t).style(n):this instanceof e?void(this.text=t):new e(t)}return Cp=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,s=n/255*5;return this.ansi(r,i,s)},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()},Ep=e}();return Op=function(n,r){var i=r.namespace,s=!1!==r.colors?t(i+":",e(i)):i+":";return n[0]=s+" "+n[0],n}}()),n.use(Gp()),n.set(Rp?jp:(Rp=1,jp=function(e,t){try{Function.prototype.apply.call(console.log,console,t)}catch(e){}})),Lp=n}();var Hp,Vp,zp,qp,Kp,Jp,Zp=np.exports;function Xp(){if(qp)return zp;qp=1;const e=$,t=x,n=(Bf||(Bf=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t){return(0,r.default)(s.default,e,t)};var n=(_f||(_f=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var n=s(of),r=s(wf()),i=s(If);function s(e){return e&&e.__esModule?e:{default:e}}t.default=(0,i.default)(((e,t,i)=>{var s=(0,n.default)(t)?[]:{};e(t,((e,t,n)=>{(0,r.default)(e)(((e,...r)=>{r.length<2&&([r]=r),s[t]=r,n(e)}))}),(e=>i(e,s)))}),3),e.exports=t.default}(rf,rf.exports)),rf.exports),r=o(n),i=(Uf||(Uf=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var n=i(Wf),r=i(If);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}(xf,xf.exports)),xf.exports),s=o(i);function o(e){return e&&e.__esModule?e:{default:e}}e.exports=t.default}(nf,nf.exports)),nf.exports),r=R,{MESSAGE:i}=Nu,{Stream:s,PassThrough:o}=tp,a=tf,c=Zp("winston:file"),l=M,u=function(){if(Vp)return Hp;Vp=1;const e=$,{StringDecoder:t}=L,{Stream:n}=tp;function r(){}return Hp=(i,s)=>{const o=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 s?s(t):c.emit("error",t),void c.destroy();!function t(){if(!c.destroyed)return e.read(n,o,0,o.length,u,((e,n)=>{if(e)return s?s(e):c.emit("error",e),void c.destroy();if(!n)return l&&((null==i.start||d>i.start)&&(s?s(null,l):c.emit("line",l)),d++,l=""),setTimeout(t,1e3);let r=a.write(o.slice(0,n));s||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)&&(s?s(null,r[f]):c.emit("line",r[f])),d++;return l=r[h],u+=n,t()}));e.close(n,r)}()})),s?c.destroy:c},Hp}();return zp=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 o,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 s=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 s?t():(this._drain=!0,this._stream.once("drain",(()=>{this._drain=!1,t()}))),c("written",s,this._drain),this.finishIfEnding(),s}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 s="",o=[],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&&o.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&&o.length>=n.rows&&o.shift(),o.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,o)})),c.on("data",(e=>{const t=(e=(s+e).split(/\n+/)).length-1;let r=0;for(;r<t;r++)(!n.start||a>=n.start)&&l(e[r]),a++;s=e[t]})),c.on("close",(()=>{s&&l(s,!0),"desc"===n.order&&(o=o.reverse()),r&&r(null,o)}))}stream(e={}){const n=t.join(this.dirname,this.filename),r=new s,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 o,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),s=[];this.zippedArchive&&s.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)),s.push(function(e){this.tailable?this._checkMaxFilesTailable(r,i,e):(this._created+=1,this._checkMaxFilesIncrementing(r,i,e))}.bind(this)),n(s,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 s=this._created-this.maxFiles,o=`${r}${0!==s?s:""}${n}${this.zippedArchive?".gz":""}`,a=t.join(this.dirname,o);e.unlink(a,i)}_checkMaxFilesTailable(r,i,s){const o=[];if(!this.maxFiles)return;const a=this.zippedArchive?".gz":"";for(let n=this.maxFiles-1;n>1;n--)o.push(function(n,s){let o=`${i}${n-1}${r}${a}`;const c=t.join(this.dirname,o);e.exists(c,(l=>{if(!l)return s(null);o=`${i}${n}${r}${a}`,e.rename(c,t.join(this.dirname,o),s)}))}.bind(this,n));n(o,(()=>{e.rename(t.join(this.dirname,`${i}${r}${a}`),t.join(this.dirname,`${i}1${r}${a}`),s)}))}_compressFile(t,n,i){e.access(t,e.F_OK,(s=>{if(s)return i();var o=r.createGzip(),a=e.createReadStream(t),c=e.createWriteStream(n);c.on("finish",(()=>{e.unlink(t,i)})),a.pipe(o).pipe(c)}))}_createLogDirIfNotExist(t){e.existsSync(t)||e.mkdirSync(t,{recursive:!0})}},zp}const Qp=e=>null!==e&&"object"==typeof e&&"function"==typeof e.pipe;Qp.writable=e=>Qp(e)&&!1!==e.writable&&"function"==typeof e._write&&"object"==typeof e._writableState,Qp.readable=e=>Qp(e)&&!1!==e.readable&&"function"==typeof e._read&&"object"==typeof e._readableState,Qp.duplex=e=>Qp.writable(e)&&Qp.readable(e),Qp.transform=e=>Qp.duplex(e)&&"function"==typeof e._transform;var eg,tg,ng=Qp;!function(e){Object.defineProperty(e,"Console",{configurable:!0,enumerable:!0,get:()=>function(){if(ef)return Qh;ef=1;const e=M,{LEVEL:t,MESSAGE:n}=Nu,r=tf;return Qh=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:()=>Xp()}),Object.defineProperty(e,"Http",{configurable:!0,enumerable:!0,get:()=>function(){if(Jp)return Kp;Jp=1;const e=F,t=U,{Stream:n}=tp,r=tf,{configure:i}=od();return Kp=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 s="";const o=this._request(e,i,r);return t.destroy=()=>o.destroy(),o.on("data",(e=>{const n=(e=(s+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)}s=e[n]})),o.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,s,o){const a=Object.assign({},this.headers);s&&s.bearer&&(a.Authorization=`Bearer ${s.bearer}`);const c=(this.ssl?t:e).request({...this.options,method:"POST",host:this.host,port:this.port,path:`/${o.replace(/^\//,"")}`,headers:a,auth:s&&s.username&&s.password?`${s.username}:${s.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"))}},Kp}()}),Object.defineProperty(e,"Stream",{configurable:!0,enumerable:!0,get:()=>function(){if(tg)return eg;tg=1;const e=ng,{MESSAGE:t}=Nu,n=M,r=tf;return eg=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()}}}()})}(nh);var rg={};const ig=Ql,{configs:sg}=Nu;rg.cli=ig.levels(sg.cli),rg.npm=ig.levels(sg.npm),rg.syslog=ig.levels(sg.syslog),rg.addColors=ig.levels;var og={exports:{}},ag={exports:{}};!function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var n=l(of),r=l(Rf),i=l(Wf),s=l(Of),o=l(Pf),a=l(wf()),c=l(If);function l(e){return e&&e.__esModule?e:{default:e}}function u(e,t,n){n=(0,s.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,o.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}(ag,ag.exports);var cg=ag.exports,lg={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}(lg,lg.exports);var ug=lg.exports;!function(e,t){Object.defineProperty(t,"__esModule",{value:!0});var n=o(cg),r=o(ug),i=o(wf()),s=o(If);function o(e){return e&&e.__esModule?e:{default:e}}t.default=(0,s.default)((function(e,t,s){return(0,n.default)(e,(0,r.default)((0,i.default)(t)),s)}),3),e.exports=t.default}(og,og.exports);var dg=og.exports,hg=Object.prototype.toString,fg=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=hg.call(e).slice(8,-1);return(t="Function"===n?t.substring(t.indexOf("(")+1,t.indexOf(")")):n)||"anonymous"}(e),r},pg={};!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 s=r.stack;return Error.prepareStackTrace=i,Error.stackTraceLimit=n,s},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,s=null,o=null,a=null,c="native"===n[5];if(n[1]){var l=(s=n[1]).lastIndexOf(".");if("."==s[l-1]&&l--,l>0){r=s.substr(0,l),i=s.substr(l+1);var u=r.indexOf(".Module");u>0&&(s=s.substr(u+1),r=r.substr(0,u))}o=null}i&&(o=r,a=i),"<anonymous>"===i&&(a=null,s=null);var d={fileName:n[2]||null,lineNumber:parseInt(n[3],10)||null,functionName:s,typeName:o,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)}}(pg);const{Writable:gg}=tp,mg=M,yg=dg,vg=Zp("winston:exception"),bg=fg,wg=pg,Sg=class extends gg{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 _g=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:mg.loadavg(),uptime:mg.uptime()}}getTrace(e){return(e?wg.parse(e):wg.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 Sg(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 s(){vg("doExit",i),vg("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(s);yg(n,((e,t)=>{const n=bg(t),r=e.transport||e;function i(e){return()=>{vg(e),n()}}r._ending=!0,r.once("finish",i("finished")),r.once("error",i("error"))}),(()=>i&&s())),this.logger.log(t),i&&(r=setTimeout(s,3e3))}_getExceptionHandlers(){return this.logger.transports.filter((e=>(e.transport||e).handleExceptions))}};const{Writable:Ig}=tp,xg=M,kg=dg,Eg=Zp("winston:rejection"),Cg=fg,Og=pg,$g=class extends Ig{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 Ng,Mg,Ag,Tg,Pg=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:xg.loadavg(),uptime:xg.uptime()}}getTrace(e){return(e?Og.parse(e):Og.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 $g(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 s(){Eg("doExit",i),Eg("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(s);kg(n,((e,t)=>{const n=Cg(t),r=e.transport||e;function i(e){return()=>{Eg(e),n()}}r._ending=!0,r.once("finish",i("finished")),r.once("error",i("error"))}),(()=>i&&s())),this.logger.log(t),i&&(r=setTimeout(s,3e3))}_getRejectionHandlers(){return this.logger.transports.filter((e=>(e.transport||e).handleRejections))}};function Dg(){if(Tg)return Ag;Tg=1;const{Stream:e,Transform:t}=tp,n=dg,{LEVEL:r,SPLAT:i}=Nu,s=ng,o=_g,a=Pg,c=Xh,l=(Mg||(Mg=1,Ng=class{constructor(e){const t=Dg();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)}}),Ng),{warn:u}=Kd,d=rg,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:s=!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||ad()(),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 o(this),this.rejections=new a(this),this.profilers={},this.exitOnError=s,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[s]=n;if("object"==typeof s&&null!==s&&!(t&&t.match&&t.match(h))){const o=Object.assign({},this.defaultMeta,s,{[r]:e,[i]:n,level:e,message:t});return s.message&&(o.message=`${o.message} ${s.message}`),s.stack&&(o.stack=s.stack),s.cause&&(o.cause=s.cause),this.write(o),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=!s(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(!s(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)}}),Ag=f}const{LEVEL:jg}=Nu,Rg=rg,Lg=Dg(),Fg=Zp("winston:create-logger");var Ug=function(e={}){e.levels=e.levels||Rg.npm.levels;class t extends Lg{constructor(e){super(e)}}const n=new t(e);return Object.keys(e.levels).forEach((function(e){Fg('Define prototype method for "%s"',e),"log"!==e?(t.prototype[e]=function(...t){const r=this||n;if(1===t.length){const[i]=t,s=i&&i.message&&i||{message:i};return s.level=s[jg]=e,r._addDefaultMeta(s),r.write(s),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 Bg=Ug;var Wg=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=Bg(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=Ql,{warn:n}=Kd;e.version="3.17.0",e.transports=nh,e.config=rg,e.addColors=t.levels,e.format=t.format,e.createLogger=Ug,e.Logger=Dg(),e.ExceptionHandler=_g,e.RejectionHandler=Pg,e.Container=Wg,e.Transport=tf,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"])}(Xl);var Yg=Pl(Xl),Gg={exports:{}};!function(e,t){var n=u;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=o(e,t))}(t=Gg.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 s=["buffer","hex","binary","base64"];function o(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===s.indexOf(n.encoding)&&"passthrough"!==n.algorithm)throw new Error('Encoding "'+n.encoding+'" not supported. supported values: '+s.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,s=Object.prototype.toString.call(t),o=/\[object (.*)\]/i.exec(s);if(o=(o=o?o[1]:"unknown:["+s+"]").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"===o||"function"===o||"asyncfunction"===o){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["_"+o]){if(e.ignoreUnknown)return r("["+o+"]");throw new Error('Unknown object type "'+o+'"')}this["_"+o](t)},_array:function(t,i){i=void 0!==i?i:!1!==e.unorderedArrays;var s=this;if(r("array:"+t.length+":"),!i||t.length<=1)return t.forEach((function(e){return s.dispatch(e)}));var o=[],a=t.map((function(t){var r=new l,i=n.slice();return c(e,r,i).dispatch(t),o=o.concat(i.slice(n.length)),r.read().toString()}));return n=n.concat(o),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=o(e,t),n).dispatch(e)}}(0,Gg.exports);var Hg,Vg,zg,qg={exports:{}};function Kg(){return Hg||(Hg=1,(e=qg).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 s(e){return null!=e&&"[object Object]"===Object.prototype.toString.call(e)}function o(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(o(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)o(t,n)&&(e[n]=t[n]);return o(t,"toString")&&(e.toString=t.toString),o(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,s=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),s>0)for(n=0;n<s;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,s,a,c=[],l=arguments.length;for(s=0;s<l;s++){if(i="","object"==typeof arguments[s]){for(a in i+="\n["+s+"] ",arguments[0])o(arguments[0],a)&&(i+=a+": "+arguments[0][a]+", ");i=i.slice(0,-2)}else i=arguments[s];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 O(e,t){var n,r=h({},e);for(n in t)o(t,n)&&(s(e[n])&&s(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)o(e,n)&&!o(t,n)&&s(e[n])&&(r[n]=h({},r[n]));return r}function $(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)o(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 M=/(\[[^\[]*\])|(\\)?([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,T={},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()),T[t]=T[t]||function(e){var t,n,r=e.match(M);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,s="";for(i=0;i<n;i++)s+=C(r[i])?r[i].call(t,e):r[i];return s}}(t),T[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)o(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 Y,G=/\d/,H=/\d\d/,V=/\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,se=/[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,oe=/^[1-9]\d?/,ae=/^([1-9]\d|\d)/;function ce(e,t,n){Y[e]=C(t)?t:function(e){return e&&n?n:t}}function le(e,t){return o(Y,e)?Y[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}Y={};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&&o(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,H),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 Oe,$e=Ne("FullYear",!0);function Ne(e,t){return function(n){return null!=n?(Ae(this,e,n),r.updateOffset(this,t),this):Me(this,e)}}function Me(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,s,o,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}s=n,o=e.month(),a=29!==(a=e.date())||1!==o||ye(s)?a:28,i?r.setUTCFullYear(s,o,a):r.setFullYear(s,o,a)}}function Te(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}Oe=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,oe),ce("MM",K,H),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=se,Le=se;function Fe(e,t,n){var r,i,s,o=e.toLocaleLowerCase();if(!this._monthsParse)for(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[],r=0;r<12;++r)s=f([2e3,r]),this._shortMonthsParse[r]=this.monthsShort(s,"").toLocaleLowerCase(),this._longMonthsParse[r]=this.months(s,"").toLocaleLowerCase();return n?"MMM"===t?-1!==(i=Oe.call(this._shortMonthsParse,o))?i:null:-1!==(i=Oe.call(this._longMonthsParse,o))?i:null:"MMM"===t?-1!==(i=Oe.call(this._shortMonthsParse,o))||-1!==(i=Oe.call(this._longMonthsParse,o))?i:null:-1!==(i=Oe.call(this._longMonthsParse,o))||-1!==(i=Oe.call(this._shortMonthsParse,o))?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,Te(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):Me(this,"Month")}function We(){function e(e,t){return t.length-e.length}var t,n,r,i,s=[],o=[],a=[];for(t=0;t<12;t++)n=f([2e3,t]),r=ue(this.monthsShort(n,"")),i=ue(this.months(n,"")),s.push(r),o.push(i),a.push(i),a.push(r);s.sort(e),o.sort(e),a.sort(e),this._monthsRegex=new RegExp("^("+a.join("|")+")","i"),this._monthsShortRegex=this._monthsRegex,this._monthsStrictRegex=new RegExp("^("+o.join("|")+")","i"),this._monthsShortStrictRegex=new RegExp("^("+s.join("|")+")","i")}function Ye(e,t,n,r,i,s,o){var a;return e<100&&e>=0?(a=new Date(e+400,t,n,r,i,s,o),isFinite(a.getFullYear())&&a.setFullYear(e)):a=new Date(e,t,n,r,i,s,o),a}function Ge(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 He(e,t,n){var r=7+t-n;return-(7+Ge(e,0,r).getUTCDay()-t)%7+r-1}function Ve(e,t,n,r,i){var s,o,a=1+7*(t-1)+(7+n-r)%7+He(e,r,i);return a<=0?o=Ce(s=e-1)+a:a>Ce(e)?(s=e+1,o=a-Ce(e)):(s=e,o=a),{year:s,dayOfYear:o}}function ze(e,t,n){var r,i,s=He(e.year(),t,n),o=Math.floor((e.dayOfYear()-s-1)/7)+1;return o<1?r=o+qe(i=e.year()-1,t,n):o>qe(e.year(),t,n)?(r=o-qe(e.year(),t,n),i=e.year()+1):(i=e.year(),r=o),{week:r,year:i}}function qe(e,t,n){var r=He(e,t,n),i=He(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,oe),ce("ww",K,H),ce("W",K,oe),ce("WW",K,H),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=se,et=se,tt=se;function nt(e,t,n){var r,i,s,o=e.toLocaleLowerCase();if(!this._weekdaysParse)for(this._weekdaysParse=[],this._shortWeekdaysParse=[],this._minWeekdaysParse=[],r=0;r<7;++r)s=f([2e3,1]).day(r),this._minWeekdaysParse[r]=this.weekdaysMin(s,"").toLocaleLowerCase(),this._shortWeekdaysParse[r]=this.weekdaysShort(s,"").toLocaleLowerCase(),this._weekdaysParse[r]=this.weekdays(s,"").toLocaleLowerCase();return n?"dddd"===t?-1!==(i=Oe.call(this._weekdaysParse,o))?i:null:"ddd"===t?-1!==(i=Oe.call(this._shortWeekdaysParse,o))?i:null:-1!==(i=Oe.call(this._minWeekdaysParse,o))?i:null:"dddd"===t?-1!==(i=Oe.call(this._weekdaysParse,o))||-1!==(i=Oe.call(this._shortWeekdaysParse,o))||-1!==(i=Oe.call(this._minWeekdaysParse,o))?i:null:"ddd"===t?-1!==(i=Oe.call(this._shortWeekdaysParse,o))||-1!==(i=Oe.call(this._weekdaysParse,o))||-1!==(i=Oe.call(this._minWeekdaysParse,o))?i:null:-1!==(i=Oe.call(this._minWeekdaysParse,o))||-1!==(i=Oe.call(this._weekdaysParse,o))||-1!==(i=Oe.call(this._shortWeekdaysParse,o))?i:null}function rt(){function e(e,t){return t.length-e.length}var t,n,r,i,s,o=[],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,"")),s=ue(this.weekdays(n,"")),o.push(r),a.push(i),c.push(s),l.push(r),l.push(i),l.push(s);o.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("^("+o.join("|")+")","i")}function it(){return this.hours()%12||12}function st(e,t){D(e,0,0,(function(){return this.localeData().meridiem(this.hours(),this.minutes(),t)}))}function ot(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)})),st("a",!0),st("A",!1),ce("a",ot),ce("A",ot),ce("H",K,ae),ce("h",K,oe),ce("k",K,oe),ce("HH",K,H),ce("hh",K,H),ce("kk",K,H),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,s=0;s<e.length;){for(t=(i=ft(e[s]).split("-")).length,n=(n=ft(e[s+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--}s++}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]>Te(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,s,o,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])){s=(c[2]||" ")+It[t][0];break}if(null==s)return void(e._isValid=!1)}if(!r&&null!=s)return void(e._isValid=!1);if(c[4]){if(!St.exec(c[4]))return void(e._isValid=!1);o="Z"}e._f=i+(s||"")+(o||""),Tt(e)}else e._isValid=!1}function Ot(e){var t=parseInt(e,10);return t<=49?2e3+t:t<=999?1900+t:t}function $t(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,s){var o=[Ot(e),De.indexOf(t),parseInt(n,10),parseInt(r,10),parseInt(i,10)];return s&&o.push(parseInt(s,10)),o}(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=Ge.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 Mt(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,s,o=[];if(!e._d){for(r=Mt(e),e._w&&null==e._a[we]&&null==e._a[be]&&function(e){var t,n,r,i,s,o,a,c,l;null!=(t=e._w).GG||null!=t.W||null!=t.E?(s=1,o=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)):(s=e._locale._week.dow,o=e._locale._week.doy,l=ze(jt(),s,o),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+s,(t.e<0||t.e>6)&&(c=!0)):i=s),r<1||r>qe(n,s,o)?p(e)._overflowWeeks=!0:null!=c?p(e)._overflowWeekday=!0:(a=Ve(n,r,i,s,o),e._a[ve]=a.year,e._dayOfYear=a.dayOfYear)}(e),null!=e._dayOfYear&&(s=Nt(e._a[ve],r[ve]),(e._dayOfYear>Ce(s)||0===e._dayOfYear)&&(p(e)._overflowDayOfYear=!0),n=Ge(s,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]=o[t]=r[t];for(;t<7;t++)e._a[t]=o[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?Ge:Ye).apply(null,o),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 Tt(e){if(e._f!==r.ISO_8601)if(e._f!==r.RFC_2822){e._a=[],p(e).empty=!0;var t,n,i,s,o,a,c,l=""+e._i,u=l.length,d=0;for(c=(i=L(e._f,e._locale).match(M)||[]).length,t=0;t<c;t++)s=i[t],(n=(l.match(le(s,e))||[])[0])&&((o=l.substr(0,l.indexOf(n))).length>0&&p(e).unusedInput.push(o),l=l.slice(l.indexOf(n)+n.length),d+=n.length),P[s]?(n?p(e).empty=!1:p(e).unusedTokens.push(s),me(s,n,e)):e._strict&&!n&&p(e).unusedTokens.push(s);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 $t(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,s,o,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++)s=0,o=!1,t=b({},e),null!=e._useUTC&&(t._useUTC=e._useUTC),t._f=e._f[i],Tt(t),g(t)&&(o=!0),s+=p(t).charsLeftOver,s+=10*p(t).unusedTokens.length,p(t).score=s,a?s<r&&(r=s,n=t):(null==r||s<r||o)&&(r=s,n=t,o&&(a=!0));h(e,n||t)}(e):n?Tt(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,$t(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)):s(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,o){var c={};return!0!==t&&!1!==t||(r=t,t=void 0),!0!==n&&!1!==n||(r=n,n=void 0),(s(e)&&a(e)||i(e)&&0===e.length)&&(e=void 0),c._isAMomentObject=!0,c._useUTC=c._isUTC=o,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(o(e,t)&&(-1===Oe.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,s=t.week||t.isoWeek||0,o=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=+o+7*s,this._months=+i+3*r+12*n,this._data={},this._locale=yt(),this._bubble()}function Yt(e){return e instanceof Wt}function Gt(e){return e<0?-1*Math.round(-1*e):Math.round(e)}function Ht(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)}))}Ht("Z",":"),Ht("ZZ",""),ce("Z",ie),ce("ZZ",ie),pe(["Z","ZZ"],(function(e,t,n){n._useUTC=!0,n._tzm=zt(ie,e)}));var Vt=/([\+\-]|\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(Vt)||["-",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,s=e,a=null;return Yt(e)?s={ms:e._milliseconds,d:e._days,M:e._months}:l(e)||!isNaN(+e)?(s={},t?s[t]=+e:s.milliseconds=+e):(a=Zt.exec(e))?(n="-"===a[1]?-1:1,s={y:0,d:he(a[we])*n,h:he(a[Se])*n,m:he(a[_e])*n,s:he(a[Ie])*n,ms:he(Gt(1e3*a[xe]))*n}):(a=Xt.exec(e))?(n="-"===a[1]?-1:1,s={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==s?s={}:"object"==typeof s&&("from"in s||"to"in s)&&(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(s.from),jt(s.to)),(s={}).ms=i.milliseconds,s.M=i.months),r=new Wt(s),Yt(e)&&o(e,"_locale")&&(r._locale=e._locale),Yt(e)&&o(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 s=t._milliseconds,o=Gt(t._days),a=Gt(t._months);e.isValid()&&(i=null==i||i,a&&Ue(e,Me(e,"Month")+a*n),o&&Ae(e,"Date",Me(e,"Date")+o*n),s&&e._d.setTime(e._d.valueOf()+s*n),i&&r.updateOffset(e,o||a))}Qt.fn=Wt.prototype,Qt.invalid=function(){return Qt(NaN)};var sn=nn(1,"add"),on=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=s(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||o(e,n);return r&&i}(e)||null==e}function ln(e){var t,n=s(e)&&!a(e),r=!1,i=["sameDay","nextDay","lastDay","nextWeek","lastWeek","sameElse"];for(t=0;t<i.length;t+=1)r=r||o(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,s=[],o=[],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),o.push(n),s.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("^("+o.join("|")+")","i"),this._erasAbbrRegex=new RegExp("^("+s.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 s;return null==e?ze(this,r,i).year:(t>(s=qe(e,r,i))&&(t=s),kn.call(this,e,t,n,r,i))}function kn(e,t,n,r,i){var s=Ve(e,t,n,r,i),o=Ge(s.year,0,s.dayOfYear);return this.year(o.getUTCFullYear()),this.month(o.getUTCMonth()),this.date(o.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,H),ce("gg",K,H),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",G),pe("Q",(function(e,t){t[be]=3*(he(e)-1)})),D("D",["DD",2],"Do","date"),ce("D",K,oe),ce("DD",K,H),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",V),pe(["DDD","DDDD"],(function(e,t,n){n._dayOfYear=he(e)})),D("m",["mm",2],0,"minute"),ce("m",K,ae),ce("mm",K,H),pe(["m","mm"],_e);var Cn=Ne("Minutes",!1);D("s",["ss",2],0,"second"),ce("s",K,ae),ce("ss",K,H),pe(["s","ss"],Ie);var On,$n,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,G),ce("SS",X,H),ce("SSS",X,V),On="SSSS";On.length<=9;On+="S")ce(On,te);function Mn(e,t){t[xe]=he(1e3*("0."+e))}for(On="S";On.length<=9;On+="S")pe(On,Mn);$n=Ne("Milliseconds",!1),D("z",0,0,"zoneAbbr"),D("zz",0,0,"zoneName");var An=w.prototype;function Tn(e){return e}An.add=sn,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"),s=r.calendarFormat(this,i)||"sameElse",o=t&&(C(t[s])?t[s].call(this,n):t[s]);return this.format(o||this.localeData().calendar(s,this,jt(n)))},An.clone=function(){return new w(this)},An.diff=function(e,t,n){var r,i,s;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":s=un(this,r)/12;break;case"month":s=un(this,r);break;case"quarter":s=un(this,r)/3;break;case"second":s=(this-r)/1e3;break;case"minute":s=(this-r)/6e4;break;case"hour":s=(this-r)/36e5;break;case"day":s=(this-r-i)/864e5;break;case"week":s=(this-r-i)/6048e5;break;default:s=this-r}return n?s:de(s)},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),s=S(t)?t:jt(t);return!!(this.isValid()&&i.isValid()&&s.isValid())&&("("===(r=r||"()")[0]?this.isAfter(i,n):!this.isBefore(i,n))&&(")"===r[1]?this.isBefore(s,n):!this.isAfter(s,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)o(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=on,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,s=this.localeData().eras();for(e=0,t=s.length;e<t;++e)if(n=s[e].since<=s[e].until?1:-1,i=this.clone().startOf("day").valueOf(),s[e].since<=i&&i<=s[e].until||s[e].until<=i&&i<=s[e].since)return(this.year()-r(s[e].since).year())*n+s[e].offset;return this.year()},An.year=$e,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 Te(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=Me(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=$n,An.utcOffset=function(e,t,n){var i,s=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"),s!==e&&(!t||this._changeInProgress?rn(this,Qt(e-s,"m"),1,!1):this._changeInProgress||(this._changeInProgress=!0,r.updateOffset(this,!0),this._changeInProgress=null)),this}return this._isUTC?s: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",$e),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),s=0;for(n=0;n<r;n++)he(e[n])!==he(t[n])&&s++;return s+i}(t._a,e.toArray())>0):this._isDSTShifted=!1,this._isDSTShifted}));var Pn=$.prototype;function Dn(e,t,n,r){var i=yt(),s=f().set(r,t);return i[n](s,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,s=yt(),o=e?s._week.dow:0,a=[];if(null!=n)return Dn(t,(n+o)%7,r,"day");for(i=0;i<7;i++)a[i]=Dn(t,(i+o)%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(M).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=Tn,Pn.postformat=Tn,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)o(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,s,o,a,c=this.eras();for(e=e.toUpperCase(),r=0,i=c.length;r<i;++r)if(s=c[r].name.toUpperCase(),o=c[r].abbr.toUpperCase(),a=c[r].narrow.toUpperCase(),n)switch(t){case"N":case"NN":case"NNN":if(o===e)return c[r];break;case"NNNN":if(s===e)return c[r];break;case"NNNNN":if(a===e)return c[r]}else if([s,o,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 o(this,"_erasAbbrRegex")||_n.call(this),e?this._erasAbbrRegex:this._erasRegex},Pn.erasNameRegex=function(e){return o(this,"_erasNameRegex")||_n.call(this),e?this._erasNameRegex:this._erasRegex},Pn.erasNarrowRegex=function(e){return o(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,s;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]||(s="^"+this.months(i,"")+"|^"+this.monthsShort(i,""),this._monthsParse[r]=new RegExp(s.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?(o(this,"_monthsRegex")||We.call(this),e?this._monthsStrictRegex:this._monthsRegex):(o(this,"_monthsRegex")||(this._monthsRegex=Le),this._monthsStrictRegex&&e?this._monthsStrictRegex:this._monthsRegex)},Pn.monthsShortRegex=function(e){return this._monthsParseExact?(o(this,"_monthsRegex")||We.call(this),e?this._monthsShortStrictRegex:this._monthsShortRegex):(o(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,s;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]||(s="^"+this.weekdays(i,"")+"|^"+this.weekdaysShort(i,"")+"|^"+this.weekdaysMin(i,""),this._weekdaysParse[r]=new RegExp(s.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?(o(this,"_weekdaysRegex")||rt.call(this),e?this._weekdaysStrictRegex:this._weekdaysRegex):(o(this,"_weekdaysRegex")||(this._weekdaysRegex=Qe),this._weekdaysStrictRegex&&e?this._weekdaysStrictRegex:this._weekdaysRegex)},Pn.weekdaysShortRegex=function(e){return this._weekdaysParseExact?(o(this,"_weekdaysRegex")||rt.call(this),e?this._weekdaysShortStrictRegex:this._weekdaysShortRegex):(o(this,"_weekdaysShortRegex")||(this._weekdaysShortRegex=et),this._weekdaysShortStrictRegex&&e?this._weekdaysShortStrictRegex:this._weekdaysShortRegex)},Pn.weekdaysMinRegex=function(e){return this._weekdaysParseExact?(o(this,"_weekdaysRegex")||rt.call(this),e?this._weekdaysMinStrictRegex:this._weekdaysMinRegex):(o(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 Yn(e){return function(){return this.as(e)}}var Gn=Yn("ms"),Hn=Yn("s"),Vn=Yn("m"),zn=Yn("h"),qn=Yn("d"),Kn=Yn("w"),Jn=Yn("M"),Zn=Yn("Q"),Xn=Yn("y"),Qn=Gn;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"),sr=er("days"),or=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,s,o,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?"-":"",s=hr(this._months)!==hr(d)?"-":"",o=hr(this._days)!==hr(d)?"-":"",a=hr(this._milliseconds)!==hr(d)?"-":"",i+"P"+(n?s+n+"Y":"")+(u?s+u+"M":"")+(l?o+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=Gn,pr.asSeconds=Hn,pr.asMinutes=Vn,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,s=this._milliseconds,o=this._days,a=this._months,c=this._data;return s>=0&&o>=0&&a>=0||s<=0&&o<=0&&a<=0||(s+=864e5*Un(Wn(a)+o),o=0,a=0),c.milliseconds=s%1e3,e=de(s/1e3),c.seconds=e%60,t=de(e/60),c.minutes=t%60,n=de(t/60),c.hours=n%24,o+=de(n/24),a+=i=de(Bn(o)),o-=Un(Wn(i)),r=de(a/12),a%=12,c.days=o,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=sr,pr.weeks=function(){return de(this.days()/7)},pr.months=or,pr.years=ar,pr.humanize=function(e,t){if(!this.isValid())return this.localeData().invalidDate();var n,r,i=!1,s=lr;return"object"==typeof e&&(t=e,e=!1),"boolean"==typeof e&&(i=e),"object"==typeof t&&(s=Object.assign({},lr,t),null!=t.s&&null==t.ss&&(s.ss=t.s-1)),r=function(e,t,n,r){var i=Qt(e).abs(),s=cr(i.as("s")),o=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=s<=n.ss&&["s",s]||s<n.s&&["ss",s]||o<=1&&["m"]||o<n.m&&["mm",o]||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,s,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=
|
|
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=Yt,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(O(ut[e]._config,t)):(null!=(r=pt(e))&&(i=r._config),t=O(i,t),null==r&&(t.abbr=e),(n=new $(t)).parentLocale=ut[e],ut[e]=n),gt(e)}else null!=ut[e]&&(null!=ut[e].parentLocale?(ut[e]=ut[e].parentLocale,e===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}()),qg.exports;var e}function Jg(){if(zg)return Vg;zg=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=M,t=k,n=Kg(),r=d,i=R,s={};Vg=s;var o=["daily","test","m","h","custom"],a="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||a;let i=r?n.utc():n().local();if(e&&-1!==o.indexOf(e.type))switch(e.type){case"m":var s=Math.floor(i.minutes()/e.digit)*e.digit;return i.minutes(s).format(t);case"h":var c=Math.floor(i.hour()/e.digit)*e.digit;return i.hour(c).format(t);case"daily":case"custom":case"test":return i.format(t)}return i.format(t)},s.setAuditLog=function(n,r,i){var s=null;if(n){var o=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);s=JSON.parse(e.readFileSync(l,{encoding:"utf-8"}))}else l=t.resolve(c+"/.audit.json"),s=JSON.parse(e.readFileSync(l,{encoding:"utf-8"}))}catch(n){if("ENOENT"!==n.code)return null;s={keep:{days:!1,amount:Number(a[1])},auditLog:r||c+"/.audit.json",files:[]}}s.keep={days:"d"===o,amount:Number(a[1])}}}return s},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,d=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||a;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&&(d=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+(d?"."+d:"");if(b.match(/%DATE%/)&&(S=b.replace(/%DATE%/g,d||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(d&&l&&o.indexOf(l.type)>-1||g>0){f.verbose&&console.log(new Date,"[FileStreamRotator] Rotating file: ",l?l.type:"",g?"size: "+g:"");var O,M=new i;return M.auditLog=p,M.end=function(){$.end.apply($,arguments)},h($,M),M.on("close",(function(){O&&O.close()})),M.on("new",(function(n){M.auditLog=f.addLogToAudit(n,M.auditLog,M,f.verbose),r.create_symlink&&function(n,r,i){let s=r||"current.log",o=t.dirname(n),a=t.basename(n),c=o+"/"+s;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&&M.emit("addWatcher",n)})),M.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){M.emit("createLog",t)}(0,t)}}))}catch(e){n&&console.log(new Date,"[FileStreamRotator] Could not add watcher for "+t)}}(t,f.verbose))})),M.on("createLog",(function(t){try{e.lstatSync(t)}catch(n){$&&"function"==$.end&&$.end(),$=e.createWriteStream(t,C),M.emit("new",t),h($,M)}})),M.write=function(t,n){var i=l?this.getDate(l,v,r.utc):d;if(i!=d||g&&y>g){var s=b+(d&&l?"."+i:"");b.match(/%DATE%/)&&d&&(s=b.replace(/%DATE%/g,i)),g&&y>g?s+="."+ ++m+r.extension:(m=0,s+=r.extension),y=0,f.verbose&&console.log(new Date,c.format("[FileStreamRotator] Changing logs from %s to %s",S,s)),d=i,w=S,S=s,!0===r.end_stream?$.end():$.destroy(),u(S),$=e.createWriteStream(s,C),M.emit("new",s),M.emit("rotate",w,s),h($,M)}$.write(t,n),y+=Buffer.byteLength(t,n)}.bind(this),process.nextTick((function(){M.emit("new",S)})),M.emit("new",S),M}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}),"")},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 Vg}const Zg=M,Xg=A,Qg=k,em=c,tm=F,nm=Gg.exports,rm=Mu.MESSAGE,im=j.PassThrough,sm=tf,om={json:!1,colorize:!1,eol:Xg.EOL,logstash:null,prettyPrint:!1,label:null,stringify:!1,depth:null,showLevel:!0,timestamp:()=>(new Date).toISOString()},am=function(e){if(e=e||{},sm.call(this,e),this.options=Object.assign({},om,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 im,this.logStream.pipe(e.stream);else{if(this.filename=e.filename?Qg.basename(e.filename):"winston.log",this.dirname=e.dirname||Qg.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=Jg().getStream({filename:Qg.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:Qg.join(this.dirname,"."+nm(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{Zg.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(!Zg.existsSync(e))return}catch(t){return t.message=`Error occurred while checking existence of ${e}: ${t.message}`,void this.emit("error",t)}try{if(Zg.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=tm.createGzip(),n=Zg.createReadStream(e);n.on("error",(t=>{t.message=`Error occurred while reading ${e}: ${t.message}`,this.emit("error",t)}));const r=Zg.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{Zg.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 cm=am;em.inherits(am,sm),am.prototype.name="dailyRotateFile";const lm=function(){};am.prototype.log=function(e,t){t=t||lm,this.logStream.write(e[rm]+this.options.eol),this.emit("logged",e),t(null,!0)},am.prototype.close=function(){this.logStream&&this.logStream.end((()=>{this.emit("finish")}))},am.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 Zg.readdirSync(this.dirname).filter((t=>Qg.basename(t).match(e)))})();0===r.length&&t&&t(null,n);const i=s=>{if(!s)return;const o=Qg.join(this.dirname,s);let a,c="";if(s.endsWith(".gz")){a=new im;const e=Zg.createReadStream(o);e.on("error",(e=>{e.message=`Error occurred while reading ${o}: ${e.message}`,a.emit("error",e)})),e.pipe(tm.createGunzip()).pipe(a)}else a=Zg.createReadStream(o,{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 um=cm;Xl.transports.DailyRotateFile=um;var dm=Dl(um);const hm=Date.now();let fm=Math.ceil(hm/1e3);var pm=()=>fm+=1;const gm=E(D(),"kemu-user-services"),mm=E(D(),"kemu-test-services"),ym="KMU-CB-v1",vm=process.env.HUB_PKG_VERSION||'"1.7.4"';var bm;!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"}(bm||(bm={}));const wm=e=>({...e,type:Array.isArray(e.type)?e.type.map((e=>ll[e])):ll[e.type]}),Sm=async e=>{try{return await I(e,"utf-8")}catch(e){return null}},_m=e=>{if(e&&e.startsWith(ym)){const t=e.slice(9),n=decodeURI(t);return Sl(n)}return null},Im=async(e,t,n)=>{let r=[];e.variants?.length&&(r=e.variants.map((e=>({...e,...e.inputs?{inputs:e.inputs.map(wm)}:{},...e.outputs?{outputs:e.outputs.map(wm)}:{}}))));const i={...e,path:t,customWidgets:[],...e.inputs?{inputs:e.inputs.map(wm)}:{inputs:[]},...e.outputs?{outputs:e.outputs.map(wm)}:{outputs:[]},variants:r,...e.widgetUI&&n?.widgetUIContents?{widgetUIContents:n.widgetUIContents}:{}},s=await(async(e,t,n=console.log)=>{const r=[];if(t.customWidgets?.length)for(const i of t.customWidgets){const t=await Sm(E(e,i));if(!t){n(`Error loading custom widget file ${i}`);continue}const s=t.startsWith(ym)?t:`${ym}${t}`,o=_m(s);if(!o){n(`Custom widget file "${i}" is not a valid Kemu Clipboard item`);continue}const a=Object.values(o).filter((e=>e.type===bm.widgetGroup&&!e.groupId));if(a.length>1){n(`Custom widget file "${i}" contains more than one top level widgetGroup`);continue}const c=a[0];if(!c){n(`Custom widget file "${i}" does not contain a top level widgetGroup`);continue}const l=c.state,u={name:l.name,color:l.color,description:l.description,contents:s,rootGroupId:c.id,icon:l.icon,protocolVersion:l.protocolVersion||"2"};r.push(u)}return r})(t,e,n?.log);if(s.length?i.customWidgets=s:delete i.customWidgets,i.variants?.length)for(const e of i.variants)if(e.svgIcon)try{const n=await I(E(t,e.svgIcon),"utf-8");e.svgIcon=n}catch(t){n?.log&&n?.log(`Error loading svgIcon for variant ${e.id}: ${t}`)}return i},xm=async e=>{try{return await b(e,w.F_OK),!0}catch{return!1}};let km=null,Em=null;const Cm=()=>km||gm,$m=()=>Em||mm;let Om=null;const Mm={setGlobalUserId:e=>Om?.setGlobalUserId?.(e),captureError:e=>Om?.captureError?.(e),flushMessages:async()=>Om?.flushMessages?.(),isEnabled:()=>!!Om};var Nm={...Mm,setTracker:e=>{Om=e}};const Tm=Zl("servicesManager"),Am={};let Dm=null,Pm=null,jm=null;class Lm extends Error{code;originalError;constructor(e,t,n){super(e),this.code=t,this.originalError=n,this.name="ServiceError"}}const Rm=async e=>{try{return await b(e),!0}catch{return!1}},Fm=async e=>{if(!Dm)throw new Error('IPC config not set, call "setHubIpcConfig" first.');let t;if(e.info.internal)if("linux"===P()){const n=process.env.XDG_STATE_HOME||k.join(D(),".local","state");t=k.join(n,"kemu-hub","service-logs",e.info.name);try{await v(t,{recursive:!0})}catch(n){Tm(`Failed to create log directory ${t}, falling back to service path`),t=e.info.path}}else t=e.info.path;else t=k.join(e.info.path,"..");const n=e.logsEnabled?((e,t)=>{const n=Yg.createLogger({level:"info",format:Yg.format.combine(Yg.format.timestamp(),Yg.format.errors({stack:!0}),Yg.format.json()),defaultMeta:{service:e},transports:[new dm({filename:k.join(t,"service-%DATE%.log"),datePattern:"YYYY-MM-DD",maxSize:"5m",maxFiles:"5d",auditFile:k.join(t,".service-log-audit.json")})]});return n.getLastLogs=async(n=100)=>{try{const r=k.join(t,".service-log-audit.json"),i=await y.readFile(r,"utf-8"),s=Sl(i);if(!s)return console.warn(`Missing audit file for ${e}, skipping log retrieval.`),[];const o=async e=>(await y.readFile(e,"utf-8")).split("\n").filter((e=>e.trim())),a=[],c=[...s.files].reverse();for(const e of c){const t=await o(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;Nm.isEnabled()&&Nm.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===dl.Javascript){Tm(`Spawning service ${e.info.name} with sessionId ${e.info.sessionId}`);const t=k.join(e.info.path,"processor.js"),i=k.join(e.info.path,"processor.mjs"),s=await Rm(t)?t:i,o=[`--sessionId=${e.info.sessionId.toString()}`,`--ipcSpace=${Dm.appSpace}`,`--ipcId=${Dm?.id}`,`--recipePath=${Dm.recipePath||""}`];if(e.info.internal&&o.push("--internal=true"),!jm)throw new Error('Get secrets function not set, call "setGetSecretsFunction" first.');const a=await jm({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 Lm(`Missing required environment variables: ${c.join(", ")}`,"MISSING_REQUIRED_SECRETS");return new Promise(((t,i)=>{if(!Pm)throw new Error('Spawn function not set, call "setSpawnNodeFunction" first.');const c=Pm({args:[s,...o],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),Tm(`[${e.info.name}] - stdout: ${r}`))})),c.stderr.on("data",(t=>{const i=t.toString().trim();i&&(n?.error(i),r(new Error(i)),Tm(`[${e.info.name}] - stderr: ${i}`))})),c.on("exit",(t=>{const r=`exited with code ${t}`;n?.info(r,{code:t}),Tm(`[${e.info.name}] ${r}`)})),c.on("spawn",(()=>{const r=`spawned with PID ${c.pid}`;n?.info(r,{pid:c.pid}),Tm(`[${e.info.name}] ${r}`),t(c)})),c.on("error",(t=>{n?.error(`[${e.info.name}] error`,t),Tm(`[${e.info.name}] error: ${t}`),r(t),i(new Lm(`Error spawning service ${e.info.name}: ${t}`,"SPAWN_ERROR"))}))}))}throw`Unsupported processor type ${e.info.processor}`}catch(t){if(r(t),t instanceof Lm)throw t;throw`Error spawning service ${e.info.name}: ${t}`}},Um=e=>e?.name?e?.version?e?.description?e?.processor?[dl.Javascript,dl.Executable,dl.Python].includes(e?.processor)?null:"Invalid processor":"Missing processor":"Missing description":"Missing version":"Missing name",Bm=async(e,t)=>{const n=k.join(e,"manifest.json");if(!await Rm(n)){const t=`Missing manifest for service ${e}. Aborting.`;return Tm(t),{error:t}}const r=await I(n,"utf-8"),i=Sl(r),s=Um(i);if(!i||s){const t=`Invalid service manifest [${e}]: ${s}. Aborting.`;return Tm(t),{error:t}}let o;if(delete i.internal,t?.singleServiceName&&i.name!==t.singleServiceName)return{error:`Skipping service ${i.name} as it does not match the singleServiceName option`};await Promise.all([(async()=>{if(i.widgetUI)try{o=await I(k.join(e,"widgetUI.js"))}catch(e){const t=`Error loading widgetUI file ${i.name}: ${e}`;return Tm(t),{error:t}}})(),(async()=>{if(i.svgIcon){const t=await Sm(k.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=k.join(e,t),{error:r,service:s}=await Bm(n);r?Tm(`Error loading sub-service ${t}: ${r}`):s&&(s.info.parentService={name:i.name,version:i.version})}delete i.subServices})(),(async()=>{if(i.variants?.length)for(const t of i.variants)if(t.svgIcon)try{const n=await I(k.join(e,t.svgIcon),"utf-8");t.svgIcon=n}catch(e){Tm(`Error loading svgIcon for variant ${t.id}: ${e}`)}})()]);const a=pm(),c=t?.fixedSession||a;Tm(`Loaded service ${i.name} with sessionId ${c}`);const l=await Im(i,e,{widgetUIContents:o});return Wm(l),Am[c]={info:{...l,path:e,sessionId:c},status:"loaded",childProcess:null,logsEnabled:t?.logsEnabled},{service:Am[c]}},Wm=e=>{e.widgetUIContents?e.uiContentChecksum=(e=>{const t=p("sha256");return t.update(e),t.digest("hex")})(e.widgetUIContents):e.uiContentChecksum=void 0},Ym=async e=>{try{return e.childProcess=await Fm(e),e.status="started",e.errorMsg=void 0,e.errorCode=void 0,!0}catch(t){return Tm(`Service [${e.info.name}] error: ${t}`),e.status="error",t instanceof Lm?(e.errorMsg=t.message,e.errorCode=t.code):(e.errorMsg="string"==typeof t?t:JSON.stringify(t),e.errorCode="UNKNOWN_ERROR"),!1}},Gm=e=>{const{path:t,...n}=e.info;return{...n}},Hm=()=>Object.values(Am).filter((e=>"running"===e.status)).map(Gm),Vm=e=>{if(!e?.kill)return Tm(`Failed to kill service ${e?.pid} because it is not a child process`),!1;let t=e.kill("SIGINT");return t||(Tm(`Failed to send SIGINT to service ${e.pid} using SIGINT`),t=e.kill("SIGTERM"),t||(Tm(`Failed to send SIGTERM to service ${e.pid} using SIGTERM`),t=e.kill("SIGKILL"),t||Tm(`Failed to send SIGKILL to service ${e.pid} using SIGKILL`))),t},zm=async e=>{const{serviceName:t,version:n,force:r,timeout:i=15e3}=e,s=Object.values(Am).find((t=>t.info.name===e.serviceName&&t.info.version===e.version));if(!s)return null;if(s.info.internal&&!r)throw`Cannot stop internal service ${t}`;if(s.childProcess){Tm(`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);s.childProcess.once("exit",((n,i)=>{clearTimeout(r),Tm(`Service ${t} process exited with code ${n} and signal ${i}`),e()})),s.childProcess.once("error",(n=>{clearTimeout(r),Tm(`Service ${t} process error: ${n.message}`),e()}))}));Vm(s.childProcess);try{await r,Tm(`Service ${t} process successfully terminated`)}catch(e){Tm(`Warning: ${e instanceof Error?e.message:"Unknown error"} while waiting for service ${t} to stop`)}}return s.status="stopped",Tm(`Service ${t} stopped`),s},qm=e=>e.info.internal?e.info.path:k.join(e.info.path,".."),Km=e=>!!e.internal;var Jm={isOfficialKemuService:e=>e.name.startsWith("kemu.io"),loadServices:async(e,t)=>{if(!await xm(e))return void Tm(`Failed to load services from "${e}". Directory does not exist.`);const n=(await S(e,{withFileTypes:!0})).filter((e=>e.isDirectory())).map((e=>e.name));Tm(`Found ${n.length} services in "${e}"`);for(let r=0;r<n.length;r++){const i=n[r],s=k.join(e,i),{error:o,service:a}=await Bm(`${s}${t?.internalServices?"":"/dist"}`,{...t,logsEnabled:Array.isArray(t?.enableLogs)?t?.enableLogs.includes(i):t?.enableLogs});o&&Tm(`Failed to load service ${s}. Please check logs`),a&&t?.internalServices&&(a.info.internal=!0)}},launchServices:async e=>{if(Tm("Initializing services"),!Dm)throw new Error('IPC config not set, call "setHubIpcConfig" first.');for(const t in Am){const n=Am[t];e.noSpawningList&&e.noSpawningList.includes(n.info.name)?Tm(`Service ${n.info.name} is in the noSpawningList. Skipping.`):Ym(n)}Tm("Services initialized")},setServiceStatus:(e,t)=>{const n=Am[e];return n?(n.status=t,!0):(Tm(`Service with serviceId ${e} not found`),!1)},getActiveServices:Hm,getMatchingService:(e,t)=>{const n=Object.values(Am).filter((e=>"running"===e.status));for(const r of n)if(r.info.name===e){if(r.info.version===t)return r;if(Ol(r.info.version,t,">="))return r}return null},getServiceBySessionId:e=>Am[e]||null,killAllServices:()=>{for(const e in Am){const t=Am[e];if(t.childProcess)try{Tm(`Killing service ${t.info.name} with PID ${t.childProcess.pid}`),Vm(t.childProcess)}catch(e){Tm(`Error killing service ${t.info.name}: ${e}`)}}},addDevService:async(e,t,n)=>{const r={info:{...await Im(t,t.path),sessionId:e},status:n,startedAt:new Date,devMode:!0,childProcess:null};Am[e]=r,Wm(Am[e].info)},setServiceManifest:(e,t,n)=>{const r=Am[e];if(!r)return Tm(`Service with sessionId ${e} not found`),!1;const i=Um(t);if(i)return Tm(`Invalid manifest for service ${r.info.name}: ${i}`),!1;Wm(t),r.info={...r.info,...t},n&&(r.status=n)},getMatchingDevService:(e,t,n)=>{const r=Object.values(Am).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:()=>Hm().filter((e=>e.internal)),getAllServices:()=>Object.values(Am),stopService:zm,uninstallService:async(e,t)=>{Tm(`Uninstalling service ${e} v${t}`);const n=await zm({serviceName:e,version:t});if(!n)return!1;Tm(`Service ${e} stopped. Removing from disk...`);const r=qm(n),i=Cm();return r.startsWith(i)?(await _(r,{recursive:!0,force:!0,maxRetries:3}),Tm(`Service ${e} successfully removed from disk`),(e=>{Am[e],delete Am[e]})(n.info.sessionId),!0):(Tm(`Service ${e} is not installed in the user services directory. Aborting.`),!1)},getAllServiceVersions:e=>Object.values(Am).filter((t=>t.info.name===e)),setHubIpcConfig:e=>{Dm={...e}},loadAndLaunch:async(e,t,n)=>{const r=$(e,t),{error:i,service:s}=await Bm(r);if(i||!s)return{errorMsg:i};try{s.info.internal=!!n,s.childProcess=await Fm(s),s.status="started"}catch(e){s.status="error",e instanceof Lm?(Tm(`Service spawning error: ${e.message} (${e.code})`),s.errorMsg=e.message,s.errorCode=e.code):(Tm(`Error launching service ${s.info.name}: ${e}`),s.errorMsg="string"==typeof e?e:JSON.stringify(e))}return{service:s,errorCode:s.errorCode,errorMsg:s.errorMsg}},getServiceRootDirectory:qm,setSpawnNodeFunction:e=>{Pm=e},setGetSecretsFunction:e=>{jm=e},restartService:async(e,t)=>{Tm(`Restarting service ${e} v${t}`);const n=await zm({serviceName:e,version:t,force:!0});return!!n&&Ym(n)},getFailedServices:()=>Object.values(Am).filter((e=>"error"===e.status)).map((e=>({...Gm(e),errorMsg:e.errorMsg||"",errorCode:e.errorCode,status:e.status}))),isInternalKemuService:Km,isNotInternalKemuService:e=>!Km(e),isNotDevService:e=>!e.devMode};class Zm{constructor(){}appspace="app.";socketRoot="/tmp/";id=A.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=A.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 Xm{constructor(e){e||(e=new Zm),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 Qm=Dl((function(){Object.defineProperties(this,{data:{enumerable:!0,get:function(){return t},set:function(e){t=e}},type:{enumerable:!0,get:function(){return e},set:function(t){e=t}},load:{enumerable:!0,writable:!1,value:function(n){try{n=JSON.parse(n),e=n.type,t=n.data}catch(r){e="error",t={message:"Invalid JSON response format",err:r,response:n}}}},JSON:{enumerable:!0,get:function(){return JSON.stringify({type:e,data:t})}}});var e="",t={}})),ey=Dl((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 ty{}class ny{}const ry=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 ty,t=ny){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 ty}}())}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 iy{constructor(){}on(e,t,n=!1){return ry.string(e),ry.function(t),ry.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(ry.string(e),e!=this.#e.toString()&&"*"!=e||(e=this.#e),!this.#t[e])return this;if("*"==t)return delete this.#t[e],this;ry.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){ry.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)=>{ry.string(e),ry.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 sy=new Xm;class oy extends iy{constructor(e,t){super(),this.config=e,this.log=t,this.publish=super.emit,e.maxRetries&&(this.retriesRemaining=e.maxRetries),sy=new Xm(this.config)}Client=oy;queue=new ey;socket=!1;connect=ly;emit=ay;retriesRemaining=0;explicitlyDisconnected=!1}function ay(e,t){this.log("dispatching event to ",this.id,this.path," : ",e,",",t);let n=new Qm;n.type=e,n.data=t,n=this.config.rawBuffer?Buffer.from(e,this.config.encoding):sy.format(n),this.config.sync?this.queue.add(cy.bind(this,n)):this.socket.write(n)}function cy(e){this.log("dispatching event to ",this.id,this.path," : ",e),this.socket.write(e)}function ly(){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=M.readFileSync(e.config.tls.private)),e.config.tls.public&&(e.config.tls.cert=M.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(M.readFileSync(e.config.tls.trustedConnections[t]))}Object.assign(e.config.tls,t),e.socket=G.connect(e.config.tls)}else e.log("Connecting client via TCP to",t),e.socket=Y.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=Y.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)!=sy.delimiter||-1==t.indexOf(sy.delimiter))return void e.log("Messages are large, You may want to consider smaller messages.");this.ipcBuffer="";const n=sy.parse(t),r=n.length;for(let t=0;t<r;t++){let r=new Qm;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 uy=new Xm;class dy extends iy{constructor(e,t,n,r){super(),this.config=t,this.path=e,this.port=r,this.log=n,this.publish=super.emit,uy=new Xm(this.config),this.on("close",py.bind(this))}udp4=!1;udp6=!1;server=!1;sockets=[];emit=hy;broadcast=fy;onStart(e){this.publish("start",e)}stop(){this.server.close()}start(){this.path?this.config.unlink?M.unlink(this.path,vy.bind(this)):vy.bind(this)():this.log("Socket Server Path not specified, refusing to start")}}function hy(e,t,n){this.log("dispatching event to socket"," : ",t,n);let r=new Qm;if(r.type=t,r.data=n,this.config.rawBuffer?(this.log(this.config.encoding),r=Buffer.from(t,this.config.encoding)):r=uy.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 fy(e,t){this.log("broadcasting event to all known sockets listening to ",this.path," : ",this.port?this.port:"",e,t);let n=new Qm;if(n.type=e,n.data=t,n=this.config.rawBuffer?Buffer.from(e,this.config.encoding):uy.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 py(){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 gy(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)==uy.delimiter&&-1!=t.indexOf(uy.delimiter))for(r.ipcBuffer="",t=uy.parse(t);t.length>0;){let e=new Qm;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 my(e){this.publish("close",e)}function yy(e){this.sockets.push(e),e.setEncoding&&e.setEncoding(this.config.encoding),this.log("## socket connection to server detected ##"),e.on("close",my.bind(this)),e.on("error",function(e){this.log("server socket error",e),this.publish("error",e)}.bind(this)),e.on("data",gy.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 vy(){return this.log("starting server on ",this.path,this.port?`:${this.port}`:""),this.udp4||this.udp6?(this.server=H.createSocket(this.udp4?"udp4":"udp6"),this.server.write=wy.bind(this),this.server.on("listening",function(){yy.bind(this)(this.server)}.bind(this))):(this.log("starting TLS server",this.config.tls),this.config.tls?by.bind(this)():this.server=Y.createServer(yy.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 by(){if(this.log("starting TLS server",this.config.tls),this.config.tls.private?this.config.tls.key=M.readFileSync(this.config.tls.private):this.config.tls.key=M.readFileSync(`${__dirname}/../local-node-ipc-certs/private/server.key`),this.config.tls.public?this.config.tls.cert=M.readFileSync(this.config.tls.public):this.config.tls.cert=M.readFileSync(`${__dirname}/../local-node-ipc-certs/server.pub`),this.config.tls.dhparam&&(this.config.tls.dhparam=M.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(M.readFileSync(this.config.tls.trustedConnections[e]))}this.server=G.createServer(this.config.tls,yy.bind(this))}function wy(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 Sy{constructor(){}config=new Zm;of={};server=!1;get connectTo(){return Cy}get connectToNet(){return $y}get disconnect(){return Iy}get serve(){return xy}get serveNet(){return Ey}get log(){return _y}set connectTo(e){return Cy}set connectToNet(e){return $y}set disconnect(e){return Iy}set serve(e){return xy}set serveNet(e){return Ey}set log(e){return _y}}function _y(...e){if(!this.config.silent){for(let t=0,n=e.length;t<n;t++)"object"==typeof e[t]&&(e[t]=c.inspect(e[t],{depth:this.config.logDepth,colors:this.config.logInColor}));this.config.logger(e.join(" "))}}function Iy(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 xy(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=ky),this.server=new dy(e,this.config,_y),this.server.on("start",t)}function ky(){}function Ey(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=ky),this.server=new dy(e,this.config,_y,t),n&&(this.server[n]=!0,"udp4"===n&&"::1"===e&&(this.server.path="127.0.0.1")),this.server.on("start",r)}function Cy(e,t,n){if("function"==typeof t&&(n=t,t=!1),n||(n=ky),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 oy(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 $y(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=ky),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 oy(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 Oy=new class extends Sy{constructor(){super()}IPC=Sy};const My=Object.values({protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8}).reduce(((e,t)=>e+t),0),Ny=e=>{try{return JSON.parse(e)}catch(e){return null}},Ty="undefined"!=typeof window,Ay={protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8},Dy={protocolPrefix:4,txtLength:4},Py=Object.values(Ay).reduce(((e,t)=>e+t),0),jy=Object.values(Dy).reduce(((e,t)=>e+t),0),Ly=["width","height","colorSpace"],Ry=(e,t)=>{const n={},r=[];let i=0,s=Array.isArray(e)?[]:{};const o=(e,s)=>{const a=(e=>{const t="undefined"!=typeof Buffer&&e instanceof Buffer,n=e instanceof ArrayBuffer,r=e instanceof Uint8ClampedArray,i=e instanceof Uint8Array,s=e instanceof Int8Array;return t?"Buffer":n?"ArrayBuffer":r?"Uint8ClampedArray":i?"Uint8Array":s?"Int8Array":null})(e);if(!a){if(Array.isArray(e)){const t=[];for(let n=0;n<e.length;n++)t[n]=o(e[n],`${s}[${n}]`);return t}if("object"==typeof e){const t={},n=(e=>{const t=e instanceof Int16Array,n=e instanceof Uint16Array,r=e instanceof Int32Array,i=e instanceof Uint32Array,s=e instanceof Float32Array,o=e instanceof Float64Array,a=e instanceof BigInt64Array,c=e instanceof BigUint64Array;return t?"Int16Array":n?"Uint16Array":r?"Int32Array":i?"Uint32Array":s?"Float32Array":o?"Float64Array":a?"BigInt64Array":c?"BigUint64Array":null})(e);if(n)throw new Error(`Unsupported binary type [${n}] at path "${s}"`);for(const n in e)Object.hasOwn(e,n)||Ly.includes(n)||console.warn(`Allowing inherited property: ${n} from path: ${s}`),t[n]=o(e[n],`${s.length?`${s}.`:""}${n}`);return t}return e}n[s]={index:i,length:e.byteLength,binaryType:a},"Buffer"===t?r.push(Buffer.from(e)):"ArrayBuffer"===a?r.push(e):r.push(e.buffer),i+=e.byteLength};s=o(e,"");let a=null;if(r.length>1)if("ArrayBuffer"===t){const e=r.reduce(((e,t)=>e+t.byteLength),0),t=new Uint8Array(e);let n=0;for(let e=0;e<r.length;e++)t.set(new Uint8Array(r[e]),n),n+=r[e].byteLength;a=t.buffer}else a=Buffer.concat(r);else 1===r.length&&(a=r[0]);return a?{map:n,combinedData:a,sourceCopy:s}:null},Fy=(e,t,n)=>{const r=t.match(/(\[\d+\])|([^[\].]+)/g)||[];let i=e;for(let e=0;e<r.length;e++){let t=r[e];const s=t.startsWith("[")&&t.endsWith("]"),o=e===r.length-1;if(s){t=t.slice(1,-1);const s=parseInt(t,10);if(!Array.isArray(i))throw new Error(`Expected an array at key "${r.slice(0,e).join(".")}" but found an object.`);o?i[s]=n:(i[s]||(i[s]=r[e+1].startsWith("[")?[]:{}),i=i[s])}else o?i[t]=n:(i[t]||(i[t]=r[e+1].startsWith("[")?[]:{}),i=i[t])}return e},Uy=(e,t,n)=>{const r="undefined"!=typeof Buffer,i=t instanceof Uint8Array;for(const s in n)if(Object.hasOwn(n,s)){const{index:o,length:a,binaryType:c}=n[s];let l=null;if(r&&t instanceof Buffer)switch(c){case"Buffer":l=t.subarray(o,o+a);break;case"ArrayBuffer":l=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(o,o+a);break;case"Uint8Array":l=new Uint8Array(t.subarray(o,o+a));break;case"Uint8ClampedArray":l=new Uint8ClampedArray(t.subarray(o,o+a));break;case"Int8Array":l=new Int8Array(t.subarray(o,o+a))}else if(t instanceof ArrayBuffer||t instanceof Uint8Array)switch(c){case"Buffer":if(r){l=Buffer.from(t.slice(o,o+a));break}case"ArrayBuffer":l=i?t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(o,o+a):t.slice(o,o+a);break;case"Uint8Array":l=i?t.slice(o,o+a):new Uint8Array(t.slice(o,o+a));break;case"Uint8ClampedArray":l=new Uint8ClampedArray(t.slice(o,o+a));break;case"Int8Array":l=new Int8Array(t.slice(o,o+a))}l&&Fy(e,s,l)}return e},By=e=>Jl(e),Wy="KMSG",Yy="KCMD",Gy=By("klProtocol");var Hy={encode:(e,t,n)=>{const r={json:e.json},i=Ry(r.json,"Buffer"),s=i?.combinedData;i&&(r.jsonBinaryMap=i.map,r.json=i.sourceCopy);const o=s?s.byteLength:0,a=JSON.stringify(r),c=Buffer.from(a),l=c.byteLength,u=Ay.protocolPrefix+Ay.protocolVersion+Ay.jsonLength+Ay.binaryLength+Ay.fromServiceId+Ay.toServiceId+Ay.sentAt+l+o,d=Buffer.alloc(u),h=Date.now();let f=0;return d.write(Wy,f),f+=Ay.protocolPrefix,d.writeUInt8(1,f),f+=Ay.protocolVersion,d.writeUInt32LE(l,f),f+=Ay.jsonLength,d.writeUInt32LE(o,f),f+=Ay.binaryLength,d.writeUInt32LE(t,f),f+=Ay.fromServiceId,d.writeUInt32LE(n,f),f+=Ay.toServiceId,d.writeBigInt64LE(BigInt(h),f),f+=Ay.sentAt,c.copy(d,f),f+=l,s&&o&&s.copy(d,f),d},decodeHeader:e=>{let t=0;const n=e.toString("utf-8",t,Ay.protocolPrefix);if(t+=Ay.protocolPrefix,n!==Wy)return null;if(e.byteLength<Py)return Gy(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const r=e.readUInt8(t);t+=Ay.protocolVersion;const i=e.readUInt32LE(t);t+=Ay.jsonLength;const s=e.readUInt32LE(t);t+=Ay.binaryLength;const o=e.readUInt32LE(t);t+=Ay.fromServiceId;const a=e.readUInt32LE(t);t+=Ay.toServiceId;const c=e.readBigInt64LE(t);t+=Ay.sentAt;const l=i+s,u=e.subarray(t,t+l),d=e.subarray(0,Py);let h=null;return e.byteLength-Py-i-s>0&&(h=e.subarray(Py+i+s)),{header:{protocolVersion:r,jsonLength:i,binaryLength:s,fromServiceId:o,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=Ny(n);if(!i?.json)return Gy("Invalid JSON in KL message"),null;i.jsonBinaryMap&&r.byteLength&&Uy(i.json,r,i.jsonBinaryMap);const s=Buffer.concat([e.headerPackage,t]);let o=s,a=null;const c=Py+e.jsonLength+e.binaryLength;return s.byteLength>c&&(a=s.subarray(c),o=s.subarray(0,c)),{message:{json:i.json,rawMessage:o},remaining:a}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<Py)return Gy("Invalid Header Size"),e;let n=0;return n+=Ay.protocolPrefix,n+=Ay.protocolVersion,n+=Ay.jsonLength,n+=Ay.binaryLength,void 0!==t.fromServiceId&&e.writeUInt32LE(t.fromServiceId,n),n+=Ay.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=jy+r,s=Buffer.alloc(i);return s.write(Yy,t),t+=Dy.protocolPrefix,s.writeUint32LE(r,t),t+=Dy.txtLength,n.copy(s,t),s},decodeCommand:e=>{let t=0;if(e.byteLength<jy)return{command:null};const n=e.toString("utf-8",t,Dy.protocolPrefix);if(t+=Dy.protocolPrefix,n!==Yy)return{command:null};const r=e.readUInt32LE(t);t+=Dy.txtLength;const i=e.toString("utf-8",t,t+r),s=e.byteLength-jy-r;let o=null;s>0&&(o=e.subarray(jy+r));let a=0;return s<0&&(a=Math.abs(s)),{command:i,remainingData:o,missing:a}}};const Vy="KMSG",zy="KCMD",qy=By("klProtocol"),Ky=new TextEncoder;var Jy={encode:(e,t,n)=>{const r={json:e.json},i=Ry(e.json,"ArrayBuffer"),s=i?.combinedData;i&&(r.jsonBinaryMap=i.map,r.json=i.sourceCopy);const o=s?s.byteLength:0,a=JSON.stringify(r),c=Ky.encode(a),l=c.byteLength,u=new ArrayBuffer(Ay.protocolPrefix+Ay.protocolVersion+Ay.jsonLength+Ay.binaryLength+Ay.fromServiceId+Ay.toServiceId+Ay.sentAt+l+o),d=new DataView(u),h=new Uint8Array(u),f=Date.now();let p=0;for(let e=0;e<4;++e)h[p++]=Vy.charCodeAt(e);return d.setUint8(p,1),p+=Ay.protocolVersion,d.setUint32(p,l,!0),p+=Ay.jsonLength,d.setUint32(p,o,!0),p+=Ay.binaryLength,d.setUint32(p,t,!0),p+=Ay.fromServiceId,d.setUint32(p,n,!0),p+=Ay.toServiceId,d.setBigInt64(p,BigInt(f),!0),p+=Ay.sentAt,h.set(c,p),p+=l,s&&o&&h.set(new Uint8Array(s),p),u},decodeHeader:e=>{const t=new DataView(e);let n=0,r="";for(let e=0;e<Ay.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==Vy)return null;if(e.byteLength<Py)return qy.log(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const i=t.getUint8(n);n+=Ay.protocolVersion;const s=t.getUint32(n,!0);n+=Ay.jsonLength;const o=t.getUint32(n,!0);n+=Ay.binaryLength;const a=t.getUint32(n,!0);n+=Ay.fromServiceId;const c=t.getUint32(n,!0);n+=Ay.toServiceId;const l=t.getBigInt64(n,!0);n+=Ay.sentAt;const u=s+o,d=e.slice(n,n+u),h=new Uint8Array(e,0,Py);let f=null;return e.byteLength-Py-s-o>0&&(f=new Uint8Array(e,Py+s+o).slice().buffer),{header:{protocolVersion:i,jsonLength:s,binaryLength:o,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 s=(new TextDecoder).decode(n.subarray(0,e.jsonLength)),o=n.subarray(e.jsonLength,e.jsonLength+e.binaryLength),a=Ny(s);if(!a?.json)return qy.log("Invalid JSON in KL message"),null;a.jsonBinaryMap&&o.byteLength&&Uy(a.json,o,a.jsonBinaryMap);const c=new Uint8Array(e.headerPackage.byteLength+n.byteLength);c.set(new Uint8Array(e.headerPackage),0),c.set(n,e.headerPackage.byteLength);let l=c,u=null;const d=Py+e.jsonLength+e.binaryLength;return c.byteLength>d&&(u=c.subarray(d),l=c.subarray(0,d)),{message:{json:a.json,...o.length?{binaryData:o.buffer}:{},rawMessage:l.buffer},remaining:u?.buffer??null}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<Py)return qy("Invalid Header Size"),e;let n=0;n+=Ay.protocolPrefix,n+=Ay.protocolVersion,n+=Ay.jsonLength,n+=Ay.binaryLength;const r=new DataView(e);return void 0!==t.fromServiceId&&r.setUint32(n,t.fromServiceId,!0),n+=Ay.fromServiceId,void 0!==t.toServiceId&&r.setUint32(n,t.toServiceId,!0),e},encodeCommand:e=>{let t=0;const n=Ky.encode(e),r=n.byteLength,i=new ArrayBuffer(jy+r),s=new DataView(i),o=new Uint8Array(i);for(let e=0;e<4;++e)o[t++]=zy.charCodeAt(e);return s.setUint32(t,r,!0),t+=Dy.txtLength,o.set(n,t),i},decodeCommand:e=>{const t=new DataView(e);let n=0;if(e.byteLength<jy)return{command:null};let r="";for(let e=0;e<Dy.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==zy)return{command:null};const i=t.getUint32(n,!0);n+=Dy.txtLength;const s=e.byteLength-jy-i,o=new Uint8Array(e,n,Math.min(i,e.byteLength-jy)),a=(new TextDecoder).decode(o);let c=null;s>0&&(c=e.slice(jy+i));let l=0;return s<0&&(l=Math.abs(s)),{command:a,remainingData:c,missing:l}}};const Zy=By("klTransmissionManager"),Xy=()=>{const e=(t,n,r,i)=>{let s=n,o=null;const a=t instanceof ArrayBuffer;if(Zy(`RAW: ${t.toString()}`),!s||s.partialHeaderData){let c;if(a?(c=s?.partialHeaderData?new Uint8Array([...new Uint8Array(s.partialHeaderData),...new Uint8Array(t)]).buffer:t,o=Jy.decodeHeader(c)):(c=s?.partialHeaderData?Buffer.concat([s.partialHeaderData,t]):t,o=Hy.decodeHeader(c)),!o){const{command:t,missing:s,remainingData:o}=a?Jy.decodeCommand(c):Hy.decodeCommand(c);return t?i({command:t,complete:!0,rawMessage:c}):Zy(s?`ERROR: Missing ${s} bytes to complete the command. This partial command will be aborted.`:`ERROR: Invalid state, message was decoded without a header or partial header data. Discarding ${c.byteLength} bytes`),o?(Zy(`${o.byteLength} bytes remain after processing command. Re-analyzing...`),e(o,n,r,i)):void 0}if(o.partialHeader)return s={firstPackageAt:Date.now(),partialHeaderData:c},r(s);if(!o.header)return Zy(`ERROR: Invalid state, message was decoded without a header or partial header data. Discarding ${c.byteLength} bytes`);const l=o.header;s={firstPackageAt:Date.now(),header:{...l,totalBytesReceived:l.packages[0].byteLength,totalBytesExpected:l.binaryLength+l.jsonLength,remaining:o.remaining}},r(s)}else s.header&&s.header.totalBytesReceived<s.header.totalBytesExpected&&(s.header.packages.push(t),s.header.totalBytesReceived+=t.byteLength,r(s));if(s.header&&s.header.totalBytesReceived>=s.header.totalBytesExpected){const t=Date.now()-s.header.sentAt.getTime(),n=Date.now()-s.firstPackageAt;Zy(`Received ${s.header.totalBytesReceived} of ${s.header.totalBytesExpected} expected in ${t} ms, elapsed since first package: ${n}ms`);const o=a?Jy.decodeFullKlMessage(s.header):Hy.decodeFullKlMessage(s.header),c=s.header.totalBytesReceived,l=s.header.remaining;r(null),o&&i({klMessage:o.message,complete:!0,sourceServiceId:s.header.fromServiceId,targetServiceId:s.header.toServiceId,rawMessage:o.message.rawMessage});let u=l;if(o?.remaining&&(u=a?l?((e,t)=>{const n=e.byteLength+t.byteLength,r=new ArrayBuffer(n),i=new Uint8Array(e),s=new Uint8Array(t),o=new Uint8Array(r);return o.set(i),o.set(s,i.length),r})(l,o.remaining):o.remaining:l?Buffer.concat([l,o.remaining]):o.remaining),u)return Zy(`${u.byteLength} bytes remaining after processing message with ${c} bytes of data. Re-analyzing...`),e(u,null,r,i)}};return e};Oy.config={...Oy.config,id:"widgets",retry:1500,silent:!0,rawBuffer:!0,appspace:"kemu.",encoding:"hex"};const Qy={info:Zl("ipcServer:info"),data:Zl("ipcServer:data")};let ev,tv,nv,rv,iv={};const sv=Xy(),ov=e=>{iv[e]&&(Qy.info(`Client disconnected [${e}]`),delete iv[e],tv&&tv(e))};var av=(e,t)=>{const n=iv[e];if(!n)return Qy.info(`Cannot send message to unknown client [${e}]`),!1;if(t.length>=My)return Qy.info("Message is too long to be a command. Use sendMessage instead."),!1;const r=Hy.encodeCommand(t);return n.socket.write(r),!0},cv=(e,t)=>{const n=iv[e];return!!n&&(Qy.info(`Renaming socket id [${e}] to [${t}]`),delete iv[e],n.socket.id=t,iv[t]=n,n.socket.removeListener("close",n.disconnectHandler),n.disconnectHandler=()=>ov(t),n.socket.on("close",n.disconnectHandler),!0)};let lv=Hy;Ty&&(lv=Jy);var uv,dv=lv;!function(e){e.FunctionNotFound="FNC_NOT_FOUND",e.ParentEventCallbackError="PARENT_EVENT_CALLBACK_ERROR"}(uv||(uv={}));let hv=Math.ceil(Date.now()/1e3);var fv={exports:{}};const pv=["nodebuffer","arraybuffer","fragments"],gv="undefined"!=typeof Blob;gv&&pv.push("blob");var mv={BINARY_TYPES:pv,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:gv,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}};const{EMPTY_BUFFER:yv}=mv,vv=Buffer[Symbol.species];function bv(e,t,n,r,i){for(let s=0;s<i;s++)n[r+s]=e[s]^t[3&s]}function wv(e,t){for(let n=0;n<e.length;n++)e[n]^=t[3&n]}if(fv.exports={concat:function(e,t){if(0===e.length)return yv;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 vv(n.buffer,n.byteOffset,r):n},mask:bv,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 vv(t):ArrayBuffer.isView(t)?n=new vv(t.buffer,t.byteOffset,t.byteLength):(n=Buffer.from(t),e.readOnly=!1),n},unmask:wv},!process.env.WS_NO_BUFFER_UTIL)try{const e=require("bufferutil");fv.exports.mask=function(t,n,r,i,s){s<48?bv(t,n,r,i,s):e.mask(t,n,r,i,s)},fv.exports.unmask=function(t,n){t.length<32?wv(t,n):e.unmask(t,n)}}catch(k){}var Sv=fv.exports;const _v=Symbol("kDone"),Iv=Symbol("kRun"),xv=F,kv=Sv,Ev=class{constructor(e){this[_v]=()=>{this.pending--,this[Iv]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Iv]()}[Iv](){if(this.pending!==this.concurrency&&this.jobs.length){const e=this.jobs.shift();this.pending++,e(this[_v])}}},{kStatusCode:Cv}=mv,$v=Buffer[Symbol.species],Ov=Buffer.from([0,0,255,255]),Mv=Symbol("permessage-deflate"),Nv=Symbol("total-length"),Tv=Symbol("callback"),Av=Symbol("buffers"),Dv=Symbol("error");let Pv;var jv=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,!Pv){const e=void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10;Pv=new Ev(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[Tv];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){Pv.add((r=>{this._decompress(e,t,((e,t)=>{r(),n(e,t)}))}))}compress(e,t,n){Pv.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]?xv.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=xv.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[Mv]=this,this._inflate[Nv]=0,this._inflate[Av]=[],this._inflate.on("error",Fv),this._inflate.on("data",Rv)}this._inflate[Tv]=n,this._inflate.write(e),t&&this._inflate.write(Ov),this._inflate.flush((()=>{const e=this._inflate[Dv];if(e)return this._inflate.close(),this._inflate=null,void n(e);const i=kv.concat(this._inflate[Av],this._inflate[Nv]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Nv]=0,this._inflate[Av]=[],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]?xv.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=xv.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[Nv]=0,this._deflate[Av]=[],this._deflate.on("data",Lv)}this._deflate[Tv]=n,this._deflate.write(e),this._deflate.flush(xv.Z_SYNC_FLUSH,(()=>{if(!this._deflate)return;let e=kv.concat(this._deflate[Av],this._deflate[Nv]);t&&(e=new $v(e.buffer,e.byteOffset,e.length-4)),this._deflate[Tv]=null,this._deflate[Nv]=0,this._deflate[Av]=[],t&&this.params[`${r}_no_context_takeover`]&&this._deflate.reset(),n(null,e)}))}};function Lv(e){this[Av].push(e),this[Nv]+=e.length}function Rv(e){this[Nv]+=e.length,this[Mv]._maxPayload<1||this[Nv]<=this[Mv]._maxPayload?this[Av].push(e):(this[Dv]=new RangeError("Max payload size exceeded"),this[Dv].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Dv][Cv]=1009,this.removeListener("data",Rv),this.reset())}function Fv(e){this[Mv]._inflate=null,e[Cv]=1007,this[Tv](e)}var Uv={exports:{}};const{isUtf8:Bv}=L,{hasBlob:Wv}=mv;function Yv(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(Uv.exports={isBlob:function(e){return Wv&&"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:Yv,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]},Bv)Uv.exports.isValidUTF8=function(e){return e.length<24?Yv(e):Bv(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{const e=require("utf-8-validate");Uv.exports.isValidUTF8=function(t){return t.length<32?Yv(t):e(t)}}catch(k){}var Gv=Uv.exports;const{Writable:Hv}=j,Vv=jv,{BINARY_TYPES:zv,EMPTY_BUFFER:qv,kStatusCode:Kv,kWebSocket:Jv}=mv,{concat:Zv,toArrayBuffer:Xv,unmask:Qv}=Sv,{isValidStatusCode:eb,isValidUTF8:tb}=Gv,nb=Buffer[Symbol.species];const{randomFillSync:rb}=d,ib=jv,{EMPTY_BUFFER:sb,kWebSocket:ob,NOOP:ab}=mv,{isBlob:cb,isValidStatusCode:lb}=Gv,{mask:ub,toBuffer:db}=Sv,hb=Symbol("kByteLength"),fb=Buffer.alloc(4),pb=8192;let gb,mb=pb;function yb(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 vb(e,t,n){yb(e,t,n),e.onerror(t)}const{kForOnEventAttribute:bb,kListener:wb}=mv,Sb=Symbol("kCode"),_b=Symbol("kData"),Ib=Symbol("kError"),xb=Symbol("kMessage"),kb=Symbol("kReason"),Eb=Symbol("kTarget"),Cb=Symbol("kType"),$b=Symbol("kWasClean");class Ob{constructor(e){this[Eb]=null,this[Cb]=e}get target(){return this[Eb]}get type(){return this[Cb]}}Object.defineProperty(Ob.prototype,"target",{enumerable:!0}),Object.defineProperty(Ob.prototype,"type",{enumerable:!0});class Mb extends Ob{constructor(e,t={}){super(e),this[Sb]=void 0===t.code?0:t.code,this[kb]=void 0===t.reason?"":t.reason,this[$b]=void 0!==t.wasClean&&t.wasClean}get code(){return this[Sb]}get reason(){return this[kb]}get wasClean(){return this[$b]}}Object.defineProperty(Mb.prototype,"code",{enumerable:!0}),Object.defineProperty(Mb.prototype,"reason",{enumerable:!0}),Object.defineProperty(Mb.prototype,"wasClean",{enumerable:!0});class Nb extends Ob{constructor(e,t={}){super(e),this[Ib]=void 0===t.error?null:t.error,this[xb]=void 0===t.message?"":t.message}get error(){return this[Ib]}get message(){return this[xb]}}Object.defineProperty(Nb.prototype,"error",{enumerable:!0}),Object.defineProperty(Nb.prototype,"message",{enumerable:!0});class Tb extends Ob{constructor(e,t={}){super(e),this[_b]=void 0===t.data?null:t.data}get data(){return this[_b]}}Object.defineProperty(Tb.prototype,"data",{enumerable:!0});const Ab={addEventListener(e,t,n={}){for(const r of this.listeners(e))if(!n[bb]&&r[wb]===t&&!r[bb])return;let r;if("message"===e)r=function(e,n){const r=new Tb("message",{data:n?e:e.toString()});r[Eb]=this,Pb(t,this,r)};else if("close"===e)r=function(e,n){const r=new Mb("close",{code:e,reason:n.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[Eb]=this,Pb(t,this,r)};else if("error"===e)r=function(e){const n=new Nb("error",{error:e,message:e.message});n[Eb]=this,Pb(t,this,n)};else{if("open"!==e)return;r=function(){const e=new Ob("open");e[Eb]=this,Pb(t,this,e)}}r[bb]=!!n[bb],r[wb]=t,n.once?this.once(e,r):this.on(e,r)},removeEventListener(e,t){for(const n of this.listeners(e))if(n[wb]===t&&!n[bb]){this.removeListener(e,n);break}}};var Db={CloseEvent:Mb,ErrorEvent:Nb,Event:Ob,EventTarget:Ab,MessageEvent:Tb};function Pb(e,t,n){"object"==typeof e&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}const{tokenChars:jb}=Gv;function Lb(e,t,n){void 0===e[t]?e[t]=[n]:e[t].push(n)}var Rb={format:function(e){return Object.keys(e).map((t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map((e=>[t].concat(Object.keys(e).map((t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map((e=>!0===e?t:`${t}=${e}`)).join("; ")}))).join("; "))).join(", ")})).join(", ")},parse:function(e){const t=Object.create(null);let n,r,i=Object.create(null),s=!1,o=!1,a=!1,c=-1,l=-1,u=-1,d=0;for(;d<e.length;d++)if(l=e.charCodeAt(d),void 0===n)if(-1===u&&1===jb[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?(Lb(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===jb[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),Lb(i,e.slice(c,u),!0),44===l&&(Lb(t,n,i),i=Object.create(null),n=void 0),c=u=-1}else{if(61!==l||-1===c||-1!==u)throw new SyntaxError(`Unexpected character at index ${d}`);r=e.slice(c,d),c=u=-1}else if(o){if(1!==jb[l])throw new SyntaxError(`Unexpected character at index ${d}`);-1===c?c=d:s||(s=!0),o=!1}else if(a)if(1===jb[l])-1===c&&(c=d);else if(34===l&&-1!==c)a=!1,u=d;else{if(92!==l)throw new SyntaxError(`Unexpected character at index ${d}`);o=!0}else if(34===l&&61===e.charCodeAt(d-1))a=!0;else if(-1===u&&1===jb[l])-1===c&&(c=d);else if(-1===c||32!==l&&9!==l){if(59!==l&&44!==l)throw new SyntaxError(`Unexpected character at index ${d}`);{if(-1===c)throw new SyntaxError(`Unexpected character at index ${d}`);-1===u&&(u=d);let o=e.slice(c,u);s&&(o=o.replace(/\\/g,""),s=!1),Lb(i,r,o),44===l&&(Lb(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?Lb(t,h,i):(void 0===r?Lb(i,h,!0):Lb(i,r,s?h.replace(/\\/g,""):h),Lb(t,n,i)),t}};const Fb=R,Ub=W,Bb=B,Wb=Y,Yb=G,{randomBytes:Gb,createHash:Hb}=d,{URL:Vb}=V,zb=jv,qb=class extends Hv{constructor(e={}){super(),this._allowSynchronousEvents=void 0===e.allowSynchronousEvents||e.allowSynchronousEvents,this._binaryType=e.binaryType||zv[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=0|e.maxPayload,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Jv]=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 nb(t.buffer,t.byteOffset+e,t.length-e),new nb(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 nb(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[Vv.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=qv;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]&&Qv(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[Vv.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?Zv(n,t):"arraybuffer"===this._binaryType?Xv(Zv(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=Zv(n,t);if(!this._skipUTF8Validation&&!tb(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,qv),this.end();else{const n=e.readUInt16BE(0);if(!eb(n)){const e=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");return void t(e)}const r=new nb(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!tb(r)){const e=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");return void t(e)}this._loop=!1,this.emit("conclude",n,r),this.end()}this._state=0}}createError(e,t,n,r,i){this._loop=!1,this._errored=!0;const s=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(s,this.createError),s.code=i,s[Kv]=r,s}},Kb=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=ab,this[ob]=void 0}static frame(e,t){let n,r,i=!1,s=2,o=!1;t.mask&&(n=t.maskBuffer||fb,t.generateMask?t.generateMask(n):(mb===pb&&(void 0===gb&&(gb=Buffer.alloc(pb)),rb(gb,0,pb),mb=0),n[0]=gb[mb++],n[1]=gb[mb++],n[2]=gb[mb++],n[3]=gb[mb++]),o=!(n[0]|n[1]|n[2]|n[3]),s=6),"string"==typeof e?r=t.mask&&!o||void 0===t[hb]?(e=Buffer.from(e)).length:t[hb]:(r=e.length,i=t.mask&&t.readOnly&&!o);let a=r;r>=65536?(s+=8,a=127):r>125&&(s+=2,a=126);const c=Buffer.allocUnsafe(i?r+s:s);return c[0]=t.fin?128|t.opcode:t.opcode,t.rsv1&&(c[0]|=64),c[1]=a,126===a?c.writeUInt16BE(r,2):127===a&&(c[2]=c[3]=0,c.writeUIntBE(r,4,6)),t.mask?(c[1]|=128,c[s-4]=n[0],c[s-3]=n[1],c[s-2]=n[2],c[s-1]=n[3],o?[c,e]:i?(ub(e,n,c,s,r),[c]):(ub(e,n,e,0,r),[c,e])):[c,e]}close(t,n,r,i){let s;if(void 0===t)s=sb;else{if("number"!=typeof t||!lb(t))throw new TypeError("First argument must be a valid error code number");if(void 0!==n&&n.length){const e=Buffer.byteLength(n);if(e>123)throw new RangeError("The message must not be greater than 123 bytes");s=Buffer.allocUnsafe(2+e),s.writeUInt16BE(t,0),"string"==typeof n?s.write(n,2):s.set(n,2)}else s=Buffer.allocUnsafe(2),s.writeUInt16BE(t,0)}const o={[hb]:s.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};0!==this._state?this.enqueue([this.dispatch,s,!1,o,i]):this.sendFrame(e.frame(s,o),i)}ping(t,n,r){let i,s;if("string"==typeof t?(i=Buffer.byteLength(t),s=!1):cb(t)?(i=t.size,s=!1):(i=(t=db(t)).length,s=db.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");const o={[hb]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};cb(t)?0!==this._state?this.enqueue([this.getBlobData,t,!1,o,r]):this.getBlobData(t,!1,o,r):0!==this._state?this.enqueue([this.dispatch,t,!1,o,r]):this.sendFrame(e.frame(t,o),r)}pong(t,n,r){let i,s;if("string"==typeof t?(i=Buffer.byteLength(t),s=!1):cb(t)?(i=t.size,s=!1):(i=(t=db(t)).length,s=db.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");const o={[hb]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};cb(t)?0!==this._state?this.enqueue([this.getBlobData,t,!1,o,r]):this.getBlobData(t,!1,o,r):0!==this._state?this.enqueue([this.dispatch,t,!1,o,r]):this.sendFrame(e.frame(t,o),r)}send(e,t,n){const r=this._extensions[ib.extensionName];let i,s,o=t.binary?2:1,a=t.compress;"string"==typeof e?(i=Buffer.byteLength(e),s=!1):cb(e)?(i=e.size,s=!1):(i=(e=db(e)).length,s=db.readOnly),this._firstFragment?(this._firstFragment=!1,a&&r&&r.params[r._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(a=i>=r._threshold),this._compress=a):(a=!1,o=0),t.fin&&(this._firstFragment=!0);const c={[hb]:i,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:s,rsv1:a};cb(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[hb],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(yb,this,e,i)}this._bufferedBytes-=r[hb];const s=db(t);n?this.dispatch(s,n,r,i):(this._state=0,this.sendFrame(e.frame(s,r),i),this.dequeue())})).catch((e=>{process.nextTick(vb,this,e,i)}))}dispatch(t,n,r,i){if(!n)return void this.sendFrame(e.frame(t,r),i);const s=this._extensions[ib.extensionName];this._bufferedBytes+=r[hb],this._state=1,s.compress(t,r.fin,((t,n)=>{this._socket.destroyed?yb(this,new Error("The socket was closed while data was being compressed"),i):(this._bufferedBytes-=r[hb],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][hb],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][hb],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:Jb}=Gv,{BINARY_TYPES:Zb,EMPTY_BUFFER:Xb,GUID:Qb,kForOnEventAttribute:ew,kListener:tw,kStatusCode:nw,kWebSocket:rw,NOOP:iw}=mv,{EventTarget:{addEventListener:sw,removeEventListener:ow}}=Db,{format:aw,parse:cw}=Rb,{toBuffer:lw}=Sv,uw=3e4,dw=Symbol("kAborted"),hw=[8,13],fw=["CONNECTING","OPEN","CLOSING","CLOSED"],pw=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;let gw=class e extends Fb{constructor(t,n,r){super(),this._binaryType=Zb[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Xb,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]),yw(this,t,n,r)):(this._autoPong=r.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Zb.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 qb({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),s=new Kb(t,this._extensions,r.generateMask);this._receiver=i,this._sender=s,this._socket=t,i[rw]=this,s[rw]=this,t[rw]=this,i.on("conclude",Iw),i.on("drain",xw),i.on("error",kw),i.on("message",Cw),i.on("ping",$w),i.on("pong",Ow),s.onerror=Nw,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on("close",Aw),t.on("data",Dw),t.on("end",Pw),t.on("error",jw),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[zb.extensionName]&&this._extensions[zb.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())})),Tw(this)):this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();else{const e="WebSocket was closed before the connection was established";Sw(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||Xb,n,r)):_w(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||Xb,n,r)):_w(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 _w(this,t,r);const i={binary:"string"!=typeof t,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[zb.extensionName]||(i.compress=!1),this._sender.send(t||Xb,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";Sw(this,this._req,e)}}};Object.defineProperty(gw,"CONNECTING",{enumerable:!0,value:fw.indexOf("CONNECTING")}),Object.defineProperty(gw.prototype,"CONNECTING",{enumerable:!0,value:fw.indexOf("CONNECTING")}),Object.defineProperty(gw,"OPEN",{enumerable:!0,value:fw.indexOf("OPEN")}),Object.defineProperty(gw.prototype,"OPEN",{enumerable:!0,value:fw.indexOf("OPEN")}),Object.defineProperty(gw,"CLOSING",{enumerable:!0,value:fw.indexOf("CLOSING")}),Object.defineProperty(gw.prototype,"CLOSING",{enumerable:!0,value:fw.indexOf("CLOSING")}),Object.defineProperty(gw,"CLOSED",{enumerable:!0,value:fw.indexOf("CLOSED")}),Object.defineProperty(gw.prototype,"CLOSED",{enumerable:!0,value:fw.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((e=>{Object.defineProperty(gw.prototype,e,{enumerable:!0})})),["open","error","close","message"].forEach((e=>{Object.defineProperty(gw.prototype,`on${e}`,{enumerable:!0,get(){for(const t of this.listeners(e))if(t[ew])return t[tw];return null},set(t){for(const t of this.listeners(e))if(t[ew]){this.removeListener(e,t);break}"function"==typeof t&&this.addEventListener(e,t,{[ew]:!0})}})})),gw.prototype.addEventListener=sw,gw.prototype.removeEventListener=ow;var mw=gw;function yw(e,t,n,r){const i={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:hw[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,!hw.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${hw.join(", ")})`);let s;if(t instanceof Vb)s=t;else try{s=new Vb(t)}catch(e){throw new SyntaxError(`Invalid URL: ${t}`)}"http:"===s.protocol?s.protocol="ws:":"https:"===s.protocol&&(s.protocol="wss:"),e._url=s.href;const o="wss:"===s.protocol,a="ws+unix:"===s.protocol;let c;if("ws:"===s.protocol||o||a?a&&!s.pathname?c="The URL's pathname is empty":s.hash&&(c="The URL contains a fragment identifier"):c='The URL\'s protocol must be one of "ws:", "wss:", "http:", "https", or "ws+unix:"',c){const t=new SyntaxError(c);if(0===e._redirects)throw t;return void vw(e,t)}const l=o?443:80,u=Gb(16).toString("base64"),d=o?Ub.request:Bb.request,h=new Set;let f,p;if(i.createConnection=i.createConnection||(o?ww:bw),i.defaultPort=i.defaultPort||l,i.port=s.port||l,i.host=s.hostname.startsWith("[")?s.hostname.slice(1,-1):s.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":u,Connection:"Upgrade",Upgrade:"websocket"},i.path=s.pathname+s.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(f=new zb(!0!==i.perMessageDeflate?i.perMessageDeflate:{},!1,i.maxPayload),i.headers["Sec-WebSocket-Extensions"]=aw({[zb.extensionName]:f.offer()})),n.length){for(const e of n){if("string"!=typeof e||!pw.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),(s.username||s.password)&&(i.auth=`${s.username}:${s.password}`),a){const e=i.path.split(":");i.socketPath=e[0],i.path=e[1]}if(i.followRedirects){if(0===e._redirects){e._originalIpc=a,e._originalSecure=o,e._originalHostOrSocketPath=a?i.socketPath:s.host;const t=r&&r.headers;if(r={...r,headers:{}},t)for(const[e,n]of Object.entries(t))r.headers[e.toLowerCase()]=n}else if(0===e.listenerCount("redirect")){const t=a?!!e._originalIpc&&i.socketPath===e._originalHostOrSocketPath:!e._originalIpc&&s.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!o)&&(delete i.headers.authorization,delete i.headers.cookie,t||delete i.headers.host,i.auth=void 0)}i.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(i.auth).toString("base64")),p=e._req=d(i),e._redirects&&e.emit("redirect",e.url,p)}else p=e._req=d(i);i.timeout&&p.on("timeout",(()=>{Sw(e,p,"Opening handshake has timed out")})),p.on("error",(t=>{null===p||p[dw]||(p=e._req=null,vw(e,t))})),p.on("response",(s=>{const o=s.headers.location,a=s.statusCode;if(o&&i.followRedirects&&a>=300&&a<400){if(++e._redirects>i.maxRedirects)return void Sw(e,p,"Maximum redirects exceeded");let s;p.abort();try{s=new Vb(o,t)}catch(t){const n=new SyntaxError(`Invalid URL: ${o}`);return void vw(e,n)}yw(e,s,n,r)}else e.emit("unexpected-response",p,s)||Sw(e,p,`Unexpected server response: ${s.statusCode}`)})),p.on("upgrade",((t,n,r)=>{if(e.emit("upgrade",t),e.readyState!==gw.CONNECTING)return;p=e._req=null;const s=t.headers.upgrade;if(void 0===s||"websocket"!==s.toLowerCase())return void Sw(e,n,"Invalid Upgrade header");const o=Hb("sha1").update(u+Qb).digest("base64");if(t.headers["sec-websocket-accept"]!==o)return void Sw(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 Sw(e,n,c);a&&(e._protocol=a);const l=t.headers["sec-websocket-extensions"];if(void 0!==l){if(!f)return void Sw(e,n,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");let r;try{r=cw(l)}catch(t){return void Sw(e,n,"Invalid Sec-WebSocket-Extensions header")}const i=Object.keys(r);if(1!==i.length||i[0]!==zb.extensionName)return void Sw(e,n,"Server indicated an extension that was not requested");try{f.accept(r[zb.extensionName])}catch(t){return void Sw(e,n,"Invalid Sec-WebSocket-Extensions header")}e._extensions[zb.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 vw(e,t){e._readyState=gw.CLOSING,e._errorEmitted=!0,e.emit("error",t),e.emitClose()}function bw(e){return e.path=e.socketPath,Wb.connect(e)}function ww(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=Wb.isIP(e.host)?"":e.host),Yb.connect(e)}function Sw(e,t,n){e._readyState=gw.CLOSING;const r=new Error(n);Error.captureStackTrace(r,Sw),t.setHeader?(t[dw]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(vw,e,r)):(t.destroy(r),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function _w(e,t,n){if(t){const n=Jb(t)?t.size:lw(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){const t=new Error(`WebSocket is not open: readyState ${e.readyState} (${fw[e.readyState]})`);process.nextTick(n,t)}}function Iw(e,t){const n=this[rw];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,void 0!==n._socket[rw]&&(n._socket.removeListener("data",Dw),process.nextTick(Mw,n._socket),1005===e?n.close():n.close(e,t))}function xw(){const e=this[rw];e.isPaused||e._socket.resume()}function kw(e){const t=this[rw];void 0!==t._socket[rw]&&(t._socket.removeListener("data",Dw),process.nextTick(Mw,t._socket),t.close(e[nw])),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e))}function Ew(){this[rw].emitClose()}function Cw(e,t){this[rw].emit("message",e,t)}function $w(e){const t=this[rw];t._autoPong&&t.pong(e,!this._isServer,iw),t.emit("ping",e)}function Ow(e){this[rw].emit("pong",e)}function Mw(e){e.resume()}function Nw(e){const t=this[rw];t.readyState!==gw.CLOSED&&(t.readyState===gw.OPEN&&(t._readyState=gw.CLOSING,Tw(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e)))}function Tw(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),uw)}function Aw(){const e=this[rw];let t;this.removeListener("close",Aw),this.removeListener("data",Dw),this.removeListener("end",Pw),e._readyState=gw.CLOSING,this._readableState.endEmitted||e._closeFrameReceived||e._receiver._writableState.errorEmitted||null===(t=e._socket.read())||e._receiver.write(t),e._receiver.end(),this[rw]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",Ew),e._receiver.on("finish",Ew))}function Dw(e){this[rw]._receiver.write(e)||this.pause()}function Pw(){const e=this[rw];e._readyState=gw.CLOSING,e._receiver.end(),this.end()}function jw(){const e=this[rw];this.removeListener("error",jw),this.on("error",iw),e&&(e._readyState=gw.CLOSING,this.destroy())}const{tokenChars:Lw}=Gv;var Rw={parse:function(e){const t=new Set;let n=-1,r=-1,i=0;for(;i<e.length;i++){const s=e.charCodeAt(i);if(-1===r&&1===Lw[s])-1===n&&(n=i);else if(0===i||32!==s&&9!==s){if(44!==s)throw new SyntaxError(`Unexpected character at index ${i}`);{if(-1===n)throw new SyntaxError(`Unexpected character at index ${i}`);-1===r&&(r=i);const s=e.slice(n,r);if(t.has(s))throw new SyntaxError(`The "${s}" subprotocol is duplicated`);t.add(s),n=r=-1}}else-1===r&&-1!==n&&(r=i)}if(-1===n||-1!==r)throw new SyntaxError("Unexpected end of input");const s=e.slice(n,i);if(t.has(s))throw new SyntaxError(`The "${s}" subprotocol is duplicated`);return t.add(s),t}};const Fw=R,Uw=B,{createHash:Bw}=d,Ww=Rb,Yw=jv,Gw=Rw,Hw=mw,{GUID:Vw,kWebSocket:zw}=mv,qw=/^[+/0-9A-Za-z]{22}==$/;function Kw(e){e._state=2,e.emit("close")}function Jw(){this.destroy()}function Zw(e,t,n,r){n=n||Uw.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} ${Uw.STATUS_CODES[t]}\r\n`+Object.keys(r).map((e=>`${e}: ${r[e]}`)).join("\r\n")+"\r\n\r\n"+n)}function Xw(e,t,n,r,i){if(e.listenerCount("wsClientError")){const r=new Error(i);Error.captureStackTrace(r,Xw),e.emit("wsClientError",r,n,t)}else Zw(n,r,i)}var Qw=Dl(class extends Fw{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:Hw,...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=Uw.createServer(((e,t)=>{const n=Uw.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(Kw,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(Kw,this);else{const e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close((()=>{Kw(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",Jw);const i=e.headers["sec-websocket-key"],s=e.headers.upgrade,o=+e.headers["sec-websocket-version"];if("GET"!==e.method)return void Xw(this,e,t,405,"Invalid HTTP method");if(void 0===s||"websocket"!==s.toLowerCase())return void Xw(this,e,t,400,"Invalid Upgrade header");if(void 0===i||!qw.test(i))return void Xw(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");if(8!==o&&13!==o)return void Xw(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header");if(!this.shouldHandle(e))return void Zw(t,400);const a=e.headers["sec-websocket-protocol"];let c=new Set;if(void 0!==a)try{c=Gw.parse(a)}catch(n){return void Xw(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 Yw(this.options.perMessageDeflate,!0,this.options.maxPayload);try{const e=Ww.parse(l);e[Yw.extensionName]&&(r.accept(e[Yw.extensionName]),u[Yw.extensionName]=r)}catch(n){return void Xw(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header")}}if(this.options.verifyClient){const s={origin:e.headers[8===o?"sec-websocket-origin":"origin"],secure:!(!e.socket.authorized&&!e.socket.encrypted),req:e};if(2===this.options.verifyClient.length)return void this.options.verifyClient(s,((s,o,a,l)=>{if(!s)return Zw(t,o||401,a,l);this.completeUpgrade(u,i,c,e,t,n,r)}));if(!this.options.verifyClient(s))return Zw(t,401)}this.completeUpgrade(u,i,c,e,t,n,r)}completeUpgrade(e,t,n,r,i,s,o){if(!i.readable||!i.writable)return i.destroy();if(i[zw])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return Zw(i,503);const a=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Bw("sha1").update(t+Vw).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[Yw.extensionName]){const t=e[Yw.extensionName].params,n=Ww.format({[Yw.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",Jw),c.setSocket(i,s,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(c),c.on("close",(()=>{this.clients.delete(c),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Kw,this)}))),o(c,r)}});const eS=Zl("websocketServer"),tS={},nS=Xy();let rS,iS,sS,oS,aS;const cS=e=>{const t=tS[e];t&&t.socket.close()};var lS=e=>{aS=new Qw({port:e,maxPayload:1048576e3}),aS.on("connection",(e=>{const t=pm();eS(`New client connected. Registered as "${t}"`),e.id=t,tS[t]={socket:e,activeMessage:null},rS&&rS(t),e.on("message",(t=>{if(t instanceof Buffer){const n=tS[e.id];nS(t,n.activeMessage,(e=>n.activeMessage=e),(t=>{if(!t.complete)return;const r=t=>{e.send(t),eS(`Writing ${t.byteLength} bytes to socket [${n.socket.id}]: ${t.toString()}`)},i=()=>{cS(n.socket.id)};if(t.command)return eS(`Received command from client [${n.socket.id}]: ${t.command}`),void(sS&&sS(n.socket.id,t.command,r,i));t.klMessage&&oS&&oS({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",(()=>{eS(`Client disconnected: ${e.id}`),iS&&iS(e.id),delete tS[e.id]})),e.on("error",(()=>{eS(`Error on client connection: ${e.id}`)}))})),console.log(`WebSocket server is running on port ${e}`)},uS=e=>{rS=e},dS=e=>{iS=e},hS=e=>{sS=e},fS=(e,t)=>{const n=tS[e];if(!n)return eS(`Cannot send message to unknown client [${e}]`),!1;if(t.length>=My)return eS("Message is too long to be a command. Use sendMessage instead."),!1;const r=Hy.encodeCommand(t);return n.socket.send(r),!0},pS=e=>oS=e,gS=cS;const mS=Zl("stopService"),yS=async e=>{const t=e.args[0];if(!t)return e.reply({error:"No service name provided"});const n=Jm.getAllServiceVersions(t);mS(`Stopping ${n.length} services with name: ${t}`);for(const e of n)await Jm.stopService({serviceName:e.info.name,version:e.info.version});const r=n.map((e=>`${e.info.name}@${e.info.version}`));e.reply({success:[r]})},vS=Zl("removeService"),bS=async e=>{const t=e.args[0],n=e.args[1];if(!t)return e.reply({error:"No service name provided"});let r=Jm.getAllServiceVersions(t);n&&(r=r.filter((e=>e.info.version===n))),vS(`Removing ${r.length} service(s) with name: ${t}`);for(const e of r)await Jm.uninstallService(e.info.name,e.info.version);const i=r.map((e=>`${e.info.name}@${e.info.version}`));e.reply({success:[i]})},wS=Zl("launchService"),SS=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=Cm();wS(`Loading service ${t}@${n} from ${i}`);const{errorMsg:s,service:o,errorCode:a}=await Jm.loadAndLaunch(i,r,!1);if(s||"started"!==o?.status)return e.reply({error:`Failed to launch service ${t}@${n}: ${s||"error-not-provided"}`,errCode:a});const c=Date.now(),l=3e4,u=async()=>{const r=o.status;return"running"===r?(wS(`Service ${t}@${n} loaded and started`),e.reply({success:[]})):(wS(`Service ${t}@${n} not yet started, status: ${r}`),"stopped"===r||"error"===r?e.reply({error:`Error launching service: "${o.errorMsg||"failed to initiate"}"`}):Date.now()-c>l?e.reply({error:"Timeout waiting for service to start"}):(wS("Retrying in 1 second..."),void setTimeout(u,1e3)))};u()}catch(r){return wS(`Error loading service ${t}@${n}: ${r?.message||r}`),e.reply({error:r?.message||"There was an error loading the service"})}},_S=Zl("getMatchingServices"),IS=async e=>{const t=e.args[0],n=[],r=[];_S(`Checking for matching services: ${t.map((e=>e.name)).join(", ")}`);for(const{name:e,version:i}of t){const t=Jm.getMatchingService(e,i);t?n.push({name:e,version:i,installationPath:Jm.getServiceRootDirectory(t)}):r.push({name:e,version:i})}_S(`Found ${n.length} available services and ${r.length} missing services.`),e.reply({success:[{available:n,missing:r}]})},xS=Zl("getSecretsValues");let kS;var ES=async e=>{const t=e.args[0].services;if(!kS)throw new Error("getSecretValuesFn is not set. Please call setGetSecretValuesFunction before using this function.");xS(`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 kS({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})},CS=e=>{kS=e};const $S=Zl("getMappedSecrets");let OS;var MS=async e=>{const t=e.args[0].services;$S(`Getting mapped secrets for services: ${t.map((e=>`${e.name}@${e.version}`)).join(", ")}`);const n=await OS(t),r=[{services:t.map((e=>({name:e.name,version:e.version,secrets:n[e.name]||[]})))}];e.reply({success:r})};const NS=Zl("getServiceContents"),TS=({reply:e,args:t})=>{const[n]=t;NS(`Received GetServiceContents request for service ${n.serviceName} v${n.version}`);const r=Jm.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}]});NS(`Service ${n.serviceName} v${n.version} not found`),e({error:`Service ${n.serviceName} v${n.version} not found`})};let AS={globalApiKey:void 0,environment:"production"};const DS=()=>({...AS}),PS=Zl("apis"),jS=()=>{const e=DS();if(!e.serviceUrl)throw new Error("Unknown server URL. Please call `edgeConfig.setEdgeConfig` before using the APIs.");return e.serviceUrl},LS=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}}},RS={},FS=async e=>{const t=(e=>{const t=RS[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 LS(`${jS()}/v1/organization/validate/apiKey`,{apiKey:e},{"Content-Type":"application/json"});return n?(PS(`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&&(RS[e]={features:r,lastCheckedAt:new Date}),{valid:n,features:r,error:i}},US=Zl("activeClients");let BS={},WS={};const YS=(e,t)=>`${e}_${t}`,GS=e=>BS[e]||null,HS=(e,t)=>{const n=YS(e,t);return WS[n]||[]},VS=()=>{for(const e in BS){const t=BS[e];if(t?.transport===gl.WS){const e=Hy.encodeCommand(hl.ServicesListChanged);t.send(e)}}},zS=async e=>{const t=[],{serviceSessionId:n,transport:r,send:i,terminateFn:s,extraInfo:o,isDevClient:a}=e,c=e=>{console.warn(e),s&&s()};if(r===gl.WS){if(!o.user?.wsApiKey)return void c(`Attempted to register a WebSocket client without an API key. SessionId: ${n}`);const{valid:e,error:t}=await FS(o.user?.wsApiKey);if(!e&&!t)return void c(`Attempted to register a WebSocket client with an invalid API key. SessionId: ${n}`);t&&(o.user?.wsApiKey&&Nm.captureError({error:new Error(t),message:`Error validating api key "${o.user?.wsApiKey}"`,data:o}),US(`Unable to validate API Key, usage will be limited. SessionId: ${n}`))}BS[n]={serviceSessionId:n,transport:r,isDevClient:!!a,broadcastSubscriptions:t,send:i,extraInfo:o,terminate:()=>{s&&s()},addSubscription:e=>{if(!t.some((t=>t.targetService.serviceName===e.serviceName&&t.targetService.version===e.version))){t.push({targetService:e});const r=YS(e.serviceName,e.version);return WS[r]=WS[r]||[],WS[r].some((e=>e.serviceId===n))||WS[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=YS(e.serviceName,e.version),s=WS[i]?.findIndex((e=>e.serviceId===n));if(-1!==s&&(WS[i]?.splice(s,1),!WS[i]?.length)){const t=Jm.getMatchingService(e.serviceName,e.version);if(t?.info.eventEmitter&&"running"===t.status){const e=GS(t.info.sessionId);e?.extraInfo.ipcSocketId&&av(e?.extraInfo.ipcSocketId,hl.BroadcastEnd)}}}},removeAllSubscriptions:()=>{for(const e of t){const t=YS(e.targetService.serviceName,e.targetService.version),r=WS[t]?.findIndex((e=>e.serviceId===n));-1!==r&&WS[t]?.splice(r,1)}t.length=0}},r===gl.IPC&&(VS(),qS(n))},qS=e=>{const t=Jm.getServiceBySessionId(e);if(t?.info.eventEmitter&&HS(t.info.name,t.info.version).length){const t=GS(e);t?.extraInfo.ipcSocketId&&av(t?.extraInfo.ipcSocketId,hl.BroadcastStart)}},KS=e=>{const t=BS[e];var n;delete BS[e],t?.transport===gl.IPC?VS():(t?.removeAllSubscriptions(),(()=>{const e=Object.values(BS);for(const t of e)if(t.transport===gl.IPC){const e=t.extraInfo.ipcSocketId,n=Jm.getServiceBySessionId(t.serviceSessionId);n?.info.eventEmitter&&(HS(n.info.name,n.info.version).length||e&&av(e,hl.BroadcastEnd))}})(),t?.extraInfo.user?.wsApiKey&&(n=t.extraInfo.user.wsApiKey,delete RS[n]))},JS=Zl("ipc:handleIpcClientCommand"),ZS=(e,t,n)=>{const r=((e,t)=>{if(e.startsWith(hl.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 JS(`Ignoring ACK response from IPC service ${e} with no service id`);JS(`Received ACK from IPC service ${e}. Marking as running.`);let r=e;t&&e&&e!==t&&(cv(e,t),r=t);let i=!1;t&&(i=Jm.setServiceStatus(t,"running")),i?zS({serviceSessionId:t||e,transport:gl.IPC,send:n,extraInfo:{ipcSocketId:t}}):av(r,hl.SendManifest)}));!r&&JS(`Received unknown command [${t}] from service ${e}`)};let XS={};q.platform();const QS=async e=>{const t=e.args[0];if(XS.chooseDirectory)try{const n=await XS.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"})},e_=async e=>{const t=e.args[0];if(XS.chooseFile)try{const n=await XS.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 t_={},n_={},r_={};function i_(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`positive integer expected, not ${e}`)}function s_(e){if("boolean"!=typeof e)throw new Error(`boolean expected, not ${e}`)}function o_(e){return e instanceof Uint8Array||null!=e&&"object"==typeof e&&"Uint8Array"===e.constructor.name}function a_(e,...t){if(!o_(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 c_(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.wrapConstructor");i_(e.outputLen),i_(e.blockLen)}function l_(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 u_(e,t){a_(e);const n=t.outputLen;if(e.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}Object.defineProperty(r_,"__esModule",{value:!0}),r_.output=r_.exists=r_.hash=r_.bytes=r_.bool=r_.number=r_.isBytes=void 0,r_.number=i_,r_.bool=s_,r_.isBytes=o_,r_.bytes=a_,r_.hash=c_,r_.exists=l_,r_.output=u_;const d_={number:i_,bool:s_,bytes:a_,hash:c_,exists:l_,output:u_};r_.default=d_;var h_={};Object.defineProperty(h_,"__esModule",{value:!0}),h_.add5L=h_.add5H=h_.add4H=h_.add4L=h_.add3H=h_.add3L=h_.add=h_.rotlBL=h_.rotlBH=h_.rotlSL=h_.rotlSH=h_.rotr32L=h_.rotr32H=h_.rotrBL=h_.rotrBH=h_.rotrSL=h_.rotrSH=h_.shrSL=h_.shrSH=h_.toBig=h_.split=h_.fromBig=void 0;const f_=BigInt(2**32-1),p_=BigInt(32);function g_(e,t=!1){return t?{h:Number(e&f_),l:Number(e>>p_&f_)}:{h:0|Number(e>>p_&f_),l:0|Number(e&f_)}}function m_(e,t=!1){let n=new Uint32Array(e.length),r=new Uint32Array(e.length);for(let i=0;i<e.length;i++){const{h:s,l:o}=g_(e[i],t);[n[i],r[i]]=[s,o]}return[n,r]}h_.fromBig=g_,h_.split=m_;const y_=(e,t)=>BigInt(e>>>0)<<p_|BigInt(t>>>0);h_.toBig=y_;const v_=(e,t,n)=>e>>>n;h_.shrSH=v_;const b_=(e,t,n)=>e<<32-n|t>>>n;h_.shrSL=b_;const w_=(e,t,n)=>e>>>n|t<<32-n;h_.rotrSH=w_;const S_=(e,t,n)=>e<<32-n|t>>>n;h_.rotrSL=S_;const __=(e,t,n)=>e<<64-n|t>>>n-32;h_.rotrBH=__;const I_=(e,t,n)=>e>>>n-32|t<<64-n;h_.rotrBL=I_;const x_=(e,t)=>t;h_.rotr32H=x_;const k_=e=>e;h_.rotr32L=k_;const E_=(e,t,n)=>e<<n|t>>>32-n;h_.rotlSH=E_;const C_=(e,t,n)=>t<<n|e>>>32-n;h_.rotlSL=C_;const $_=(e,t,n)=>t<<n-32|e>>>64-n;h_.rotlBH=$_;const O_=(e,t,n)=>e<<n-32|t>>>64-n;function M_(e,t,n,r){const i=(t>>>0)+(r>>>0);return{h:e+n+(i/2**32|0)|0,l:0|i}}h_.rotlBL=O_,h_.add=M_;const N_=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0);h_.add3L=N_;const T_=(e,t,n,r)=>t+n+r+(e/2**32|0)|0;h_.add3H=T_;const A_=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0);h_.add4L=A_;const D_=(e,t,n,r,i)=>t+n+r+i+(e/2**32|0)|0;h_.add4H=D_;const P_=(e,t,n,r,i)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(i>>>0);h_.add5L=P_;const j_=(e,t,n,r,i,s)=>t+n+r+i+s+(e/2**32|0)|0;h_.add5H=j_;const L_={fromBig:g_,split:m_,toBig:y_,shrSH:v_,shrSL:b_,rotrSH:w_,rotrSL:S_,rotrBH:__,rotrBL:I_,rotr32H:x_,rotr32L:k_,rotlSH:E_,rotlSL:C_,rotlBH:$_,rotlBL:O_,add:M_,add3L:N_,add3H:T_,add4L:A_,add4H:D_,add5H:j_,add5L:P_};h_.default=L_;var R_={},F_={};Object.defineProperty(F_,"__esModule",{value:!0}),F_.crypto=void 0,F_.crypto="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0,function(e){
|
|
10
|
+
var e=$,t=x,n=Kg(),r=u,s=j,o={};Vg=o;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)}}o.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},o.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},o.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 s=Math.floor(i.minutes()/e.digit)*e.digit;return i.minutes(s).format(t);case"h":var o=Math.floor(i.hour()/e.digit)*e.digit;return i.hour(o).format(t);case"daily":case"custom":case"test":return i.format(t)}return i.format(t)},o.setAuditLog=function(n,r,i){var s=null;if(n){var o=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);s=JSON.parse(e.readFileSync(l,{encoding:"utf-8"}))}else l=t.resolve(c+"/.audit.json"),s=JSON.parse(e.readFileSync(l,{encoding:"utf-8"}))}catch(n){if("ENOENT"!==n.code)return null;s={keep:{days:!1,amount:Number(a[1])},auditLog:r||c+"/.audit.json",files:[]}}s.keep={days:"d"===o,amount:Number(a[1])}}}return s},o.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)}},o.addLogToAudit=function(e,t,i,s){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,s),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,s),i.emit("logRemoved",e),!1})),t.files=d}o.writeAuditLog(t,s)}return t},o.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=o.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"},O=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 $,N=new s;return N.auditLog=p,N.end=function(){O.end.apply(O,arguments)},h(O,N),N.on("close",(function(){$&&$.close()})),N.on("new",(function(n){N.auditLog=f.addLogToAudit(n,N.auditLog,N,f.verbose),r.create_symlink&&function(n,r,i){let s=r||"current.log",o=t.dirname(n),a=t.basename(n),c=o+"/"+s;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){$&&$.close(),r.watch_log&&($=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){O&&"function"==O.end&&O.end(),O=e.createWriteStream(t,C),N.emit("new",t),h(O,N)}})),N.write=function(t,n){var s=l?this.getDate(l,v,r.utc):u;if(s!=u||g&&y>g){var o=b+(u&&l?"."+s:"");b.match(/%DATE%/)&&u&&(o=b.replace(/%DATE%/g,s)),g&&y>g?o+="."+ ++m+r.extension:(m=0,o+=r.extension),y=0,f.verbose&&console.log(new Date,i.format("[FileStreamRotator] Changing logs from %s to %s",S,o)),u=s,w=S,S=o,!0===r.end_stream?O.end():O.destroy(),d(S),O=e.createWriteStream(o,C),N.emit("new",o),N.emit("rotate",w,o),h(O,N)}O.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(){O.emit("new",S)})),O};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 Vg}const Zg=$,Xg=M,Qg=x,em=i,tm=R,nm=Gg.exports,rm=Nu.MESSAGE,im=P.PassThrough,sm=tf,om={json:!1,colorize:!1,eol:Xg.EOL,logstash:null,prettyPrint:!1,label:null,stringify:!1,depth:null,showLevel:!0,timestamp:()=>(new Date).toISOString()},am=function(e){if(e=e||{},sm.call(this,e),this.options=Object.assign({},om,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 im,this.logStream.pipe(e.stream);else{if(this.filename=e.filename?Qg.basename(e.filename):"winston.log",this.dirname=e.dirname||Qg.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=Jg().getStream({filename:Qg.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:Qg.join(this.dirname,"."+nm(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{Zg.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(!Zg.existsSync(e))return}catch(t){return t.message=`Error occurred while checking existence of ${e}: ${t.message}`,void this.emit("error",t)}try{if(Zg.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=tm.createGzip(),n=Zg.createReadStream(e);n.on("error",(t=>{t.message=`Error occurred while reading ${e}: ${t.message}`,this.emit("error",t)}));const r=Zg.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{Zg.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 cm=am;em.inherits(am,sm),am.prototype.name="dailyRotateFile";const lm=function(){};am.prototype.log=function(e,t){t=t||lm,this.logStream.write(e[rm]+this.options.eol),this.emit("logged",e),t(null,!0)},am.prototype.close=function(){this.logStream&&this.logStream.end((()=>{this.emit("finish")}))},am.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 Zg.readdirSync(this.dirname).filter((t=>Qg.basename(t).match(e)))})();0===r.length&&t&&t(null,n);const i=s=>{if(!s)return;const o=Qg.join(this.dirname,s);let a,c="";if(s.endsWith(".gz")){a=new im;const e=Zg.createReadStream(o);e.on("error",(e=>{e.message=`Error occurred while reading ${o}: ${e.message}`,a.emit("error",e)})),e.pipe(tm.createGunzip()).pipe(a)}else a=Zg.createReadStream(o,{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 um=cm;Xl.transports.DailyRotateFile=um;var dm=Pl(um);const hm=Date.now();let fm=Math.ceil(hm/1e3);var pm=()=>fm+=1;const gm=k(A(),"kemu-user-services"),mm=k(A(),"kemu-test-services"),ym="KMU-CB-v1",vm=process.env.HUB_PKG_VERSION||'"1.9.5"';var bm;!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"}(bm||(bm={}));const wm=e=>({...e,type:Array.isArray(e.type)?e.type.map((e=>ll[e])):ll[e.type]}),Sm=async e=>{try{return await _(e,"utf-8")}catch(e){return null}},_m=e=>{if(e&&e.startsWith(ym)){const t=e.slice(9),n=decodeURI(t);return Sl(n)}return null},Im=async(e,t,n)=>{let r=[];e.variants?.length&&(r=e.variants.map((e=>({...e,...e.inputs?{inputs:e.inputs.map(wm)}:{},...e.outputs?{outputs:e.outputs.map(wm)}:{}}))));const i={...e,path:t,customWidgets:[],...e.inputs?{inputs:e.inputs.map(wm)}:{inputs:[]},...e.outputs?{outputs:e.outputs.map(wm)}:{outputs:[]},variants:r,...e.widgetUI&&n?.widgetUIContents?{widgetUIContents:n.widgetUIContents}:{}},s=await(async(e,t,n=console.log)=>{const r=[];if(t.customWidgets?.length)for(const i of t.customWidgets){const t=await Sm(k(e,i));if(!t){n(`Error loading custom widget file ${i}`);continue}const s=t.startsWith(ym)?t:`${ym}${t}`,o=_m(s);if(!o){n(`Custom widget file "${i}" is not a valid Kemu Clipboard item`);continue}const a=Object.values(o).filter((e=>e.type===bm.widgetGroup&&!e.groupId));if(a.length>1){n(`Custom widget file "${i}" contains more than one top level widgetGroup`);continue}const c=a[0];if(!c){n(`Custom widget file "${i}" does not contain a top level widgetGroup`);continue}const l=c.state,u={name:l.name,color:l.color,description:l.description,contents:s,rootGroupId:c.id,icon:l.icon,protocolVersion:l.protocolVersion||"2"};r.push(u)}return r})(t,e,n?.log);if(s.length?i.customWidgets=s:delete i.customWidgets,i.variants?.length)for(const e of i.variants)if(e.svgIcon)try{const n=await _(k(t,e.svgIcon),"utf-8");e.svgIcon=n}catch(t){n?.log&&n?.log(`Error loading svgIcon for variant ${e.id}: ${t}`)}return i},xm=async e=>{try{return await v(e,b.F_OK),!0}catch{return!1}};let km=null,Em=null;const Cm=()=>km||gm,Om=()=>Em||mm;let $m=null;const Nm={setGlobalUserId:e=>$m?.setGlobalUserId?.(e),captureError:e=>$m?.captureError?.(e),flushMessages:async()=>$m?.flushMessages?.(),isEnabled:()=>!!$m};var Mm={...Nm,setTracker:e=>{$m=e}};const Am=Zl("servicesManager"),Tm={};let Pm=null,Dm=null,jm=null,Rm=!1;class Lm extends Error{code;originalError;constructor(e,t,n){super(e),this.code=t,this.originalError=n,this.name="ServiceError"}}const Fm=async e=>{try{return await v(e),!0}catch{return!1}},Um=async e=>{if(!Pm)throw new Error('IPC config not set, call "setHubIpcConfig" first.');let t;if(e.info.internal)if("linux"===T()){const n=process.env.XDG_STATE_HOME||x.join(A(),".local","state");t=x.join(n,"kemu-hub","service-logs",e.info.name);try{await y(t,{recursive:!0})}catch(n){Am(`Failed to create log directory ${t}, falling back to service path`),t=e.info.path}}else t=e.info.path;else t=x.join(e.info.path,"..");const n=e.logsEnabled?((e,t)=>{const n=Yg.createLogger({level:"info",format:Yg.format.combine(Yg.format.timestamp(),Yg.format.errors({stack:!0}),Yg.format.json()),defaultMeta:{service:e},transports:[new dm({filename:x.join(t,"service-%DATE%.log"),datePattern:"YYYY-MM-DD",maxSize:"5m",maxFiles:"5d",auditFile:x.join(t,".service-log-audit.json")})]});return n.getLastLogs=async(n=100)=>{try{const r=x.join(t,".service-log-audit.json"),i=await m.readFile(r,"utf-8"),s=Sl(i);if(!s)return console.warn(`Missing audit file for ${e}, skipping log retrieval.`),[];const o=async e=>(await m.readFile(e,"utf-8")).split("\n").filter((e=>e.trim())),a=[],c=[...s.files].reverse();for(const e of c){const t=await o(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;Mm.isEnabled()&&Mm.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===dl.Javascript){Am(`Spawning service ${e.info.name} with sessionId ${e.info.sessionId}`);const t=x.join(e.info.path,"processor.js"),i=x.join(e.info.path,"processor.mjs"),s=await Fm(t)?t:i,o=[`--sessionId=${e.info.sessionId.toString()}`,`--ipcSpace=${Pm.appSpace}`,`--ipcId=${Pm?.id}`,`--recipePath=${Pm.recipePath||""}`];if(e.info.internal&&o.push("--internal=true"),!jm)throw new Error('Get secrets function not set, call "setGetSecretsFunction" first.');const a=await jm({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 Lm(`Missing required environment variables: ${c.join(", ")}`,"MISSING_REQUIRED_SECRETS");return new Promise(((t,i)=>{if(!Dm)throw new Error('Spawn function not set, call "setSpawnNodeFunction" first.');const c=Dm({args:[s,...o],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),Am(`[${e.info.name}] - stdout: ${r}`))})),c.stderr.on("data",(t=>{const i=t.toString().trim();i&&(n?.error(i),r(new Error(i)),Am(`[${e.info.name}] - stderr: ${i}`))})),c.on("exit",(t=>{const r=`exited with code ${t}`;n?.info(r,{code:t}),Am(`[${e.info.name}] ${r}`)})),c.on("spawn",(()=>{const r=`spawned with PID ${c.pid}`;n?.info(r,{pid:c.pid}),Am(`[${e.info.name}] ${r}`),t(c)})),c.on("error",(t=>{n?.error(`[${e.info.name}] error`,t),Am(`[${e.info.name}] error: ${t}`),r(t),i(new Lm(`Error spawning service ${e.info.name}: ${t}`,"SPAWN_ERROR"))}))}))}throw`Unsupported processor type ${e.info.processor}`}catch(t){if(r(t),t instanceof Lm)throw t;throw`Error spawning service ${e.info.name}: ${t}`}},Bm=e=>e?.name?e?.version?e?.description?e?.processor?[dl.Javascript,dl.Executable,dl.Python].includes(e?.processor)?null:"Invalid processor":"Missing processor":"Missing description":"Missing version":"Missing name",Wm=async(e,t)=>{const n=x.join(e,"manifest.json");if(!await Fm(n)){const t=`Missing manifest for service ${e}. Aborting.`;return Am(t),{error:t}}const r=await _(n,"utf-8"),i=Sl(r),s=Bm(i);if(!i||s){const t=`Invalid service manifest [${e}]: ${s}. Aborting.`;return Am(t),{error:t}}let o;if(delete i.internal,t?.singleServiceName&&i.name!==t.singleServiceName)return{error:`Skipping service ${i.name} as it does not match the singleServiceName option`};await Promise.all([(async()=>{if(i.widgetUI)try{o=await _(x.join(e,"widgetUI.js"))}catch(e){const t=`Error loading widgetUI file ${i.name}: ${e}`;return Am(t),{error:t}}})(),(async()=>{if(i.svgIcon){const t=await Sm(x.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=x.join(e,t),{error:r,service:s}=await Wm(n);r?Am(`Error loading sub-service ${t}: ${r}`):s&&(s.info.parentService={name:i.name,version:i.version})}delete i.subServices})(),(async()=>{if(i.variants?.length)for(const t of i.variants)if(t.svgIcon)try{const n=await _(x.join(e,t.svgIcon),"utf-8");t.svgIcon=n}catch(e){Am(`Error loading svgIcon for variant ${t.id}: ${e}`)}})()]);const a=pm(),c=t?.fixedSession||a;Am(`Loaded service ${i.name} with sessionId ${c}`);const l=await Im(i,e,{widgetUIContents:o});return Ym(l),Tm[c]={info:{...l,path:e,sessionId:c},status:"loaded",childProcess:null,logsEnabled:t?.logsEnabled},{service:Tm[c]}},Ym=e=>{e.widgetUIContents?e.uiContentChecksum=(e=>{const t=f("sha256");return t.update(e),t.digest("hex")})(e.widgetUIContents):e.uiContentChecksum=void 0},Gm=async e=>{try{return e.childProcess=await Um(e),e.status="started",e.errorMsg=void 0,e.errorCode=void 0,!0}catch(t){return Am(`Service [${e.info.name}] error: ${t}`),e.status="error",t instanceof Lm?(e.errorMsg=t.message,e.errorCode=t.code):(e.errorMsg="string"==typeof t?t:JSON.stringify(t),e.errorCode="UNKNOWN_ERROR"),!1}},Hm=e=>{const{path:t,...n}=e.info;return{...n}},Vm=()=>Object.values(Tm).filter((e=>"running"===e.status)).map(Hm),zm=e=>{if(!e?.kill)return Am(`Failed to kill service ${e?.pid} because it is not a child process`),!1;let t=e.kill("SIGINT");return t||(Am(`Failed to send SIGINT to service ${e.pid} using SIGINT`),t=e.kill("SIGTERM"),t||(Am(`Failed to send SIGTERM to service ${e.pid} using SIGTERM`),t=e.kill("SIGKILL"),t||Am(`Failed to send SIGKILL to service ${e.pid} using SIGKILL`))),t},qm=async e=>{const{serviceName:t,version:n,force:r,timeout:i=15e3}=e,s=Object.values(Tm).find((t=>t.info.name===e.serviceName&&t.info.version===e.version));if(!s)return null;if(s.info.internal&&!r)throw`Cannot stop internal service ${t}`;if(s.childProcess){Am(`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);s.childProcess.once("exit",((n,i)=>{clearTimeout(r),Am(`Service ${t} process exited with code ${n} and signal ${i}`),e()})),s.childProcess.once("error",(n=>{clearTimeout(r),Am(`Service ${t} process error: ${n.message}`),e()}))}));zm(s.childProcess);try{await r,Am(`Service ${t} process successfully terminated`)}catch(e){Am(`Warning: ${e instanceof Error?e.message:"Unknown error"} while waiting for service ${t} to stop`)}}return s.status="stopped",Am(`Service ${t} stopped`),s},Km=e=>e.info.internal?e.info.path:x.join(e.info.path,".."),Jm=e=>!!e.internal;var Zm={isOfficialKemuService:e=>e.name.startsWith("kemu.io"),loadServices:async(e,t)=>{if(!await xm(e))return void Am(`Failed to load services from "${e}". Directory does not exist.`);const n=(await w(e,{withFileTypes:!0})).filter((e=>e.isDirectory())).map((e=>e.name));Am(`Found ${n.length} services in "${e}"`);for(let r=0;r<n.length;r++){const i=n[r],s=x.join(e,i),{error:o,service:a}=await Wm(`${s}${t?.internalServices?"":"/dist"}`,{...t,logsEnabled:Array.isArray(t?.enableLogs)?t?.enableLogs.includes(i):t?.enableLogs});o&&Am(`Failed to load service ${s}. Please check logs`),a&&t?.internalServices&&(a.info.internal=!0)}},launchServices:async e=>{if(Am("Initializing services"),!Pm)throw new Error('IPC config not set, call "setHubIpcConfig" first.');for(const t in Tm){const n=Tm[t];e.noSpawningList&&e.noSpawningList.includes(n.info.name)?Am(`Service ${n.info.name} is in the noSpawningList. Skipping.`):Gm(n)}Am("Services initialized")},setServiceStatus:(e,t)=>{const n=Tm[e];return n?(n.status=t,!0):(Am(`Service with serviceId ${e} not found`),!1)},getActiveServices:Vm,getMatchingService:(e,t)=>{const n=Object.values(Tm).filter((e=>"running"===e.status));for(const r of n)if(r.info.name===e){if(r.info.version===t)return r;if($l(r.info.version,t,">="))return r}return null},getServiceBySessionId:e=>Tm[e]||null,killAllServices:()=>{for(const e in Tm){const t=Tm[e];if(t.childProcess)try{Am(`Killing service ${t.info.name} with PID ${t.childProcess.pid}`),zm(t.childProcess)}catch(e){Am(`Error killing service ${t.info.name}: ${e}`)}}},addDevService:async(e,t,n)=>{const r={info:{...await Im(t,t.path),sessionId:e},status:n,startedAt:new Date,devMode:!0,childProcess:null};Tm[e]=r,Ym(Tm[e].info)},setServiceManifest:(e,t,n)=>{const r=Tm[e];if(!r)return Am(`Service with sessionId ${e} not found`),!1;const i=Bm(t);if(i)return Am(`Invalid manifest for service ${r.info.name}: ${i}`),!1;Ym(t),r.info={...r.info,...t},n&&(r.status=n)},getMatchingDevService:(e,t,n)=>{const r=Object.values(Tm).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:()=>Vm().filter((e=>e.internal)),getAllServices:()=>Object.values(Tm),stopService:qm,uninstallService:async(e,t)=>{Am(`Uninstalling service ${e} v${t}`);const n=await qm({serviceName:e,version:t});if(!n)return!1;Am(`Service ${e} stopped. Removing from disk...`);const r=Km(n),i=Cm();return r.startsWith(i)?(await S(r,{recursive:!0,force:!0,maxRetries:3}),Am(`Service ${e} successfully removed from disk`),(e=>{Tm[e],delete Tm[e]})(n.info.sessionId),!0):(Am(`Service ${e} is not installed in the user services directory. Aborting.`),!1)},getAllServiceVersions:e=>Object.values(Tm).filter((t=>t.info.name===e)),setHubIpcConfig:e=>{Pm={...e}},setEnableServiceLogsConfig:e=>{Rm=e},loadAndLaunch:async(e,t,n)=>{const r=C(e,t),{error:i,service:s}=await Wm(r,{logsEnabled:Rm});if(i||!s)return{errorMsg:i};try{s.info.internal=!!n,s.childProcess=await Um(s),s.status="started"}catch(e){s.status="error",e instanceof Lm?(Am(`Service spawning error: ${e.message} (${e.code})`),s.errorMsg=e.message,s.errorCode=e.code):(Am(`Error launching service ${s.info.name}: ${e}`),s.errorMsg="string"==typeof e?e:JSON.stringify(e))}return{service:s,errorCode:s.errorCode,errorMsg:s.errorMsg}},getServiceRootDirectory:Km,setSpawnNodeFunction:e=>{Dm=e},setGetSecretsFunction:e=>{jm=e},restartService:async(e,t)=>{Am(`Restarting service ${e} v${t}`);const n=await qm({serviceName:e,version:t,force:!0});return!!n&&Gm(n)},getFailedServices:()=>Object.values(Tm).filter((e=>"error"===e.status)).map((e=>({...Hm(e),errorMsg:e.errorMsg||"",errorCode:e.errorCode,status:e.status}))),isInternalKemuService:Jm,isNotInternalKemuService:e=>!Jm(e),isNotDevService:e=>!e.devMode};class Xm{constructor(){}appspace="app.";socketRoot="/tmp/";id=M.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=M.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 Qm{constructor(e){e||(e=new Xm),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 ey=Pl((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={}})),ty=Pl((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 ny{}class ry{}const iy=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 ny,t=ry){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 ny}}())}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 sy{constructor(){}on(e,t,n=!1){return iy.string(e),iy.function(t),iy.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(iy.string(e),e!=this.#e.toString()&&"*"!=e||(e=this.#e),!this.#t[e])return this;if("*"==t)return delete this.#t[e],this;iy.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){iy.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)=>{iy.string(e),iy.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 oy=new Qm;class ay extends sy{constructor(e,t){super(),this.config=e,this.log=t,this.publish=super.emit,e.maxRetries&&(this.retriesRemaining=e.maxRetries),oy=new Qm(this.config)}Client=ay;queue=new ty;socket=!1;connect=uy;emit=cy;retriesRemaining=0;explicitlyDisconnected=!1}function cy(e,t){this.log("dispatching event to ",this.id,this.path," : ",e,",",t);let n=new ey;n.type=e,n.data=t,n=this.config.rawBuffer?Buffer.from(e,this.config.encoding):oy.format(n),this.config.sync?this.queue.add(ly.bind(this,n)):this.socket.write(n)}function ly(e){this.log("dispatching event to ",this.id,this.path," : ",e),this.socket.write(e)}function uy(){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=W.connect(e.config.tls)}else e.log("Connecting client via TCP to",t),e.socket=B.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=B.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)!=oy.delimiter||-1==t.indexOf(oy.delimiter))return void e.log("Messages are large, You may want to consider smaller messages.");this.ipcBuffer="";const n=oy.parse(t),r=n.length;for(let t=0;t<r;t++){let r=new ey;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 dy=new Qm;class hy extends sy{constructor(e,t,n,r){super(),this.config=t,this.path=e,this.port=r,this.log=n,this.publish=super.emit,dy=new Qm(this.config),this.on("close",gy.bind(this))}udp4=!1;udp6=!1;server=!1;sockets=[];emit=fy;broadcast=py;onStart(e){this.publish("start",e)}stop(){this.server.close()}start(){this.path?this.config.unlink?$.unlink(this.path,by.bind(this)):by.bind(this)():this.log("Socket Server Path not specified, refusing to start")}}function fy(e,t,n){this.log("dispatching event to socket"," : ",t,n);let r=new ey;if(r.type=t,r.data=n,this.config.rawBuffer?(this.log(this.config.encoding),r=Buffer.from(t,this.config.encoding)):r=dy.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 py(e,t){this.log("broadcasting event to all known sockets listening to ",this.path," : ",this.port?this.port:"",e,t);let n=new ey;if(n.type=e,n.data=t,n=this.config.rawBuffer?Buffer.from(e,this.config.encoding):dy.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 gy(){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 my(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)==dy.delimiter&&-1!=t.indexOf(dy.delimiter))for(r.ipcBuffer="",t=dy.parse(t);t.length>0;){let e=new ey;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 yy(e){this.publish("close",e)}function vy(e){this.sockets.push(e),e.setEncoding&&e.setEncoding(this.config.encoding),this.log("## socket connection to server detected ##"),e.on("close",yy.bind(this)),e.on("error",function(e){this.log("server socket error",e),this.publish("error",e)}.bind(this)),e.on("data",my.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 by(){return this.log("starting server on ",this.path,this.port?`:${this.port}`:""),this.udp4||this.udp6?(this.server=Y.createSocket(this.udp4?"udp4":"udp6"),this.server.write=Sy.bind(this),this.server.on("listening",function(){vy.bind(this)(this.server)}.bind(this))):(this.log("starting TLS server",this.config.tls),this.config.tls?wy.bind(this)():this.server=B.createServer(vy.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 wy(){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=W.createServer(this.config.tls,vy.bind(this))}function Sy(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 _y{constructor(){}config=new Xm;of={};server=!1;get connectTo(){return Oy}get connectToNet(){return $y}get disconnect(){return xy}get serve(){return ky}get serveNet(){return Cy}get log(){return Iy}set connectTo(e){return Oy}set connectToNet(e){return $y}set disconnect(e){return xy}set serve(e){return ky}set serveNet(e){return Cy}set log(e){return Iy}}function Iy(...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 xy(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 ky(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=Ey),this.server=new hy(e,this.config,Iy),this.server.on("start",t)}function Ey(){}function Cy(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=Ey),this.server=new hy(e,this.config,Iy,t),n&&(this.server[n]=!0,"udp4"===n&&"::1"===e&&(this.server.path="127.0.0.1")),this.server.on("start",r)}function Oy(e,t,n){if("function"==typeof t&&(n=t,t=!1),n||(n=Ey),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 ay(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 $y(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=Ey),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 ay(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 Ny=new class extends _y{constructor(){super()}IPC=_y};const My=Object.values({protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8}).reduce(((e,t)=>e+t),0),Ay=e=>{try{return JSON.parse(e)}catch(e){return null}},Ty="undefined"!=typeof window,Py={protocolPrefix:4,protocolVersion:1,jsonLength:4,binaryLength:4,fromServiceId:4,toServiceId:4,sentAt:8},Dy={protocolPrefix:4,txtLength:4},jy=Object.values(Py).reduce(((e,t)=>e+t),0),Ry=Object.values(Dy).reduce(((e,t)=>e+t),0),Ly=["width","height","colorSpace"],Fy=(e,t)=>{const n={},r=[];let i=0,s=Array.isArray(e)?[]:{};const o=(e,s)=>{const a=(e=>{const t="undefined"!=typeof Buffer&&e instanceof Buffer,n=e instanceof ArrayBuffer,r=e instanceof Uint8ClampedArray,i=e instanceof Uint8Array,s=e instanceof Int8Array;return t?"Buffer":n?"ArrayBuffer":r?"Uint8ClampedArray":i?"Uint8Array":s?"Int8Array":null})(e);if(!a){if(Array.isArray(e)){const t=[];for(let n=0;n<e.length;n++)t[n]=o(e[n],`${s}[${n}]`);return t}if("object"==typeof e){const t={},n=(e=>{const t=e instanceof Int16Array,n=e instanceof Uint16Array,r=e instanceof Int32Array,i=e instanceof Uint32Array,s=e instanceof Float32Array,o=e instanceof Float64Array,a=e instanceof BigInt64Array,c=e instanceof BigUint64Array;return t?"Int16Array":n?"Uint16Array":r?"Int32Array":i?"Uint32Array":s?"Float32Array":o?"Float64Array":a?"BigInt64Array":c?"BigUint64Array":null})(e);if(n)throw new Error(`Unsupported binary type [${n}] at path "${s}"`);for(const n in e)Object.hasOwn(e,n)||Ly.includes(n)||console.warn(`Allowing inherited property: ${n} from path: ${s}`),t[n]=o(e[n],`${s.length?`${s}.`:""}${n}`);return t}return e}n[s]={index:i,length:e.byteLength,binaryType:a},"Buffer"===t?r.push(Buffer.from(e)):"ArrayBuffer"===a?r.push(e):r.push(e.buffer),i+=e.byteLength};s=o(e,"");let a=null;if(r.length>1)if("ArrayBuffer"===t){const e=r.reduce(((e,t)=>e+t.byteLength),0),t=new Uint8Array(e);let n=0;for(let e=0;e<r.length;e++)t.set(new Uint8Array(r[e]),n),n+=r[e].byteLength;a=t.buffer}else a=Buffer.concat(r);else 1===r.length&&(a=r[0]);return a?{map:n,combinedData:a,sourceCopy:s}:null},Uy=(e,t,n)=>{const r=t.match(/(\[\d+\])|([^[\].]+)/g)||[];let i=e;for(let e=0;e<r.length;e++){let t=r[e];const s=t.startsWith("[")&&t.endsWith("]"),o=e===r.length-1;if(s){t=t.slice(1,-1);const s=parseInt(t,10);if(!Array.isArray(i))throw new Error(`Expected an array at key "${r.slice(0,e).join(".")}" but found an object.`);o?i[s]=n:(i[s]||(i[s]=r[e+1].startsWith("[")?[]:{}),i=i[s])}else o?i[t]=n:(i[t]||(i[t]=r[e+1].startsWith("[")?[]:{}),i=i[t])}return e},By=(e,t,n)=>{const r="undefined"!=typeof Buffer,i=t instanceof Uint8Array;for(const s in n)if(Object.hasOwn(n,s)){const{index:o,length:a,binaryType:c}=n[s];let l=null;if(r&&t instanceof Buffer)switch(c){case"Buffer":l=t.subarray(o,o+a);break;case"ArrayBuffer":l=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(o,o+a);break;case"Uint8Array":l=new Uint8Array(t.subarray(o,o+a));break;case"Uint8ClampedArray":l=new Uint8ClampedArray(t.subarray(o,o+a));break;case"Int8Array":l=new Int8Array(t.subarray(o,o+a))}else if(t instanceof ArrayBuffer||t instanceof Uint8Array)switch(c){case"Buffer":if(r){l=Buffer.from(t.slice(o,o+a));break}case"ArrayBuffer":l=i?t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength).slice(o,o+a):t.slice(o,o+a);break;case"Uint8Array":l=i?t.slice(o,o+a):new Uint8Array(t.slice(o,o+a));break;case"Uint8ClampedArray":l=new Uint8ClampedArray(t.slice(o,o+a));break;case"Int8Array":l=new Int8Array(t.slice(o,o+a))}l&&Uy(e,s,l)}return e},Wy=e=>Jl(e),Yy="KMSG",Gy="KCMD",Hy=Wy("klProtocol");var Vy={encode:(e,t,n)=>{const r={json:e.json},i=Fy(r.json,"Buffer"),s=i?.combinedData;i&&(r.jsonBinaryMap=i.map,r.json=i.sourceCopy);const o=s?s.byteLength:0,a=JSON.stringify(r),c=Buffer.from(a),l=c.byteLength,u=Py.protocolPrefix+Py.protocolVersion+Py.jsonLength+Py.binaryLength+Py.fromServiceId+Py.toServiceId+Py.sentAt+l+o,d=Buffer.alloc(u),h=Date.now();let f=0;return d.write(Yy,f),f+=Py.protocolPrefix,d.writeUInt8(1,f),f+=Py.protocolVersion,d.writeUInt32LE(l,f),f+=Py.jsonLength,d.writeUInt32LE(o,f),f+=Py.binaryLength,d.writeUInt32LE(t,f),f+=Py.fromServiceId,d.writeUInt32LE(n,f),f+=Py.toServiceId,d.writeBigInt64LE(BigInt(h),f),f+=Py.sentAt,c.copy(d,f),f+=l,s&&o&&s.copy(d,f),d},decodeHeader:e=>{let t=0;const n=e.toString("utf-8",t,Py.protocolPrefix);if(t+=Py.protocolPrefix,n!==Yy)return null;if(e.byteLength<jy)return Hy(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const r=e.readUInt8(t);t+=Py.protocolVersion;const i=e.readUInt32LE(t);t+=Py.jsonLength;const s=e.readUInt32LE(t);t+=Py.binaryLength;const o=e.readUInt32LE(t);t+=Py.fromServiceId;const a=e.readUInt32LE(t);t+=Py.toServiceId;const c=e.readBigInt64LE(t);t+=Py.sentAt;const l=i+s,u=e.subarray(t,t+l),d=e.subarray(0,jy);let h=null;return e.byteLength-jy-i-s>0&&(h=e.subarray(jy+i+s)),{header:{protocolVersion:r,jsonLength:i,binaryLength:s,fromServiceId:o,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=Ay(n);if(!i?.json)return Hy("Invalid JSON in KL message"),null;i.jsonBinaryMap&&r.byteLength&&By(i.json,r,i.jsonBinaryMap);const s=Buffer.concat([e.headerPackage,t]);let o=s,a=null;const c=jy+e.jsonLength+e.binaryLength;return s.byteLength>c&&(a=s.subarray(c),o=s.subarray(0,c)),{message:{json:i.json,rawMessage:o},remaining:a}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<jy)return Hy("Invalid Header Size"),e;let n=0;return n+=Py.protocolPrefix,n+=Py.protocolVersion,n+=Py.jsonLength,n+=Py.binaryLength,void 0!==t.fromServiceId&&e.writeUInt32LE(t.fromServiceId,n),n+=Py.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=Ry+r,s=Buffer.alloc(i);return s.write(Gy,t),t+=Dy.protocolPrefix,s.writeUint32LE(r,t),t+=Dy.txtLength,n.copy(s,t),s},decodeCommand:e=>{let t=0;if(e.byteLength<Ry)return{command:null};const n=e.toString("utf-8",t,Dy.protocolPrefix);if(t+=Dy.protocolPrefix,n!==Gy)return{command:null};const r=e.readUInt32LE(t);t+=Dy.txtLength;const i=e.toString("utf-8",t,t+r),s=e.byteLength-Ry-r;let o=null;s>0&&(o=e.subarray(Ry+r));let a=0;return s<0&&(a=Math.abs(s)),{command:i,remainingData:o,missing:a}}};const zy="KMSG",qy="KCMD",Ky=Wy("klProtocol"),Jy=new TextEncoder;var Zy={encode:(e,t,n)=>{const r={json:e.json},i=Fy(e.json,"ArrayBuffer"),s=i?.combinedData;i&&(r.jsonBinaryMap=i.map,r.json=i.sourceCopy);const o=s?s.byteLength:0,a=JSON.stringify(r),c=Jy.encode(a),l=c.byteLength,u=new ArrayBuffer(Py.protocolPrefix+Py.protocolVersion+Py.jsonLength+Py.binaryLength+Py.fromServiceId+Py.toServiceId+Py.sentAt+l+o),d=new DataView(u),h=new Uint8Array(u),f=Date.now();let p=0;for(let e=0;e<4;++e)h[p++]=zy.charCodeAt(e);return d.setUint8(p,1),p+=Py.protocolVersion,d.setUint32(p,l,!0),p+=Py.jsonLength,d.setUint32(p,o,!0),p+=Py.binaryLength,d.setUint32(p,t,!0),p+=Py.fromServiceId,d.setUint32(p,n,!0),p+=Py.toServiceId,d.setBigInt64(p,BigInt(f),!0),p+=Py.sentAt,h.set(c,p),p+=l,s&&o&&h.set(new Uint8Array(s),p),u},decodeHeader:e=>{const t=new DataView(e);let n=0,r="";for(let e=0;e<Py.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==zy)return null;if(e.byteLength<jy)return Ky.log(`Received a Partial Header with ${e.byteLength} bytes. Waiting for more data.`),{partialHeader:!0,remaining:null};const i=t.getUint8(n);n+=Py.protocolVersion;const s=t.getUint32(n,!0);n+=Py.jsonLength;const o=t.getUint32(n,!0);n+=Py.binaryLength;const a=t.getUint32(n,!0);n+=Py.fromServiceId;const c=t.getUint32(n,!0);n+=Py.toServiceId;const l=t.getBigInt64(n,!0);n+=Py.sentAt;const u=s+o,d=e.slice(n,n+u),h=new Uint8Array(e,0,jy);let f=null;return e.byteLength-jy-s-o>0&&(f=new Uint8Array(e,jy+s+o).slice().buffer),{header:{protocolVersion:i,jsonLength:s,binaryLength:o,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 s=(new TextDecoder).decode(n.subarray(0,e.jsonLength)),o=n.subarray(e.jsonLength,e.jsonLength+e.binaryLength),a=Ay(s);if(!a?.json)return Ky.log("Invalid JSON in KL message"),null;a.jsonBinaryMap&&o.byteLength&&By(a.json,o,a.jsonBinaryMap);const c=new Uint8Array(e.headerPackage.byteLength+n.byteLength);c.set(new Uint8Array(e.headerPackage),0),c.set(n,e.headerPackage.byteLength);let l=c,u=null;const d=jy+e.jsonLength+e.binaryLength;return c.byteLength>d&&(u=c.subarray(d),l=c.subarray(0,d)),{message:{json:a.json,...o.length?{binaryData:o.buffer}:{},rawMessage:l.buffer},remaining:u?.buffer??null}},patchEncodedHeader:(e,t)=>{if(null==t.fromServiceId&&void 0===t.toServiceId)return e;if(e.byteLength<jy)return Ky("Invalid Header Size"),e;let n=0;n+=Py.protocolPrefix,n+=Py.protocolVersion,n+=Py.jsonLength,n+=Py.binaryLength;const r=new DataView(e);return void 0!==t.fromServiceId&&r.setUint32(n,t.fromServiceId,!0),n+=Py.fromServiceId,void 0!==t.toServiceId&&r.setUint32(n,t.toServiceId,!0),e},encodeCommand:e=>{let t=0;const n=Jy.encode(e),r=n.byteLength,i=new ArrayBuffer(Ry+r),s=new DataView(i),o=new Uint8Array(i);for(let e=0;e<4;++e)o[t++]=qy.charCodeAt(e);return s.setUint32(t,r,!0),t+=Dy.txtLength,o.set(n,t),i},decodeCommand:e=>{const t=new DataView(e);let n=0;if(e.byteLength<Ry)return{command:null};let r="";for(let e=0;e<Dy.protocolPrefix;++e)r+=String.fromCharCode(t.getUint8(n++));if(r!==qy)return{command:null};const i=t.getUint32(n,!0);n+=Dy.txtLength;const s=e.byteLength-Ry-i,o=new Uint8Array(e,n,Math.min(i,e.byteLength-Ry)),a=(new TextDecoder).decode(o);let c=null;s>0&&(c=e.slice(Ry+i));let l=0;return s<0&&(l=Math.abs(s)),{command:a,remainingData:c,missing:l}}};const Xy=Wy("klTransmissionManager"),Qy=()=>{const e=(t,n,r,i)=>{let s=n,o=null;const a=t instanceof ArrayBuffer;if(Xy(`RAW: ${t.toString()}`),!s||s.partialHeaderData){let c;if(a?(c=s?.partialHeaderData?new Uint8Array([...new Uint8Array(s.partialHeaderData),...new Uint8Array(t)]).buffer:t,o=Zy.decodeHeader(c)):(c=s?.partialHeaderData?Buffer.concat([s.partialHeaderData,t]):t,o=Vy.decodeHeader(c)),!o){const{command:t,missing:s,remainingData:o}=a?Zy.decodeCommand(c):Vy.decodeCommand(c);return t?i({command:t,complete:!0,rawMessage:c}):Xy(s?`ERROR: Missing ${s} bytes to complete the command. This partial command will be aborted.`:`ERROR: Invalid state, message was decoded without a header or partial header data. Discarding ${c.byteLength} bytes`),o?(Xy(`${o.byteLength} bytes remain after processing command. Re-analyzing...`),e(o,n,r,i)):void 0}if(o.partialHeader)return s={firstPackageAt:Date.now(),partialHeaderData:c},r(s);if(!o.header)return Xy(`ERROR: Invalid state, message was decoded without a header or partial header data. Discarding ${c.byteLength} bytes`);const l=o.header;s={firstPackageAt:Date.now(),header:{...l,totalBytesReceived:l.packages[0].byteLength,totalBytesExpected:l.binaryLength+l.jsonLength,remaining:o.remaining}},r(s)}else s.header&&s.header.totalBytesReceived<s.header.totalBytesExpected&&(s.header.packages.push(t),s.header.totalBytesReceived+=t.byteLength,r(s));if(s.header&&s.header.totalBytesReceived>=s.header.totalBytesExpected){const t=Date.now()-s.header.sentAt.getTime(),n=Date.now()-s.firstPackageAt;Xy(`Received ${s.header.totalBytesReceived} of ${s.header.totalBytesExpected} expected in ${t} ms, elapsed since first package: ${n}ms`);const o=a?Zy.decodeFullKlMessage(s.header):Vy.decodeFullKlMessage(s.header),c=s.header.totalBytesReceived,l=s.header.remaining;r(null),o&&i({klMessage:o.message,complete:!0,sourceServiceId:s.header.fromServiceId,targetServiceId:s.header.toServiceId,rawMessage:o.message.rawMessage});let u=l;if(o?.remaining&&(u=a?l?((e,t)=>{const n=e.byteLength+t.byteLength,r=new ArrayBuffer(n),i=new Uint8Array(e),s=new Uint8Array(t),o=new Uint8Array(r);return o.set(i),o.set(s,i.length),r})(l,o.remaining):o.remaining:l?Buffer.concat([l,o.remaining]):o.remaining),u)return Xy(`${u.byteLength} bytes remaining after processing message with ${c} bytes of data. Re-analyzing...`),e(u,null,r,i)}};return e};Ny.config={...Ny.config,id:"widgets",retry:1500,silent:!0,rawBuffer:!0,appspace:"kemu.",encoding:"hex"};const ev={info:Zl("ipcServer:info"),data:Zl("ipcServer:data")};let tv,nv,rv,iv,sv={};const ov=Qy(),av=e=>{sv[e]&&(ev.info(`Client disconnected [${e}]`),delete sv[e],nv&&nv(e))};var cv=(e,t)=>{const n=sv[e];if(!n)return ev.info(`Cannot send message to unknown client [${e}]`),!1;if(t.length>=My)return ev.info("Message is too long to be a command. Use sendMessage instead."),!1;const r=Vy.encodeCommand(t);return n.socket.write(r),!0},lv=(e,t)=>{const n=sv[e];return!!n&&(ev.info(`Renaming socket id [${e}] to [${t}]`),delete sv[e],n.socket.id=t,sv[t]=n,n.socket.removeListener("close",n.disconnectHandler),n.disconnectHandler=()=>av(t),n.socket.on("close",n.disconnectHandler),!0)};let uv=Vy;Ty&&(uv=Zy);var dv,hv=uv;!function(e){e.FunctionNotFound="FNC_NOT_FOUND",e.FunctionNotAllowed="FNC_NOT_ALLOWED",e.ParentEventCallbackError="PARENT_EVENT_CALLBACK_ERROR"}(dv||(dv={}));let fv=Math.ceil(Date.now()/1e3);var pv={exports:{}};const gv=["nodebuffer","arraybuffer","fragments"],mv="undefined"!=typeof Blob;mv&&gv.push("blob");var yv={BINARY_TYPES:gv,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:mv,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}};const{EMPTY_BUFFER:vv}=yv,bv=Buffer[Symbol.species];function wv(e,t,n,r,i){for(let s=0;s<i;s++)n[r+s]=e[s]^t[3&s]}function Sv(e,t){for(let n=0;n<e.length;n++)e[n]^=t[3&n]}if(pv.exports={concat:function(e,t){if(0===e.length)return vv;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 bv(n.buffer,n.byteOffset,r):n},mask:wv,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 bv(t):ArrayBuffer.isView(t)?n=new bv(t.buffer,t.byteOffset,t.byteLength):(n=Buffer.from(t),e.readOnly=!1),n},unmask:Sv},!process.env.WS_NO_BUFFER_UTIL)try{const e=require("bufferutil");pv.exports.mask=function(t,n,r,i,s){s<48?wv(t,n,r,i,s):e.mask(t,n,r,i,s)},pv.exports.unmask=function(t,n){t.length<32?Sv(t,n):e.unmask(t,n)}}catch(x){}var _v=pv.exports;const Iv=Symbol("kDone"),xv=Symbol("kRun"),kv=R,Ev=_v,Cv=class{constructor(e){this[Iv]=()=>{this.pending--,this[xv]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[xv]()}[xv](){if(this.pending!==this.concurrency&&this.jobs.length){const e=this.jobs.shift();this.pending++,e(this[Iv])}}},{kStatusCode:Ov}=yv,$v=Buffer[Symbol.species],Nv=Buffer.from([0,0,255,255]),Mv=Symbol("permessage-deflate"),Av=Symbol("total-length"),Tv=Symbol("callback"),Pv=Symbol("buffers"),Dv=Symbol("error");let jv;var Rv=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,!jv){const e=void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10;jv=new Cv(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[Tv];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){jv.add((r=>{this._decompress(e,t,((e,t)=>{r(),n(e,t)}))}))}compress(e,t,n){jv.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]?kv.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=kv.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[Mv]=this,this._inflate[Av]=0,this._inflate[Pv]=[],this._inflate.on("error",Uv),this._inflate.on("data",Fv)}this._inflate[Tv]=n,this._inflate.write(e),t&&this._inflate.write(Nv),this._inflate.flush((()=>{const e=this._inflate[Dv];if(e)return this._inflate.close(),this._inflate=null,void n(e);const i=Ev.concat(this._inflate[Pv],this._inflate[Av]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Av]=0,this._inflate[Pv]=[],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]?kv.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=kv.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[Av]=0,this._deflate[Pv]=[],this._deflate.on("data",Lv)}this._deflate[Tv]=n,this._deflate.write(e),this._deflate.flush(kv.Z_SYNC_FLUSH,(()=>{if(!this._deflate)return;let e=Ev.concat(this._deflate[Pv],this._deflate[Av]);t&&(e=new $v(e.buffer,e.byteOffset,e.length-4)),this._deflate[Tv]=null,this._deflate[Av]=0,this._deflate[Pv]=[],t&&this.params[`${r}_no_context_takeover`]&&this._deflate.reset(),n(null,e)}))}};function Lv(e){this[Pv].push(e),this[Av]+=e.length}function Fv(e){this[Av]+=e.length,this[Mv]._maxPayload<1||this[Av]<=this[Mv]._maxPayload?this[Pv].push(e):(this[Dv]=new RangeError("Max payload size exceeded"),this[Dv].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Dv][Ov]=1009,this.removeListener("data",Fv),this.reset())}function Uv(e){this[Mv]._inflate=null,e[Ov]=1007,this[Tv](e)}var Bv={exports:{}};const{isUtf8:Wv}=D,{hasBlob:Yv}=yv;function Gv(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(Bv.exports={isBlob:function(e){return Yv&&"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:Gv,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]},Wv)Bv.exports.isValidUTF8=function(e){return e.length<24?Gv(e):Wv(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{const e=require("utf-8-validate");Bv.exports.isValidUTF8=function(t){return t.length<32?Gv(t):e(t)}}catch(x){}var Hv=Bv.exports;const{Writable:Vv}=P,zv=Rv,{BINARY_TYPES:qv,EMPTY_BUFFER:Kv,kStatusCode:Jv,kWebSocket:Zv}=yv,{concat:Xv,toArrayBuffer:Qv,unmask:eb}=_v,{isValidStatusCode:tb,isValidUTF8:nb}=Hv,rb=Buffer[Symbol.species];const{randomFillSync:ib}=u,sb=Rv,{EMPTY_BUFFER:ob,kWebSocket:ab,NOOP:cb}=yv,{isBlob:lb,isValidStatusCode:ub}=Hv,{mask:db,toBuffer:hb}=_v,fb=Symbol("kByteLength"),pb=Buffer.alloc(4),gb=8192;let mb,yb=gb;function vb(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 bb(e,t,n){vb(e,t,n),e.onerror(t)}const{kForOnEventAttribute:wb,kListener:Sb}=yv,_b=Symbol("kCode"),Ib=Symbol("kData"),xb=Symbol("kError"),kb=Symbol("kMessage"),Eb=Symbol("kReason"),Cb=Symbol("kTarget"),Ob=Symbol("kType"),$b=Symbol("kWasClean");class Nb{constructor(e){this[Cb]=null,this[Ob]=e}get target(){return this[Cb]}get type(){return this[Ob]}}Object.defineProperty(Nb.prototype,"target",{enumerable:!0}),Object.defineProperty(Nb.prototype,"type",{enumerable:!0});class Mb extends Nb{constructor(e,t={}){super(e),this[_b]=void 0===t.code?0:t.code,this[Eb]=void 0===t.reason?"":t.reason,this[$b]=void 0!==t.wasClean&&t.wasClean}get code(){return this[_b]}get reason(){return this[Eb]}get wasClean(){return this[$b]}}Object.defineProperty(Mb.prototype,"code",{enumerable:!0}),Object.defineProperty(Mb.prototype,"reason",{enumerable:!0}),Object.defineProperty(Mb.prototype,"wasClean",{enumerable:!0});class Ab extends Nb{constructor(e,t={}){super(e),this[xb]=void 0===t.error?null:t.error,this[kb]=void 0===t.message?"":t.message}get error(){return this[xb]}get message(){return this[kb]}}Object.defineProperty(Ab.prototype,"error",{enumerable:!0}),Object.defineProperty(Ab.prototype,"message",{enumerable:!0});class Tb extends Nb{constructor(e,t={}){super(e),this[Ib]=void 0===t.data?null:t.data}get data(){return this[Ib]}}Object.defineProperty(Tb.prototype,"data",{enumerable:!0});const Pb={addEventListener(e,t,n={}){for(const r of this.listeners(e))if(!n[wb]&&r[Sb]===t&&!r[wb])return;let r;if("message"===e)r=function(e,n){const r=new Tb("message",{data:n?e:e.toString()});r[Cb]=this,jb(t,this,r)};else if("close"===e)r=function(e,n){const r=new Mb("close",{code:e,reason:n.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[Cb]=this,jb(t,this,r)};else if("error"===e)r=function(e){const n=new Ab("error",{error:e,message:e.message});n[Cb]=this,jb(t,this,n)};else{if("open"!==e)return;r=function(){const e=new Nb("open");e[Cb]=this,jb(t,this,e)}}r[wb]=!!n[wb],r[Sb]=t,n.once?this.once(e,r):this.on(e,r)},removeEventListener(e,t){for(const n of this.listeners(e))if(n[Sb]===t&&!n[wb]){this.removeListener(e,n);break}}};var Db={CloseEvent:Mb,ErrorEvent:Ab,Event:Nb,EventTarget:Pb,MessageEvent:Tb};function jb(e,t,n){"object"==typeof e&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}const{tokenChars:Rb}=Hv;function Lb(e,t,n){void 0===e[t]?e[t]=[n]:e[t].push(n)}var Fb={format:function(e){return Object.keys(e).map((t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map((e=>[t].concat(Object.keys(e).map((t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map((e=>!0===e?t:`${t}=${e}`)).join("; ")}))).join("; "))).join(", ")})).join(", ")},parse:function(e){const t=Object.create(null);let n,r,i=Object.create(null),s=!1,o=!1,a=!1,c=-1,l=-1,u=-1,d=0;for(;d<e.length;d++)if(l=e.charCodeAt(d),void 0===n)if(-1===u&&1===Rb[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?(Lb(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===Rb[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),Lb(i,e.slice(c,u),!0),44===l&&(Lb(t,n,i),i=Object.create(null),n=void 0),c=u=-1}else{if(61!==l||-1===c||-1!==u)throw new SyntaxError(`Unexpected character at index ${d}`);r=e.slice(c,d),c=u=-1}else if(o){if(1!==Rb[l])throw new SyntaxError(`Unexpected character at index ${d}`);-1===c?c=d:s||(s=!0),o=!1}else if(a)if(1===Rb[l])-1===c&&(c=d);else if(34===l&&-1!==c)a=!1,u=d;else{if(92!==l)throw new SyntaxError(`Unexpected character at index ${d}`);o=!0}else if(34===l&&61===e.charCodeAt(d-1))a=!0;else if(-1===u&&1===Rb[l])-1===c&&(c=d);else if(-1===c||32!==l&&9!==l){if(59!==l&&44!==l)throw new SyntaxError(`Unexpected character at index ${d}`);{if(-1===c)throw new SyntaxError(`Unexpected character at index ${d}`);-1===u&&(u=d);let o=e.slice(c,u);s&&(o=o.replace(/\\/g,""),s=!1),Lb(i,r,o),44===l&&(Lb(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?Lb(t,h,i):(void 0===r?Lb(i,h,!0):Lb(i,r,s?h.replace(/\\/g,""):h),Lb(t,n,i)),t}};const Ub=j,Bb=U,Wb=F,Yb=B,Gb=W,{randomBytes:Hb,createHash:Vb}=u,{URL:zb}=G,qb=Rv,Kb=class extends Vv{constructor(e={}){super(),this._allowSynchronousEvents=void 0===e.allowSynchronousEvents||e.allowSynchronousEvents,this._binaryType=e.binaryType||qv[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=0|e.maxPayload,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Zv]=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 rb(t.buffer,t.byteOffset+e,t.length-e),new rb(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 rb(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[zv.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=Kv;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]&&eb(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[zv.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?Xv(n,t):"arraybuffer"===this._binaryType?Qv(Xv(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=Xv(n,t);if(!this._skipUTF8Validation&&!nb(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,Kv),this.end();else{const n=e.readUInt16BE(0);if(!tb(n)){const e=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");return void t(e)}const r=new rb(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!nb(r)){const e=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");return void t(e)}this._loop=!1,this.emit("conclude",n,r),this.end()}this._state=0}}createError(e,t,n,r,i){this._loop=!1,this._errored=!0;const s=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(s,this.createError),s.code=i,s[Jv]=r,s}},Jb=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=cb,this[ab]=void 0}static frame(e,t){let n,r,i=!1,s=2,o=!1;t.mask&&(n=t.maskBuffer||pb,t.generateMask?t.generateMask(n):(yb===gb&&(void 0===mb&&(mb=Buffer.alloc(gb)),ib(mb,0,gb),yb=0),n[0]=mb[yb++],n[1]=mb[yb++],n[2]=mb[yb++],n[3]=mb[yb++]),o=!(n[0]|n[1]|n[2]|n[3]),s=6),"string"==typeof e?r=t.mask&&!o||void 0===t[fb]?(e=Buffer.from(e)).length:t[fb]:(r=e.length,i=t.mask&&t.readOnly&&!o);let a=r;r>=65536?(s+=8,a=127):r>125&&(s+=2,a=126);const c=Buffer.allocUnsafe(i?r+s:s);return c[0]=t.fin?128|t.opcode:t.opcode,t.rsv1&&(c[0]|=64),c[1]=a,126===a?c.writeUInt16BE(r,2):127===a&&(c[2]=c[3]=0,c.writeUIntBE(r,4,6)),t.mask?(c[1]|=128,c[s-4]=n[0],c[s-3]=n[1],c[s-2]=n[2],c[s-1]=n[3],o?[c,e]:i?(db(e,n,c,s,r),[c]):(db(e,n,e,0,r),[c,e])):[c,e]}close(t,n,r,i){let s;if(void 0===t)s=ob;else{if("number"!=typeof t||!ub(t))throw new TypeError("First argument must be a valid error code number");if(void 0!==n&&n.length){const e=Buffer.byteLength(n);if(e>123)throw new RangeError("The message must not be greater than 123 bytes");s=Buffer.allocUnsafe(2+e),s.writeUInt16BE(t,0),"string"==typeof n?s.write(n,2):s.set(n,2)}else s=Buffer.allocUnsafe(2),s.writeUInt16BE(t,0)}const o={[fb]:s.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};0!==this._state?this.enqueue([this.dispatch,s,!1,o,i]):this.sendFrame(e.frame(s,o),i)}ping(t,n,r){let i,s;if("string"==typeof t?(i=Buffer.byteLength(t),s=!1):lb(t)?(i=t.size,s=!1):(i=(t=hb(t)).length,s=hb.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");const o={[fb]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};lb(t)?0!==this._state?this.enqueue([this.getBlobData,t,!1,o,r]):this.getBlobData(t,!1,o,r):0!==this._state?this.enqueue([this.dispatch,t,!1,o,r]):this.sendFrame(e.frame(t,o),r)}pong(t,n,r){let i,s;if("string"==typeof t?(i=Buffer.byteLength(t),s=!1):lb(t)?(i=t.size,s=!1):(i=(t=hb(t)).length,s=hb.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");const o={[fb]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};lb(t)?0!==this._state?this.enqueue([this.getBlobData,t,!1,o,r]):this.getBlobData(t,!1,o,r):0!==this._state?this.enqueue([this.dispatch,t,!1,o,r]):this.sendFrame(e.frame(t,o),r)}send(e,t,n){const r=this._extensions[sb.extensionName];let i,s,o=t.binary?2:1,a=t.compress;"string"==typeof e?(i=Buffer.byteLength(e),s=!1):lb(e)?(i=e.size,s=!1):(i=(e=hb(e)).length,s=hb.readOnly),this._firstFragment?(this._firstFragment=!1,a&&r&&r.params[r._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(a=i>=r._threshold),this._compress=a):(a=!1,o=0),t.fin&&(this._firstFragment=!0);const c={[fb]:i,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:s,rsv1:a};lb(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[fb],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(vb,this,e,i)}this._bufferedBytes-=r[fb];const s=hb(t);n?this.dispatch(s,n,r,i):(this._state=0,this.sendFrame(e.frame(s,r),i),this.dequeue())})).catch((e=>{process.nextTick(bb,this,e,i)}))}dispatch(t,n,r,i){if(!n)return void this.sendFrame(e.frame(t,r),i);const s=this._extensions[sb.extensionName];this._bufferedBytes+=r[fb],this._state=1,s.compress(t,r.fin,((t,n)=>{this._socket.destroyed?vb(this,new Error("The socket was closed while data was being compressed"),i):(this._bufferedBytes-=r[fb],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][fb],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][fb],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:Zb}=Hv,{BINARY_TYPES:Xb,EMPTY_BUFFER:Qb,GUID:ew,kForOnEventAttribute:tw,kListener:nw,kStatusCode:rw,kWebSocket:iw,NOOP:sw}=yv,{EventTarget:{addEventListener:ow,removeEventListener:aw}}=Db,{format:cw,parse:lw}=Fb,{toBuffer:uw}=_v,dw=3e4,hw=Symbol("kAborted"),fw=[8,13],pw=["CONNECTING","OPEN","CLOSING","CLOSED"],gw=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;let mw=class e extends Ub{constructor(t,n,r){super(),this._binaryType=Xb[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Qb,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]),vw(this,t,n,r)):(this._autoPong=r.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Xb.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 Kb({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),s=new Jb(t,this._extensions,r.generateMask);this._receiver=i,this._sender=s,this._socket=t,i[iw]=this,s[iw]=this,t[iw]=this,i.on("conclude",xw),i.on("drain",kw),i.on("error",Ew),i.on("message",Ow),i.on("ping",$w),i.on("pong",Nw),s.onerror=Aw,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on("close",Pw),t.on("data",Dw),t.on("end",jw),t.on("error",Rw),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[qb.extensionName]&&this._extensions[qb.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())})),Tw(this)):this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();else{const e="WebSocket was closed before the connection was established";_w(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||Qb,n,r)):Iw(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||Qb,n,r)):Iw(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 Iw(this,t,r);const i={binary:"string"!=typeof t,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[qb.extensionName]||(i.compress=!1),this._sender.send(t||Qb,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";_w(this,this._req,e)}}};Object.defineProperty(mw,"CONNECTING",{enumerable:!0,value:pw.indexOf("CONNECTING")}),Object.defineProperty(mw.prototype,"CONNECTING",{enumerable:!0,value:pw.indexOf("CONNECTING")}),Object.defineProperty(mw,"OPEN",{enumerable:!0,value:pw.indexOf("OPEN")}),Object.defineProperty(mw.prototype,"OPEN",{enumerable:!0,value:pw.indexOf("OPEN")}),Object.defineProperty(mw,"CLOSING",{enumerable:!0,value:pw.indexOf("CLOSING")}),Object.defineProperty(mw.prototype,"CLOSING",{enumerable:!0,value:pw.indexOf("CLOSING")}),Object.defineProperty(mw,"CLOSED",{enumerable:!0,value:pw.indexOf("CLOSED")}),Object.defineProperty(mw.prototype,"CLOSED",{enumerable:!0,value:pw.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((e=>{Object.defineProperty(mw.prototype,e,{enumerable:!0})})),["open","error","close","message"].forEach((e=>{Object.defineProperty(mw.prototype,`on${e}`,{enumerable:!0,get(){for(const t of this.listeners(e))if(t[tw])return t[nw];return null},set(t){for(const t of this.listeners(e))if(t[tw]){this.removeListener(e,t);break}"function"==typeof t&&this.addEventListener(e,t,{[tw]:!0})}})})),mw.prototype.addEventListener=ow,mw.prototype.removeEventListener=aw;var yw=mw;function vw(e,t,n,r){const i={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:fw[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,!fw.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${fw.join(", ")})`);let s;if(t instanceof zb)s=t;else try{s=new zb(t)}catch(e){throw new SyntaxError(`Invalid URL: ${t}`)}"http:"===s.protocol?s.protocol="ws:":"https:"===s.protocol&&(s.protocol="wss:"),e._url=s.href;const o="wss:"===s.protocol,a="ws+unix:"===s.protocol;let c;if("ws:"===s.protocol||o||a?a&&!s.pathname?c="The URL's pathname is empty":s.hash&&(c="The URL contains a fragment identifier"):c='The URL\'s protocol must be one of "ws:", "wss:", "http:", "https", or "ws+unix:"',c){const t=new SyntaxError(c);if(0===e._redirects)throw t;return void bw(e,t)}const l=o?443:80,u=Hb(16).toString("base64"),d=o?Bb.request:Wb.request,h=new Set;let f,p;if(i.createConnection=i.createConnection||(o?Sw:ww),i.defaultPort=i.defaultPort||l,i.port=s.port||l,i.host=s.hostname.startsWith("[")?s.hostname.slice(1,-1):s.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":u,Connection:"Upgrade",Upgrade:"websocket"},i.path=s.pathname+s.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(f=new qb(!0!==i.perMessageDeflate?i.perMessageDeflate:{},!1,i.maxPayload),i.headers["Sec-WebSocket-Extensions"]=cw({[qb.extensionName]:f.offer()})),n.length){for(const e of n){if("string"!=typeof e||!gw.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),(s.username||s.password)&&(i.auth=`${s.username}:${s.password}`),a){const e=i.path.split(":");i.socketPath=e[0],i.path=e[1]}if(i.followRedirects){if(0===e._redirects){e._originalIpc=a,e._originalSecure=o,e._originalHostOrSocketPath=a?i.socketPath:s.host;const t=r&&r.headers;if(r={...r,headers:{}},t)for(const[e,n]of Object.entries(t))r.headers[e.toLowerCase()]=n}else if(0===e.listenerCount("redirect")){const t=a?!!e._originalIpc&&i.socketPath===e._originalHostOrSocketPath:!e._originalIpc&&s.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!o)&&(delete i.headers.authorization,delete i.headers.cookie,t||delete i.headers.host,i.auth=void 0)}i.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(i.auth).toString("base64")),p=e._req=d(i),e._redirects&&e.emit("redirect",e.url,p)}else p=e._req=d(i);i.timeout&&p.on("timeout",(()=>{_w(e,p,"Opening handshake has timed out")})),p.on("error",(t=>{null===p||p[hw]||(p=e._req=null,bw(e,t))})),p.on("response",(s=>{const o=s.headers.location,a=s.statusCode;if(o&&i.followRedirects&&a>=300&&a<400){if(++e._redirects>i.maxRedirects)return void _w(e,p,"Maximum redirects exceeded");let s;p.abort();try{s=new zb(o,t)}catch(t){const n=new SyntaxError(`Invalid URL: ${o}`);return void bw(e,n)}vw(e,s,n,r)}else e.emit("unexpected-response",p,s)||_w(e,p,`Unexpected server response: ${s.statusCode}`)})),p.on("upgrade",((t,n,r)=>{if(e.emit("upgrade",t),e.readyState!==mw.CONNECTING)return;p=e._req=null;const s=t.headers.upgrade;if(void 0===s||"websocket"!==s.toLowerCase())return void _w(e,n,"Invalid Upgrade header");const o=Vb("sha1").update(u+ew).digest("base64");if(t.headers["sec-websocket-accept"]!==o)return void _w(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 _w(e,n,c);a&&(e._protocol=a);const l=t.headers["sec-websocket-extensions"];if(void 0!==l){if(!f)return void _w(e,n,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");let r;try{r=lw(l)}catch(t){return void _w(e,n,"Invalid Sec-WebSocket-Extensions header")}const i=Object.keys(r);if(1!==i.length||i[0]!==qb.extensionName)return void _w(e,n,"Server indicated an extension that was not requested");try{f.accept(r[qb.extensionName])}catch(t){return void _w(e,n,"Invalid Sec-WebSocket-Extensions header")}e._extensions[qb.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 bw(e,t){e._readyState=mw.CLOSING,e._errorEmitted=!0,e.emit("error",t),e.emitClose()}function ww(e){return e.path=e.socketPath,Yb.connect(e)}function Sw(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=Yb.isIP(e.host)?"":e.host),Gb.connect(e)}function _w(e,t,n){e._readyState=mw.CLOSING;const r=new Error(n);Error.captureStackTrace(r,_w),t.setHeader?(t[hw]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(bw,e,r)):(t.destroy(r),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function Iw(e,t,n){if(t){const n=Zb(t)?t.size:uw(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){const t=new Error(`WebSocket is not open: readyState ${e.readyState} (${pw[e.readyState]})`);process.nextTick(n,t)}}function xw(e,t){const n=this[iw];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,void 0!==n._socket[iw]&&(n._socket.removeListener("data",Dw),process.nextTick(Mw,n._socket),1005===e?n.close():n.close(e,t))}function kw(){const e=this[iw];e.isPaused||e._socket.resume()}function Ew(e){const t=this[iw];void 0!==t._socket[iw]&&(t._socket.removeListener("data",Dw),process.nextTick(Mw,t._socket),t.close(e[rw])),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e))}function Cw(){this[iw].emitClose()}function Ow(e,t){this[iw].emit("message",e,t)}function $w(e){const t=this[iw];t._autoPong&&t.pong(e,!this._isServer,sw),t.emit("ping",e)}function Nw(e){this[iw].emit("pong",e)}function Mw(e){e.resume()}function Aw(e){const t=this[iw];t.readyState!==mw.CLOSED&&(t.readyState===mw.OPEN&&(t._readyState=mw.CLOSING,Tw(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e)))}function Tw(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),dw)}function Pw(){const e=this[iw];let t;this.removeListener("close",Pw),this.removeListener("data",Dw),this.removeListener("end",jw),e._readyState=mw.CLOSING,this._readableState.endEmitted||e._closeFrameReceived||e._receiver._writableState.errorEmitted||null===(t=e._socket.read())||e._receiver.write(t),e._receiver.end(),this[iw]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",Cw),e._receiver.on("finish",Cw))}function Dw(e){this[iw]._receiver.write(e)||this.pause()}function jw(){const e=this[iw];e._readyState=mw.CLOSING,e._receiver.end(),this.end()}function Rw(){const e=this[iw];this.removeListener("error",Rw),this.on("error",sw),e&&(e._readyState=mw.CLOSING,this.destroy())}const{tokenChars:Lw}=Hv;var Fw={parse:function(e){const t=new Set;let n=-1,r=-1,i=0;for(;i<e.length;i++){const s=e.charCodeAt(i);if(-1===r&&1===Lw[s])-1===n&&(n=i);else if(0===i||32!==s&&9!==s){if(44!==s)throw new SyntaxError(`Unexpected character at index ${i}`);{if(-1===n)throw new SyntaxError(`Unexpected character at index ${i}`);-1===r&&(r=i);const s=e.slice(n,r);if(t.has(s))throw new SyntaxError(`The "${s}" subprotocol is duplicated`);t.add(s),n=r=-1}}else-1===r&&-1!==n&&(r=i)}if(-1===n||-1!==r)throw new SyntaxError("Unexpected end of input");const s=e.slice(n,i);if(t.has(s))throw new SyntaxError(`The "${s}" subprotocol is duplicated`);return t.add(s),t}};const Uw=j,Bw=F,{createHash:Ww}=u,Yw=Fb,Gw=Rv,Hw=Fw,Vw=yw,{GUID:zw,kWebSocket:qw}=yv,Kw=/^[+/0-9A-Za-z]{22}==$/;function Jw(e){e._state=2,e.emit("close")}function Zw(){this.destroy()}function Xw(e,t,n,r){n=n||Bw.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} ${Bw.STATUS_CODES[t]}\r\n`+Object.keys(r).map((e=>`${e}: ${r[e]}`)).join("\r\n")+"\r\n\r\n"+n)}function Qw(e,t,n,r,i){if(e.listenerCount("wsClientError")){const r=new Error(i);Error.captureStackTrace(r,Qw),e.emit("wsClientError",r,n,t)}else Xw(n,r,i)}var eS=Pl(class extends Uw{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:Vw,...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=Bw.createServer(((e,t)=>{const n=Bw.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(Jw,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(Jw,this);else{const e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close((()=>{Jw(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",Zw);const i=e.headers["sec-websocket-key"],s=e.headers.upgrade,o=+e.headers["sec-websocket-version"];if("GET"!==e.method)return void Qw(this,e,t,405,"Invalid HTTP method");if(void 0===s||"websocket"!==s.toLowerCase())return void Qw(this,e,t,400,"Invalid Upgrade header");if(void 0===i||!Kw.test(i))return void Qw(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");if(8!==o&&13!==o)return void Qw(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header");if(!this.shouldHandle(e))return void Xw(t,400);const a=e.headers["sec-websocket-protocol"];let c=new Set;if(void 0!==a)try{c=Hw.parse(a)}catch(n){return void Qw(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 Gw(this.options.perMessageDeflate,!0,this.options.maxPayload);try{const e=Yw.parse(l);e[Gw.extensionName]&&(r.accept(e[Gw.extensionName]),u[Gw.extensionName]=r)}catch(n){return void Qw(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header")}}if(this.options.verifyClient){const s={origin:e.headers[8===o?"sec-websocket-origin":"origin"],secure:!(!e.socket.authorized&&!e.socket.encrypted),req:e};if(2===this.options.verifyClient.length)return void this.options.verifyClient(s,((s,o,a,l)=>{if(!s)return Xw(t,o||401,a,l);this.completeUpgrade(u,i,c,e,t,n,r)}));if(!this.options.verifyClient(s))return Xw(t,401)}this.completeUpgrade(u,i,c,e,t,n,r)}completeUpgrade(e,t,n,r,i,s,o){if(!i.readable||!i.writable)return i.destroy();if(i[qw])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return Xw(i,503);const a=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Ww("sha1").update(t+zw).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[Gw.extensionName]){const t=e[Gw.extensionName].params,n=Yw.format({[Gw.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",Zw),c.setSocket(i,s,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(c),c.on("close",(()=>{this.clients.delete(c),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Jw,this)}))),o(c,r)}});const tS=Zl("websocketServer"),nS={},rS=Qy();let iS,sS,oS,aS,cS;const lS=["https://app.kemu.io","https://dev.kemu.io","https://stage.kemu.io","https://local.kemu.io:3003"],uS=e=>{const t=nS[e];t&&t.socket.close()};var dS=e=>{cS=new eS({port:e,maxPayload:1048576e3,verifyClient:(e,t)=>{const n=e.req.headers.origin;n&&lS.includes(n)?t(!0):t(!1,401,"Origin not allowed")}}),cS.on("connection",(e=>{const t=pm();tS(`New client connected. Registered as "${t}"`),e.id=t,nS[t]={socket:e,activeMessage:null},iS&&iS(t),e.on("message",(t=>{if(t instanceof Buffer){const n=nS[e.id];rS(t,n.activeMessage,(e=>n.activeMessage=e),(t=>{if(!t.complete)return;const r=t=>{e.send(t),tS(`Writing ${t.byteLength} bytes to socket [${n.socket.id}]: ${t.toString()}`)},i=()=>{uS(n.socket.id)};if(t.command)return tS(`Received command from client [${n.socket.id}]: ${t.command}`),void(oS&&oS(n.socket.id,t.command,r,i));t.klMessage&&aS&&aS({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",(()=>{tS(`Client disconnected: ${e.id}`),sS&&sS(e.id),delete nS[e.id]})),e.on("error",(()=>{tS(`Error on client connection: ${e.id}`)}))})),console.log(`WebSocket server is running on port ${e}`)},hS=e=>{iS=e},fS=e=>{sS=e},pS=e=>{oS=e},gS=(e,t)=>{const n=nS[e];if(!n)return tS(`Cannot send message to unknown client [${e}]`),!1;if(t.length>=My)return tS("Message is too long to be a command. Use sendMessage instead."),!1;const r=Vy.encodeCommand(t);return n.socket.send(r),!0},mS=e=>aS=e,yS=uS;const vS=Zl("stopService"),bS=async e=>{const t=e.args[0];if(!t)return e.reply({error:"No service name provided"});const n=Zm.getAllServiceVersions(t);vS(`Stopping ${n.length} services with name: ${t}`);for(const e of n)await Zm.stopService({serviceName:e.info.name,version:e.info.version});const r=n.map((e=>`${e.info.name}@${e.info.version}`));e.reply({success:[r]})},wS=Zl("removeService"),SS=async e=>{const t=e.args[0],n=e.args[1];if(!t)return e.reply({error:"No service name provided"});let r=Zm.getAllServiceVersions(t);n&&(r=r.filter((e=>e.info.version===n))),wS(`Removing ${r.length} service(s) with name: ${t}`);for(const e of r)await Zm.uninstallService(e.info.name,e.info.version);const i=r.map((e=>`${e.info.name}@${e.info.version}`));e.reply({success:[i]})},_S=Zl("launchService"),IS=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=Cm();_S(`Loading service ${t}@${n} from ${i}`);const{errorMsg:s,service:o,errorCode:a}=await Zm.loadAndLaunch(i,r,!1);if(s||"started"!==o?.status)return e.reply({error:`Failed to launch service ${t}@${n}: ${s||"error-not-provided"}`,errCode:a});const c=Date.now(),l=3e4,u=async()=>{const r=o.status;return"running"===r?(_S(`Service ${t}@${n} loaded and started`),e.reply({success:[]})):(_S(`Service ${t}@${n} not yet started, status: ${r}`),"stopped"===r||"error"===r?e.reply({error:`Error launching service: "${o.errorMsg||"failed to initiate"}"`}):Date.now()-c>l?e.reply({error:"Timeout waiting for service to start"}):(_S("Retrying in 1 second..."),void setTimeout(u,1e3)))};u()}catch(r){return _S(`Error loading service ${t}@${n}: ${r?.message||r}`),e.reply({error:r?.message||"There was an error loading the service"})}},xS=Zl("getMatchingServices"),kS=async e=>{const t=e.args[0],n=[],r=[];xS(`Checking for matching services: ${t.map((e=>e.name)).join(", ")}`);for(const{name:e,version:i}of t){const t=Zm.getMatchingService(e,i);t?n.push({name:e,version:i,installationPath:Zm.getServiceRootDirectory(t)}):r.push({name:e,version:i})}xS(`Found ${n.length} available services and ${r.length} missing services.`),e.reply({success:[{available:n,missing:r}]})},ES=Zl("getSecretsValues");let CS;var OS=async e=>{const t=e.args[0].services;if(!CS)throw new Error("getSecretValuesFn is not set. Please call setGetSecretValuesFunction before using this function.");ES(`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 CS({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})},$S=e=>{CS=e};const NS=Zl("getMappedSecrets");let MS;var AS=async e=>{const t=e.args[0].services;NS(`Getting mapped secrets for services: ${t.map((e=>`${e.name}@${e.version}`)).join(", ")}`);const n=await MS(t),r=[{services:t.map((e=>({name:e.name,version:e.version,secrets:n[e.name]||[]})))}];e.reply({success:r})};const TS=Zl("getServiceContents"),PS=({reply:e,args:t})=>{const[n]=t;TS(`Received GetServiceContents request for service ${n.serviceName} v${n.version}`);const r=Zm.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}]});TS(`Service ${n.serviceName} v${n.version} not found`),e({error:`Service ${n.serviceName} v${n.version} not found`})};let DS={globalApiKey:void 0,environment:"production"};const jS=()=>({...DS}),RS=Zl("apis"),LS=()=>{const e=jS();if(!e.serviceUrl)throw new Error("Unknown server URL. Please call `edgeConfig.setEdgeConfig` before using the APIs.");return e.serviceUrl},FS=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}}},US={},BS=async e=>{const t=(e=>{const t=US[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 FS(`${LS()}/v1/organization/validate/apiKey`,{apiKey:e},{"Content-Type":"application/json"});return n?(RS(`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&&(US[e]={features:r,lastCheckedAt:new Date}),{valid:n,features:r,error:i}};function WS(e){return"number"==typeof e||!!/^0x[0-9a-f]+$/i.test(e)||/^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(e)}function YS(e,t){return"constructor"===t&&"function"==typeof e[t]||"__proto__"===t}var GS=Pl((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 s=t.default||{},o={_:[]};function a(e,t,r){for(var i=e,s=0;s<t.length-1;s++){var o=t[s];if(YS(i,o))return;void 0===i[o]&&(i[o]={}),i[o]!==Object.prototype&&i[o]!==Number.prototype&&i[o]!==String.prototype||(i[o]={}),i[o]===Array.prototype&&(i[o]=[]),i=i[o]}var a=t[t.length-1];YS(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 s=!n.strings[e]&&WS(t)?Number(t):t;a(o,e.split("."),s),(r[e]||[]).forEach((function(e){a(o,e.split("."),s)}))}}Object.keys(n.bools).forEach((function(e){c(e,void 0!==s[e]&&s[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)||o._.push(n.strings._||!WS(f)?f:Number(f)),t.stopEarly){o._.push.apply(o._,e.slice(u+1));break}}return Object.keys(s).forEach((function(e){var t,n,i;t=o,n=e.split("."),i=t,n.slice(0,-1).forEach((function(e){i=i[e]||{}})),n[n.length-1]in i||(a(o,e.split("."),s[e]),(r[e]||[]).forEach((function(t){a(o,t.split("."),s[e])})))})),t["--"]?o["--"]=l.slice():l.forEach((function(e){o._.push(e)})),o}));Wy("ipcClient"),Wy("kemuWidgetService"),GS(process.argv.slice(2));const HS=Zl("activeClients");let VS,zS={},qS={};const KS=(e,t)=>`${e}_${t}`,JS=e=>zS[e]||null,ZS=(e,t)=>{const n=KS(e,t);return qS[n]||[]},XS=()=>{for(const e in zS){const t=zS[e];if(t?.transport===gl.WS){const e=Vy.encodeCommand(hl.ServicesListChanged);t.send(e)}}},QS=async e=>{const t=[],{serviceSessionId:n,transport:r,send:i,terminateFn:s,extraInfo:o,isDevClient:a}=e,c=e=>{console.warn(e),s&&s()};if(r===gl.WS){if(!o.user?.wsApiKey)return void c(`Attempted to register a WebSocket client without an API key. SessionId: ${n}`);const{valid:e,error:t}=await BS(o.user?.wsApiKey);if(!e&&!t)return void c(`Attempted to register a WebSocket client with an invalid API key. SessionId: ${n}`);t&&(o.user?.wsApiKey&&Mm.captureError({error:new Error(t),message:`Error validating api key "${o.user?.wsApiKey}"`,data:o}),HS(`Unable to validate API Key, usage will be limited. SessionId: ${n}`))}zS[n]={serviceSessionId:n,transport:r,isDevClient:!!a,broadcastSubscriptions:t,send:i,extraInfo:o,terminate:()=>{s&&s()},addSubscription:e=>{if(!t.some((t=>t.targetService.serviceName===e.serviceName&&t.targetService.version===e.version))){t.push({targetService:e});const r=KS(e.serviceName,e.version);return qS[r]=qS[r]||[],qS[r].some((e=>e.serviceId===n))||qS[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=KS(e.serviceName,e.version),s=qS[i]?.findIndex((e=>e.serviceId===n));if(-1!==s&&(qS[i]?.splice(s,1),!qS[i]?.length)){const t=Zm.getMatchingService(e.serviceName,e.version);if(t?.info.eventEmitter&&"running"===t.status){const e=JS(t.info.sessionId);e?.extraInfo.ipcSocketId&&cv(e?.extraInfo.ipcSocketId,hl.BroadcastEnd)}}}},removeAllSubscriptions:()=>{for(const e of t){const t=KS(e.targetService.serviceName,e.targetService.version),r=qS[t]?.findIndex((e=>e.serviceId===n));-1!==r&&qS[t]?.splice(r,1)}t.length=0}},r===gl.IPC&&(XS(),e_(n))},e_=e=>{const t=Zm.getServiceBySessionId(e);if(t?.info.eventEmitter&&ZS(t.info.name,t.info.version).length){const t=JS(e);t?.extraInfo.ipcSocketId&&cv(t?.extraInfo.ipcSocketId,hl.BroadcastStart)}},t_=e=>{const t=zS[e];var n;t?.transport===gl.IPC?XS():(t?.removeAllSubscriptions(),(()=>{const e=Object.values(zS);for(const t of e)if(t.transport===gl.IPC){const e=t.extraInfo.ipcSocketId,n=Zm.getServiceBySessionId(t.serviceSessionId);n?.info.eventEmitter&&(ZS(n.info.name,n.info.version).length||e&&cv(e,hl.BroadcastEnd))}})(),t?.extraInfo.user?.wsApiKey&&(n=t.extraInfo.user.wsApiKey,delete US[n]),(e=>{const t=zS[e];if(t?.transport===gl.WS&&t.extraInfo.recipe){const n=[{recipe:t.extraInfo.recipe}];HS(`Notifying IPC clients that a Kemu Compose client [${t.extraInfo.recipe.name} (${t.extraInfo.recipe.poolId})] has disconnected. ServiceSessionId: ${e}`);for(const e in zS){const t=zS[e];t?.transport===gl.IPC&&VS.execute(fl.KemuComposerDisconnected,n,t.send,0,t.serviceSessionId,{async:!0}).catch((t=>{HS(`Error notifying IPC client [${e}] that a Kemu Compose client has disconnected: ${t?.message||t}`)}))}}})(e)),delete zS[e]},n_=Zl("ipc:handleIpcClientCommand"),r_=(e,t,n)=>{const r=((e,t)=>{if(e.startsWith(hl.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 n_(`Ignoring ACK response from IPC service ${e} with no service id`);n_(`Received ACK from IPC service ${e}. Marking as running.`);let r=e;t&&e&&e!==t&&(lv(e,t),r=t);let i=!1;t&&(i=Zm.setServiceStatus(t,"running")),i?QS({serviceSessionId:t||e,transport:gl.IPC,send:n,extraInfo:{ipcSocketId:t}}):cv(r,hl.SendManifest)}));!r&&n_(`Received unknown command [${t}] from service ${e}`)};let i_={};V.platform();const s_=async e=>{const t=e.args[0];if(i_.chooseDirectory)try{const n=await i_.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"})},o_=async e=>{const t=e.args[0];if(i_.chooseFile)try{const n=await i_.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 a_={},c_={},l_={};function u_(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`positive integer expected, not ${e}`)}function d_(e){if("boolean"!=typeof e)throw new Error(`boolean expected, not ${e}`)}function h_(e){return e instanceof Uint8Array||null!=e&&"object"==typeof e&&"Uint8Array"===e.constructor.name}function f_(e,...t){if(!h_(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 p_(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.wrapConstructor");u_(e.outputLen),u_(e.blockLen)}function g_(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 m_(e,t){f_(e);const n=t.outputLen;if(e.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}Object.defineProperty(l_,"__esModule",{value:!0}),l_.output=l_.exists=l_.hash=l_.bytes=l_.bool=l_.number=l_.isBytes=void 0,l_.number=u_,l_.bool=d_,l_.isBytes=h_,l_.bytes=f_,l_.hash=p_,l_.exists=g_,l_.output=m_;const y_={number:u_,bool:d_,bytes:f_,hash:p_,exists:g_,output:m_};l_.default=y_;var v_={};Object.defineProperty(v_,"__esModule",{value:!0}),v_.add5L=v_.add5H=v_.add4H=v_.add4L=v_.add3H=v_.add3L=v_.add=v_.rotlBL=v_.rotlBH=v_.rotlSL=v_.rotlSH=v_.rotr32L=v_.rotr32H=v_.rotrBL=v_.rotrBH=v_.rotrSL=v_.rotrSH=v_.shrSL=v_.shrSH=v_.toBig=v_.split=v_.fromBig=void 0;const b_=BigInt(2**32-1),w_=BigInt(32);function S_(e,t=!1){return t?{h:Number(e&b_),l:Number(e>>w_&b_)}:{h:0|Number(e>>w_&b_),l:0|Number(e&b_)}}function __(e,t=!1){let n=new Uint32Array(e.length),r=new Uint32Array(e.length);for(let i=0;i<e.length;i++){const{h:s,l:o}=S_(e[i],t);[n[i],r[i]]=[s,o]}return[n,r]}v_.fromBig=S_,v_.split=__;const I_=(e,t)=>BigInt(e>>>0)<<w_|BigInt(t>>>0);v_.toBig=I_;const x_=(e,t,n)=>e>>>n;v_.shrSH=x_;const k_=(e,t,n)=>e<<32-n|t>>>n;v_.shrSL=k_;const E_=(e,t,n)=>e>>>n|t<<32-n;v_.rotrSH=E_;const C_=(e,t,n)=>e<<32-n|t>>>n;v_.rotrSL=C_;const O_=(e,t,n)=>e<<64-n|t>>>n-32;v_.rotrBH=O_;const $_=(e,t,n)=>e>>>n-32|t<<64-n;v_.rotrBL=$_;const N_=(e,t)=>t;v_.rotr32H=N_;const M_=e=>e;v_.rotr32L=M_;const A_=(e,t,n)=>e<<n|t>>>32-n;v_.rotlSH=A_;const T_=(e,t,n)=>t<<n|e>>>32-n;v_.rotlSL=T_;const P_=(e,t,n)=>t<<n-32|e>>>64-n;v_.rotlBH=P_;const D_=(e,t,n)=>e<<n-32|t>>>64-n;function j_(e,t,n,r){const i=(t>>>0)+(r>>>0);return{h:e+n+(i/2**32|0)|0,l:0|i}}v_.rotlBL=D_,v_.add=j_;const R_=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0);v_.add3L=R_;const L_=(e,t,n,r)=>t+n+r+(e/2**32|0)|0;v_.add3H=L_;const F_=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0);v_.add4L=F_;const U_=(e,t,n,r,i)=>t+n+r+i+(e/2**32|0)|0;v_.add4H=U_;const B_=(e,t,n,r,i)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(i>>>0);v_.add5L=B_;const W_=(e,t,n,r,i,s)=>t+n+r+i+s+(e/2**32|0)|0;v_.add5H=W_;const Y_={fromBig:S_,split:__,toBig:I_,shrSH:x_,shrSL:k_,rotrSH:E_,rotrSL:C_,rotrBH:O_,rotrBL:$_,rotr32H:N_,rotr32L:M_,rotlSH:A_,rotlSL:T_,rotlBH:P_,rotlBL:D_,add:j_,add3L:R_,add3H:L_,add4L:F_,add4H:U_,add5H:W_,add5L:B_};v_.default=Y_;var G_={},H_={};Object.defineProperty(H_,"__esModule",{value:!0}),H_.crypto=void 0,H_.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=F_,n=r_;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,s=57,o=65,a=70,c=97,l=102;function u(e){return e>=i&&e<=s?e-i:e>=o&&e<=a?e-(o-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)),s=u(e.charCodeAt(i+1));if(void 0===n||void 0===s){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+s}return r},e.nextTick=async()=>{},e.asyncLoop=async function(t,n,r){let i=Date.now();for(let s=0;s<t;s++){r(s);const t=Date.now()-i;t>=0&&t<n||(await(0,e.nextTick)(),i+=t)}},e.utf8ToBytes=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")}}(R_),Object.defineProperty(n_,"__esModule",{value:!0}),n_.shake256=n_.shake128=n_.keccak_512=n_.keccak_384=n_.keccak_256=n_.keccak_224=n_.sha3_512=n_.sha3_384=n_.sha3_256=n_.sha3_224=n_.Keccak=n_.keccakP=void 0;const U_=r_,B_=h_,W_=R_,Y_=[],G_=[],H_=[],V_=BigInt(0),z_=BigInt(1),q_=BigInt(2),K_=BigInt(7),J_=BigInt(256),Z_=BigInt(113);for(let e=0,t=z_,n=1,r=0;e<24;e++){[n,r]=[r,(2*n+3*r)%5],Y_.push(2*(5*r+n)),G_.push((e+1)*(e+2)/2%64);let i=V_;for(let e=0;e<7;e++)t=(t<<z_^(t>>K_)*Z_)%J_,t&q_&&(i^=z_<<(z_<<BigInt(e))-z_);H_.push(i)}const[X_,Q_]=(0,B_.split)(H_,!0),eI=(e,t,n)=>n>32?(0,B_.rotlBH)(e,t,n):(0,B_.rotlSH)(e,t,n),tI=(e,t,n)=>n>32?(0,B_.rotlBL)(e,t,n):(0,B_.rotlSL)(e,t,n);function nI(e,t=24){const n=new Uint32Array(10);for(let r=24-t;r<24;r++){for(let t=0;t<10;t++)n[t]=e[t]^e[t+10]^e[t+20]^e[t+30]^e[t+40];for(let t=0;t<10;t+=2){const r=(t+8)%10,i=(t+2)%10,s=n[i],o=n[i+1],a=eI(s,o,1)^n[r],c=tI(s,o,1)^n[r+1];for(let n=0;n<50;n+=10)e[t+n]^=a,e[t+n+1]^=c}let t=e[2],i=e[3];for(let n=0;n<24;n++){const r=G_[n],s=eI(t,i,r),o=tI(t,i,r),a=Y_[n];t=e[a],i=e[a+1],e[a]=s,e[a+1]=o}for(let t=0;t<50;t+=10){for(let r=0;r<10;r++)n[r]=e[t+r];for(let r=0;r<10;r++)e[t+r]^=~n[(r+2)%10]&n[(r+4)%10]}e[0]^=X_[r],e[1]^=Q_[r]}n.fill(0)}n_.keccakP=nI;class rI extends W_.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,U_.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,W_.u32)(this.state)}keccak(){W_.isLE||(0,W_.byteSwap32)(this.state32),nI(this.state32,this.rounds),W_.isLE||(0,W_.byteSwap32)(this.state32),this.posOut=0,this.pos=0}update(e){(0,U_.exists)(this);const{blockLen:t,state:n}=this,r=(e=(0,W_.toBytes)(e)).length;for(let i=0;i<r;){const s=Math.min(t-this.pos,r-i);for(let t=0;t<s;t++)n[this.pos++]^=e[i++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:n,blockLen:r}=this;e[n]^=t,128&t&&n===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){(0,U_.exists)(this,!1),(0,U_.bytes)(e),this.finish();const t=this.state,{blockLen:n}=this;for(let r=0,i=e.length;r<i;){this.posOut>=n&&this.keccak();const s=Math.min(n-this.posOut,i-r);e.set(t.subarray(this.posOut,this.posOut+s),r),this.posOut+=s,r+=s}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return(0,U_.number)(e),this.xofInto(new Uint8Array(e))}digestInto(e){if((0,U_.output)(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:t,suffix:n,outputLen:r,rounds:i,enableXOF:s}=this;return e||(e=new rI(t,n,r,s,i)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=n,e.outputLen=r,e.enableXOF=s,e.destroyed=this.destroyed,e}}n_.Keccak=rI;const iI=(e,t,n)=>(0,W_.wrapConstructor)((()=>new rI(t,e,n)));n_.sha3_224=iI(6,144,28),n_.sha3_256=iI(6,136,32),n_.sha3_384=iI(6,104,48),n_.sha3_512=iI(6,72,64),n_.keccak_224=iI(1,144,28),n_.keccak_256=iI(1,136,32),n_.keccak_384=iI(1,104,48),n_.keccak_512=iI(1,72,64);const sI=(e,t,n)=>(0,W_.wrapXOFConstructorWithOpts)(((r={})=>new rI(t,e,void 0===r.dkLen?n:r.dkLen,!0)));n_.shake128=sI(31,168,16),n_.shake256=sI(31,136,32);const{sha3_512:oI}=n_,aI=(e=4,t=Math.random)=>{let n="";for(;n.length<e;)n+=Math.floor(36*t()).toString(36);return n};function cI(e){let t=0n;for(const n of e.values())t=(t<<8n)+BigInt(n);return t}const lI=(e="")=>cI(oI(e)).toString(36).slice(1),uI=Array.from({length:26},((e,t)=>String.fromCharCode(t+97))),dI=({globalObj:e=(void 0!==Al?Al:"undefined"!=typeof window?window:{}),random:t=Math.random}={})=>{const n=Object.keys(e).toString(),r=n.length?n+aI(32,t):aI(32,t);return lI(r).substring(0,32)},hI=e=>()=>e++,fI=({random:e=Math.random,counter:t=hI(Math.floor(476782367*e())),length:n=24,fingerprint:r=dI({random:e})}={})=>function(){const i=(e=>uI[Math.floor(e()*uI.length)])(e),s=Date.now().toString(36),o=t().toString(36),a=aI(n,e);return`${i+lI(`${s+a+o+r}`).substring(1,n)}`},pI=fI();t_.getConstants=()=>({defaultLength:24,bigLength:32}),t_.init=fI,t_.createId=pI,t_.bufToBigInt=cI,t_.createCounter=hI,t_.createFingerprint=dI,t_.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:gI,init:mI,getConstants:yI,isCuid:vI}=t_;var bI=gI;const wI=Zl("getUniqueId"),SI=({reply:e,sourceServiceId:t})=>(wI(`Generating unique id for service "${t}"`),e({success:[bI()]})),_I=Zl("getActiveServices"),II=async({transport:e,sourceServiceId:t,reply:n})=>{if(_I(`Received GetServices request from ${e} [${t}]`),e===gl.WS){let e=Jm.getActiveServices();const r=GS(t);if(!r)return n({error:"Client not found",errCode:"CLIENT_NOT_FOUND"});let i=[];if(r.transport===gl.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(Jm.isInternalKemuService),s=e.filter((e=>e.devMode&&Jm.isNotInternalKemuService(e))),o=e.filter((e=>Jm.isOfficialKemuService(e)&&Jm.isNotInternalKemuService(e)&&Jm.isNotDevService(e))).sort(((e,t)=>e.name.localeCompare(t.name))),a=e.filter((e=>Jm.isNotDevService(e)&&Jm.isNotInternalKemuService(e)&&!Jm.isOfficialKemuService(e))),c=await(async e=>{const{features:t}=await FS(e);return t})(r.extraInfo.user?.wsApiKey),l=c?.hub_services??0,u=o.slice(0,-1!==l?l:o.length);-1!==l&&(i=o.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,...s,...u,...a]}const s=Jm.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:Jm.isInternalKemuService(e),svgIcon:e.svgIcon,color:e.color,shortTitle:e.shortTitle})));n({success:[{available:e.map((e=>{const{widgetUIContents:t,...n}=e;return{...n}})),failed:s,installed:i}]})}};let xI="runtime",kI=null;const EI=()=>xI,CI=Zl("getSystemInfo"),$I=async({reply:e})=>{CI("Received GetSystemInfo request"),e({success:[await(async()=>({platformArch:_l(),isDesktopHub:"desktop"===EI(),isRuntimeHub:"runtime"===EI(),hubVersion:vm,...kI?{updateAvailable:kI}:{}}))()]})},OI=Zl("removeService"),MI=async({args:e,sourceServiceId:t,reply:n})=>{const r=e[0],i=r.serviceName,s=r.version;if(!i)return n({error:"No service name provided"});if(!s)return n({error:"No service version provided"});const o=Jm.getAllServiceVersions(i),a=o.find((e=>e.info.version===s));if(!a)return n({error:"Service not found"});OI(`Removing ${o.length} service(s) with name: ${i}`);const c=a.info.publicationId;let l;if(await Jm.uninstallService(a.info.name,a.info.version),c){const e=GS(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"});OI(`Updating license details for "${c}"`);const i=await(async e=>{const{data:t,error:n}=await LS(`${jS()}/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=>(OI(`Error updating license details for "${c}": ${e}`),{error:e.message,remaining:void 0})));l=i?.remaining}n({success:[{remaining:l,service:{name:i,version:s}}]})},NI=Zl("getDecryptedEdgeApiKey"),TI=({reply:e})=>(NI("Getting decrypted edge API key"),e({success:[DS().globalApiKey]})),AI=({reply:e})=>{NI("Getting hub config");const t=DS();return e({success:[{kemuApiKey:t.globalApiKey,environment:t.environment}]})},DI=C(z(import.meta.url));let PI=null;const jI=Zl("hub"),LI=new function(){const e={};let t=console.log;const n={};let r="hub";const i={},s=e=>!i[e],o=(e,t,n,r,i,o)=>{let a=Ty?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=dv.encode(c,n,r)),i(a,{msg:c,sourceServiceId:n,targetServiceId:r})};return{setLogger:e=>{t=e},processMessage:(r,i,s,a)=>{if(!a)return!1;const c=a;if(e[c.messageId]){const t=e[c.messageId];return t&&(clearTimeout(t.timer),t.fulfilled||(t.fulfilled=!0,"response"===c.type?t.resolve(c.args):"error"===c.type&&t.reject(c.args[0])),delete e[c.messageId]),!0}if("execute"!==c.type&&t&&t(`No pending execution found for message id "${c.messageId}"`),"execute"===c.type){const e=n[c.functionName];if(e){const t=e=>{o(c.functionName,c.messageId,s.targetServiceId,s.sourceServiceId,i,e)};e({transport:r,args:c.args,reply:t,messageId:c.messageId,sourceServiceId:s.sourceServiceId,send:i})}else{const e=`Function "${c.functionName}" not found.`;t&&t(e),o(c.functionName,c.messageId,s.targetServiceId,s.sourceServiceId,i,{error:e,errCode:"FNC_NOT_FOUND"})}return!0}return!1},execute:async(n,i,o,a,c,l)=>{if(!o){const e="No send buffer function provided.";throw t&&t(e),e}hv+=1;const u=`${r}-${hv}-exec-${n.substring(0,10)}`,d={messageId:u,functionName:n,send:o,sourceServiceId:a,targetServiceId:c,args:i||[],fulfilled:!1,resolve:()=>{},reject:()=>{}};d.promise=new Promise(((e,t)=>{d.resolve=e,d.reject=t}));let h=Ty?new ArrayBuffer(0):Buffer.alloc(0);const f={json:{functionName:n,args:i,messageId:u,type:"execute"}};s(c)&&(h=dv.encode(f,a,c)),e[u]=d,t&&t(`Calling remote function "${n}" 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((()=>{t&&t(`Remote function ${u} timed out`);const r=e[u];r&&!r.fulfilled&&(r.fulfilled=!0,d.reject(`Function ${n} Timed out`)),delete e[u]}),l?.timeout||3e4)),o(h,{sourceServiceId:a,targetServiceId:c,msg:f}),d.promise},sendResponse:o,registerFunction:(e,t)=>{n[e]=t},getTransportSendFunction:t=>{const n=e[t];return n?n.send:null},setServiceName:e=>{r=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,n,i,o)=>{hv+=1;const a=`${r}-${hv}-multicast-${e.substring(0,10)}`;let c=Ty?new ArrayBuffer(0):Buffer.alloc(0);const l={json:{functionName:e,args:n,messageId:a,type:"execute"}};let u=s(i[0].serviceId);u&&(c=dv.encode(l,o,i[0].serviceId));for(let n=0;n<i.length;n++)try{const r=i[n];t&&t(`Broadcasting function "${e}" with message id "${a}" to client [${r.serviceId}]`),0!==n&&(u=s(r.serviceId),u&&(c=dv.patchEncodedHeader(c,{toServiceId:r.serviceId}))),r.sendFn(c,{msg:l,sourceServiceId:o,targetServiceId:r.serviceId})}catch(e){t&&t(`Error broadcasting to client at index ${n}`)}},disableServiceEncoding:(e,t)=>{i[e]=t}}}("hub");LI.setLogger(jI);const RI={[fl.RebootToInstallUpdate]:null,[fl.GetFileContentFromCacheId]:null},FI=(e,t)=>{const{transmission:n}=t;if(0!==n.targetServiceId){const r=GS(n.targetServiceId);if(!r)return jI(`Service [${e}] ${n.sourceServiceId} is sending data to an unknown service ["${n.targetServiceId}"]`),!0;r.transport,gl.IPC;const i=t.json?.messageId;return jI(`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},UI=({sourceServiceId:e,args:t})=>{const n=Jm.getServiceBySessionId(e);if(n){const r=HS(n.info.name,n.info.version),i=HS(n.info.name,"*");if(!r.length&&!i.length)return;const s=[...r,...i],o={...t[0],source:{serviceName:n.info.name,serviceVersion:n.info.version,sessionId:e}};LI.broadcast(fl.BroadcastEvent,[o],s,0)}},BI=e=>{const{send:t,transmission:n,json:r}=e;jI(`Raw message Id received from WS: ${r?.messageId}`),FI(gl.WS,e)||LI.processMessage(gl.WS,t,n,r)},WI=e=>{const t=(n=e,`${hl.SocketAcknowledge}${n}`);var n;fS(e,t)},YI=(e,t)=>{jI(`Received unknown command [${t}] from service ${e}`)},GI=async e=>{const{args:t,sourceServiceId:n,send:r,reply:i}=e,s=n,o=t[0],a=o?.user?.apiKey||DS().globalApiKey;if(!a)return jI(`Received ACK from WS service ${n} but no API key was provided`),i({error:"No API key was provided",errCode:"MISSING_API_KEY"});o.user?.id&&Nm.setGlobalUserId(o.user?.id),await zS({serviceSessionId:n,transport:gl.WS,send:r,terminateFn:()=>{gS(n)},extraInfo:{websocketId:s,user:{wsApiKey:a,userEmail:o.user?.email,userId:o.user?.id}}}),i({success:[]})},HI=e=>{jI(`WS Client ${e} disconnected`),KS(e)},VI=async({sourceServiceId:e,args:t,transport:n,send:r})=>{if(n!==gl.IPC){var i;jI(`Received manifest from non IPC service ${e}.`)}else{const n=t[0];if(n.devMode){const t=Jm.getMatchingDevService(n.name,n.version,"stopped");if(t){jI(`Found matching previous service ${t.info.name} (${t.info.version}). Reactivating previous client with session id ${t.info.sessionId}`);const s=GS(t.info.sessionId);if(!s)return void jI(`Could not find previous client instance for ${t.info.name} (${t.info.version}). Aborting manifest injection`);s.send=r,BS[i=e]?delete BS[i]:US(`Could not find source client with session id ${i}`),cv(e,t.info.sessionId);const o=await Im(n,n.path);t.info={...t.info,...o},jI(`Updating manifest for dev service ${t.info.sessionId}`),Jm.setServiceManifest(t.info.sessionId,o,"running"),jI(`Asking service ${e} to assume previous session id ${t.info.sessionId}`),av(t.info.sessionId,(e=>`${hl.AssumeSession}${e}`)(t.info.sessionId)),(e=>{const t=BS[e];t?t.isDevClient?(t.disconnected=!1,t.transport===gl.IPC&&(VS(),qS(e))):US(`Client with session id ${e} is not a dev client`):US(`Could not find source client with session id ${e}`)})(t.info.sessionId)}else{Jm.addDevService(e,n,"running");const t=GS(e);t?t.isDevClient=!0:zS({serviceSessionId:e,transport:gl.IPC,send:r,extraInfo:{ipcSocketId:e},isDevClient:!0})}return}jI(`Received manifest from non dev service ${e} [${n.name}@(${n.version})]. Ignoring...`)}};var zI=async e=>{var t;jI("Starting Kemu Hub..."),t=e.desktopMode?"desktop":"runtime",xI=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&&Nm.setTracker(e.errorTracker),(e=>{AS={...AS,...e}})({serviceUrl:e.serviceUrl,globalApiKey:e.globalApiKey,environment:e.environment}),LI.registerFunction(fl.GetServiceContents,TS),LI.registerFunction(fl.GetServices,II),LI.registerFunction(fl.GetSystemInfo,$I),LI.registerFunction(fl.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"})})),LI.registerFunction(fl.UnsubscribeFromService,(({transport:e,reply:t,args:n,sourceServiceId:r})=>{if(e===gl.WS){const[e]=n,i=GS(r);if(!i)return t({error:`Session id "${r}" not found`});jI(`Service ${r} unsubscribing from "${e.targetService.serviceName} (${e.targetService.version})"`),t({success:[]}),i?.removeSubscription({serviceName:e.targetService.serviceName,version:e.targetService.version})}})),LI.registerFunction(fl.SubscribeToService,(({transport:e,reply:t,args:n,sourceServiceId:r})=>{if(e===gl.WS){const[e]=n,i=GS(r),s=e.targetService;if(!i)return t({error:`Session id "${r}" not found`});if(jI(`Service ${r} subscribing to "${s.serviceName} (${s.version})"`),"hub"===s.serviceName)return i.addSubscription(s),void t({success:[]});if(!i.addSubscription(s))return jI(`Service ${r} already subscribed to "${s.serviceName} (${s.version})", ignoring request.`),t({success:[]});const o=Jm.getMatchingService(s.serviceName,s.version);if(!o)return jI(`Service ${s.serviceName} ${s.version} not active yet`),t({success:[]});if(!o.info.eventEmitter)return jI(`Service ${s.serviceName} ${s.version} does not have an event emitter, removing subscription`),i.removeSubscription(s),t({error:`Service "${s.serviceName} (${s.version})" does not produce events`});const a=GS(o.info.sessionId);return a?.extraInfo.ipcSocketId&&(jI(`Sending Broadcast START command to service ${o.info.sessionId}`),av(a?.extraInfo.ipcSocketId,hl.BroadcastStart)),t({success:[]})}})),LI.registerFunction("stopService",yS),LI.registerFunction("removeService",bS),LI.registerFunction("launchService",SS),LI.registerFunction("getMatchingServices",IS),LI.registerFunction("getSecretsValues",ES),LI.registerFunction(fl.GetMappedSecrets,MS),LI.registerFunction(fl.BroadcastEvent,UI),LI.registerFunction(fl.ServiceManifest,VI),LI.registerFunction(fl.ChooseDirectoryDialog,QS),LI.registerFunction(fl.ChooseFileDialog,e_),LI.registerFunction(fl.GetUniqueId,SI),LI.registerFunction(fl.GetDecryptedEdgeApiKey,TI),LI.registerFunction(fl.GetHubConfig,AI),LI.registerFunction(fl.SocketAckResponse,GI),LI.registerFunction(fl.UninstallService,MI),Object.entries(RI).forEach((([e,t])=>{t?LI.registerFunction(e,t):(jI(`Skipping registration of "${e}" because it's not implemented`),LI.registerFunction(e,(({reply:t})=>{t({error:`This hub does not support "${e}"`,errCode:"FUNCTION_NOT_SUPPORTED"})})))})),(e=>{rv=e})((e=>{const{send:t,transmission:n,json:r}=e;jI(`Raw message Id received from IPC: ${r?.messageId}`),FI(gl.IPC,e)||LI.processMessage(gl.IPC,t,n,r)})),pS(BI),uS(WI),hS(YI),dS(HI),(e=>{nv=e})(ZS),(e=>{ev=e})((e=>{const t=(e=>`${hl.IpcAcknowledge}${e}`)(e);av(e,t)})),(e=>{tv=e})((e=>{jI(`IPC socket [${e}] disconnected`);const t=GS(e);if(t){jI(`Found matching service for disconnected socket. SessionId: ${t.serviceSessionId}`);const e=Jm.getServiceBySessionId(t.serviceSessionId);Jm.setServiceStatus(t.serviceSessionId,"stopped"),e?.devMode?(t.disconnected=!0,VS()):KS(t.serviceSessionId)}})),await(e=>(e?.ipcId&&(Oy.config.id=e.ipcId),e?.ipcAppSpace&&(Oy.config.appspace=e.ipcAppSpace),new Promise((e=>{Oy.serve((()=>{Qy.info("IPC Server Initiated"),Oy.server.on("data",((e,t)=>{const n=iv[t.id];n?(Qy.data(`IPC Socket [${t.id}] data ${e.byteLength} bytes`),sv(e,n.activeMessage,(e=>n.activeMessage=e),(e=>{if(!e.complete)return;const n=e=>{t.write(e)};if(e.command)return Qy.data(`Received command from client [${t.id}]: ${e.command}`),void(nv&&nv(t.id,e.command,n));e.klMessage&&rv&&rv({send:n,transmission:{sourceServiceId:e.sourceServiceId??-1,targetServiceId:e.targetServiceId??-1,rawMessage:e.rawMessage},json:e.klMessage.json})}))):Qy.data(`Received data from unknown client [${t.id}]. Ignoring.`)})),Oy.server.on("connect",(e=>{const t=pm();Qy.info(`New client connected. Registered as "${t}"`),e.id=t,iv[t]={socket:e,activeMessage:null,disconnectHandler:()=>ov(t)},e.on("close",iv[t].disconnectHandler),ev&&ev(t)})),Oy.server.on("disconnect",(e=>{ov(e.id)})),Oy.server.on("error",(e=>{console.log(`IPC Server Error: ${e}`)})),e()})),Oy.server.start()}))))({ipcAppSpace:n,ipcId:r}),e?.ws?.disabled||await lS(e?.ws?.port||5368);const i=e?.defaultServicesPath||k.resolve(DI,"defaultServices");PI=i;const s=process.env.DEV_SESSION_ID;Jm.setHubIpcConfig({recipePath:e?.recipeRootPath,appSpace:n,id:r}),e?.servicesInstallPath&&(e=>{km=e})(e.servicesInstallPath),e?.testServicesInstallPath&&(e=>{Em=e})(e.testServicesInstallPath);const o=Cm(),a=$m(),c=async({requiredSecrets:e})=>{const t=Object.keys(e).reduce(((e,t)=>({...e,[t]:process.env[t]})),{});return t.__KEMU_USER_SERVICES_PATH=o,t.__KEMU_USER_TEST_SERVICES_PATH=a,t.__KEMU_SERVICE_URL=DS().serviceUrl,t.__KEMU_ENVIRONMENT=DS().environment,t};e?.getServiceSecretsFn?(Jm.setGetSecretsFunction(e.getServiceSecretsFn),CS(e.getServiceSecretsFn)):(Jm.setGetSecretsFunction(c),CS(c)),(e=>{OS=e})(e?.getMappedSecretsFn?e.getMappedSecretsFn:async e=>e.reduce(((e,t)=>({...e,[t.name]:[]})),{})),Jm.setSpawnNodeFunction(e?.spawnFn?e.spawnFn:({args:e,options:t})=>{const n={...process.env};return K("node",e||[],{...t,env:{...n,...t?.env}})}),e?.noDefaultServices||await Jm.loadServices(i,{fixedSession:s?parseInt(s):void 0,singleServiceName:process.env.DEV_SINGLE_SERVICE_NAME,internalServices:!0,enableLogs:!0}),null!==e?.servicesInstallPath&&(await xm(o)||await v(o,{recursive:!0}),await Jm.loadServices(o,{internalServices:!1,singleServiceName:process.env.DEV_SINGLE_SERVICE_NAME,enableLogs:!!e?.enableServiceLogs}));const l=process.env.DEV_NO_SPAWN_LIST?.split(",");await Jm.launchServices({noSpawningList:l||[]}),jI("Kemu Hub started"),(e?.onChooseDirectory||e?.onChooseFile)&&(e=>{XS=e})({chooseDirectory:e.onChooseDirectory,chooseFile:e.onChooseFile})},qI=e=>{if(e===gl.WS)return{handleWebsocketConnectionEvent:WI,handleWebsocketClientDisconnectionEvent:HI,handleWebsocketMessage:BI,handleWebsocketClientCommand:YI,getRemoteInvoke:()=>LI}},KI=(e=[])=>{let t;const n=new Promise((n=>{const r=()=>{if(Jm.getAllServices().every((e=>"running"===e.status))&&e.every((e=>"running"===Jm.getMatchingService(e.name,e.version)?.status)))return n();t=setTimeout(r,100)};r()}));return n.abort=()=>{t&&clearTimeout(t)},n};let JI;const ZI=mc("run"),XI=vl(),QI=1e3,ex=x(process.argv.slice(2));global.ImageData=Q,Oe({createCanvas:(e,t)=>te(e,t),loadImage:async e=>{const t=await ee(e),n=te(t.width,t.height).getContext("2d");n.drawImage(t,0,0,t.width,t.height);return n.getImageData(0,0,t.width,t.height)}});const tx={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:we.ImageData}},loadImageFile:async e=>{const t=await ee(e),n=te(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=te(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 nx={start:async r=>{r=r||{};const i=r?.recipePath||ex.recipePath||process.env.KEMU_EDGE_RECIPE_PATH||process.cwd();if(!i)throw new Error("`recipePath` not provided. Please specify it in the config object, via a command line argument [--recipePath] or as an environment variable [KEMU_EDGE_RECIPE_PATH].");e({path:J(Z(i),".env")});const s=r.apiKey||process.env.KEMU_API_KEY;if(!s)throw new Error("Missing API key. Please provide it via config.apiKey or KEMU_API_KEY environment variable.");const o=i.endsWith(".json")||i.endsWith(".kemu"),a=o?X(i):i,c=o?i:J(a,"recipe.kemu"),l=(e=>{try{return JSON.parse(e||"")}catch(e){return null}})(await t(Z(c),"utf-8"));if(!l)throw new Error("Failed to parse recipe file");const{serviceUrl:u,apiKey:d,environment:h}=((e,t)=>{const n=Ta(e,t),r=Buffer.from(n,"base64").toString("utf8"),[i,s,o]=r.split("<@>");if(!s||!i||!o)throw new Error("Invalid API key.");return{serviceUrl:s,apiKey:i,environment:o}})(l,s);await Ls();const f={id:l.id||String(Date.now()),version:1,author:""};(e=>{Wr=e})(console);const p=qI(Ee.WS),g=(e,t)=>{if(t)p?.handleWebsocketMessage({send:y,transmission:{rawMessage:e,sourceServiceId:t.sourceServiceId,targetServiceId:t.targetServiceId},json:t.msg?.json});else{const t=e instanceof Buffer?e.toString():e;p?.handleWebsocketClientCommand(QI,t)}},m=(rc={instanceServiceId:QI,sendBuf:g,sendCmd:g,triggerOnCommand:(...e)=>ic(...e),triggerOnConnected:()=>sc(),triggerOnDisconnected:()=>oc(),triggerOnMessageReceived:(...e)=>ac(...e)},rc);const y=(e,t)=>{if(t)m.triggerOnMessageReceived({send:g,transmission:{rawMessage:e,sourceServiceId:t.sourceServiceId,targetServiceId:t.targetServiceId},json:t.msg.json});else{const t=e instanceof Buffer?e.toString():e;m.triggerOnCommand(t)}},v=wl(),b=p.getRemoteInvoke();v.disableServiceEncoding(0,!0),b.disableServiceEncoding(QI,!0);const w=Object.values(l.blocks[ve].gates).filter((e=>e.type===Ze.hubService&&e.state.service&&!0!==e.state.service?.webOnly)),S=w.map((e=>{const t=e.state.service;return{name:t.name,version:t.version}})),_=J(a,"services"),I=await n(_).then((()=>!0)).catch((()=>!1));await zI({globalApiKey:d,serviceUrl:u,recipeRootPath:a,servicesInstallPath:I?J(a,"services"):null,noDefaultServices:!0,environment:h,ws:{disabled:!0},ipc:{appSpace:"kemu-runner.",id:f.id}}),ZI("Waiting for services to run"),await KI(S),ZI("All services are running"),na(XI);const x=await Qo(l,"runner",f.version,f.author,va.Desktop);return JI=x,bl(x),await ml(d),new Promise(((e,t)=>{var n;yl("acknowledged",(async()=>{await XI.getServices();const{failed:n,sendToInputWidget:r,invokeRecipeLoadedWidgets:i}=await ta(x);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)})),ZI("Recipe started"),e({sendToInputWidget:(e,t)=>"number"==typeof t?r(e,{type:we.Number,value:t}):"string"==typeof t?r(e,{type:we.String,value:t}):"boolean"==typeof t?r(e,{type:we.Boolean,value:t}):Array.isArray(t)?r(e,{type:we.Array,value:t}):r(e,t)})})),m.triggerOnConnected(),m.triggerOnCommand((n=QI,`${Ie.SocketAcknowledge}${n}`))}))},terminate:async()=>{JI&&await ea(JI)},onVariableChange:(e,t)=>jr(e,t)};void 0===typeof process.env.BLOCKS_INSTALL_DIR&&console.warn("Missing `BLOCKS_INSTALL_DIR` env var");process.env.BLOCKS_INSTALL_DIR;export{we as DataType,nx as default,tx 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=H_,n=l_;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,s=57,o=65,a=70,c=97,l=102;function u(e){return e>=i&&e<=s?e-i:e>=o&&e<=a?e-(o-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)),s=u(e.charCodeAt(i+1));if(void 0===n||void 0===s){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+s}return r},e.nextTick=async()=>{},e.asyncLoop=async function(t,n,r){let i=Date.now();for(let s=0;s<t;s++){r(s);const t=Date.now()-i;t>=0&&t<n||(await(0,e.nextTick)(),i+=t)}},e.utf8ToBytes=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")}}(G_),Object.defineProperty(c_,"__esModule",{value:!0}),c_.shake256=c_.shake128=c_.keccak_512=c_.keccak_384=c_.keccak_256=c_.keccak_224=c_.sha3_512=c_.sha3_384=c_.sha3_256=c_.sha3_224=c_.Keccak=c_.keccakP=void 0;const V_=l_,z_=v_,q_=G_,K_=[],J_=[],Z_=[],X_=BigInt(0),Q_=BigInt(1),eI=BigInt(2),tI=BigInt(7),nI=BigInt(256),rI=BigInt(113);for(let e=0,t=Q_,n=1,r=0;e<24;e++){[n,r]=[r,(2*n+3*r)%5],K_.push(2*(5*r+n)),J_.push((e+1)*(e+2)/2%64);let i=X_;for(let e=0;e<7;e++)t=(t<<Q_^(t>>tI)*rI)%nI,t&eI&&(i^=Q_<<(Q_<<BigInt(e))-Q_);Z_.push(i)}const[iI,sI]=(0,z_.split)(Z_,!0),oI=(e,t,n)=>n>32?(0,z_.rotlBH)(e,t,n):(0,z_.rotlSH)(e,t,n),aI=(e,t,n)=>n>32?(0,z_.rotlBL)(e,t,n):(0,z_.rotlSL)(e,t,n);function cI(e,t=24){const n=new Uint32Array(10);for(let r=24-t;r<24;r++){for(let t=0;t<10;t++)n[t]=e[t]^e[t+10]^e[t+20]^e[t+30]^e[t+40];for(let t=0;t<10;t+=2){const r=(t+8)%10,i=(t+2)%10,s=n[i],o=n[i+1],a=oI(s,o,1)^n[r],c=aI(s,o,1)^n[r+1];for(let n=0;n<50;n+=10)e[t+n]^=a,e[t+n+1]^=c}let t=e[2],i=e[3];for(let n=0;n<24;n++){const r=J_[n],s=oI(t,i,r),o=aI(t,i,r),a=K_[n];t=e[a],i=e[a+1],e[a]=s,e[a+1]=o}for(let t=0;t<50;t+=10){for(let r=0;r<10;r++)n[r]=e[t+r];for(let r=0;r<10;r++)e[t+r]^=~n[(r+2)%10]&n[(r+4)%10]}e[0]^=iI[r],e[1]^=sI[r]}n.fill(0)}c_.keccakP=cI;class lI extends q_.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,V_.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,q_.u32)(this.state)}keccak(){q_.isLE||(0,q_.byteSwap32)(this.state32),cI(this.state32,this.rounds),q_.isLE||(0,q_.byteSwap32)(this.state32),this.posOut=0,this.pos=0}update(e){(0,V_.exists)(this);const{blockLen:t,state:n}=this,r=(e=(0,q_.toBytes)(e)).length;for(let i=0;i<r;){const s=Math.min(t-this.pos,r-i);for(let t=0;t<s;t++)n[this.pos++]^=e[i++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:n,blockLen:r}=this;e[n]^=t,128&t&&n===r-1&&this.keccak(),e[r-1]^=128,this.keccak()}writeInto(e){(0,V_.exists)(this,!1),(0,V_.bytes)(e),this.finish();const t=this.state,{blockLen:n}=this;for(let r=0,i=e.length;r<i;){this.posOut>=n&&this.keccak();const s=Math.min(n-this.posOut,i-r);e.set(t.subarray(this.posOut,this.posOut+s),r),this.posOut+=s,r+=s}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return(0,V_.number)(e),this.xofInto(new Uint8Array(e))}digestInto(e){if((0,V_.output)(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){const{blockLen:t,suffix:n,outputLen:r,rounds:i,enableXOF:s}=this;return e||(e=new lI(t,n,r,s,i)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=n,e.outputLen=r,e.enableXOF=s,e.destroyed=this.destroyed,e}}c_.Keccak=lI;const uI=(e,t,n)=>(0,q_.wrapConstructor)((()=>new lI(t,e,n)));c_.sha3_224=uI(6,144,28),c_.sha3_256=uI(6,136,32),c_.sha3_384=uI(6,104,48),c_.sha3_512=uI(6,72,64),c_.keccak_224=uI(1,144,28),c_.keccak_256=uI(1,136,32),c_.keccak_384=uI(1,104,48),c_.keccak_512=uI(1,72,64);const dI=(e,t,n)=>(0,q_.wrapXOFConstructorWithOpts)(((r={})=>new lI(t,e,void 0===r.dkLen?n:r.dkLen,!0)));c_.shake128=dI(31,168,16),c_.shake256=dI(31,136,32);const{sha3_512:hI}=c_,fI=(e=4,t=Math.random)=>{let n="";for(;n.length<e;)n+=Math.floor(36*t()).toString(36);return n};function pI(e){let t=0n;for(const n of e.values())t=(t<<8n)+BigInt(n);return t}const gI=(e="")=>pI(hI(e)).toString(36).slice(1),mI=Array.from({length:26},((e,t)=>String.fromCharCode(t+97))),yI=({globalObj:e=(void 0!==Tl?Tl:"undefined"!=typeof window?window:{}),random:t=Math.random}={})=>{const n=Object.keys(e).toString(),r=n.length?n+fI(32,t):fI(32,t);return gI(r).substring(0,32)},vI=e=>()=>e++,bI=({random:e=Math.random,counter:t=vI(Math.floor(476782367*e())),length:n=24,fingerprint:r=yI({random:e})}={})=>function(){const i=(e=>mI[Math.floor(e()*mI.length)])(e),s=Date.now().toString(36),o=t().toString(36),a=fI(n,e);return`${i+gI(`${s+a+o+r}`).substring(1,n)}`},wI=bI();a_.getConstants=()=>({defaultLength:24,bigLength:32}),a_.init=bI,a_.createId=wI,a_.bufToBigInt=pI,a_.createCounter=vI,a_.createFingerprint=yI,a_.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:SI,init:_I,getConstants:II,isCuid:xI}=a_;var kI=SI;const EI=Zl("getUniqueId"),CI=({reply:e,sourceServiceId:t})=>(EI(`Generating unique id for service "${t}"`),e({success:[kI()]})),OI=Zl("getActiveServices"),$I=async({transport:e,sourceServiceId:t,reply:n})=>{if(OI(`Received GetServices request from ${e} [${t}]`),e===gl.WS){let e=Zm.getActiveServices();const r=JS(t);if(!r)return n({error:"Client not found",errCode:"CLIENT_NOT_FOUND"});let i=[];if(r.transport===gl.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(Zm.isInternalKemuService),s=e.filter((e=>e.devMode&&Zm.isNotInternalKemuService(e))),o=e.filter((e=>Zm.isOfficialKemuService(e)&&Zm.isNotInternalKemuService(e)&&Zm.isNotDevService(e))).sort(((e,t)=>e.name.localeCompare(t.name))),a=e.filter((e=>Zm.isNotDevService(e)&&Zm.isNotInternalKemuService(e)&&!Zm.isOfficialKemuService(e))),c=await(async e=>{const{features:t}=await BS(e);return t})(r.extraInfo.user?.wsApiKey),l=c?.hub_services??0,u=o.slice(0,-1!==l?l:o.length);-1!==l&&(i=o.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,...s,...u,...a]}const s=Zm.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:Zm.isInternalKemuService(e),svgIcon:e.svgIcon,color:e.color,shortTitle:e.shortTitle})));n({success:[{available:e.map((e=>{const{widgetUIContents:t,...n}=e;return{...n}})),failed:s,installed:i}]})}};let NI="runtime",MI=null;const AI=()=>NI,TI=Zl("getSystemInfo"),PI=async({reply:e})=>{TI("Received GetSystemInfo request"),e({success:[await(async()=>({platformArch:_l(),isDesktopHub:"desktop"===AI(),isRuntimeHub:"runtime"===AI(),hubVersion:vm,...MI?{updateAvailable:MI}:{}}))()]})},DI=Zl("removeService"),jI=async({args:e,sourceServiceId:t,reply:n})=>{const r=e[0],i=r.serviceName,s=r.version;if(!i)return n({error:"No service name provided"});if(!s)return n({error:"No service version provided"});const o=Zm.getAllServiceVersions(i),a=o.find((e=>e.info.version===s));if(!a)return n({error:"Service not found"});DI(`Removing ${o.length} service(s) with name: ${i}`);const c=a.info.publicationId;let l;if(await Zm.uninstallService(a.info.name,a.info.version),c){const e=JS(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"});DI(`Updating license details for "${c}"`);const i=await(async e=>{const{data:t,error:n}=await FS(`${LS()}/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=>(DI(`Error updating license details for "${c}": ${e}`),{error:e.message,remaining:void 0})));l=i?.remaining}n({success:[{remaining:l,service:{name:i,version:s}}]})},RI=Zl("getDecryptedEdgeApiKey"),LI=({reply:e})=>(RI("Getting decrypted edge API key"),e({success:[jS().globalApiKey]})),FI=({reply:e})=>{RI("Getting hub config");const t=jS();return e({success:[{kemuApiKey:t.globalApiKey,environment:t.environment}]})};let UI,BI,WI,YI,GI;const HI=e=>e.transport===gl.IPC&&(e.reply({error:"Transport is not allowed to call this function"}),!0);var VI=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(!UI)return e.reply({error:"Get recipe secrets function not set"});const i=await UI({...t[0]}),s={};for(const e of r)s[e]=e in i?i[e]:null;const o=[{secrets:s}];e.reply({success:o})},zI=async e=>{const t=e.args,n=t[0].recipeUuid,r=t[0].secretsMap;if(HI(e))return;if(!BI)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 BI({recipeUuid:n,secretsMap:r})}];e.reply({success:i})},qI=async e=>{const t=e.args,n=t[0].recipeUuid,r=t[0].secretName;if(HI(e))return;if(!WI)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 WI({recipeUuid:n,secretName:r})}];e.reply({success:i})},KI=async e=>{const t=e.args[0].recipeUuid;if(!YI)return e.reply({error:"Get recipe secret mappings function not set"});if(!t)return e.reply({error:"Invalid request parameters"});const n=[{secrets:await YI({recipeUuid:t})}];e.reply({success:n})},JI=async e=>{const t=e.args,n=t[0].hubServiceName,r=t[0].secrets;return GI?n&&r?Array.isArray(r)?(await GI({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 ZI,XI,QI;const ex=e=>e.transport===gl.IPC&&(e.reply({error:"You are not allowed to manage secrets using this transport"}),!0);var tx=async e=>{if(e.args,ex(e))return;if(!QI)return e.reply({error:"Get hub secrets function not set"});const t=[{contexts:await QI()}];e.reply({success:t})},nx=async e=>{const t=e.args;if(ex(e))return;if(!ZI)return e.reply({error:"Add hub secret function not set"});const n=[{contexts:await ZI(t[0])}];e.reply({success:n})},rx=async e=>{const t=e.args;if(ex(e))return;if(!XI)return e.reply({error:"Delete hub secret function not set"});const n=[{contexts:await XI(t[0])}];e.reply({success:n})};const ix=E(H(import.meta.url));let sx=null;const ox=Zl("hub"),ax=new function(){const e={};let t,n=console.log;const r={};let i="hub";const s={},o=e=>!s[e],a=(e,t,n,r,i,s)=>{let a=Ty?new ArrayBuffer(0):Buffer.alloc(0);const c={json:{functionName:e,args:s.success?s.success:[s],messageId:t,type:s.success?"response":"error"}};return o(r)&&(a=hv.encode(c,n,r)),i(a,{msg:c,sourceServiceId:n,targetServiceId:r})};return{setLogger:e=>{n=e},processMessage:(i,s,o,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,o.targetServiceId,o.sourceServiceId,s,e)};if(t&&!t({args:l.args,functionName:l.functionName,transport:i,messageId:l.messageId,sourceServiceId:o.sourceServiceId,reply:r,send:s}))return n&&n(`Function "${l.functionName}" not allowed to be invoked by client [${o.sourceServiceId}]`),r({error:"Function not allowed",errCode:"FNC_NOT_ALLOWED"}),!0;e({transport:i,args:l.args,reply:r,messageId:l.messageId,sourceServiceId:o.sourceServiceId,send:s})}else{const e=`Function "${l.functionName}" not found.`;n&&n(e),a(l.functionName,l.messageId,o.targetServiceId,o.sourceServiceId,s,{error:e,errCode:"FNC_NOT_FOUND"})}return!0}return!1},execute:async(t,r,s,a,c,l)=>{if(!s){const e="No send buffer function provided.";throw n&&n(e),e}fv+=1;const u=`${i}-${fv}-exec-${t.substring(0,10)}`,d={messageId:u,functionName:t,send:s,sourceServiceId:a,targetServiceId:c,args:r||[],fulfilled:!1,resolve:()=>{},reject:()=>{}};d.promise=new Promise(((e,t)=>{d.resolve=e,d.reject=t}));let h=Ty?new ArrayBuffer(0):Buffer.alloc(0);const f={json:{functionName:t,args:r,messageId:u,type:"execute"}};o(c)&&(h=hv.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)),s(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,s)=>{fv+=1;const a=`${i}-${fv}-multicast-${e.substring(0,10)}`;let c=Ty?new ArrayBuffer(0):Buffer.alloc(0);const l={json:{functionName:e,args:t,messageId:a,type:"execute"}};let u=o(r[0].serviceId);u&&(c=hv.encode(l,s,r[0].serviceId));for(let t=0;t<r.length;t++)try{const i=r[t];n&&n(`Broadcasting function "${e}" with message id "${a}" to client [${i.serviceId}]`),0!==t&&(u=o(i.serviceId),u&&(c=hv.patchEncodedHeader(c,{toServiceId:i.serviceId}))),i.sendFn(c,{msg:l,sourceServiceId:s,targetServiceId:i.serviceId})}catch(e){n&&n(`Error broadcasting to client at index ${t}`)}},disableServiceEncoding:(e,t)=>{s[e]=t}}}("hub");VS=ax,ax.setLogger(ox);const cx={[fl.RebootToInstallUpdate]:null,[fl.GetFileContentFromCacheId]:null,[fl.SaveRecipeToFile]:null},lx=(e,t)=>{const{transmission:n}=t;if(0!==n.targetServiceId){const r=JS(n.targetServiceId);if(!r)return ox(`Service [${e}] ${n.sourceServiceId} is sending data to an unknown service ["${n.targetServiceId}"]`),!0;r.transport,gl.IPC;const i=t.json?.messageId;return ox(`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},ux=({sourceServiceId:e,args:t})=>{const n=Zm.getServiceBySessionId(e);if(n){const r=ZS(n.info.name,n.info.version),i=ZS(n.info.name,"*");if(!r.length&&!i.length)return;const s=[...r,...i],o={...t[0],source:{serviceName:n.info.name,serviceVersion:n.info.version,sessionId:e}};ax.broadcast(fl.BroadcastEvent,[o],s,0)}},dx=async({args:e,reply:t})=>{const n=e[0];if(!n)return ox("Invalid config for SendToRecipe"),t({error:"Invalid config for SendToRecipe"});const r=(i=n.recipePoolId,Object.values(zS).find((e=>e.extraInfo.recipe?.poolId===i))||null);var i;if(!r)return ox(`No client found for recipe pool id ${n.recipePoolId}`),t({error:`No client found for recipe pool id "${n.recipePoolId}"`});try{const e=ax.execute(fl.SendToRecipe,[n],r.send,0,r.serviceSessionId,{async:!n.waitForResponse,timeout:n.timeout});n.waitForResponse?t({success:await e}):t({success:[]})}catch(e){return ox(`Error sending to recipe ${n.recipePoolId}: ${e?.message||e}`),t({error:e?.message||"There was an error sending to the recipe"})}},hx=e=>{const{send:t,transmission:n,json:r}=e;ox(`Raw message Id received from WS: ${r?.messageId}`),lx(gl.WS,e)||ax.processMessage(gl.WS,t,n,r)},fx=e=>{const t=(n=e,`${hl.SocketAcknowledge}${n}`);var n;gS(e,t)},px=(e,t)=>{ox(`Received unknown command [${t}] from service ${e}`)},gx=async e=>{const{args:t,sourceServiceId:n,send:r,reply:i}=e,s=n,o=t[0],a=o?.user?.apiKey||jS().globalApiKey;if(!a)return ox(`Received ACK from WS service ${n} but no API key was provided`),i({error:"No API key was provided",errCode:"MISSING_API_KEY"});o.user?.id&&Mm.setGlobalUserId(o.user?.id),await QS({serviceSessionId:n,transport:gl.WS,send:r,terminateFn:()=>{yS(n)},extraInfo:{websocketId:s,recipe:o.recipe,user:{wsApiKey:a,userEmail:o.user?.email,userId:o.user?.id}}}),i({success:[]})},mx=e=>{ox(`WS Client ${e} disconnected`),t_(e)},yx=e=>1===e.sourceServiceId?e.functionName===fl.GetFileContentFromCacheId:e.functionName===fl.SocketAckResponse||e.functionName===fl.ServiceManifest||e.functionName===fl.SubscribeToService||(!!JS(e.sourceServiceId)||(e.reply({error:`Session id "${e.sourceServiceId}" not found. Please acknowledge the session first.`}),!1)),vx=async({sourceServiceId:e,args:t,transport:n,send:r})=>{if(n!==gl.IPC){var i;ox(`Received manifest from non IPC service ${e}.`)}else{const n=t[0];if(n.devMode){const t=Zm.getMatchingDevService(n.name,n.version,"stopped");if(t){ox(`Found matching previous service ${t.info.name} (${t.info.version}). Reactivating previous client with session id ${t.info.sessionId}`);const s=JS(t.info.sessionId);if(!s)return void ox(`Could not find previous client instance for ${t.info.name} (${t.info.version}). Aborting manifest injection`);s.send=r,zS[i=e]?delete zS[i]:HS(`Could not find source client with session id ${i}`),lv(e,t.info.sessionId);const o=await Im(n,n.path);t.info={...t.info,...o},ox(`Updating manifest for dev service ${t.info.sessionId}`),Zm.setServiceManifest(t.info.sessionId,o,"running"),ox(`Asking service ${e} to assume previous session id ${t.info.sessionId}`),cv(t.info.sessionId,(e=>`${hl.AssumeSession}${e}`)(t.info.sessionId)),(e=>{const t=zS[e];t?t.isDevClient?(t.disconnected=!1,t.transport===gl.IPC&&(XS(),e_(e))):HS(`Client with session id ${e} is not a dev client`):HS(`Could not find source client with session id ${e}`)})(t.info.sessionId)}else{Zm.addDevService(e,n,"running");const t=JS(e);t?t.isDevClient=!0:QS({serviceSessionId:e,transport:gl.IPC,send:r,extraInfo:{ipcSocketId:e},isDevClient:!0})}return}ox(`Received manifest from non dev service ${e} [${n.name}@(${n.version})]. Ignoring...`)}};var bx=async e=>{var t;ox("Starting Kemu Hub..."),t=e.desktopMode?"desktop":"runtime",NI=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&&Mm.setTracker(e.errorTracker),(e=>{DS={...DS,...e}})({serviceUrl:e.serviceUrl,globalApiKey:e.globalApiKey,environment:e.environment}),ax.registerFunctionsMiddleware(yx),e.secrets?.serviceSecrets&&(e=>{GI=e})(e.secrets.serviceSecrets.addServiceSecretFn),e.secrets?.recipeSecrets&&((e=>{UI=e})(e.secrets.recipeSecrets.getRecipeDecryptedSecretsFn),(e=>{BI=e})(e.secrets.recipeSecrets.addRecipeSecretFn),(e=>{WI=e})(e.secrets.recipeSecrets.deleteRecipeSecretFn),(e=>{YI=e})(e.secrets.recipeSecrets.getRecipeSecretMappingsFn)),e.secrets?.hubSecrets&&((e=>{QI=e})(e.secrets.hubSecrets.getHubSecretsFn),(e=>{ZI=e})(e.secrets.hubSecrets.addHubSecretsFn),(e=>{XI=e})(e.secrets.hubSecrets.deleteHubSecretFn)),ax.registerFunction(fl.GetServiceContents,PS),ax.registerFunction(fl.GetServices,$I),ax.registerFunction(fl.GetSystemInfo,PI),ax.registerFunction(fl.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"})})),ax.registerFunction(fl.UnsubscribeFromService,(({transport:e,reply:t,args:n,sourceServiceId:r})=>{if(e===gl.WS){const[e]=n,i=JS(r);if(!i)return t({error:`Session id "${r}" not found`});ox(`Service ${r} unsubscribing from "${e.targetService.serviceName} (${e.targetService.version})"`),t({success:[]}),i?.removeSubscription({serviceName:e.targetService.serviceName,version:e.targetService.version})}})),ax.registerFunction(fl.SubscribeToService,(({transport:e,reply:t,args:n,sourceServiceId:r})=>{if(e===gl.WS){const[e]=n,i=JS(r),s=e.targetService;if(!i)return t({error:`Session id "${r}" not found`});if(ox(`Service ${r} subscribing to "${s.serviceName} (${s.version})"`),"hub"===s.serviceName)return i.addSubscription(s),void t({success:[]});if(!i.addSubscription(s))return ox(`Service ${r} already subscribed to "${s.serviceName} (${s.version})", ignoring request.`),t({success:[]});const o=Zm.getMatchingService(s.serviceName,s.version);if(!o)return ox(`Service ${s.serviceName} ${s.version} not active yet`),t({success:[]});if(!o.info.eventEmitter)return ox(`Service ${s.serviceName} ${s.version} does not have an event emitter, removing subscription`),i.removeSubscription(s),t({error:`Service "${s.serviceName} (${s.version})" does not produce events`});const a=JS(o.info.sessionId);return a?.extraInfo.ipcSocketId&&(ox(`Sending Broadcast START command to service ${o.info.sessionId}`),cv(a?.extraInfo.ipcSocketId,hl.BroadcastStart)),t({success:[]})}})),ax.registerFunction("stopService",bS),ax.registerFunction("removeService",SS),ax.registerFunction("launchService",IS),ax.registerFunction("getMatchingServices",kS),ax.registerFunction("getSecretsValues",OS),ax.registerFunction(fl.GetMappedSecrets,AS),ax.registerFunction(fl.BroadcastEvent,ux),ax.registerFunction(fl.ServiceManifest,vx),ax.registerFunction(fl.ChooseDirectoryDialog,s_),ax.registerFunction(fl.ChooseFileDialog,o_),ax.registerFunction(fl.GetUniqueId,CI),ax.registerFunction(fl.SendToRecipe,dx),ax.registerFunction(fl.GetDecryptedEdgeApiKey,LI),ax.registerFunction(fl.GetHubConfig,FI),ax.registerFunction(fl.SocketAckResponse,gx),ax.registerFunction(fl.UninstallService,jI),ax.registerFunction(fl.GetRecipeDecryptedSecretsValues,VI),ax.registerFunction(fl.GetRecipeSecretMappings,KI),ax.registerFunction(fl.AddRecipeSecretMapping,zI),ax.registerFunction(fl.DeleteRecipeSecretMapping,qI),ax.registerFunction(fl.GetHubSecrets,tx),ax.registerFunction(fl.AddHubSecrets,nx),ax.registerFunction(fl.DeleteHubSecret,rx),ax.registerFunction(fl.AddServiceSecret,JI),Object.entries(cx).forEach((([e,t])=>{t?ax.registerFunction(e,t):(ox(`Skipping registration of "${e}" because it's not implemented`),ax.registerFunction(e,(({reply:t})=>{t({error:`This hub does not support "${e}"`,errCode:"FUNCTION_NOT_SUPPORTED"})})))})),(e=>{iv=e})((e=>{const{send:t,transmission:n,json:r}=e;ox(`Raw message Id received from IPC: ${r?.messageId}`),lx(gl.IPC,e)||ax.processMessage(gl.IPC,t,n,r)})),mS(hx),hS(fx),pS(px),fS(mx),(e=>{rv=e})(r_),(e=>{tv=e})((e=>{const t=(e=>`${hl.IpcAcknowledge}${e}`)(e);cv(e,t)})),(e=>{nv=e})((e=>{ox(`IPC socket [${e}] disconnected`);const t=JS(e);if(t){ox(`Found matching service for disconnected socket. SessionId: ${t.serviceSessionId}`);const e=Zm.getServiceBySessionId(t.serviceSessionId);Zm.setServiceStatus(t.serviceSessionId,"stopped"),e?.devMode?(t.disconnected=!0,XS()):t_(t.serviceSessionId)}})),await(e=>(e?.ipcId&&(Ny.config.id=e.ipcId),e?.ipcAppSpace&&(Ny.config.appspace=e.ipcAppSpace),new Promise((e=>{Ny.serve((()=>{ev.info("IPC Server Initiated"),Ny.server.on("data",((e,t)=>{const n=sv[t.id];n?(ev.data(`IPC Socket [${t.id}] data ${e.byteLength} bytes`),ov(e,n.activeMessage,(e=>n.activeMessage=e),(e=>{if(!e.complete)return;const n=e=>{t.write(e)};if(e.command)return ev.data(`Received command from client [${t.id}]: ${e.command}`),void(rv&&rv(t.id,e.command,n));e.klMessage&&iv&&iv({send:n,transmission:{sourceServiceId:e.sourceServiceId??-1,targetServiceId:e.targetServiceId??-1,rawMessage:e.rawMessage},json:e.klMessage.json})}))):ev.data(`Received data from unknown client [${t.id}]. Ignoring.`)})),Ny.server.on("connect",(e=>{const t=pm();ev.info(`New client connected. Registered as "${t}"`),e.id=t,sv[t]={socket:e,activeMessage:null,disconnectHandler:()=>av(t)},e.on("close",sv[t].disconnectHandler),tv&&tv(t)})),Ny.server.on("disconnect",(e=>{av(e.id)})),Ny.server.on("error",(e=>{console.log(`IPC Server Error: ${e}`)})),e()})),Ny.server.start()}))))({ipcAppSpace:n,ipcId:r}),e?.ws?.disabled||await dS(e?.ws?.port||5368);const i=e?.defaultServicesPath||x.resolve(ix,"defaultServices");sx=i;const s=process.env.DEV_SESSION_ID;Zm.setHubIpcConfig({recipePath:e?.recipeRootPath,appSpace:n,id:r}),Zm.setEnableServiceLogsConfig(!!e?.enableServiceLogs),e?.servicesInstallPath&&(e=>{km=e})(e.servicesInstallPath),e?.testServicesInstallPath&&(e=>{Em=e})(e.testServicesInstallPath);const o=Cm(),a=Om(),c=async({requiredSecrets:e})=>{const t=Object.keys(e).reduce(((e,t)=>({...e,[t]:process.env[t]})),{});return t.__KEMU_USER_SERVICES_PATH=o,t.__KEMU_USER_TEST_SERVICES_PATH=a,t.__KEMU_SERVICE_URL=jS().serviceUrl,t.__KEMU_ENVIRONMENT=jS().environment,t};e?.getServiceSecretsFn?(Zm.setGetSecretsFunction(e.getServiceSecretsFn),$S(e.getServiceSecretsFn)):(Zm.setGetSecretsFunction(c),$S(c)),(e=>{MS=e})(e?.getMappedSecretsFn?e.getMappedSecretsFn:async e=>e.reduce(((e,t)=>({...e,[t.name]:[]})),{})),Zm.setSpawnNodeFunction(e?.spawnFn?e.spawnFn:({args:e,options:t})=>{const n={...process.env};return z("node",e||[],{...t,env:{...n,...t?.env}})}),e?.noDefaultServices||await Zm.loadServices(i,{fixedSession:s?parseInt(s):void 0,singleServiceName:process.env.DEV_SINGLE_SERVICE_NAME,internalServices:!0,enableLogs:!0}),null!==e?.servicesInstallPath&&(await xm(o)||await y(o,{recursive:!0}),await Zm.loadServices(o,{internalServices:!1,singleServiceName:process.env.DEV_SINGLE_SERVICE_NAME,enableLogs:!!e?.enableServiceLogs}));const l=process.env.DEV_NO_SPAWN_LIST?.split(",");await Zm.launchServices({noSpawningList:l||[]}),ox("Kemu Hub started"),(e?.onChooseDirectory||e?.onChooseFile)&&(e=>{i_=e})({chooseDirectory:e.onChooseDirectory,chooseFile:e.onChooseFile})},wx=e=>{if(e===gl.WS)return{handleWebsocketConnectionEvent:fx,handleWebsocketClientDisconnectionEvent:mx,handleWebsocketMessage:hx,handleWebsocketClientCommand:px,getRemoteInvoke:()=>ax}},Sx=(e=[])=>{let t;const n=new Promise((n=>{const r=()=>{if(Zm.getAllServices().every((e=>"running"===e.status))&&e.every((e=>"running"===Zm.getMatchingService(e.name,e.version)?.status)))return n();t=setTimeout(r,100)};r()}));return n.abort=()=>{t&&clearTimeout(t)},n};let _x;const Ix=fc("run"),xx=vl(),kx=1e3,Ex=I(process.argv.slice(2)),Cx=e=>"number"==typeof e?{type:ye.Number,value:e}:"string"==typeof e?{type:ye.String,value:e}:"boolean"==typeof e?{type:ye.Boolean,value:e}:Array.isArray(e)?{type:ye.Array,value:e}:e;global.ImageData=Z,Ee({createCanvas:(e,t)=>Q(e,t),loadImage:async e=>{const t=await X(e),n=Q(t.width,t.height).getContext("2d");n.drawImage(t,0,0,t.width,t.height);return n.getImageData(0,0,t.width,t.height)}});const Ox=e=>async()=>{throw new Error(`${e} not implemented`)},$x={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:ye.ImageData}},loadImageFile:async e=>{const t=await X(e),n=Q(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=Q(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 Nx={start:async r=>{r=r||{};const i=r?.recipePath||Ex.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:s}=await e({path:q(K(i),".env")}),o=r.apiKey||process.env.KEMU_API_KEY;if(!o)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?J(i):i,l=a?i:q(c,"recipe.kemu"),u=(e=>{try{return JSON.parse(e||"")}catch(e){return null}})(await t(K(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=$a(e,t),r=Buffer.from(n,"base64").toString("utf8"),[i,s,o]=r.split("<@>");if(!s||!i||!o)throw new Error("Invalid API key.");return{serviceUrl:s,apiKey:i,environment:o}})(u,o);await po();const p={id:u.uuid||String(Date.now()),version:1,author:u.author.id};(e=>{Bi=e})(console);const g=wx(Ie.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(kx,t)}},y=(ec={instanceServiceId:kx,sendBuf:m,sendCmd:m,triggerOnCommand:(...e)=>tc(...e),triggerOnConnected:()=>nc(),triggerOnDisconnected:()=>rc(),triggerOnMessageReceived:(...e)=>ic(...e)},ec);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=wl(),w=g.getRemoteInvoke();b.disableServiceEncoding(0,!0),w.disableServiceEncoding(kx,!0);const S=Object.values(u.blocks[ge].gates).filter((e=>e.type===ze.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=q(c,"services"),x=await n(I).then((()=>!0)).catch((()=>!1));await bx({globalApiKey:h,serviceUrl:d,recipeRootPath:c,servicesInstallPath:x?q(c,"services"):null,noDefaultServices:!0,environment:f,ws:{disabled:!0},secrets:{recipeSecrets:{getRecipeDecryptedSecretsFn:async()=>({...s}),getRecipeSecretMappingsFn:Ox("getRecipeSecretMappingsFn"),addRecipeSecretFn:Ox("addRecipeSecretFn"),deleteRecipeSecretFn:Ox("deleteRecipeSecretFn")}},ipc:{appSpace:"kemu-runner.",id:p.id}}),Ix("Waiting for services to run"),await Sx(_),Ix("All services are running"),xa(xx);const k=await Sa(u,"runner",p.version,p.author,cr.Desktop);return _x=k,bl(k),await ml({apiKey:h,id:u.author.id}),new Promise(((e,t)=>{var n;yl("acknowledged",(async()=>{await xx.getServices();const{failed:n,sendToInputWidget:r,invokeRecipeLoadedWidgets:i}=await Ia(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)})),Ix("Recipe started"),e({sendToInputWidgetAndWaitForOutput:(e,t)=>{const n=Cx(t);return r({inputName:e,data:n,waitForOutputChild:!0})},sendToInputWidget:(e,t)=>{const n=Cx(t);return r({inputName:e,data:n,waitForOutputChild:!1})}})})),y.triggerOnConnected(),y.triggerOnCommand((n=kx,`${we.SocketAcknowledge}${n}`))}))},terminate:async()=>{_x&&await _a(_x)},onVariableChange:(e,t)=>Qr(e,t)};export{ye as DataType,Nx as default,$x as utils};
|