From a316ad0fc5dff048a44e969d65f4743043f82325 Mon Sep 17 00:00:00 2001 From: Eistee Date: Fri, 10 Apr 2026 09:42:29 +0200 Subject: [PATCH] feat: add OID display mode toggle for Blockly editor Add 4 switchable display modes for OID fields in the Blockly editor: - Name: show object common.name (default, current behavior) - Name path: show all parent names joined with dots - ID: show last segment of object ID - Full ID: show complete object ID Features: - Toolbar dropdown button with custom gift-tag SVG icons (blue for name modes, orange for ID modes, filled for path variants) - Workspace context menu entries as alternative - Persisted in localStorage across sessions - Translated labels in all 11 ioBroker languages - Only affects visual display, not generated JavaScript code Co-Authored-By: Claude Opus 4.6 (1M context) --- README.md | 1 + admin/assets/OpenAiDialog-CANTLp4d.js | 13 - ...g-BliYIniL.js => OpenAiDialog-CdW_zvS-.js} | 2 +- admin/assets/index-CEbKg781.js | 1230 ----------------- admin/assets/index-Cd8FZ0ou.js | 1 - .../{index-CZzmETwg.js => index-Dl-EtX3d.js} | 2 +- .../{index-B0ByV4SK.js => index-DqPwE1_T.js} | 2 +- .../{index-bny2V8S2.js => index-DvPtUWVN.js} | 184 +-- admin/assets/index-ns4mNOlq.js | 16 - admin/google-blockly/own/blocks_words.js | 7 + admin/google-blockly/own/field_oid.js | 348 ++++- admin/tab.html | 2 +- build/lib/debugger.js | 4 +- build/lib/debugger.js.map | 2 +- build/lib/inspect.js.map | 2 +- build/lib/nodeModulesManagement.js | 4 +- build/lib/nodeModulesManagement.js.map | 2 +- build/lib/protectFs.js.map | 2 +- build/main.js.map | 2 +- src-admin/package-lock.json | 21 +- src-editor/package-lock.json | 54 +- .../public/google-blockly/own/blocks_words.js | 7 + .../public/google-blockly/own/field_oid.js | 348 ++++- src-editor/src/Components/BlocklyEditor.tsx | 260 ++++ src-editor/src/Components/BlocklyEditorTS.tsx | 31 + .../src/Components/blockly-plugins/index.ts | 7 + src-editor/src/Editor.tsx | 85 ++ src-editor/src/assets/oid-id-full.svg | 8 + src-editor/src/assets/oid-id.svg | 5 + src-editor/src/assets/oid-name-path.svg | 8 + src-editor/src/assets/oid-name.svg | 5 + src-editor/src/i18n/de.json | 2 + src-editor/src/i18n/en.json | 2 + src-editor/src/i18n/es.json | 2 + src-editor/src/i18n/fr.json | 2 + src-editor/src/i18n/it.json | 2 + src-editor/src/i18n/nl.json | 2 + src-editor/src/i18n/pl.json | 2 + src-editor/src/i18n/pt.json | 2 + src-editor/src/i18n/ru.json | 2 + src-editor/src/i18n/uk.json | 2 + src-editor/src/i18n/zh-cn.json | 2 + 42 files changed, 1212 insertions(+), 1475 deletions(-) delete mode 100644 admin/assets/OpenAiDialog-CANTLp4d.js rename admin/assets/{OpenAiDialog-BliYIniL.js => OpenAiDialog-CdW_zvS-.js} (99%) delete mode 100644 admin/assets/index-CEbKg781.js delete mode 100644 admin/assets/index-Cd8FZ0ou.js rename admin/assets/{index-CZzmETwg.js => index-Dl-EtX3d.js} (99%) rename admin/assets/{index-B0ByV4SK.js => index-DqPwE1_T.js} (99%) rename admin/assets/{index-bny2V8S2.js => index-DvPtUWVN.js} (60%) delete mode 100644 admin/assets/index-ns4mNOlq.js create mode 100644 src-editor/src/assets/oid-id-full.svg create mode 100644 src-editor/src/assets/oid-id.svg create mode 100644 src-editor/src/assets/oid-name-path.svg create mode 100644 src-editor/src/assets/oid-name.svg diff --git a/README.md b/README.md index 683673bcc..5ff0ef264 100644 --- a/README.md +++ b/README.md @@ -27,6 +27,7 @@ Executes Javascript, Typescript Scripts. ### **WORK IN PROGRESS** --> ### WORK IN PROGRESS +* (Eistee82) Added OID display mode toggle for Blockly editor: 4 display modes (Name, Name path, State ID, Full ID) with toolbar dropdown, context menu, optional object icons, and translations in 11 languages * Per-provider test buttons in adapter config (OpenAI, Anthropic, Gemini, DeepSeek, Custom API) * Optional API key field for custom base URL providers (e.g. Ollama without auth) * Provider icons on test buttons and in model dropdown diff --git a/admin/assets/OpenAiDialog-CANTLp4d.js b/admin/assets/OpenAiDialog-CANTLp4d.js deleted file mode 100644 index 00aefcbe1..000000000 --- a/admin/assets/OpenAiDialog-CANTLp4d.js +++ /dev/null @@ -1,13 +0,0 @@ -import{c as ie,j as n}from"./createSvgIcon-DPvF8xqu.js";import{j as S,b as H,k as J,c as re}from"./iobroker_javascript__loadShare__react__loadShare__.mjs-CTZOFJS2.js";import{_ as F,a as Q,b as Z,i as $,h as X,c as oe,$ as ae,d as ce,e as le,f as de,g as ee}from"./iobroker_javascript__loadShare___mf_0_mui_mf_1_material__loadShare__.mjs-QWG5Arqe.js";import{_ as l}from"./iobroker_javascript__loadShare___mf_0_iobroker_mf_1_adapter_mf_2_react_mf_2_v5__loadShare__.mjs-DkBjPSMw.js";import{_ as me}from"./preload-helper-BDBacUwf.js";import{C as he,b as ue,R as fe}from"./index-gIA8x-8f.js";import pe from"./ScriptEditorVanillaMonaco-DSYvOslZ.js";import{c as te,I as ge}from"./index-C49cpVll.js";import{h as ye}from"./index-bny2V8S2.js";import"./iobroker_javascript__loadShare__react__loadShare__.mjs_commonjs-proxy-CE9lvhW8.js";import"./iobroker_javascript__loadShare__prop_mf_2_types__loadShare__.mjs-BCtSFofY.js";import"./virtual_mf-REMOTE_ENTRY_ID_iobroker_javascript__remoteEntry_js-s4ROfmWJ.js";import"./iobroker_javascript__loadShare__react_mf_2_dom__loadShare__.mjs_commonjs-proxy-RQRRZMX5.js";import"./iobroker_javascript__loadShare__react_mf_2_dom__loadShare__.mjs-DeVAS-oa.js";import"./inheritsLoose-B0Ba5G9z.js";const ve=ie(n.jsx("path",{d:"M11.07 12.85c.77-1.39 2.25-2.21 3.11-3.44.91-1.29.4-3.7-2.18-3.7-1.69 0-2.52 1.28-2.87 2.34L6.54 6.96C7.25 4.83 9.18 3 11.99 3c2.35 0 3.96 1.07 4.78 2.41.7 1.15 1.11 3.3.03 4.9-1.2 1.77-2.35 2.31-2.97 3.45-.25.46-.35.76-.35 2.24h-2.89c-.01-.78-.13-2.05.48-3.15M14 20c0 1.1-.9 2-2 2s-2-.9-2-2 .9-2 2-2 2 .9 2 2"}),"QuestionMark"),je=me(()=>import("./docs-BrInh2Pn.js"),[],import.meta.url);let G=null;async function xe(s){if(G)return G;const f=await s.getObjectViewSystem("state","","香"),r=await s.getObjectViewSystem("channel","","香"),v=await s.getObjectViewSystem("device","","香"),d=await s.getObjectViewSystem("folder","","香"),k=await s.getObjectViewSystem("enum","","香");return G=Object.assign(f,r,v,d,k),G}function V(s,f){return s&&typeof s=="object"?s[f]||s.en:s||""}async function Ie(s){var P,N,L,K;const f=l.I18n.getLanguage(),r=await xe(s),v=Object.keys(r).sort(),d=new he,k=[],A=["UNREACH_STICKY"],W=[ue.Types.info],_=[],b=[],R=[],D=[];v.forEach(m=>{var a,h,c;((a=r[m])==null?void 0:a.type)==="enum"?_.push(m):(c=(h=r[m])==null?void 0:h.common)!=null&&c.smartName&&D.push(m)}),_.forEach(m=>{m.startsWith("enum.rooms.")?b.push(m):m.startsWith("enum.functions.")&&R.push(m);const a=r[m].common.members;a!=null&&a.length&&a.forEach(h=>{r[h]&&(D.includes(h)||D.push(h))})});const M={id:"",objects:r,_keysOptional:v,_usedIdsOptional:k,ignoreIndicators:A,excludedTypes:W},E=[];D.forEach(m=>{M.id=m;const a=d.detect(M);a&&a.forEach(h=>{var w;const c=(w=h.states.find(i=>i.id))==null?void 0:w.id;if(!c||E.find(i=>i.id===c))return;const j=r[c],z={id:c,name:V(j.common.name,f),type:j.type,deviceType:h.type,states:h.states.filter(i=>i.id).map(i=>({id:i.id,name:i.name,role:i.defaultRole,type:r[i.id].common.type,unit:r[i.id].common.unit,read:r[i.id].common.read===void 0?!0:r[i.id].common.read,write:r[i.id].common.write===void 0?!0:r[i.id].common.write}))},T=c.split(".");let e,o;(j.type==="channel"||j.type==="state")&&(T.pop(),e=T.join("."),r[e]&&(r[e].type==="channel"||r[e].type==="folder")?(T.pop(),o=T.join("."),(!r[o]||r[o].type!=="device"&&r[e].type!=="folder")&&(o=void 0)):e=void 0);const I=b.find(i=>{var x,p,t;return(x=r[i].common.members)!=null&&x.includes(c)||e&&((p=r[i].common.members)!=null&&p.includes(e))?!0:o&&((t=r[i].common.members)==null?void 0:t.includes(o))});I&&(z.room=V(r[I].common.name,f));const g=R.find(i=>{var x,p,t;return(x=r[i].common.members)!=null&&x.includes(c)||e&&((p=r[i].common.members)!=null&&p.includes(e))?!0:o&&((t=r[i].common.members)==null?void 0:t.includes(o))});g&&(z.function=V(r[g].common.name,f)),E.push(z)})});for(let m=0;m(await je).default,we={ru:"Russian",en:"English",de:"German",es:"Spanish",fr:"French",it:"Italian",pl:"Polish",nl:"Dutch",pt:"Portuguese",uk:"Ukrainian","zh-cn":"Chinese"},Y={flexShrink:0,opacity:.7},ne={openai:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor",style:Y,children:n.jsx("path",{d:"M22.282 9.821a5.985 5.985 0 0 0-.516-4.91 6.046 6.046 0 0 0-6.51-2.9A6.065 6.065 0 0 0 4.981 4.18a5.985 5.985 0 0 0-3.998 2.9 6.046 6.046 0 0 0 .743 7.097 5.98 5.98 0 0 0 .51 4.911 6.051 6.051 0 0 0 6.515 2.9A5.985 5.985 0 0 0 13.26 24a6.056 6.056 0 0 0 5.772-4.206 5.99 5.99 0 0 0 3.997-2.9 6.056 6.056 0 0 0-.747-7.073zM13.26 22.43a4.476 4.476 0 0 1-2.876-1.04l.141-.081 4.779-2.758a.795.795 0 0 0 .392-.681v-6.737l2.02 1.168a.071.071 0 0 1 .038.052v5.583a4.504 4.504 0 0 1-4.494 4.494zM3.6 18.304a4.47 4.47 0 0 1-.535-3.014l.142.085 4.783 2.759a.771.771 0 0 0 .78 0l5.843-3.369v2.332a.08.08 0 0 1-.033.062L9.74 19.95a4.5 4.5 0 0 1-6.14-1.646zM2.34 7.896a4.485 4.485 0 0 1 2.366-1.973V11.6a.766.766 0 0 0 .388.676l5.815 3.355-2.02 1.168a.076.076 0 0 1-.071 0l-4.83-2.786A4.504 4.504 0 0 1 2.34 7.872zm16.597 3.855-5.833-3.387L15.119 7.2a.076.076 0 0 1 .071 0l4.83 2.791a4.494 4.494 0 0 1-.676 8.105v-5.678a.79.79 0 0 0-.407-.667zm2.01-3.023-.141-.085-4.774-2.782a.776.776 0 0 0-.785 0L9.409 9.23V6.897a.066.066 0 0 1 .028-.061l4.83-2.787a4.5 4.5 0 0 1 6.68 4.66zm-12.64 4.135-2.02-1.164a.08.08 0 0 1-.038-.057V6.075a4.5 4.5 0 0 1 7.375-3.453l-.142.08L8.704 5.46a.795.795 0 0 0-.393.681zm1.097-2.365 2.602-1.5 2.607 1.5v2.999l-2.597 1.5-2.607-1.5z"})}),anthropic:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor",style:Y,children:n.jsx("path",{d:"M17.304 3.54h-3.604L7.128 20.46h3.604l1.345-3.462h6.932l1.345 3.462H24L17.304 3.54zm-3.45 10.696 2.647-6.812 2.647 6.812h-5.295zM6.696 3.54H3.092L0 20.46h3.604L6.696 3.54z"})}),gemini:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor",style:Y,children:n.jsx("path",{d:"M12 0A12 12 0 0 0 0 12a12 12 0 0 0 12 12 12 12 0 0 0 12-12A12 12 0 0 0 12 0z"})}),deepseek:n.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor",style:Y,children:n.jsx("path",{d:"M5 3h6a9 9 0 0 1 0 18H5V3zm4 14V7h2a5 5 0 0 1 0 10H9z"})})};async function se(s,f){const r=Object.keys(f);for(let v=0;v{const[f,r]=S(window.localStorage.getItem("openai-question")||""),[v,d]=S(""),[k,A]=S(!1),[W,_]=S(!1),[b,R]=S(window.localStorage.getItem("openai-model")||""),[D,M]=S(!1),[E,P]=S([]),[N,L]=S(!0),[K,m]=S(null),a=H(null),h=H(null),c=H({}),j=H(null),z=J(async e=>{L(!0),m(null);try{const o=await se(s.socket,s.runningInstances);if(e!=null&&e.current)return;if(!o){L(!1);return}h.current=o;const I=Object.keys(s.runningInstances)[0];if(!I){m(l.I18n.t("No running javascript instance found")),L(!1);return}const g=[],w={},i=[],x=[],p=(t,B)=>{for(const O of t){const C=O.toLowerCase();C.includes("embedding")||C.includes("moderation")||C.startsWith("dall-e")||C.startsWith("tts-")||C.startsWith("whisper")||C.startsWith("babbage")||C.startsWith("davinci")||C.startsWith("sora")||C.startsWith("omni-moderation")||w[O]||(g.push(O),w[O]=B)}};if((o.gptKey||o.gptBaseUrl)&&x.push(s.socket.sendTo(I,"testApiConnection",{apiKey:o.gptKey,baseUrl:o.gptBaseUrl||"",provider:"openai"}).then(t=>{t.models?p(t.models,"openai"):t.error&&i.push(`OpenAI: ${t.error}`)}).catch(t=>{i.push(`OpenAI: ${String(t)}`)})),o.claudeKey&&x.push(s.socket.sendTo(I,"testApiConnection",{apiKey:o.claudeKey,provider:"anthropic"}).then(t=>{t.models?p(t.models,"anthropic"):t.error&&i.push(`Anthropic: ${t.error}`)}).catch(t=>{i.push(`Anthropic: ${String(t)}`)})),o.geminiKey&&x.push(s.socket.sendTo(I,"testApiConnection",{apiKey:o.geminiKey,provider:"gemini"}).then(t=>{t.models?p(t.models,"gemini"):t.error&&i.push(`Gemini: ${t.error}`)}).catch(t=>{i.push(`Gemini: ${String(t)}`)})),o.deepseekKey&&x.push(s.socket.sendTo(I,"testApiConnection",{apiKey:o.deepseekKey,provider:"deepseek"}).then(t=>{t.models?p(t.models,"deepseek"):t.error&&i.push(`DeepSeek: ${t.error}`)}).catch(t=>{i.push(`DeepSeek: ${String(t)}`)})),await Promise.all(x),e!=null&&e.current)return;if(c.current=w,g.length>0){g.sort(),P(g);const t=window.localStorage.getItem("openai-model");t&&g.includes(t)?R(t):R(g[0])}i.length>0&&m(i.join("; "))}catch(o){console.error("Failed to fetch models:",o),e!=null&&e.current||m(l.I18n.t("Request failed: %s",String(o)))}e!=null&&e.current||L(!1)},[s.socket,s.runningInstances]);re(()=>{const e={current:!1};return z(e),()=>{e.current=!0}},[z]);const T=J(async()=>{let e;a.current?e=a.current:(e=await Ie(s.socket),a.current=e,console.log(`devices: ${JSON.stringify(e,null,2)}`));let o=h.current;o||(o=await se(s.socket,s.runningInstances),h.current=o);let I;if(j.current?I=j.current:(I=await _e(),j.current=I),!o){M(!0);return}const g=c.current[b];if(!g){_(l.I18n.t("Please select a valid model"));return}let w,i;g==="anthropic"?(w=o.claudeKey,i=""):g==="gemini"?(w=o.geminiKey,i=""):g==="deepseek"?(w=o.deepseekKey,i=""):(w=o.gptKey,i=o.gptBaseUrl||"");const x=Object.keys(s.runningInstances)[0];if(!x){_(l.I18n.t("No running javascript instance found"));return}A(!0),_(!1);try{const p=await s.socket.sendTo(x,"chatCompletion",{apiKey:w,baseUrl:i,model:b,provider:g,messages:[{role:"system",content:`You are programmer. Here is a documentation: - -${I}`},{role:"system",content:`Here is list of devices: - -${JSON.stringify(e,null,2)}`},{role:"user",content:`Write JavaScript code that does: - -${f} -Return only code. -Write comments in ${we[l.I18n.getLanguage()]||"English"}. -You can call async function directly in the code without encapsulate them in async function as this code will be already executed in async function. -Do not import any libraries as all functions are already imported.`}]});if(p.error)_(p.error);else{let t=p.content||"";t=t.replace(/[\s\S]*?<\/think>/gi,""),t=t.replace(/<\|endoftext\|>/g,""),t=t.replace(/<\|im_start\|>[\s\S]*?<\|im_end\|>/g,""),t=t.replace(/<\|im_start\|>[\s\S]*/g,"");const B=t.match(/```(?:javascript|js|typescript)?\n?([\s\S]*?)```/m);let O;if(B)O=B[1].trim();else{const C=t.split(` -`),U=[];let q=!1;for(const y of C){const u=y.trim();!q&&u===""||(!q&&(u.startsWith("//")||u.startsWith("const ")||u.startsWith("let ")||u.startsWith("var ")||u.startsWith("function ")||u.startsWith("async ")||u.startsWith("await ")||u.startsWith("if ")||u.startsWith("for ")||u.startsWith("on(")||u.startsWith("schedule(")||u.startsWith("setState")||u.startsWith("getState")||u.startsWith("createState")||u.startsWith("$")||u.startsWith("'use strict'")||u.startsWith('"use strict"'))&&(q=!0),q&&U.push(y))}for(;U.length>0;){const y=U[U.length-1].trim();if(y===""||y.length>0&&!y.startsWith("//")&&!y.startsWith("*")&&!y.startsWith("}")&&!y.startsWith(");")&&!y.endsWith(";")&&!y.endsWith("}")&&!y.endsWith(")")&&!y.endsWith(",")&&!y.endsWith("{")&&/^[A-Z]/.test(y))U.pop();else break}O=U.join(` -`).trim()}d(O||"")}}catch(p){console.error("Chat request failed:",p),_(l.I18n.t("Request failed: %s",String(p)))}A(!1)},[f,b,s.runningInstances,s.socket]);return n.jsxs(F,{maxWidth:"lg",sx:{"& .MuiDialog-paper":{height:"calc(100% - 100px)"}},open:!0,onClose:()=>s.onClose(),fullWidth:!0,children:[D&&n.jsxs(F,{maxWidth:"lg",open:!0,onClose:()=>M(!1),fullWidth:!0,children:[n.jsx(Q,{children:l.I18n.t("No API key found")}),n.jsxs(Z,{style:{display:"flex",flexDirection:"column",gap:8},children:[n.jsx("div",{children:l.I18n.t("You have to enter at least one API key in the configuration of javascript adapter.")}),n.jsx($,{variant:"contained",onClick:()=>{const e=Object.keys(s.runningInstances);window.open(`../../#tab-instances/config/${e[0]||"system.adapter.javascript.0"}`,"_blank"),M(!1)},children:l.I18n.t("Open configuration")})]}),n.jsx(X,{children:n.jsx($,{variant:"contained",startIcon:n.jsx(te,{}),onClick:()=>M(!1),children:l.I18n.t("Close")})})]}),n.jsx(Q,{children:l.I18n.t("AI code generator")}),n.jsxs(Z,{style:{display:"flex",flexDirection:"column",gap:8,height:"100%"},children:[n.jsx("div",{children:n.jsx(oe,{variant:"standard",multiline:!0,autoFocus:!0,disabled:k,fullWidth:!0,onKeyUp:e=>{e.key==="Enter"&&e.ctrlKey&&T()},label:l.I18n.t("Enter your question"),helperText:l.I18n.t("Press Ctrl+Enter to get the answer"),value:f,onChange:e=>{window.localStorage.setItem("openai-question",e.target.value),r(e.target.value)}})}),n.jsxs("div",{style:{display:"flex",alignItems:"baseline"},children:[n.jsx($,{variant:"contained",disabled:k||!f||!b,startIcon:n.jsx(ve,{}),onClick:async()=>T(),children:k?n.jsx(ae,{size:24}):l.I18n.t("Ask")}),n.jsxs(ce,{style:{width:300,marginLeft:20},disabled:k,variant:"standard",error:!!K,children:[n.jsx(le,{children:l.I18n.t("Model")}),n.jsxs(de,{variant:"standard",value:b,disabled:N||!!K,renderValue:e=>n.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:8},children:[ne[c.current[e]],e]}),onChange:e=>{window.localStorage.setItem("openai-model",e.target.value),W&&_(!1),R(e.target.value)},children:[N&&n.jsx(ee,{value:"",disabled:!0,children:l.I18n.t("Loading models...")}),E.map(e=>n.jsx(ee,{value:e,children:n.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:8},children:[ne[c.current[e]],e]})},e))]})]}),K&&n.jsx($,{style:{marginLeft:10},variant:"outlined",color:"error",startIcon:n.jsx(fe,{}),onClick:()=>{z()},children:l.I18n.t("Retry")})]}),K&&n.jsx("div",{style:{color:s.themeType==="dark"?"#984242":"#bb0000"},children:K}),n.jsx("div",{children:l.I18n.t("Result")}),n.jsx("div",{style:{height:"calc(100% - 155px)"},children:W?n.jsx("div",{style:{color:s.themeType==="dark"?"#984242":"#bb0000"},children:W}):n.jsx(pe,{triggerPrettier:1,adapterName:s.adapterName,runningInstances:s.runningInstances,style:{height:"100%",width:"100%",resize:"none"},name:"ai",socket:s.socket,readOnly:!0,checkJs:!0,code:v,isDark:s.themeType==="dark",language:s.language||"javascript"})})]}),n.jsxs(X,{children:[n.jsx($,{color:"grey",variant:"outlined",disabled:!v,startIcon:n.jsx(ye,{}),onClick:()=>{l.Utils.copyToClipboard(v),window.alert(l.I18n.t("Copied"))},children:l.I18n.t("Copy to clipboard")}),n.jsx($,{color:"primary",variant:"contained",disabled:!v||!!W,startIcon:n.jsx(ge,{}),onClick:()=>{s.onAddCode(v),s.onClose()},children:l.I18n.t("Use generated code")}),n.jsx($,{color:"grey",variant:"contained",startIcon:n.jsx(te,{}),onClick:()=>s.onClose(),children:l.I18n.t("Close")})]})]})};export{De as default}; diff --git a/admin/assets/OpenAiDialog-BliYIniL.js b/admin/assets/OpenAiDialog-CdW_zvS-.js similarity index 99% rename from admin/assets/OpenAiDialog-BliYIniL.js rename to admin/assets/OpenAiDialog-CdW_zvS-.js index f9d3550a2..ca2678411 100644 --- a/admin/assets/OpenAiDialog-BliYIniL.js +++ b/admin/assets/OpenAiDialog-CdW_zvS-.js @@ -1,4 +1,4 @@ -import{c as le,j as n}from"./createSvgIcon-DPvF8xqu.js";import{j as _,b as H,k as Z,c as de}from"./iobroker_javascript__loadShare__react__loadShare__.mjs-CTZOFJS2.js";import{_ as ee,a as te,b as se,i as K,h as ne,c as me,$ as ue,d as he,e as ge,f as fe,g as ie}from"./iobroker_javascript__loadShare___mf_0_mui_mf_1_material__loadShare__.mjs-QWG5Arqe.js";import{_ as o}from"./iobroker_javascript__loadShare___mf_0_iobroker_mf_1_adapter_mf_2_react_mf_2_v5__loadShare__.mjs-DkBjPSMw.js";import{_ as pe}from"./preload-helper-BDBacUwf.js";import{C as ye,b as ve,R as be}from"./index-gIA8x-8f.js";import je from"./ScriptEditorVanillaMonaco-DSYvOslZ.js";import{c as ae,I as xe}from"./index-C49cpVll.js";import{h as Ie}from"./index-CEbKg781.js";import"./iobroker_javascript__loadShare__react__loadShare__.mjs_commonjs-proxy-CE9lvhW8.js";import"./iobroker_javascript__loadShare__prop_mf_2_types__loadShare__.mjs-BCtSFofY.js";import"./virtual_mf-REMOTE_ENTRY_ID_iobroker_javascript__remoteEntry_js-s4ROfmWJ.js";import"./iobroker_javascript__loadShare__react_mf_2_dom__loadShare__.mjs_commonjs-proxy-RQRRZMX5.js";import"./iobroker_javascript__loadShare__react_mf_2_dom__loadShare__.mjs-DeVAS-oa.js";import"./inheritsLoose-B0Ba5G9z.js";const Se=le(n.jsx("path",{d:"M11.07 12.85c.77-1.39 2.25-2.21 3.11-3.44.91-1.29.4-3.7-2.18-3.7-1.69 0-2.52 1.28-2.87 2.34L6.54 6.96C7.25 4.83 9.18 3 11.99 3c2.35 0 3.96 1.07 4.78 2.41.7 1.15 1.11 3.3.03 4.9-1.2 1.77-2.35 2.31-2.97 3.45-.25.46-.35.76-.35 2.24h-2.89c-.01-.78-.13-2.05.48-3.15M14 20c0 1.1-.9 2-2 2s-2-.9-2-2 .9-2 2-2 2 .9 2 2"}),"QuestionMark"),Ce=pe(()=>import("./docs-compact-CKNGiYh2.js"),[],import.meta.url);let Q=null;async function we(e){if(Q)return Q;const h=await e.getObjectViewSystem("state","","香"),a=await e.getObjectViewSystem("channel","","香"),I=await e.getObjectViewSystem("device","","香"),r=await e.getObjectViewSystem("folder","","香"),S=await e.getObjectViewSystem("enum","","香");return Q=Object.assign(h,a,I,r,S),Q}function G(e,h){return e&&typeof e=="object"?e[h]||e.en:e||""}async function ke(e){var P,q,U,z;const h=o.I18n.getLanguage(),a=await we(e),I=Object.keys(a).sort(),r=new ye,S=[],E=["UNREACH_STICKY"],$=[ve.Types.info],N=[],W=[],M=[],D=[];I.forEach(g=>{var l,d,c;((l=a[g])==null?void 0:l.type)==="enum"?N.push(g):(c=(d=a[g])==null?void 0:d.common)!=null&&c.smartName&&D.push(g)}),N.forEach(g=>{g.startsWith("enum.rooms.")?W.push(g):g.startsWith("enum.functions.")&&M.push(g);const l=a[g].common.members;l!=null&&l.length&&l.forEach(d=>{a[d]&&(D.includes(d)||D.push(d))})});const R={id:"",objects:a,_keysOptional:I,_usedIdsOptional:S,ignoreIndicators:E,excludedTypes:$},C=[];D.forEach(g=>{R.id=g;const l=r.detect(R);l&&l.forEach(d=>{var i;const c=(i=d.states.find(t=>t.id))==null?void 0:i.id;if(!c||C.find(t=>t.id===c))return;const v=a[c],L={id:c,name:G(v.common.name,h),type:v.type,deviceType:d.type,states:d.states.filter(t=>t.id).map(t=>({id:t.id,name:t.name,role:t.defaultRole,type:a[t.id].common.type,unit:a[t.id].common.unit,read:a[t.id].common.read===void 0?!0:a[t.id].common.read,write:a[t.id].common.write===void 0?!0:a[t.id].common.write}))},A=c.split(".");let b,w;(v.type==="channel"||v.type==="state")&&(A.pop(),b=A.join("."),a[b]&&(a[b].type==="channel"||a[b].type==="folder")?(A.pop(),w=A.join("."),(!a[w]||a[w].type!=="device"&&a[b].type!=="folder")&&(w=void 0)):b=void 0);const V=W.find(t=>{var y,m,p;return(y=a[t].common.members)!=null&&y.includes(c)||b&&((m=a[t].common.members)!=null&&m.includes(b))?!0:w&&((p=a[t].common.members)==null?void 0:p.includes(w))});V&&(L.room=G(a[V].common.name,h));const B=M.find(t=>{var y,m,p;return(y=a[t].common.members)!=null&&y.includes(c)||b&&((m=a[t].common.members)!=null&&m.includes(b))?!0:w&&((p=a[t].common.members)==null?void 0:p.includes(w))});B&&(L.function=G(a[B].common.name,h)),C.push(L)})});for(let g=0;g(await Ce).default,_e={ru:"Russian",en:"English",de:"German",es:"Spanish",fr:"French",it:"Italian",pl:"Polish",nl:"Dutch",pt:"Portuguese",uk:"Ukrainian","zh-cn":"Chinese"},Re={width:16,height:16,flexShrink:0,opacity:.7},Te={openai:"img/openai.svg",anthropic:"img/anthropic.svg",gemini:"img/gemini.svg",deepseek:"img/deepseek.svg",custom:"img/custom.svg"};function oe({provider:e}){return Te[e]?n.jsx("img",{src:`./img/${e}.svg`,alt:e,style:Re,onError:a=>{a.target.style.display="none"}}):null}async function re(e,h){const a=Object.keys(h);for(let I=0;I{const[h,a]=_(window.localStorage.getItem("openai-question")||""),[I,r]=_(""),[S,E]=_(!1),[$,N]=_(""),[W,M]=_(!1),[D,R]=_(!1),[C,P]=_(window.localStorage.getItem("openai-model")||""),[q,U]=_(!1),[z,g]=_([]),[l,d]=_(!0),[c,v]=_(null),L=H(null),A=H(null),b=H({}),w=H(null),V=Z(async i=>{d(!0),v(null);try{const t=await re(e.socket,e.runningInstances);if(i!=null&&i.current)return;if(!t){d(!1);return}A.current=t;const y=Object.keys(e.runningInstances)[0];if(!y){v(o.I18n.t("No running javascript instance found")),d(!1);return}const m=[],p={},u=[],T=[],k=(s,Y)=>{for(const j of s){const O=j.toLowerCase();O.includes("embedding")||O.includes("moderation")||O.startsWith("dall-e")||O.startsWith("tts-")||O.startsWith("whisper")||O.startsWith("babbage")||O.startsWith("davinci")||O.startsWith("sora")||O.startsWith("omni-moderation")||p[j]||(m.push(j),p[j]=Y)}};if(t.gptKey&&T.push(e.socket.sendTo(y,"testApiConnection",{apiKey:t.gptKey,provider:"openai"}).then(s=>{s.models?k(s.models,"openai"):s.error&&u.push(`OpenAI: ${s.error}`)}).catch(s=>{u.push(`OpenAI: ${String(s)}`)})),t.gptBaseUrl&&T.push(e.socket.sendTo(y,"testApiConnection",{apiKey:t.gptBaseUrlKey||"",baseUrl:t.gptBaseUrl,provider:"openai"}).then(s=>{s.models?k(s.models,"custom"):s.error&&u.push(`Custom: ${s.error}`)}).catch(s=>{u.push(`Custom: ${String(s)}`)})),t.claudeKey&&T.push(e.socket.sendTo(y,"testApiConnection",{apiKey:t.claudeKey,provider:"anthropic"}).then(s=>{s.models?k(s.models,"anthropic"):s.error&&u.push(`Anthropic: ${s.error}`)}).catch(s=>{u.push(`Anthropic: ${String(s)}`)})),t.geminiKey&&T.push(e.socket.sendTo(y,"testApiConnection",{apiKey:t.geminiKey,provider:"gemini"}).then(s=>{s.models?k(s.models,"gemini"):s.error&&u.push(`Gemini: ${s.error}`)}).catch(s=>{u.push(`Gemini: ${String(s)}`)})),t.deepseekKey&&T.push(e.socket.sendTo(y,"testApiConnection",{apiKey:t.deepseekKey,provider:"deepseek"}).then(s=>{s.models?k(s.models,"deepseek"):s.error&&u.push(`DeepSeek: ${s.error}`)}).catch(s=>{u.push(`DeepSeek: ${String(s)}`)})),await Promise.all(T),i!=null&&i.current)return;if(b.current=p,m.length>0){m.sort(),g(m);const s=window.localStorage.getItem("openai-model");s&&m.includes(s)?P(s):P(m[0])}u.length>0&&v(u.join("; "))}catch(t){console.error("Failed to fetch models:",t),i!=null&&i.current||v(o.I18n.t("Request failed: %s",String(t)))}i!=null&&i.current||d(!1)},[e.socket,e.runningInstances]);de(()=>{const i={current:!1};return V(i),()=>{i.current=!0}},[V]);const B=Z(async()=>{let i;L.current?i=L.current:(i=await ke(e.socket),L.current=i,console.log(`devices: ${JSON.stringify(i,null,2)}`));let t=A.current;t||(t=await re(e.socket,e.runningInstances),A.current=t);let y;if(w.current?y=w.current:(y=await Oe(),w.current=y),!t){U(!0);return}const m=b.current[C];if(!m){R(o.I18n.t("Please select a valid model"));return}let p,u;m==="anthropic"?(p=t.claudeKey,u=""):m==="gemini"?(p=t.geminiKey,u=""):m==="deepseek"?(p=t.deepseekKey,u=""):m==="custom"?(p=t.gptBaseUrlKey||"",u=t.gptBaseUrl||""):(p=t.gptKey,u="");const T=Object.keys(e.runningInstances)[0];if(!T){R(o.I18n.t("No running javascript instance found"));return}E(o.I18n.t("Planning...")),R(!1),N(""),M(!1),r("");try{const k=await e.socket.sendTo(T,"chatCompletion",{timeout:6e5,apiKey:p,baseUrl:u,model:C,provider:m,messages:[{role:"user",content:`Devices in my smart home: +import{c as le,j as n}from"./createSvgIcon-DPvF8xqu.js";import{j as _,b as H,k as Z,c as de}from"./iobroker_javascript__loadShare__react__loadShare__.mjs-CTZOFJS2.js";import{_ as ee,a as te,b as se,i as K,h as ne,c as me,$ as ue,d as he,e as ge,f as fe,g as ie}from"./iobroker_javascript__loadShare___mf_0_mui_mf_1_material__loadShare__.mjs-QWG5Arqe.js";import{_ as o}from"./iobroker_javascript__loadShare___mf_0_iobroker_mf_1_adapter_mf_2_react_mf_2_v5__loadShare__.mjs-DkBjPSMw.js";import{_ as pe}from"./preload-helper-BDBacUwf.js";import{C as ye,b as ve,R as be}from"./index-gIA8x-8f.js";import je from"./ScriptEditorVanillaMonaco-DSYvOslZ.js";import{c as ae,I as xe}from"./index-C49cpVll.js";import{h as Ie}from"./index-DvPtUWVN.js";import"./iobroker_javascript__loadShare__react__loadShare__.mjs_commonjs-proxy-CE9lvhW8.js";import"./iobroker_javascript__loadShare__prop_mf_2_types__loadShare__.mjs-BCtSFofY.js";import"./virtual_mf-REMOTE_ENTRY_ID_iobroker_javascript__remoteEntry_js-s4ROfmWJ.js";import"./iobroker_javascript__loadShare__react_mf_2_dom__loadShare__.mjs_commonjs-proxy-RQRRZMX5.js";import"./iobroker_javascript__loadShare__react_mf_2_dom__loadShare__.mjs-DeVAS-oa.js";import"./inheritsLoose-B0Ba5G9z.js";const Se=le(n.jsx("path",{d:"M11.07 12.85c.77-1.39 2.25-2.21 3.11-3.44.91-1.29.4-3.7-2.18-3.7-1.69 0-2.52 1.28-2.87 2.34L6.54 6.96C7.25 4.83 9.18 3 11.99 3c2.35 0 3.96 1.07 4.78 2.41.7 1.15 1.11 3.3.03 4.9-1.2 1.77-2.35 2.31-2.97 3.45-.25.46-.35.76-.35 2.24h-2.89c-.01-.78-.13-2.05.48-3.15M14 20c0 1.1-.9 2-2 2s-2-.9-2-2 .9-2 2-2 2 .9 2 2"}),"QuestionMark"),Ce=pe(()=>import("./docs-compact-CKNGiYh2.js"),[],import.meta.url);let Q=null;async function we(e){if(Q)return Q;const h=await e.getObjectViewSystem("state","","香"),a=await e.getObjectViewSystem("channel","","香"),I=await e.getObjectViewSystem("device","","香"),r=await e.getObjectViewSystem("folder","","香"),S=await e.getObjectViewSystem("enum","","香");return Q=Object.assign(h,a,I,r,S),Q}function G(e,h){return e&&typeof e=="object"?e[h]||e.en:e||""}async function ke(e){var P,q,U,z;const h=o.I18n.getLanguage(),a=await we(e),I=Object.keys(a).sort(),r=new ye,S=[],E=["UNREACH_STICKY"],$=[ve.Types.info],N=[],W=[],M=[],D=[];I.forEach(g=>{var l,d,c;((l=a[g])==null?void 0:l.type)==="enum"?N.push(g):(c=(d=a[g])==null?void 0:d.common)!=null&&c.smartName&&D.push(g)}),N.forEach(g=>{g.startsWith("enum.rooms.")?W.push(g):g.startsWith("enum.functions.")&&M.push(g);const l=a[g].common.members;l!=null&&l.length&&l.forEach(d=>{a[d]&&(D.includes(d)||D.push(d))})});const R={id:"",objects:a,_keysOptional:I,_usedIdsOptional:S,ignoreIndicators:E,excludedTypes:$},C=[];D.forEach(g=>{R.id=g;const l=r.detect(R);l&&l.forEach(d=>{var i;const c=(i=d.states.find(t=>t.id))==null?void 0:i.id;if(!c||C.find(t=>t.id===c))return;const v=a[c],L={id:c,name:G(v.common.name,h),type:v.type,deviceType:d.type,states:d.states.filter(t=>t.id).map(t=>({id:t.id,name:t.name,role:t.defaultRole,type:a[t.id].common.type,unit:a[t.id].common.unit,read:a[t.id].common.read===void 0?!0:a[t.id].common.read,write:a[t.id].common.write===void 0?!0:a[t.id].common.write}))},A=c.split(".");let b,w;(v.type==="channel"||v.type==="state")&&(A.pop(),b=A.join("."),a[b]&&(a[b].type==="channel"||a[b].type==="folder")?(A.pop(),w=A.join("."),(!a[w]||a[w].type!=="device"&&a[b].type!=="folder")&&(w=void 0)):b=void 0);const V=W.find(t=>{var y,m,p;return(y=a[t].common.members)!=null&&y.includes(c)||b&&((m=a[t].common.members)!=null&&m.includes(b))?!0:w&&((p=a[t].common.members)==null?void 0:p.includes(w))});V&&(L.room=G(a[V].common.name,h));const B=M.find(t=>{var y,m,p;return(y=a[t].common.members)!=null&&y.includes(c)||b&&((m=a[t].common.members)!=null&&m.includes(b))?!0:w&&((p=a[t].common.members)==null?void 0:p.includes(w))});B&&(L.function=G(a[B].common.name,h)),C.push(L)})});for(let g=0;g(await Ce).default,_e={ru:"Russian",en:"English",de:"German",es:"Spanish",fr:"French",it:"Italian",pl:"Polish",nl:"Dutch",pt:"Portuguese",uk:"Ukrainian","zh-cn":"Chinese"},Re={width:16,height:16,flexShrink:0,opacity:.7},Te={openai:"img/openai.svg",anthropic:"img/anthropic.svg",gemini:"img/gemini.svg",deepseek:"img/deepseek.svg",custom:"img/custom.svg"};function oe({provider:e}){return Te[e]?n.jsx("img",{src:`./img/${e}.svg`,alt:e,style:Re,onError:a=>{a.target.style.display="none"}}):null}async function re(e,h){const a=Object.keys(h);for(let I=0;I{const[h,a]=_(window.localStorage.getItem("openai-question")||""),[I,r]=_(""),[S,E]=_(!1),[$,N]=_(""),[W,M]=_(!1),[D,R]=_(!1),[C,P]=_(window.localStorage.getItem("openai-model")||""),[q,U]=_(!1),[z,g]=_([]),[l,d]=_(!0),[c,v]=_(null),L=H(null),A=H(null),b=H({}),w=H(null),V=Z(async i=>{d(!0),v(null);try{const t=await re(e.socket,e.runningInstances);if(i!=null&&i.current)return;if(!t){d(!1);return}A.current=t;const y=Object.keys(e.runningInstances)[0];if(!y){v(o.I18n.t("No running javascript instance found")),d(!1);return}const m=[],p={},u=[],T=[],k=(s,Y)=>{for(const j of s){const O=j.toLowerCase();O.includes("embedding")||O.includes("moderation")||O.startsWith("dall-e")||O.startsWith("tts-")||O.startsWith("whisper")||O.startsWith("babbage")||O.startsWith("davinci")||O.startsWith("sora")||O.startsWith("omni-moderation")||p[j]||(m.push(j),p[j]=Y)}};if(t.gptKey&&T.push(e.socket.sendTo(y,"testApiConnection",{apiKey:t.gptKey,provider:"openai"}).then(s=>{s.models?k(s.models,"openai"):s.error&&u.push(`OpenAI: ${s.error}`)}).catch(s=>{u.push(`OpenAI: ${String(s)}`)})),t.gptBaseUrl&&T.push(e.socket.sendTo(y,"testApiConnection",{apiKey:t.gptBaseUrlKey||"",baseUrl:t.gptBaseUrl,provider:"openai"}).then(s=>{s.models?k(s.models,"custom"):s.error&&u.push(`Custom: ${s.error}`)}).catch(s=>{u.push(`Custom: ${String(s)}`)})),t.claudeKey&&T.push(e.socket.sendTo(y,"testApiConnection",{apiKey:t.claudeKey,provider:"anthropic"}).then(s=>{s.models?k(s.models,"anthropic"):s.error&&u.push(`Anthropic: ${s.error}`)}).catch(s=>{u.push(`Anthropic: ${String(s)}`)})),t.geminiKey&&T.push(e.socket.sendTo(y,"testApiConnection",{apiKey:t.geminiKey,provider:"gemini"}).then(s=>{s.models?k(s.models,"gemini"):s.error&&u.push(`Gemini: ${s.error}`)}).catch(s=>{u.push(`Gemini: ${String(s)}`)})),t.deepseekKey&&T.push(e.socket.sendTo(y,"testApiConnection",{apiKey:t.deepseekKey,provider:"deepseek"}).then(s=>{s.models?k(s.models,"deepseek"):s.error&&u.push(`DeepSeek: ${s.error}`)}).catch(s=>{u.push(`DeepSeek: ${String(s)}`)})),await Promise.all(T),i!=null&&i.current)return;if(b.current=p,m.length>0){m.sort(),g(m);const s=window.localStorage.getItem("openai-model");s&&m.includes(s)?P(s):P(m[0])}u.length>0&&v(u.join("; "))}catch(t){console.error("Failed to fetch models:",t),i!=null&&i.current||v(o.I18n.t("Request failed: %s",String(t)))}i!=null&&i.current||d(!1)},[e.socket,e.runningInstances]);de(()=>{const i={current:!1};return V(i),()=>{i.current=!0}},[V]);const B=Z(async()=>{let i;L.current?i=L.current:(i=await ke(e.socket),L.current=i,console.log(`devices: ${JSON.stringify(i,null,2)}`));let t=A.current;t||(t=await re(e.socket,e.runningInstances),A.current=t);let y;if(w.current?y=w.current:(y=await Oe(),w.current=y),!t){U(!0);return}const m=b.current[C];if(!m){R(o.I18n.t("Please select a valid model"));return}let p,u;m==="anthropic"?(p=t.claudeKey,u=""):m==="gemini"?(p=t.geminiKey,u=""):m==="deepseek"?(p=t.deepseekKey,u=""):m==="custom"?(p=t.gptBaseUrlKey||"",u=t.gptBaseUrl||""):(p=t.gptKey,u="");const T=Object.keys(e.runningInstances)[0];if(!T){R(o.I18n.t("No running javascript instance found"));return}E(o.I18n.t("Planning...")),R(!1),N(""),M(!1),r("");try{const k=await e.socket.sendTo(T,"chatCompletion",{timeout:6e5,apiKey:p,baseUrl:u,model:C,provider:m,messages:[{role:"user",content:`Devices in my smart home: ${JSON.stringify(i)} I need a plan for this task: ${h} diff --git a/admin/assets/index-CEbKg781.js b/admin/assets/index-CEbKg781.js deleted file mode 100644 index b3e8b0c31..000000000 --- a/admin/assets/index-CEbKg781.js +++ /dev/null @@ -1,1230 +0,0 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-Cd8FZ0ou.js","./createSvgIcon-DPvF8xqu.js","./iobroker_javascript__loadShare__react__loadShare__.mjs-CTZOFJS2.js","./iobroker_javascript__loadShare__react__loadShare__.mjs_commonjs-proxy-CE9lvhW8.js","./iobroker_javascript__loadShare__prop_mf_2_types__loadShare__.mjs-BCtSFofY.js","./iobroker_javascript__loadShare___mf_0_iobroker_mf_1_adapter_mf_2_react_mf_2_v5__loadShare__.mjs-DkBjPSMw.js","./iobroker_javascript__loadShare___mf_0_mui_mf_1_material__loadShare__.mjs-QWG5Arqe.js","./index-C49cpVll.js","./virtual_mf-REMOTE_ENTRY_ID_iobroker_javascript__remoteEntry_js-s4ROfmWJ.js","./preload-helper-BDBacUwf.js","./iobroker_javascript__loadShare__react_mf_2_dom__loadShare__.mjs_commonjs-proxy-RQRRZMX5.js","./iobroker_javascript__loadShare__react_mf_2_dom__loadShare__.mjs-DeVAS-oa.js","./inheritsLoose-B0Ba5G9z.js","./index-BCK6q-N6.css","./index-CZzmETwg.js","./ScriptEditorVanillaMonaco-DSYvOslZ.js","./ScriptEditor-C-fO5h68.js","./Save-Cld9qv9i.js","./OpenAiDialog-BliYIniL.js","./index-gIA8x-8f.js"])))=>i.map(i=>d[i]); -import{d as Xy}from"./virtual_mf-REMOTE_ENTRY_ID_iobroker_javascript__remoteEntry_js-s4ROfmWJ.js";import{j as g,c as ht,g as Cw,r as Tw,_ as Tg,i as Zy}from"./createSvgIcon-DPvF8xqu.js";import{r as Ek}from"./iobroker_javascript__loadShare__react_mf_2_dom__loadShare__.mjs_commonjs-proxy-RQRRZMX5.js";import{a as Y,_ as Ik,b as Bo,c as Mt,d as xk,e as kw,f as kg,g as rm,h as am,i as lm,j as vt,k as _n,l as rs,m as Xr,n as Sw,o as Sg,p as Dk,q as Ak,r as Ew,s as Rk,t as pn}from"./iobroker_javascript__loadShare__react__loadShare__.mjs-CTZOFJS2.js";import{_ as Gt,a as as,b as Vt,c as vo,d as _i,e as Eg,f as wi,g as Ge,h as Kt,i as De,j as Yl,k as Jl,l as ql,m as Xl,n as Zl,o as Me,p as Iw,q as $i,r as Ig,s as Qy,t as xg,u as Dg,v as Dn,w as xw,x as Ok,y as cm,z as $t,A as Mk,B as e_,C as Nk,D as Yp,E as bc,F as Lk,G as Pk,H as Bk,I as jk,J as Dw,K as Fk,L as zk,M as t_,N as gn,O as Uk,P as Hk,Q as Wk,R as Gk,S as Vk,T as Aw,U as Kk,V as Ag,W as Rw,X as Yk}from"./iobroker_javascript__loadShare___mf_0_mui_mf_1_material__loadShare__.mjs-QWG5Arqe.js";import{_ as b}from"./iobroker_javascript__loadShare___mf_0_iobroker_mf_1_adapter_mf_2_react_mf_2_v5__loadShare__.mjs-DkBjPSMw.js";import{I as zo,a as qs,b as dc,C as Jk,c as Ow,F as qk,d as Xk,e as vc,f as Rg,g as Zk,h as Qk,i as eS,j as tS,M as sS,k as oS,l as iS,m as nS,_ as rS,n as Ql,o as aS,p as lS,q as ec,r as s_,s as cS,t as uS,u as dS,v as hS,w as o_,x as Wc,y as pS,z as gS,A as mS,B as fS,D as $S,E as bS,G as vS,H as Mw,J as Nw,K as Lw,L as yS,N as _S,O as wS,P as CS,Q as TS,R as kS}from"./index-C49cpVll.js";import{y as SS,_ as ES,a as IS,m as xS,S as i_,T as n_}from"./inheritsLoose-B0Ba5G9z.js";import{c as wn}from"./iobroker_javascript__loadShare__react__loadShare__.mjs_commonjs-proxy-CE9lvhW8.js";function Si(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}import{_ as On}from"./preload-helper-BDBacUwf.js";import{P as Z}from"./iobroker_javascript__loadShare__prop_mf_2_types__loadShare__.mjs-BCtSFofY.js";import{_ as DS}from"./iobroker_javascript__loadShare__react_mf_2_dom__loadShare__.mjs-DeVAS-oa.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const l of document.querySelectorAll('link[rel="modulepreload"]'))r(l);new MutationObserver(l=>{for(const u of l)if(u.type==="childList")for(const d of u.addedNodes)d.tagName==="LINK"&&d.rel==="modulepreload"&&r(d)}).observe(document,{childList:!0,subtree:!0});function i(l){const u={};return l.integrity&&(u.integrity=l.integrity),l.referrerPolicy&&(u.referrerPolicy=l.referrerPolicy),l.crossOrigin==="use-credentials"?u.credentials="include":l.crossOrigin==="anonymous"?u.credentials="omit":u.credentials="same-origin",u}function r(l){if(l.ep)return;l.ep=!0;const u=i(l);fetch(l.href,u)}})();var Pw,r_=Ek;Pw=r_.createRoot,r_.hydrateRoot;var Bw={exports:{}},rt={};var Gc=60103,Vc=60106,Zr=60107,Qr=60108,ea=60114,ta=60109,sa=60110,oa=60112,ia=60113,um=60120,na=60115,ra=60116,jw=60121,Fw=60122,zw=60117,Uw=60129,Hw=60131;if(typeof Symbol=="function"&&Symbol.for){var Rt=Symbol.for;Gc=Rt("react.element"),Vc=Rt("react.portal"),Zr=Rt("react.fragment"),Qr=Rt("react.strict_mode"),ea=Rt("react.profiler"),ta=Rt("react.provider"),sa=Rt("react.context"),oa=Rt("react.forward_ref"),ia=Rt("react.suspense"),um=Rt("react.suspense_list"),na=Rt("react.memo"),ra=Rt("react.lazy"),jw=Rt("react.block"),Fw=Rt("react.server.block"),zw=Rt("react.fundamental"),Uw=Rt("react.debug_trace_mode"),Hw=Rt("react.legacy_hidden")}function Rs(a){if(typeof a=="object"&&a!==null){var s=a.$$typeof;switch(s){case Gc:switch(a=a.type,a){case Zr:case ea:case Qr:case ia:case um:return a;default:switch(a=a&&a.$$typeof,a){case sa:case oa:case ra:case na:case ta:return a;default:return s}}case Vc:return s}}}var AS=ta,RS=Gc,OS=oa,MS=Zr,NS=ra,LS=na,PS=Vc,BS=ea,jS=Qr,FS=ia;rt.ContextConsumer=sa;rt.ContextProvider=AS;rt.Element=RS;rt.ForwardRef=OS;rt.Fragment=MS;rt.Lazy=NS;rt.Memo=LS;rt.Portal=PS;rt.Profiler=BS;rt.StrictMode=jS;rt.Suspense=FS;rt.isAsyncMode=function(){return!1};rt.isConcurrentMode=function(){return!1};rt.isContextConsumer=function(a){return Rs(a)===sa};rt.isContextProvider=function(a){return Rs(a)===ta};rt.isElement=function(a){return typeof a=="object"&&a!==null&&a.$$typeof===Gc};rt.isForwardRef=function(a){return Rs(a)===oa};rt.isFragment=function(a){return Rs(a)===Zr};rt.isLazy=function(a){return Rs(a)===ra};rt.isMemo=function(a){return Rs(a)===na};rt.isPortal=function(a){return Rs(a)===Vc};rt.isProfiler=function(a){return Rs(a)===ea};rt.isStrictMode=function(a){return Rs(a)===Qr};rt.isSuspense=function(a){return Rs(a)===ia};rt.isValidElementType=function(a){return typeof a=="string"||typeof a=="function"||a===Zr||a===ea||a===Uw||a===Qr||a===ia||a===um||a===Hw||typeof a=="object"&&a!==null&&(a.$$typeof===ra||a.$$typeof===na||a.$$typeof===ta||a.$$typeof===sa||a.$$typeof===oa||a.$$typeof===zw||a.$$typeof===jw||a[0]===Fw)};rt.typeOf=Rs;Bw.exports=rt;var zS=Bw.exports;function yc(a,s){const i=getComputedStyle(s);if(!i)return;let r=a===dt.Horizontal?s.clientWidth:s.clientHeight;return r!==0?(a===dt.Horizontal?r-=parseFloat(i.paddingLeft)+parseFloat(i.paddingRight):r-=parseFloat(i.paddingTop)+parseFloat(i.paddingBottom),r):void 0}function tc(a,s,i=[],r={condition:!0}){const{condition:l}=r,u=(function(d,p){var m={};for(var f in d)Object.prototype.hasOwnProperty.call(d,f)&&p.indexOf(f)<0&&(m[f]=d[f]);if(d!=null&&typeof Object.getOwnPropertySymbols=="function"){var v=0;for(f=Object.getOwnPropertySymbols(d);v(l&&window.addEventListener(a,s,u),()=>{l&&window.removeEventListener(a,s)})),[a,s,l,...i])}(function(a,s){s===void 0&&(s={});var i=s.insertAt;if(typeof document<"u"){var r=document.head||document.getElementsByTagName("head")[0],l=document.createElement("style");l.type="text/css",i==="top"&&r.firstChild?r.insertBefore(l,r.firstChild):r.appendChild(l),l.styleSheet?l.styleSheet.cssText=a:l.appendChild(document.createTextNode(a))}})(`/* === Main Container === */ -.__dbk__container { - height: 100%; - width: 100%; - - display: flex; - overflow: hidden; -} - -.__dbk__container.Horizontal { - flex-direction: row; -} - -.__dbk__container.Vertical { - flex-direction: column; -} -/* ====== */ - -/* === Wrapper for each child element === */ -.__dbk__child-wrapper { - height: 100%; - width: 100%; -} -/* ====== */ - -/* === Gutter === */ -.__dbk__gutter { - display: flex; - align-items: center; - justify-content: center; -} -/* .__dbk__gutter > div { - background: red; -} */ -.__dbk__gutter.Horizontal { - height: 100%; - padding: 0 2px; - flex-direction: column; -} -.__dbk__gutter.Horizontal:hover { - cursor: col-resize; -} - -.__dbk__gutter.Vertical { - width: 100%; - padding: 2px 0; - flex-direction: row; -} -.__dbk__gutter.Vertical:hover { - cursor: row-resize; -} - -.__dbk__gutter.Light { - background: #EDF0EF; -} -.__dbk__gutter.Light:hover > .__dbk__dragger { - background: #76747B; -} - -.__dbk__gutter.Dark { - background: #020203; -} -.__dbk__gutter.Dark:hover > .__dbk__dragger { - background: #9995A3; -} -/* ====== */ - -/* === Gutter's Dragger === */ -.__dbk__dragger { - border-radius: 2px; -} - -.__dbk__dragger.Horizontal { - width: 4px; - height: 24px; -} - -.__dbk__dragger.Vertical { - width: 24px; - height: 4px; -} - -.__dbk__dragger.Light { - background: #A6ACB5; -} - -.__dbk__dragger.Dark { - background: #434252; -} -/* ====== */`);const US=Y.forwardRef((({className:a,theme:s,draggerClassName:i,direction:r=dt.Vertical,onDragging:l},u)=>{const d=`__dbk__gutter ${r} ${a||s}`,p=`__dbk__dragger ${r} ${i||s}`;return g.jsx("div",Object.assign({className:d,ref:u,dir:r,onMouseDown:l,onTouchStart:hc?l:void 0},{children:g.jsx("div",{className:p},void 0)}),void 0)}));var vs;function Og(a,s,i){let r,l;return s?(r=a/2,l=a):i?(r=a,l=a/2):(r=a,l=a),{aGutterSize:r,bGutterSize:l}}function HS(a,s){switch(s.type){case vs.SetIsReadyToCompute:return Object.assign(Object.assign({},a),{isReady:s.payload.isReady});case vs.CreatePairs:{const{direction:i,children:r,gutters:l}=s.payload,u=r[0].parentNode;if(!u)throw new Error("Cannot create pairs - parent is undefined.");const d=yc(i,u);if(d===void 0)throw new Error(`Cannot create pairs - parent has undefined or zero size: ${d}.`);const p=[];return r.forEach(((m,f)=>{if(f>0){const v=r[f-1],_=r[f],y=l[f-1],k=i===dt.Horizontal?v.getBoundingClientRect().left:v.getBoundingClientRect().top,C=i===dt.Horizontal?_.getBoundingClientRect().right:_.getBoundingClientRect().bottom,w=i===dt.Horizontal?v.getBoundingClientRect().width+y.getBoundingClientRect().width+_.getBoundingClientRect().width:v.getBoundingClientRect().height+y.getBoundingClientRect().height+_.getBoundingClientRect().height,E=i===dt.Horizontal?y.getBoundingClientRect().width:y.getBoundingClientRect().height,R={idx:f-1,a:v,b:_,gutter:y,parent:u,start:k,end:C,size:w,gutterSize:E,aSizePct:100/r.length,bSizePct:100/r.length};p.push(R)}})),Object.assign(Object.assign({},a),{pairs:p})}case vs.StartDragging:{const{gutterIdx:i}=s.payload;return Object.assign(Object.assign({},a),{isDragging:!0,draggingIdx:i})}case vs.StopDragging:return Object.assign(Object.assign({},a),{isDragging:!1});case vs.CalculateSizes:{const{direction:i,gutterIdx:r}=s.payload,l=a.pairs[r],u=yc(i,l.parent);if(!u)throw new Error("Cannot calculate sizes - 'pair.parent' has undefined or zero size.");const d=l.gutter[i===dt.Horizontal?"clientWidth":"clientHeight"],p=r===0,m=r===a.pairs.length-1,{aGutterSize:f,bGutterSize:v}=Og(d,p,m);let _,y,k,C,w;return i===dt.Horizontal?(_=l.a.getBoundingClientRect().left,y=l.b.getBoundingClientRect().right,C=(l.a.getBoundingClientRect().width+f)/u*100,w=(l.b.getBoundingClientRect().width+v)/u*100,k=l.a.getBoundingClientRect().width+f+v+l.b.getBoundingClientRect().width):(_=l.a.getBoundingClientRect().top,y=l.b.getBoundingClientRect().bottom,C=(l.a.getBoundingClientRect().height+f)/u*100,w=(l.b.getBoundingClientRect().height+v)/u*100,k=l.a.getBoundingClientRect().height+f+v+l.b.getBoundingClientRect().height),a.pairs[r]=Object.assign(Object.assign({},l),{start:_,end:y,size:k,aSizePct:C,bSizePct:w,gutterSize:d}),Object.assign({},a)}default:return a}}function Ww(a,s=0,i=[]){return xk.toArray(a).reduce(((r,l,u)=>(zS.isFragment(l)?r.push.apply(r,Ww(l.props.children,s+1,i.concat(l.key||u))):kw(l)?r.push(kg(l,{key:i.concat(String(l.key)).join(".")})):typeof l!="string"&&typeof l!="number"||r.push(l),r)),[])}(function(a){a[a.SetIsReadyToCompute=0]="SetIsReadyToCompute",a[a.CreatePairs=1]="CreatePairs",a[a.CalculateSizes=2]="CalculateSizes",a[a.StartDragging=3]="StartDragging",a[a.StopDragging=4]="StopDragging"})(vs||(vs={}));const a_=a=>"changedTouches"in a;var dt,Mg;(function(a){a.Horizontal="Horizontal",a.Vertical="Vertical"})(dt||(dt={})),(function(a){a.Light="Light",a.Dark="Dark"})(Mg||(Mg={}));const hc=typeof window<"u"&&"ontouchstart"in window;function Jp(a){return a===dt.Horizontal?"col-resize":"row-resize"}const WS={isReady:!1,isDragging:!1,pairs:[]};function l_({direction:a=dt.Horizontal,minWidths:s=[],minHeights:i=[],initialSizes:r,gutterTheme:l=Mg.Dark,gutterClassName:u,draggerClassName:d,children:p,onResizeStarted:m,onResizeFinished:f,classes:v=[]}){const _=Ww(p),[y,k]=Ik(HS,WS),C=Bo(null),w=Bo([]),E=Bo([]);w.current=[],E.current=[];const R=Y.useCallback((ae=>{k({type:vs.SetIsReadyToCompute,payload:{isReady:ae}})}),[]),D=Y.useCallback(((ae,ce)=>{k({type:vs.StartDragging,payload:{gutterIdx:ce}});const K=y.pairs[ce];m==null||m(K.idx),K.a.style.userSelect="none",K.b.style.userSelect="none",K.gutter.style.cursor=Jp(ae),K.parent.style.cursor=Jp(ae),document.body.style.cursor=Jp(ae)}),[y.pairs]),A=Y.useCallback((()=>{k({type:vs.StopDragging});const ae=[];for(let K=0;K{k({type:vs.CalculateSizes,payload:{direction:ae,gutterIdx:ce}})}),[]),ie=Y.useCallback(((ae,ce,K)=>{k({type:vs.CreatePairs,payload:{direction:ae,children:ce,gutters:K}})}),[]),se=Y.useCallback(((ae,ce,K,ye)=>{const he=ce[0].parentNode;if(!he)throw new Error("Cannot set initial sizes - parent is undefined");if(yc(ae,he)===void 0)throw new Error("Cannot set initial sizes - parent has undefined size");ce.forEach(((je,V)=>{const tt=V===0,q=V===ce.length-1;let ee,B=0;ce.length>1&&(B=K[q?V-1:V].getBoundingClientRect()[ae===dt.Horizontal?"width":"height"],B=tt||q?B/2:B),ee=ye&&V{if(y.draggingIdx===void 0)throw new Error("Cannot adjust size - 'draggingIdx' is undefined");const K=y.pairs[y.draggingIdx];if(K.size===void 0)throw new Error("Cannot adjust size - 'pair.size' is undefined");if(K.gutterSize===void 0)throw new Error("Cannot adjust size - 'pair.gutterSize' is undefined");const ye=K.aSizePct+K.bSizePct,he=ce/K.size*ye,je=ye-ce/K.size*ye,V=y.draggingIdx===0,tt=y.draggingIdx===y.pairs.length-1,{aGutterSize:q,bGutterSize:ee}=Og(K.gutterSize,V,tt),B=`calc(${he}% - ${q}px)`,H=`calc(${je}% - ${ee}px)`;ae===dt.Horizontal?(K.a.style.width=B,K.b.style.width=H):(K.a.style.height=B,K.b.style.height=H)}),[y.draggingIdx,y.pairs,a]),z=Y.useCallback(((ae,ce,K)=>{if(!y.isDragging)return;if(y.draggingIdx===void 0)throw new Error("Cannot drag - 'draggingIdx' is undefined");const ye=y.pairs[y.draggingIdx];if(ye.start===void 0)throw new Error("Cannot drag - 'pair.start' is undefined");if(ye.size===void 0)throw new Error("Cannot drag - 'pair.size' is undefined");if(ye.gutterSize===void 0)throw new Error("Cannot drag - 'pair.gutterSize' is undefined");let he=(function(tt,q){const ee=a_(q)?q.changedTouches[0]:q;return tt===dt.Horizontal?ee.clientX:ee.clientY})(ce,ae)-ye.start,je=16,V=16;K.length>y.draggingIdx&&(je=K[y.draggingIdx]),K.length>=y.draggingIdx+1&&(V=K[y.draggingIdx+1]),he=ye.size-(ye.gutterSize+V)&&(he=ye.size-(ye.gutterSize+V)),me(ce,he)}),[y.isDragging,y.draggingIdx,y.pairs,me]),Oe=()=>{if(y.isDragging){if(y.draggingIdx===void 0)throw new Error("Cannot calculate sizes after dragging = 'state.draggingIdx' is undefined");J(a,y.draggingIdx),A()}},Ne=ae=>{y.isDragging&&(a_(ae)&&ae.preventDefault(),z(ae,a,a===dt.Horizontal?s:i))};function Ze(ae,ce){if(!ae.current)throw new Error("Can't add element to ref object - ref isn't initialized");ce&&!ae.current.includes(ce)&&ae.current.push(ce)}return tc("mouseup",Oe,[y.isDragging,A]),tc("mousemove",Ne,[a,y.isDragging,z,s,i]),tc("touchend",Oe,[y.isDragging,A],{condition:hc}),tc("touchmove",Ne,[a,y.isDragging,z,s,i],{condition:hc,passive:!hc}),Mt((function(){if(!C.current)return;const ae=C.current.parentElement;if(!ae)return;const ce=new ResizeObserver((()=>{const K=getComputedStyle(ae),ye=a===dt.Horizontal?ae.clientWidth:ae.clientHeight;R(!!K&&!!ye)}));return ce.observe(ae),()=>{ce.disconnect()}}),[C.current,a]),Mt((function(){if(y.isReady&&(!w.current||w.current[0].offsetParent)){if(!w.current||!E.current)throw new Error("Cannot create pairs - either variable 'childRefs' or 'gutterRefs' is undefined");_.length<=1?se(a,w.current,E.current,r):(se(a,w.current,E.current,r),ie(a,w.current,E.current))}}),[p,y.isReady,a,se,ie,r]),g.jsx("div",Object.assign({className:`__dbk__container ${a}`,ref:C},{children:y.isReady&&_.map(((ae,ce)=>g.jsxs(Y.Fragment,{children:[g.jsx("div",Object.assign({ref:K=>Ze(w,K),className:"__dbk__child-wrapper "+(ceZe(E,K),className:u,theme:l,draggerClassName:d,direction:a,onDragging:()=>{return J(a,K=ce),void D(a,K);var K}},void 0)]},ce)))}),void 0)}const Gw=rm({dragDropManager:void 0});function Vr(a){"@babel/helpers - typeof";return Vr=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(s){return typeof s}:function(s){return s&&typeof Symbol=="function"&&s.constructor===Symbol&&s!==Symbol.prototype?"symbol":typeof s},Vr(a)}function GS(a,s){if(Vr(a)!="object"||!a)return a;var i=a[Symbol.toPrimitive];if(i!==void 0){var r=i.call(a,s);if(Vr(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(s==="string"?String:Number)(a)}function VS(a){var s=GS(a,"string");return Vr(s)=="symbol"?s:s+""}function KS(a,s,i){return(s=VS(s))in a?Object.defineProperty(a,s,{value:i,enumerable:!0,configurable:!0,writable:!0}):a[s]=i,a}function ms(a){return"Minified Redux error #"+a+"; visit https://redux.js.org/Errors?code="+a+" for the full message or use the non-minified dev environment for full errors. "}var c_=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})(),u_=function(){return Math.random().toString(36).substring(7).split("").join(".")},d_={INIT:"@@redux/INIT"+u_(),REPLACE:"@@redux/REPLACE"+u_()};function YS(a){if(typeof a!="object"||a===null)return!1;for(var s=a;Object.getPrototypeOf(s)!==null;)s=Object.getPrototypeOf(s);return Object.getPrototypeOf(a)===s}function Vw(a,s,i){var r;if(typeof s=="function"&&typeof i=="function"||typeof i=="function"&&typeof arguments[3]=="function")throw new Error(ms(0));if(typeof s=="function"&&typeof i>"u"&&(i=s,s=void 0),typeof i<"u"){if(typeof i!="function")throw new Error(ms(1));return i(Vw)(a,s)}if(typeof a!="function")throw new Error(ms(2));var l=a,u=s,d=[],p=d,m=!1;function f(){p===d&&(p=d.slice())}function v(){if(m)throw new Error(ms(3));return u}function _(w){if(typeof w!="function")throw new Error(ms(4));if(m)throw new Error(ms(5));var E=!0;return f(),p.push(w),function(){if(E){if(m)throw new Error(ms(6));E=!1,f();var D=p.indexOf(w);p.splice(D,1),d=null}}}function y(w){if(!YS(w))throw new Error(ms(7));if(typeof w.type>"u")throw new Error(ms(8));if(m)throw new Error(ms(9));try{m=!0,u=l(u,w)}finally{m=!1}for(var E=d=p,R=0;Rr&&r[l]?r[l]:i||null,a)}function XS(a,s){return a.filter(i=>i!==s)}function Kw(a){return typeof a=="object"}function ZS(a,s){const i=new Map,r=u=>{i.set(u,i.has(u)?i.get(u)+1:1)};a.forEach(r),s.forEach(r);const l=[];return i.forEach((u,d)=>{u===1&&l.push(d)}),l}function QS(a,s){return a.filter(i=>s.indexOf(i)>-1)}const dm="dnd-core/INIT_COORDS",Kc="dnd-core/BEGIN_DRAG",hm="dnd-core/PUBLISH_DRAG_SOURCE",Yc="dnd-core/HOVER",Jc="dnd-core/DROP",qc="dnd-core/END_DRAG";function h_(a,s){return{type:dm,payload:{sourceClientOffset:s||null,clientOffset:a||null}}}const eE={type:dm,payload:{clientOffset:null,sourceClientOffset:null}};function tE(a){return function(i=[],r={publishSource:!0}){const{publishSource:l=!0,clientOffset:u,getSourceClientOffset:d}=r,p=a.getMonitor(),m=a.getRegistry();a.dispatch(h_(u)),sE(i,p,m);const f=nE(i,p);if(f==null){a.dispatch(eE);return}let v=null;if(u){if(!d)throw new Error("getSourceClientOffset must be defined");oE(d),v=d(f)}a.dispatch(h_(u,v));const y=m.getSource(f).beginDrag(p,f);if(y==null)return;iE(y),m.pinSource(f);const k=m.getSourceType(f);return{type:Kc,payload:{itemType:k,item:y,sourceId:f,clientOffset:u||null,sourceClientOffset:v||null,isSourcePublic:!!l}}}}function sE(a,s,i){Ie(!s.isDragging(),"Cannot call beginDrag while dragging."),a.forEach(function(r){Ie(i.getSource(r),"Expected sourceIds to be registered.")})}function oE(a){Ie(typeof a=="function","When clientOffset is provided, getSourceClientOffset must be a function.")}function iE(a){Ie(Kw(a),"Item must be an object.")}function nE(a,s){let i=null;for(let r=a.length-1;r>=0;r--)if(s.canDragSource(a[r])){i=a[r];break}return i}function rE(a,s,i){return s in a?Object.defineProperty(a,s,{value:i,enumerable:!0,configurable:!0,writable:!0}):a[s]=i,a}function aE(a){for(var s=1;s{const m=uE(d,p,l,r),f={type:Jc,payload:{dropResult:aE({},i,m)}};a.dispatch(f)})}}function cE(a){Ie(a.isDragging(),"Cannot call drop while not dragging."),Ie(!a.didDrop(),"Cannot call drop twice during one drag operation.")}function uE(a,s,i,r){const l=i.getTarget(a);let u=l?l.drop(r,a):void 0;return dE(u),typeof u>"u"&&(u=s===0?{}:r.getDropResult()),u}function dE(a){Ie(typeof a>"u"||Kw(a),"Drop result must either be an object or undefined.")}function hE(a){const s=a.getTargetIds().filter(a.canDropOnTarget,a);return s.reverse(),s}function pE(a){return function(){const i=a.getMonitor(),r=a.getRegistry();gE(i);const l=i.getSourceId();return l!=null&&(r.getSource(l,!0).endDrag(i,l),r.unpinSource()),{type:qc}}}function gE(a){Ie(a.isDragging(),"Cannot call endDrag while not dragging.")}function Ng(a,s){return s===null?a===null:Array.isArray(a)?a.some(i=>i===s):a===s}function mE(a){return function(i,{clientOffset:r}={}){fE(i);const l=i.slice(0),u=a.getMonitor(),d=a.getRegistry(),p=u.getItemType();return bE(l,d,p),$E(l,u,d),vE(l,u,d),{type:Yc,payload:{targetIds:l,clientOffset:r||null}}}}function fE(a){Ie(Array.isArray(a),"Expected targetIds to be an array.")}function $E(a,s,i){Ie(s.isDragging(),"Cannot call hover while not dragging."),Ie(!s.didDrop(),"Cannot call hover after drop.");for(let r=0;r=0;r--){const l=a[r],u=s.getTargetType(l);Ng(u,i)||a.splice(r,1)}}function vE(a,s,i){a.forEach(function(r){i.getTarget(r).hover(s,r)})}function yE(a){return function(){if(a.getMonitor().isDragging())return{type:hm}}}function _E(a){return{beginDrag:tE(a),publishDragSource:yE(a),hover:mE(a),drop:lE(a),endDrag:pE(a)}}class wE{receiveBackend(s){this.backend=s}getMonitor(){return this.monitor}getBackend(){return this.backend}getRegistry(){return this.monitor.registry}getActions(){const s=this,{dispatch:i}=this.store;function r(u){return(...d)=>{const p=u.apply(s,d);typeof p<"u"&&i(p)}}const l=_E(this);return Object.keys(l).reduce((u,d)=>{const p=l[d];return u[d]=r(p),u},{})}dispatch(s){this.store.dispatch(s)}constructor(s,i){this.isSetUp=!1,this.handleRefCountChange=()=>{const r=this.store.getState().refCount>0;this.backend&&(r&&!this.isSetUp?(this.backend.setup(),this.isSetUp=!0):!r&&this.isSetUp&&(this.backend.teardown(),this.isSetUp=!1))},this.store=s,this.monitor=i,s.subscribe(this.handleRefCountChange)}}function CE(a,s){return{x:a.x+s.x,y:a.y+s.y}}function Yw(a,s){return{x:a.x-s.x,y:a.y-s.y}}function TE(a){const{clientOffset:s,initialClientOffset:i,initialSourceClientOffset:r}=a;return!s||!i||!r?null:Yw(CE(s,r),i)}function kE(a){const{clientOffset:s,initialClientOffset:i}=a;return!s||!i?null:Yw(s,i)}const Fr=[],pm=[];Fr.__IS_NONE__=!0;pm.__IS_ALL__=!0;function SE(a,s){return a===Fr?!1:a===pm||typeof s>"u"?!0:QS(s,a).length>0}class EE{subscribeToStateChange(s,i={}){const{handlerIds:r}=i;Ie(typeof s=="function","listener must be a function."),Ie(typeof r>"u"||Array.isArray(r),"handlerIds, when specified, must be an array of strings.");let l=this.store.getState().stateId;const u=()=>{const d=this.store.getState(),p=d.stateId;try{p===l||p===l+1&&!SE(d.dirtyHandlerIds,r)||s()}finally{l=p}};return this.store.subscribe(u)}subscribeToOffsetChange(s){Ie(typeof s=="function","listener must be a function.");let i=this.store.getState().dragOffset;const r=()=>{const l=this.store.getState().dragOffset;l!==i&&(i=l,s())};return this.store.subscribe(r)}canDragSource(s){if(!s)return!1;const i=this.registry.getSource(s);return Ie(i,`Expected to find a valid source. sourceId=${s}`),this.isDragging()?!1:i.canDrag(this,s)}canDropOnTarget(s){if(!s)return!1;const i=this.registry.getTarget(s);if(Ie(i,`Expected to find a valid target. targetId=${s}`),!this.isDragging()||this.didDrop())return!1;const r=this.registry.getTargetType(s),l=this.getItemType();return Ng(r,l)&&i.canDrop(this,s)}isDragging(){return!!this.getItemType()}isDraggingSource(s){if(!s)return!1;const i=this.registry.getSource(s,!0);if(Ie(i,`Expected to find a valid source. sourceId=${s}`),!this.isDragging()||!this.isSourcePublic())return!1;const r=this.registry.getSourceType(s),l=this.getItemType();return r!==l?!1:i.isDragging(this,s)}isOverTarget(s,i={shallow:!1}){if(!s)return!1;const{shallow:r}=i;if(!this.isDragging())return!1;const l=this.registry.getTargetType(s),u=this.getItemType();if(u&&!Ng(l,u))return!1;const d=this.getTargetIds();if(!d.length)return!1;const p=d.indexOf(s);return r?p===d.length-1:p>-1}getItemType(){return this.store.getState().dragOperation.itemType}getItem(){return this.store.getState().dragOperation.item}getSourceId(){return this.store.getState().dragOperation.sourceId}getTargetIds(){return this.store.getState().dragOperation.targetIds}getDropResult(){return this.store.getState().dragOperation.dropResult}didDrop(){return this.store.getState().dragOperation.didDrop}isSourcePublic(){return!!this.store.getState().dragOperation.isSourcePublic}getInitialClientOffset(){return this.store.getState().dragOffset.initialClientOffset}getInitialSourceClientOffset(){return this.store.getState().dragOffset.initialSourceClientOffset}getClientOffset(){return this.store.getState().dragOffset.clientOffset}getSourceClientOffset(){return TE(this.store.getState().dragOffset)}getDifferenceFromInitialOffset(){return kE(this.store.getState().dragOffset)}constructor(s,i){this.store=s,this.registry=i}}const p_=typeof global<"u"?global:self,Jw=p_.MutationObserver||p_.WebKitMutationObserver;function qw(a){return function(){const i=setTimeout(l,0),r=setInterval(l,50);function l(){clearTimeout(i),clearInterval(r),a()}}}function IE(a){let s=1;const i=new Jw(a),r=document.createTextNode("");return i.observe(r,{characterData:!0}),function(){s=-s,r.data=s}}const xE=typeof Jw=="function"?IE:qw;class DE{enqueueTask(s){const{queue:i,requestFlush:r}=this;i.length||(r(),this.flushing=!0),i[i.length]=s}constructor(){this.queue=[],this.pendingErrors=[],this.flushing=!1,this.index=0,this.capacity=1024,this.flush=()=>{const{queue:s}=this;for(;this.indexthis.capacity){for(let r=0,l=s.length-this.index;r{this.pendingErrors.push(s),this.requestErrorThrow()},this.requestFlush=xE(this.flush),this.requestErrorThrow=qw(()=>{if(this.pendingErrors.length)throw this.pendingErrors.shift()})}}class AE{call(){try{this.task&&this.task()}catch(s){this.onError(s)}finally{this.task=null,this.release(this)}}constructor(s,i){this.onError=s,this.release=i,this.task=null}}class RE{create(s){const i=this.freeTasks,r=i.length?i.pop():new AE(this.onError,l=>i[i.length]=l);return r.task=s,r}constructor(s){this.onError=s,this.freeTasks=[]}}const Xw=new DE,OE=new RE(Xw.registerPendingError);function ME(a){Xw.enqueueTask(OE.create(a))}const gm="dnd-core/ADD_SOURCE",mm="dnd-core/ADD_TARGET",fm="dnd-core/REMOVE_SOURCE",Xc="dnd-core/REMOVE_TARGET";function NE(a){return{type:gm,payload:{sourceId:a}}}function LE(a){return{type:mm,payload:{targetId:a}}}function PE(a){return{type:fm,payload:{sourceId:a}}}function BE(a){return{type:Xc,payload:{targetId:a}}}function jE(a){Ie(typeof a.canDrag=="function","Expected canDrag to be a function."),Ie(typeof a.beginDrag=="function","Expected beginDrag to be a function."),Ie(typeof a.endDrag=="function","Expected endDrag to be a function.")}function FE(a){Ie(typeof a.canDrop=="function","Expected canDrop to be a function."),Ie(typeof a.hover=="function","Expected hover to be a function."),Ie(typeof a.drop=="function","Expected beginDrag to be a function.")}function Lg(a,s){if(s&&Array.isArray(a)){a.forEach(i=>Lg(i,!1));return}Ie(typeof a=="string"||typeof a=="symbol",s?"Type can only be a string, a symbol, or an array of either.":"Type can only be a string or a symbol.")}var bs;(function(a){a.SOURCE="SOURCE",a.TARGET="TARGET"})(bs||(bs={}));let zE=0;function UE(){return zE++}function HE(a){const s=UE().toString();switch(a){case bs.SOURCE:return`S${s}`;case bs.TARGET:return`T${s}`;default:throw new Error(`Unknown Handler Role: ${a}`)}}function g_(a){switch(a[0]){case"S":return bs.SOURCE;case"T":return bs.TARGET;default:throw new Error(`Cannot parse handler ID: ${a}`)}}function m_(a,s){const i=a.entries();let r=!1;do{const{done:l,value:[,u]}=i.next();if(u===s)return!0;r=!!l}while(!r);return!1}class WE{addSource(s,i){Lg(s),jE(i);const r=this.addHandler(bs.SOURCE,s,i);return this.store.dispatch(NE(r)),r}addTarget(s,i){Lg(s,!0),FE(i);const r=this.addHandler(bs.TARGET,s,i);return this.store.dispatch(LE(r)),r}containsHandler(s){return m_(this.dragSources,s)||m_(this.dropTargets,s)}getSource(s,i=!1){return Ie(this.isSourceId(s),"Expected a valid source ID."),i&&s===this.pinnedSourceId?this.pinnedSource:this.dragSources.get(s)}getTarget(s){return Ie(this.isTargetId(s),"Expected a valid target ID."),this.dropTargets.get(s)}getSourceType(s){return Ie(this.isSourceId(s),"Expected a valid source ID."),this.types.get(s)}getTargetType(s){return Ie(this.isTargetId(s),"Expected a valid target ID."),this.types.get(s)}isSourceId(s){return g_(s)===bs.SOURCE}isTargetId(s){return g_(s)===bs.TARGET}removeSource(s){Ie(this.getSource(s),"Expected an existing source."),this.store.dispatch(PE(s)),ME(()=>{this.dragSources.delete(s),this.types.delete(s)})}removeTarget(s){Ie(this.getTarget(s),"Expected an existing target."),this.store.dispatch(BE(s)),this.dropTargets.delete(s),this.types.delete(s)}pinSource(s){const i=this.getSource(s);Ie(i,"Expected an existing source."),this.pinnedSourceId=s,this.pinnedSource=i}unpinSource(){Ie(this.pinnedSource,"No source is pinned at the time."),this.pinnedSourceId=null,this.pinnedSource=null}addHandler(s,i,r){const l=HE(s);return this.types.set(l,i),s===bs.SOURCE?this.dragSources.set(l,r):s===bs.TARGET&&this.dropTargets.set(l,r),l}constructor(s){this.types=new Map,this.dragSources=new Map,this.dropTargets=new Map,this.pinnedSourceId=null,this.pinnedSource=null,this.store=s}}const GE=(a,s)=>a===s;function VE(a,s){return!a&&!s?!0:!a||!s?!1:a.x===s.x&&a.y===s.y}function KE(a,s,i=GE){if(a.length!==s.length)return!1;for(let r=0;r0||!KE(i,r)))return Fr;const d=r[r.length-1],p=i[i.length-1];return d!==p&&(d&&l.push(d),p&&l.push(p)),l}function JE(a,s,i){return s in a?Object.defineProperty(a,s,{value:i,enumerable:!0,configurable:!0,writable:!0}):a[s]=i,a}function qE(a){for(var s=1;s=0)&&Object.prototype.propertyIsEnumerable.call(a,r)&&(i[r]=a[r])}return i}function cI(a,s){if(a==null)return{};var i={},r=Object.keys(a),l,u;for(u=0;u=0)&&(i[l]=a[l]);return i}let $_=0;const pc=Symbol.for("__REACT_DND_CONTEXT_INSTANCE__");var Zw=am(function(s){var{children:i}=s,r=lI(s,["children"]);const[l,u]=uI(r);return Mt(()=>{if(u){const d=Qw();return++$_,()=>{--$_===0&&(d[pc]=null)}}},[]),g.jsx(Gw.Provider,{value:l,children:i})});function uI(a){if("manager"in a)return[{dragDropManager:a.manager},!1];const s=dI(a.backend,a.context,a.options,a.debugMode),i=!a.context;return[s,i]}function dI(a,s=Qw(),i,r){const l=s;return l[pc]||(l[pc]={dragDropManager:rI(a,s,i,r)}),l[pc]}function Qw(){return typeof global<"u"?global:window}var hI=function a(s,i){if(s===i)return!0;if(s&&i&&typeof s=="object"&&typeof i=="object"){if(s.constructor!==i.constructor)return!1;var r,l,u;if(Array.isArray(s)){if(r=s.length,r!=i.length)return!1;for(l=r;l--!==0;)if(!a(s[l],i[l]))return!1;return!0}if(s.constructor===RegExp)return s.source===i.source&&s.flags===i.flags;if(s.valueOf!==Object.prototype.valueOf)return s.valueOf()===i.valueOf();if(s.toString!==Object.prototype.toString)return s.toString()===i.toString();if(u=Object.keys(s),r=u.length,r!==Object.keys(i).length)return!1;for(l=r;l--!==0;)if(!Object.prototype.hasOwnProperty.call(i,u[l]))return!1;for(l=r;l--!==0;){var d=u[l];if(!a(s[d],i[d]))return!1}return!0}return s!==s&&i!==i};const pI=Si(hI),Ci=typeof window<"u"?lm:Mt;function gI(a,s,i){const[r,l]=vt(()=>s(a)),u=_n(()=>{const d=s(a);pI(r,d)||(l(d),i&&i())},[r,a,i]);return Ci(u),[r,u]}function mI(a,s,i){const[r,l]=gI(a,s,i);return Ci(function(){const d=a.getHandlerId();if(d!=null)return a.subscribeToStateChange(l,{handlerIds:[d]})},[a,l]),r}function eC(a,s,i){return mI(s,a||(()=>({})),()=>i.reconnect())}function tC(a,s){const i=[];return typeof a!="function"&&i.push(a),rs(()=>typeof a=="function"?a():a,i)}function fI(a){return rs(()=>a.hooks.dragSource(),[a])}function $I(a){return rs(()=>a.hooks.dragPreview(),[a])}let qp=!1,Xp=!1;class bI{receiveHandlerId(s){this.sourceId=s}getHandlerId(){return this.sourceId}canDrag(){Ie(!qp,"You may not call monitor.canDrag() inside your canDrag() implementation. Read more: http://react-dnd.github.io/react-dnd/docs/api/drag-source-monitor");try{return qp=!0,this.internalMonitor.canDragSource(this.sourceId)}finally{qp=!1}}isDragging(){if(!this.sourceId)return!1;Ie(!Xp,"You may not call monitor.isDragging() inside your isDragging() implementation. Read more: http://react-dnd.github.io/react-dnd/docs/api/drag-source-monitor");try{return Xp=!0,this.internalMonitor.isDraggingSource(this.sourceId)}finally{Xp=!1}}subscribeToStateChange(s,i){return this.internalMonitor.subscribeToStateChange(s,i)}isDraggingSource(s){return this.internalMonitor.isDraggingSource(s)}isOverTarget(s,i){return this.internalMonitor.isOverTarget(s,i)}getTargetIds(){return this.internalMonitor.getTargetIds()}isSourcePublic(){return this.internalMonitor.isSourcePublic()}getSourceId(){return this.internalMonitor.getSourceId()}subscribeToOffsetChange(s){return this.internalMonitor.subscribeToOffsetChange(s)}canDragSource(s){return this.internalMonitor.canDragSource(s)}canDropOnTarget(s){return this.internalMonitor.canDropOnTarget(s)}getItemType(){return this.internalMonitor.getItemType()}getItem(){return this.internalMonitor.getItem()}getDropResult(){return this.internalMonitor.getDropResult()}didDrop(){return this.internalMonitor.didDrop()}getInitialClientOffset(){return this.internalMonitor.getInitialClientOffset()}getInitialSourceClientOffset(){return this.internalMonitor.getInitialSourceClientOffset()}getSourceClientOffset(){return this.internalMonitor.getSourceClientOffset()}getClientOffset(){return this.internalMonitor.getClientOffset()}getDifferenceFromInitialOffset(){return this.internalMonitor.getDifferenceFromInitialOffset()}constructor(s){this.sourceId=null,this.internalMonitor=s.getMonitor()}}let Zp=!1;class vI{receiveHandlerId(s){this.targetId=s}getHandlerId(){return this.targetId}subscribeToStateChange(s,i){return this.internalMonitor.subscribeToStateChange(s,i)}canDrop(){if(!this.targetId)return!1;Ie(!Zp,"You may not call monitor.canDrop() inside your canDrop() implementation. Read more: http://react-dnd.github.io/react-dnd/docs/api/drop-target-monitor");try{return Zp=!0,this.internalMonitor.canDropOnTarget(this.targetId)}finally{Zp=!1}}isOver(s){return this.targetId?this.internalMonitor.isOverTarget(this.targetId,s):!1}getItemType(){return this.internalMonitor.getItemType()}getItem(){return this.internalMonitor.getItem()}getDropResult(){return this.internalMonitor.getDropResult()}didDrop(){return this.internalMonitor.didDrop()}getInitialClientOffset(){return this.internalMonitor.getInitialClientOffset()}getInitialSourceClientOffset(){return this.internalMonitor.getInitialSourceClientOffset()}getSourceClientOffset(){return this.internalMonitor.getSourceClientOffset()}getClientOffset(){return this.internalMonitor.getClientOffset()}getDifferenceFromInitialOffset(){return this.internalMonitor.getDifferenceFromInitialOffset()}constructor(s){this.targetId=null,this.internalMonitor=s.getMonitor()}}function yI(a,s,i){const r=i.getRegistry(),l=r.addTarget(a,s);return[l,()=>r.removeTarget(l)]}function _I(a,s,i){const r=i.getRegistry(),l=r.addSource(a,s);return[l,()=>r.removeSource(l)]}function Pg(a,s,i,r){let l;if(l!==void 0)return!!l;if(a===s)return!0;if(typeof a!="object"||!a||typeof s!="object"||!s)return!1;const u=Object.keys(a),d=Object.keys(s);if(u.length!==d.length)return!1;const p=Object.prototype.hasOwnProperty.bind(s);for(let m=0;m, or turn it into a drag source or a drop target itself.`)}function CI(a){return(s=null,i=null)=>{if(!kw(s)){const u=s;return a(u,i),u}const r=s;return wI(r),TI(r,i?u=>a(u,i):a)}}function sC(a){const s={};return Object.keys(a).forEach(i=>{const r=a[i];if(i.endsWith("Ref"))s[i]=a[i];else{const l=CI(r);s[i]=()=>l}}),s}function b_(a,s){typeof a=="function"?a(s):a.current=s}function TI(a,s){const i=a.ref;return Ie(typeof i!="string","Cannot connect React DnD to an element with an existing string ref. Please convert it to use a callback ref instead, or wrap it into a or
. Read more: https://reactjs.org/docs/refs-and-the-dom.html#callback-refs"),i?kg(a,{ref:r=>{b_(i,r),b_(s,r)}}):kg(a,{ref:s})}class kI{receiveHandlerId(s){this.handlerId!==s&&(this.handlerId=s,this.reconnect())}get connectTarget(){return this.dragSource}get dragSourceOptions(){return this.dragSourceOptionsInternal}set dragSourceOptions(s){this.dragSourceOptionsInternal=s}get dragPreviewOptions(){return this.dragPreviewOptionsInternal}set dragPreviewOptions(s){this.dragPreviewOptionsInternal=s}reconnect(){const s=this.reconnectDragSource();this.reconnectDragPreview(s)}reconnectDragSource(){const s=this.dragSource,i=this.didHandlerIdChange()||this.didConnectedDragSourceChange()||this.didDragSourceOptionsChange();return i&&this.disconnectDragSource(),this.handlerId?s?(i&&(this.lastConnectedHandlerId=this.handlerId,this.lastConnectedDragSource=s,this.lastConnectedDragSourceOptions=this.dragSourceOptions,this.dragSourceUnsubscribe=this.backend.connectDragSource(this.handlerId,s,this.dragSourceOptions)),i):(this.lastConnectedDragSource=s,i):i}reconnectDragPreview(s=!1){const i=this.dragPreview,r=s||this.didHandlerIdChange()||this.didConnectedDragPreviewChange()||this.didDragPreviewOptionsChange();if(r&&this.disconnectDragPreview(),!!this.handlerId){if(!i){this.lastConnectedDragPreview=i;return}r&&(this.lastConnectedHandlerId=this.handlerId,this.lastConnectedDragPreview=i,this.lastConnectedDragPreviewOptions=this.dragPreviewOptions,this.dragPreviewUnsubscribe=this.backend.connectDragPreview(this.handlerId,i,this.dragPreviewOptions))}}didHandlerIdChange(){return this.lastConnectedHandlerId!==this.handlerId}didConnectedDragSourceChange(){return this.lastConnectedDragSource!==this.dragSource}didConnectedDragPreviewChange(){return this.lastConnectedDragPreview!==this.dragPreview}didDragSourceOptionsChange(){return!Pg(this.lastConnectedDragSourceOptions,this.dragSourceOptions)}didDragPreviewOptionsChange(){return!Pg(this.lastConnectedDragPreviewOptions,this.dragPreviewOptions)}disconnectDragSource(){this.dragSourceUnsubscribe&&(this.dragSourceUnsubscribe(),this.dragSourceUnsubscribe=void 0)}disconnectDragPreview(){this.dragPreviewUnsubscribe&&(this.dragPreviewUnsubscribe(),this.dragPreviewUnsubscribe=void 0,this.dragPreviewNode=null,this.dragPreviewRef=null)}get dragSource(){return this.dragSourceNode||this.dragSourceRef&&this.dragSourceRef.current}get dragPreview(){return this.dragPreviewNode||this.dragPreviewRef&&this.dragPreviewRef.current}clearDragSource(){this.dragSourceNode=null,this.dragSourceRef=null}clearDragPreview(){this.dragPreviewNode=null,this.dragPreviewRef=null}constructor(s){this.hooks=sC({dragSource:(i,r)=>{this.clearDragSource(),this.dragSourceOptions=r||null,Bg(i)?this.dragSourceRef=i:this.dragSourceNode=i,this.reconnectDragSource()},dragPreview:(i,r)=>{this.clearDragPreview(),this.dragPreviewOptions=r||null,Bg(i)?this.dragPreviewRef=i:this.dragPreviewNode=i,this.reconnectDragPreview()}}),this.handlerId=null,this.dragSourceRef=null,this.dragSourceOptionsInternal=null,this.dragPreviewRef=null,this.dragPreviewOptionsInternal=null,this.lastConnectedHandlerId=null,this.lastConnectedDragSource=null,this.lastConnectedDragSourceOptions=null,this.lastConnectedDragPreview=null,this.lastConnectedDragPreviewOptions=null,this.backend=s}}class SI{get connectTarget(){return this.dropTarget}reconnect(){const s=this.didHandlerIdChange()||this.didDropTargetChange()||this.didOptionsChange();s&&this.disconnectDropTarget();const i=this.dropTarget;if(this.handlerId){if(!i){this.lastConnectedDropTarget=i;return}s&&(this.lastConnectedHandlerId=this.handlerId,this.lastConnectedDropTarget=i,this.lastConnectedDropTargetOptions=this.dropTargetOptions,this.unsubscribeDropTarget=this.backend.connectDropTarget(this.handlerId,i,this.dropTargetOptions))}}receiveHandlerId(s){s!==this.handlerId&&(this.handlerId=s,this.reconnect())}get dropTargetOptions(){return this.dropTargetOptionsInternal}set dropTargetOptions(s){this.dropTargetOptionsInternal=s}didHandlerIdChange(){return this.lastConnectedHandlerId!==this.handlerId}didDropTargetChange(){return this.lastConnectedDropTarget!==this.dropTarget}didOptionsChange(){return!Pg(this.lastConnectedDropTargetOptions,this.dropTargetOptions)}disconnectDropTarget(){this.unsubscribeDropTarget&&(this.unsubscribeDropTarget(),this.unsubscribeDropTarget=void 0)}get dropTarget(){return this.dropTargetNode||this.dropTargetRef&&this.dropTargetRef.current}clearDropTarget(){this.dropTargetRef=null,this.dropTargetNode=null}constructor(s){this.hooks=sC({dropTarget:(i,r)=>{this.clearDropTarget(),this.dropTargetOptions=r,Bg(i)?this.dropTargetRef=i:this.dropTargetNode=i,this.reconnect()}}),this.handlerId=null,this.dropTargetRef=null,this.dropTargetOptionsInternal=null,this.lastConnectedHandlerId=null,this.lastConnectedDropTarget=null,this.lastConnectedDropTargetOptions=null,this.backend=s}}function Mn(){const{dragDropManager:a}=Xr(Gw);return Ie(a!=null,"Expected drag drop context"),a}function EI(a,s){const i=Mn(),r=rs(()=>new kI(i.getBackend()),[i]);return Ci(()=>(r.dragSourceOptions=a||null,r.reconnect(),()=>r.disconnectDragSource()),[r,a]),Ci(()=>(r.dragPreviewOptions=s||null,r.reconnect(),()=>r.disconnectDragPreview()),[r,s]),r}function II(){const a=Mn();return rs(()=>new bI(a),[a])}class xI{beginDrag(){const s=this.spec,i=this.monitor;let r=null;return typeof s.item=="object"?r=s.item:typeof s.item=="function"?r=s.item(i):r={},r??null}canDrag(){const s=this.spec,i=this.monitor;return typeof s.canDrag=="boolean"?s.canDrag:typeof s.canDrag=="function"?s.canDrag(i):!0}isDragging(s,i){const r=this.spec,l=this.monitor,{isDragging:u}=r;return u?u(l):i===s.getSourceId()}endDrag(){const s=this.spec,i=this.monitor,r=this.connector,{end:l}=s;l&&l(i.getItem(),i),r.reconnect()}constructor(s,i,r){this.spec=s,this.monitor=i,this.connector=r}}function DI(a,s,i){const r=rs(()=>new xI(a,s,i),[s,i]);return Mt(()=>{r.spec=a},[a]),r}function AI(a){return rs(()=>{const s=a.type;return Ie(s!=null,"spec.type must be defined"),s},[a])}function RI(a,s,i){const r=Mn(),l=DI(a,s,i),u=AI(a);Ci(function(){if(u!=null){const[p,m]=_I(u,l,r);return s.receiveHandlerId(p),i.receiveHandlerId(p),m}},[r,s,i,l,u])}function OI(a,s){const i=tC(a);Ie(!i.begin,"useDrag::spec.begin was deprecated in v14. Replace spec.begin() with spec.item(). (see more here - https://react-dnd.github.io/react-dnd/docs/api/use-drag)");const r=II(),l=EI(i.options,i.previewOptions);return RI(i,r,l),[eC(i.collect,r,l),fI(l),$I(l)]}function MI(a){return rs(()=>a.hooks.dropTarget(),[a])}function NI(a){const s=Mn(),i=rs(()=>new SI(s.getBackend()),[s]);return Ci(()=>(i.dropTargetOptions=a||null,i.reconnect(),()=>i.disconnectDropTarget()),[a]),i}function LI(){const a=Mn();return rs(()=>new vI(a),[a])}function PI(a){const{accept:s}=a;return rs(()=>(Ie(a.accept!=null,"accept must be defined"),Array.isArray(s)?s:[s]),[s])}class BI{canDrop(){const s=this.spec,i=this.monitor;return s.canDrop?s.canDrop(i.getItem(),i):!0}hover(){const s=this.spec,i=this.monitor;s.hover&&s.hover(i.getItem(),i)}drop(){const s=this.spec,i=this.monitor;if(s.drop)return s.drop(i.getItem(),i)}constructor(s,i){this.spec=s,this.monitor=i}}function jI(a,s){const i=rs(()=>new BI(a,s),[s]);return Mt(()=>{i.spec=a},[a]),i}function FI(a,s,i){const r=Mn(),l=jI(a,s),u=PI(a);Ci(function(){const[p,m]=yI(u,l,r);return s.receiveHandlerId(p),i.receiveHandlerId(p),m},[r,s,l,i,u.map(d=>d.toString()).join("|")])}function zI(a,s){const i=tC(a),r=LI(),l=NI(i.options);return FI(i,r,l),[eC(i.collect,r,l),MI(l)]}function oC(a){let s=null;return()=>(s==null&&(s=a()),s)}function UI(a,s){return a.filter(i=>i!==s)}function HI(a,s){const i=new Set,r=u=>i.add(u);a.forEach(r),s.forEach(r);const l=[];return i.forEach(u=>l.push(u)),l}class WI{enter(s){const i=this.entered.length,r=l=>this.isNodeInDocument(l)&&(!l.contains||l.contains(s));return this.entered=HI(this.entered.filter(r),[s]),i===0&&this.entered.length>0}leave(s){const i=this.entered.length;return this.entered=UI(this.entered.filter(this.isNodeInDocument),s),i>0&&this.entered.length===0}reset(){this.entered=[]}constructor(s){this.entered=[],this.isNodeInDocument=s}}class GI{initializeExposedProperties(){Object.keys(this.config.exposeProperties).forEach(s=>{Object.defineProperty(this.item,s,{configurable:!0,enumerable:!0,get(){return console.warn(`Browser doesn't allow reading "${s}" until the drop event.`),null}})})}loadDataTransfer(s){if(s){const i={};Object.keys(this.config.exposeProperties).forEach(r=>{const l=this.config.exposeProperties[r];l!=null&&(i[r]={value:l(s,this.config.matchesTypes),configurable:!0,enumerable:!0})}),Object.defineProperties(this.item,i)}}canDrag(){return!0}beginDrag(){return this.item}isDragging(s,i){return i===s.getSourceId()}endDrag(){}constructor(s){this.config=s,this.item={},this.initializeExposedProperties()}}const iC="__NATIVE_FILE__",nC="__NATIVE_URL__",rC="__NATIVE_TEXT__",aC="__NATIVE_HTML__",v_=Object.freeze(Object.defineProperty({__proto__:null,FILE:iC,HTML:aC,TEXT:rC,URL:nC},Symbol.toStringTag,{value:"Module"}));function Qp(a,s,i){const r=s.reduce((l,u)=>l||a.getData(u),"");return r??i}const jg={[iC]:{exposeProperties:{files:a=>Array.prototype.slice.call(a.files),items:a=>a.items,dataTransfer:a=>a},matchesTypes:["Files"]},[aC]:{exposeProperties:{html:(a,s)=>Qp(a,s,""),dataTransfer:a=>a},matchesTypes:["Html","text/html"]},[nC]:{exposeProperties:{urls:(a,s)=>Qp(a,s,"").split(` -`),dataTransfer:a=>a},matchesTypes:["Url","text/uri-list"]},[rC]:{exposeProperties:{text:(a,s)=>Qp(a,s,""),dataTransfer:a=>a},matchesTypes:["Text","text/plain"]}};function VI(a,s){const i=jg[a];if(!i)throw new Error(`native type ${a} has no configuration`);const r=new GI(i);return r.loadDataTransfer(s),r}function eg(a){if(!a)return null;const s=Array.prototype.slice.call(a.types||[]);return Object.keys(jg).filter(i=>{const r=jg[i];return r!=null&&r.matchesTypes?r.matchesTypes.some(l=>s.indexOf(l)>-1):!1})[0]||null}const KI=oC(()=>/firefox/i.test(navigator.userAgent)),lC=oC(()=>!!window.safari);class y_{interpolate(s){const{xs:i,ys:r,c1s:l,c2s:u,c3s:d}=this;let p=i.length-1;if(s===i[p])return r[p];let m=0,f=d.length-1,v;for(;m<=f;){v=Math.floor(.5*(m+f));const k=i[v];if(ks)f=v-1;else return r[v]}p=Math.max(0,f);const _=s-i[p],y=_*_;return r[p]+l[p]*_+u[p]*y+d[p]*_*y}constructor(s,i){const{length:r}=s,l=[];for(let k=0;ks[k]{let se=new y_([0,.5,1],[m.y,m.y/v*C,m.y+C-v]).interpolate(y);return lC()&&u&&(se+=(window.devicePixelRatio-1)*C),se},E=()=>new y_([0,.5,1],[m.x,m.x/f*k,m.x+k-f]).interpolate(_),{offsetX:R,offsetY:D}=l,A=R===0||R,J=D===0||D;return{x:A?R:E(),y:J?D:w()}}let ZI=class{get window(){if(this.globalContext)return this.globalContext;if(typeof window<"u")return window}get document(){var s;return!((s=this.globalContext)===null||s===void 0)&&s.document?this.globalContext.document:this.window?this.window.document:void 0}get rootElement(){var s;return((s=this.optionsArgs)===null||s===void 0?void 0:s.rootElement)||this.window}constructor(s,i){this.ownerDocument=null,this.globalContext=s,this.optionsArgs=i}};function QI(a,s,i){return s in a?Object.defineProperty(a,s,{value:i,enumerable:!0,configurable:!0,writable:!0}):a[s]=i,a}function __(a){for(var s=1;s{this.sourcePreviewNodes.delete(s),this.sourcePreviewNodeOptions.delete(s)}}connectDragSource(s,i,r){this.sourceNodes.set(s,i),this.sourceNodeOptions.set(s,r);const l=d=>this.handleDragStart(d,s),u=d=>this.handleSelectStart(d);return i.setAttribute("draggable","true"),i.addEventListener("dragstart",l),i.addEventListener("selectstart",u),()=>{this.sourceNodes.delete(s),this.sourceNodeOptions.delete(s),i.removeEventListener("dragstart",l),i.removeEventListener("selectstart",u),i.setAttribute("draggable","false")}}connectDropTarget(s,i){const r=d=>this.handleDragEnter(d,s),l=d=>this.handleDragOver(d,s),u=d=>this.handleDrop(d,s);return i.addEventListener("dragenter",r),i.addEventListener("dragover",l),i.addEventListener("drop",u),()=>{i.removeEventListener("dragenter",r),i.removeEventListener("dragover",l),i.removeEventListener("drop",u)}}addEventListeners(s){s.addEventListener&&(s.addEventListener("dragstart",this.handleTopDragStart),s.addEventListener("dragstart",this.handleTopDragStartCapture,!0),s.addEventListener("dragend",this.handleTopDragEndCapture,!0),s.addEventListener("dragenter",this.handleTopDragEnter),s.addEventListener("dragenter",this.handleTopDragEnterCapture,!0),s.addEventListener("dragleave",this.handleTopDragLeaveCapture,!0),s.addEventListener("dragover",this.handleTopDragOver),s.addEventListener("dragover",this.handleTopDragOverCapture,!0),s.addEventListener("drop",this.handleTopDrop),s.addEventListener("drop",this.handleTopDropCapture,!0))}removeEventListeners(s){s.removeEventListener&&(s.removeEventListener("dragstart",this.handleTopDragStart),s.removeEventListener("dragstart",this.handleTopDragStartCapture,!0),s.removeEventListener("dragend",this.handleTopDragEndCapture,!0),s.removeEventListener("dragenter",this.handleTopDragEnter),s.removeEventListener("dragenter",this.handleTopDragEnterCapture,!0),s.removeEventListener("dragleave",this.handleTopDragLeaveCapture,!0),s.removeEventListener("dragover",this.handleTopDragOver),s.removeEventListener("dragover",this.handleTopDragOverCapture,!0),s.removeEventListener("drop",this.handleTopDrop),s.removeEventListener("drop",this.handleTopDropCapture,!0))}getCurrentSourceNodeOptions(){const s=this.monitor.getSourceId(),i=this.sourceNodeOptions.get(s);return __({dropEffect:this.altKeyPressed?"copy":"move"},i||{})}getCurrentDropEffect(){return this.isDraggingNativeItem()?"copy":this.getCurrentSourceNodeOptions().dropEffect}getCurrentSourcePreviewNodeOptions(){const s=this.monitor.getSourceId(),i=this.sourcePreviewNodeOptions.get(s);return __({anchorX:.5,anchorY:.5,captureDraggingState:!1},i||{})}isDraggingNativeItem(){const s=this.monitor.getItemType();return Object.keys(v_).some(i=>v_[i]===s)}beginDragNativeItem(s,i){this.clearCurrentDragSourceNode(),this.currentNativeSource=VI(s,i),this.currentNativeHandle=this.registry.addSource(s,this.currentNativeSource),this.actions.beginDrag([this.currentNativeHandle])}setCurrentDragSourceNode(s){this.clearCurrentDragSourceNode(),this.currentDragSourceNode=s;const i=1e3;this.mouseMoveTimeoutTimer=setTimeout(()=>{var r;return(r=this.rootElement)===null||r===void 0?void 0:r.addEventListener("mousemove",this.endDragIfSourceWasRemovedFromDOM,!0)},i)}clearCurrentDragSourceNode(){if(this.currentDragSourceNode){if(this.currentDragSourceNode=null,this.rootElement){var s;(s=this.window)===null||s===void 0||s.clearTimeout(this.mouseMoveTimeoutTimer||void 0),this.rootElement.removeEventListener("mousemove",this.endDragIfSourceWasRemovedFromDOM,!0)}return this.mouseMoveTimeoutTimer=null,!0}return!1}handleDragStart(s,i){s.defaultPrevented||(this.dragStartSourceIds||(this.dragStartSourceIds=[]),this.dragStartSourceIds.unshift(i))}handleDragEnter(s,i){this.dragEnterTargetIds.unshift(i)}handleDragOver(s,i){this.dragOverTargetIds===null&&(this.dragOverTargetIds=[]),this.dragOverTargetIds.unshift(i)}handleDrop(s,i){this.dropTargetIds.unshift(i)}constructor(s,i,r){this.sourcePreviewNodes=new Map,this.sourcePreviewNodeOptions=new Map,this.sourceNodes=new Map,this.sourceNodeOptions=new Map,this.dragStartSourceIds=null,this.dropTargetIds=[],this.dragEnterTargetIds=[],this.currentNativeSource=null,this.currentNativeHandle=null,this.currentDragSourceNode=null,this.altKeyPressed=!1,this.mouseMoveTimeoutTimer=null,this.asyncEndDragFrameId=null,this.dragOverTargetIds=null,this.lastClientOffset=null,this.hoverRafId=null,this.getSourceClientOffset=l=>{const u=this.sourceNodes.get(l);return u&&cC(u)||null},this.endDragNativeItem=()=>{this.isDraggingNativeItem()&&(this.actions.endDrag(),this.currentNativeHandle&&this.registry.removeSource(this.currentNativeHandle),this.currentNativeHandle=null,this.currentNativeSource=null)},this.isNodeInDocument=l=>!!(l&&this.document&&this.document.body&&this.document.body.contains(l)),this.endDragIfSourceWasRemovedFromDOM=()=>{const l=this.currentDragSourceNode;l==null||this.isNodeInDocument(l)||(this.clearCurrentDragSourceNode()&&this.monitor.isDragging()&&this.actions.endDrag(),this.cancelHover())},this.scheduleHover=l=>{this.hoverRafId===null&&typeof requestAnimationFrame<"u"&&(this.hoverRafId=requestAnimationFrame(()=>{this.monitor.isDragging()&&this.actions.hover(l||[],{clientOffset:this.lastClientOffset}),this.hoverRafId=null}))},this.cancelHover=()=>{this.hoverRafId!==null&&typeof cancelAnimationFrame<"u"&&(cancelAnimationFrame(this.hoverRafId),this.hoverRafId=null)},this.handleTopDragStartCapture=()=>{this.clearCurrentDragSourceNode(),this.dragStartSourceIds=[]},this.handleTopDragStart=l=>{if(l.defaultPrevented)return;const{dragStartSourceIds:u}=this;this.dragStartSourceIds=null;const d=sc(l);this.monitor.isDragging()&&(this.actions.endDrag(),this.cancelHover()),this.actions.beginDrag(u||[],{publishSource:!1,getSourceClientOffset:this.getSourceClientOffset,clientOffset:d});const{dataTransfer:p}=l,m=eg(p);if(this.monitor.isDragging()){if(p&&typeof p.setDragImage=="function"){const v=this.monitor.getSourceId(),_=this.sourceNodes.get(v),y=this.sourcePreviewNodes.get(v)||_;if(y){const{anchorX:k,anchorY:C,offsetX:w,offsetY:E}=this.getCurrentSourcePreviewNodeOptions(),A=XI(_,y,d,{anchorX:k,anchorY:C},{offsetX:w,offsetY:E});p.setDragImage(y,A.x,A.y)}}try{p==null||p.setData("application/json",{})}catch{}this.setCurrentDragSourceNode(l.target);const{captureDraggingState:f}=this.getCurrentSourcePreviewNodeOptions();f?this.actions.publishDragSource():setTimeout(()=>this.actions.publishDragSource(),0)}else if(m)this.beginDragNativeItem(m);else{if(p&&!p.types&&(l.target&&!l.target.hasAttribute||!l.target.hasAttribute("draggable")))return;l.preventDefault()}},this.handleTopDragEndCapture=()=>{this.clearCurrentDragSourceNode()&&this.monitor.isDragging()&&this.actions.endDrag(),this.cancelHover()},this.handleTopDragEnterCapture=l=>{if(this.dragEnterTargetIds=[],this.isDraggingNativeItem()){var u;(u=this.currentNativeSource)===null||u===void 0||u.loadDataTransfer(l.dataTransfer)}if(!this.enterLeaveCounter.enter(l.target)||this.monitor.isDragging())return;const{dataTransfer:p}=l,m=eg(p);m&&this.beginDragNativeItem(m,p)},this.handleTopDragEnter=l=>{const{dragEnterTargetIds:u}=this;if(this.dragEnterTargetIds=[],!this.monitor.isDragging())return;this.altKeyPressed=l.altKey,u.length>0&&this.actions.hover(u,{clientOffset:sc(l)}),u.some(p=>this.monitor.canDropOnTarget(p))&&(l.preventDefault(),l.dataTransfer&&(l.dataTransfer.dropEffect=this.getCurrentDropEffect()))},this.handleTopDragOverCapture=l=>{if(this.dragOverTargetIds=[],this.isDraggingNativeItem()){var u;(u=this.currentNativeSource)===null||u===void 0||u.loadDataTransfer(l.dataTransfer)}},this.handleTopDragOver=l=>{const{dragOverTargetIds:u}=this;if(this.dragOverTargetIds=[],!this.monitor.isDragging()){l.preventDefault(),l.dataTransfer&&(l.dataTransfer.dropEffect="none");return}this.altKeyPressed=l.altKey,this.lastClientOffset=sc(l),this.scheduleHover(u),(u||[]).some(p=>this.monitor.canDropOnTarget(p))?(l.preventDefault(),l.dataTransfer&&(l.dataTransfer.dropEffect=this.getCurrentDropEffect())):this.isDraggingNativeItem()?l.preventDefault():(l.preventDefault(),l.dataTransfer&&(l.dataTransfer.dropEffect="none"))},this.handleTopDragLeaveCapture=l=>{this.isDraggingNativeItem()&&l.preventDefault(),this.enterLeaveCounter.leave(l.target)&&(this.isDraggingNativeItem()&&setTimeout(()=>this.endDragNativeItem(),0),this.cancelHover())},this.handleTopDropCapture=l=>{if(this.dropTargetIds=[],this.isDraggingNativeItem()){var u;l.preventDefault(),(u=this.currentNativeSource)===null||u===void 0||u.loadDataTransfer(l.dataTransfer)}else eg(l.dataTransfer)&&l.preventDefault();this.enterLeaveCounter.reset()},this.handleTopDrop=l=>{const{dropTargetIds:u}=this;this.dropTargetIds=[],this.actions.hover(u,{clientOffset:sc(l)}),this.actions.drop({dropEffect:this.getCurrentDropEffect()}),this.isDraggingNativeItem()?this.endDragNativeItem():this.monitor.isDragging()&&this.actions.endDrag(),this.cancelHover()},this.handleSelectStart=l=>{const u=l.target;typeof u.dragDrop=="function"&&(u.tagName==="INPUT"||u.tagName==="SELECT"||u.tagName==="TEXTAREA"||u.isContentEditable||(l.preventDefault(),u.dragDrop()))},this.options=new ZI(i,r),this.actions=s.getActions(),this.monitor=s.getMonitor(),this.registry=s.getRegistry(),this.enterLeaveCounter=new WI(this.isNodeInDocument)}}const uC=function(s,i,r){return new ex(s,i,r)},tx=ht([g.jsx("path",{d:"M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2M12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8"},"0"),g.jsx("path",{d:"M12.5 7H11v6l5.25 3.15.75-1.23-4.5-2.67z"},"1")],"AccessTime"),sx=ht(g.jsx("path",{d:"M19 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2m-2 10h-4v4h-2v-4H7v-2h4V7h2v4h4z"}),"AddBox"),ox=ht(g.jsx("path",{d:"M4 8h4V4H4zm6 12h4v-4h-4zm-6 0h4v-4H4zm0-6h4v-4H4zm6 0h4v-4h-4zm6-10v4h4V4zm-6 4h4V4h-4zm6 6h4v-4h-4zm0 6h4v-4h-4z"}),"Apps"),ix=ht(g.jsx("path",{d:"M9 2c-1.05 0-2.05.16-3 .46 4.06 1.27 7 5.06 7 9.54s-2.94 8.27-7 9.54c.95.3 1.95.46 3 .46 5.52 0 10-4.48 10-10S14.52 2 9 2"}),"Brightness3"),nx=ht(g.jsx("path",{d:"M20 8h-2.81c-.45-.78-1.07-1.45-1.82-1.96L17 4.41 15.59 3l-2.17 2.17C12.96 5.06 12.49 5 12 5s-.96.06-1.41.17L8.41 3 7 4.41l1.62 1.63C7.88 6.55 7.26 7.22 6.81 8H4v2h2.09c-.05.33-.09.66-.09 1v1H4v2h2v1c0 .34.04.67.09 1H4v2h2.81c1.04 1.79 2.97 3 5.19 3s4.15-1.21 5.19-3H20v-2h-2.09c.05-.33.09-.66.09-1v-1h2v-2h-2v-1c0-.34-.04-.67-.09-1H20zm-6 8h-4v-2h4zm0-4h-4v-2h4z"}),"BugReport"),rx=ht(g.jsx("path",{d:"M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12zm-1 4 6 6v10c0 1.1-.9 2-2 2H7.99C6.89 23 6 22.1 6 21l.01-14c0-1.1.89-2 1.99-2zm-1 7h5.5L14 6.5z"}),"FileCopy"),ax=ht(g.jsx("path",{d:"M7 2v11h3v9l7-12h-4l4-8z"}),"FlashOn"),lx=ht(g.jsx("path",{d:"M3.27 5 2 6.27l6.97 6.97L6.5 19h3l1.57-3.66L16.73 21 18 19.73 3.55 5.27zM6 5v.18L8.82 8h2.4l-.72 1.68 2.1 2.1L14.21 8H20V5z"}),"FormatClear"),cx=ht(g.jsx("path",{d:"M18 4H6v2l6.5 6L6 18v2h12v-3h-7l5-5-5-5h7z"}),"Functions"),dC=ht(g.jsx("path",{d:"M11 18h2v-2h-2zm1-16C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2m0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8m0-14c-2.21 0-4 1.79-4 4h2c0-1.1.9-2 2-2s2 .9 2 2c0 2-3 1.75-3 5h2c0-2.25 3-2.5 3-5 0-2.21-1.79-4-4-4"}),"HelpOutline"),ux=ht(g.jsx("path",{d:"M21 3.01H3c-1.1 0-2 .9-2 2V9h2V4.99h18v14.03H3V15H1v4.01c0 1.1.9 1.98 2 1.98h18c1.1 0 2-.88 2-1.98v-14c0-1.11-.9-2-2-2M11 16l4-4-4-4v3H1v2h10z"}),"Input"),w_=ht(g.jsx("path",{d:"M18 8h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2m-6 9c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2m3.1-9H8.9V6c0-1.71 1.39-3.1 3.1-3.1s3.1 1.39 3.1 3.1z"}),"Lock"),dx=ht(g.jsx("path",{d:"M12 8c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2m0 2c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2m0 6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2"}),"MoreVert"),hx=ht(g.jsx("path",{d:"M12 2C6.49 2 2 6.49 2 12s4.49 10 10 10c1.38 0 2.5-1.12 2.5-2.5 0-.61-.23-1.2-.64-1.67-.08-.1-.13-.21-.13-.33 0-.28.22-.5.5-.5H16c3.31 0 6-2.69 6-6 0-4.96-4.49-9-10-9m5.5 11c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5m-3-4c-.83 0-1.5-.67-1.5-1.5S13.67 6 14.5 6s1.5.67 1.5 1.5S15.33 9 14.5 9M5 11.5c0-.83.67-1.5 1.5-1.5s1.5.67 1.5 1.5S7.33 13 6.5 13 5 12.33 5 11.5m6-4c0 .83-.67 1.5-1.5 1.5S8 8.33 8 7.5 8.67 6 9.5 6s1.5.67 1.5 1.5"}),"Palette"),gc=ht(g.jsx("path",{d:"M6 19h4V5H6zm8-14v14h4V5z"}),"Pause"),Fg=ht(g.jsx("path",{d:"M8 5v14l11-7z"}),"PlayArrow"),px=ht(g.jsx("path",{d:"M11 5v5.59H7.5l4.5 4.5 4.5-4.5H13V5zm-5 9c0 3.31 2.69 6 6 6s6-2.69 6-6h-2c0 2.21-1.79 4-4 4s-4-1.79-4-4z"}),"PlayForWork"),gx=ht(g.jsx("path",{d:"M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14"}),"Search"),mx=ht(g.jsx("path",{d:"M10.59 9.17 5.41 4 4 5.41l5.17 5.17zM14.5 4l2.04 2.04L4 18.59 5.41 20 17.96 7.46 20 9.5V4zm.33 9.41-1.41 1.41 3.13 3.13L14.5 20H20v-5.5l-2.04 2.04z"}),"Shuffle"),fx=ht(g.jsx("path",{d:"M2 20h20v-4H2zm2-3h2v2H4zM2 4v4h20V4zm4 3H4V5h2zm-4 7h20v-4H2zm2-3h2v2H4z"}),"Storage"),$x=ht(g.jsx("path",{d:"M14 17H4v2h10zm6-8H4v2h16zM4 15h16v-2H4zM4 5v2h16V5z"}),"Subject"),bx=ht(g.jsx("path",{d:"M16 17.01V10h-2v7.01h-3L15 21l4-3.99zM9 3 5 6.99h3V14h2V6.99h3z"}),"SwapVert"),vx=ht(g.jsx("path",{d:"M7.41 18.59 8.83 20 12 16.83 15.17 20l1.41-1.41L12 14zm9.18-13.18L15.17 4 12 7.17 8.83 4 7.41 5.41 12 10z"}),"UnfoldLess"),yx=ht(g.jsx("path",{d:"M12 5.83 15.17 9l1.41-1.41L12 3 7.41 7.59 8.83 9zm0 12.34L8.83 15l-1.41 1.41L12 21l4.59-4.59L15.17 15z"}),"UnfoldMore"),_c="data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20width='512'%20height='512'%20shape-rendering='geometricPrecision'%20image-rendering='optimizeQuality'%20fill-rule='evenodd'%20xmlns:v='https://vecta.io/nano'%3e%3cpath%20fill='%23efda4e'%20d='M-.5-.5h512v512H-.5V-.5z'/%3e%3cpath%20fill='%23020100'%20d='M308.5%20287.5c1.777-3.005%202.777-6.338%203-10%209.147-21.963%2025.48-35.463%2049-40.5%2021.999-4.173%2043.666-2.84%2065%204%2014.575%205.411%2025.575%2014.911%2033%2028.5l-1%202c-12.413%205.624-24.58%2011.624-36.5%2018-5.321-8.25-12.821-13.417-22.5-15.5-13.957-3.122-27.29-1.455-40%205-8.125%205.36-10.958%2012.86-8.5%2022.5%203.223%206.223%208.057%2010.723%2014.5%2013.5l64%2020c38.459%2016.085%2052.626%2044.585%2042.5%2085.5-7.572%2026.208-24.738%2042.041-51.5%2047.5-25.102%205.733-49.768%204.4-74-4-19.291-8.625-32.291-22.958-39-43%2011.266-8.887%2023.433-16.387%2036.5-22.5%203.117%206.896%206.784%2013.563%2011%2020%2012.705%2012.307%2027.872%2016.807%2045.5%2013.5%2022.189-3.504%2032.355-16.338%2030.5-38.5-2.833-6.833-7.667-11.667-14.5-14.5l-57-17c-36.004-11.84-52.67-36.673-50-74.5z'/%3e%3cpath%20fill='%23020200'%20d='M222.5%20238.5h43l-.5%20159c-2.688%2052.355-30.188%2076.855-82.5%2073.5-24.871-3.543-41.204-17.21-49-41l.5-2.5a12.14%2012.14%200%200%200%204.5-3.5c10.653-5.825%2021.32-11.325%2032-16.5%204.763%2021.72%2017.763%2028.887%2039%2021.5%204.616-2.618%207.783-6.451%209.5-11.5%201.163-5.968%202.163-11.968%203-18l.5-161z'/%3e%3cpath%20fill='%23615820'%20d='M311.5%20277.5c-.223%203.662-1.223%206.995-3%2010%20.223-3.662%201.223-6.995%203-10z'/%3e%3c/svg%3e",hC="data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20500%20500'%3e%3cpath%20fill='%234285f4'%20d='M44.271%2027.275l206.5%201v170l-58.5-36.5c-7.005-.916-12.505%201.584-16.5%207.5v147c4.625%204.412%2010.125%206.245%2016.5%205.5l57.5-35.5c.833%2054.003%201.356%20108.003.189%20162-1.272.546-45.599-.242-48.689%201.121-3.674%207.844-4.79%2011.207-13%2023.879-4.372%205.527-2.19%204.097-10.689%2012.258-5.166%202.748-4.191%203.45-14.311%206.242-17.67%201.983-35.336%201.983-53%200-9.535-3.774-10.879-4.163-18.526-11.22-5.562-4.39-11.131-11.803-11.974-15.28-4.068-7.881-3.42-9.116-5.5-13.5-3.672-1.503-35.798.203-40.746-1.335-5.823-2.314-2.946-.422-7.954-3.689-2.888-2.668-2.255-3.221-2.421-9.904L20.771%2050.275c.36-2.108-.41-5.806%202.522-11.615%204.343-5.852%205.374-7%2010.061-9.146%206.083-2.73%208.677-1.475%2010.917-2.239z'/%3e%3cpath%20d='M258.271%2030.275l154.63.407c5.654.559%2010.783%203.17%2014.37%207.093%204.907%204.408%206.204%208.723%207.5%2013.5v373c-.208%205.716-.297%207.982-4.848%2015.404-7.078%206.393-9.879%206.39-15.652%206.692-24.804%201.296-50.079%201.189-74.96%201.041-24.516-.014-68.46.89-81.5.391l-2.512-172.528c-20.083%2012.625-42.777%2025.125-63.028%2037.5-4.127%201.292-7.294.125-9.5-3.5l1-137c1.864-2.707%204.364-3.541%207.5-2.5%2020.366%2013.427%2064.35%2038.947%2065.581%2038.339l1.419-177.839z'%20fill='%23DDD'/%3e%3c/svg%3e",pC="data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20512%20512'%20width='32'%20height='32'%3e%3cpath%20fill='%23007acc'%20d='M-.5-.5h503l-1%20179h10v333h-421v-7h-91V-.5z'/%3e%3cpath%20fill='%230f81cf'%20d='M502.5-.5h9v179h-10l1-179z'/%3e%3cpath%20fill='%23fdfefe'%20d='M470.5%20227.5c.33%2017.508-.003%2034.841-1%2052-23.486-15.709-48.82-19.875-76-12.5-15.89%208.078-19.39%2019.911-10.5%2035.5%204.673%205.577%2010.173%2010.077%2016.5%2013.5l38%2019c17.945%209.278%2031.112%2023.112%2039.5%2041.5%201.352%203.22%202.186%206.553%202.5%2010a305.16%20305.16%200%200%201%201%2026c-3.553%2033.726-21.886%2054.559-55%2062.5-34.769%207.363-68.435%204.196-101-9.5-.167-19.003%200-38.003.5-57%2022.903%2021.314%2049.736%2029.147%2080.5%2023.5%2019.435-5.701%2025.268-17.868%2017.5-36.5-4.718-6.44-10.552-11.606-17.5-15.5a1552.42%201552.42%200%200%201-47-24c-27.679-19.331-38.846-45.831-33.5-79.5%206.43-26.433%2022.597-43.933%2048.5-52.5%2026.131-6.625%2052.464-7.292%2079-2a565.56%20565.56%200%200%201%2018%205.5z'/%3e%3cpath%20fill='%23fefefe'%20d='M122.5%20222.5h182v46h-65v206h-52v-206h-65v-46z'/%3e%3cpath%20fill='%2370b3e1'%20d='M470.5%20227.5c1.327%2017.505%201.327%2035.171%200%2053-.607-.124-.94-.457-1-1%20.997-17.159%201.33-34.492%201-52z'/%3e%3cpath%20fill='%236cafe0'%20d='M479.5%20386.5c1.465%205.09%202.132%2010.423%202%2016-.002%203.518-.335%206.851-1%2010a305.16%20305.16%200%200%200-1-26z'/%3e%3cpath%20fill='%231283cf'%20d='M-.5%20504.5h91v7h-91v-7z'/%3e%3c/svg%3e",gC="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI1MTIiIGhlaWdodD0iNTEyIj4KICAgIDxyYWRpYWxHcmFkaWVudCBpZD0ibXlHcmFkaWVudCI+CiAgICAgICAgPHN0b3Agb2Zmc2V0PSIxMCUiIHN0b3AtY29sb3I9IiMxQzJENUYiIC8+CiAgICAgICAgPHN0b3Agb2Zmc2V0PSI5NSUiIHN0b3AtY29sb3I9IiMwQjFENTMiIC8+CiAgICA8L3JhZGlhbEdyYWRpZW50PgogICAgPHBhdGggZmlsbD0idXJsKCcjbXlHcmFkaWVudCcpIiBkPSJNLS4xLS4xaDUxMnY1MTJILS4xVi0uMXoiLz4KICAgIDxwYXRoIGZpbGw9IiNmOGY4ZmEiCiAgICAgICAgICBkPSJNNDgyLjUgMjMxLjV2NmgtMjVjLS45NzItOC4xNy01LjYzOS0xMi4xNy0xNC0xMi05LjUzMS4wMjktMTMuMzY1IDQuNjk1LTExLjUgMTRsNC41IDQuNSAzMyA4YzE5LjM4OCA5LjYzNCAyMy4zODggMjMuODAxIDEyIDQyLjVhMzUuMDYgMzUuMDYgMCAwIDAtOCA2Yy0xMy45MjU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0yLjc4Ny0xLjMxLTUuNzg3LTEtOSA4Ljg0OS0uMzI2IDE3LjUxNi4wMDcgMjYgMXoiLz4KICAgIDxwYXRoIGZpbGw9IiNhNWFjYmYiCiAgICAgICAgICBkPSJNMTEzLjUgMzAxLjVjLjk3OC4zMTEgMS42NDUuOTc4IDIgMmwtMTYgMWMtNS43MTEtLjAwNS0xMS4wNDQtLjY3Mi0xNi0yYTEyOC4xOSAxMjguMTkgMCAwIDAgMTUuNSAxYzUuMjE2LS4wMDYgMTAuMDQ5LS42NzMgMTQuNS0yeiIvPgogICAgPHBhdGggZmlsbD0iI2E1YWNjMCIgZD0iTTIzMy41IDIwOS41djk0aDY5di0xN2MtMTMuNTEuMzI5LTI2Ljg0NC0uMDA0LTQwLTFoNDF2MTloLTcxYTIyNTYuNDEgMjI1Ni40MSAwIDAgMSAxLTk1eiIvPgogICAgPHBhdGggZmlsbD0iI2E2YWNjMCIKICAgICAgICAgIGQ9Ik0zMTYuNSAyMDkuNWMtLjk5OCAzMS4xNjItMS4zMzIgNjIuNDk2LTEgOTRoNzN2LTE3Yy0xNC44NDMuMzI5LTI5LjUxLS4wMDQtNDQtMWg0NXYxOWgtNzVhMjMwNC45NSAyMzA0Ljk1IDAgMCAxIDEtOTZjLjYwNy4xMjQuOTQuNDU3IDEgMXoiLz4KPC9zdmc+";class $m extends Y.Component{isShowInstance;oldId;constructor(s){super(s),this.state={name:s.name,id:s.id,instance:s.instance||0,prefix:$m.getPrefix(s.id)},this.isShowInstance=!s.folder&&!!s.instances&&(!!s.instance||!!s.instances[0]||s.instances.length>1),this.oldId=s.id}static getPrefix(s){const i=(s||"").split(".");return i.pop(),i.join(".")}getId(s){return s=(s||"").replace(/[\\/\][*,;'"`<>?\s]/g,"_"),`${this.state.prefix}.${s}`}handleCancel=()=>{this.props.onClose()};handleOk=()=>{this.props.onRename(this.oldId,this.state.id,this.state.name,this.state.instance===0?0:this.state.instance||void 0),this.props.onClose()};handleChange=s=>{this.setState({name:s,id:this.getId(s)})};render(){return g.jsxs(Gt,{onClose:()=>!1,maxWidth:"md",fullWidth:!0,open:!0,"aria-labelledby":"confirmation-dialog-title",children:[g.jsx(as,{id:"confirmation-dialog-title",children:b.I18n.t("Rename")}),g.jsx(Vt,{children:g.jsxs("form",{noValidate:!0,autoComplete:"off",children:[g.jsx(vo,{variant:"standard",style:{width:"100%"},id:"standard-name",autoFocus:!0,label:b.I18n.t("Name"),value:this.state.name,onKeyUp:s=>{s.key==="Enter"&&(s.preventDefault(),setTimeout(()=>this.handleOk(),200))},onChange:s=>this.handleChange(s.target.value),margin:"normal"}),g.jsx(vo,{variant:"standard",id:"standard-name-id",style:{width:"100%"},label:b.I18n.t("ID"),value:this.state.id,disabled:!0,margin:"normal"}),this.isShowInstance&&g.jsxs(_i,{variant:"standard",children:[g.jsx(Eg,{htmlFor:"instance",children:b.I18n.t("Instance")}),g.jsx(wi,{variant:"standard",value:this.state.instance,onChange:s=>this.setState({instance:parseInt(s.target.value,10)}),inputProps:{name:"instance",id:"instance"},children:this.props.instances.map(s=>g.jsx(Ge,{value:s,children:s||"0"},s))})]})]})}),g.jsxs(Kt,{children:[g.jsx(De,{variant:"contained",onClick:this.handleOk,color:"primary",startIcon:g.jsx(zo,{}),children:b.I18n.t("Ok")}),g.jsx(De,{color:"grey",variant:"contained",onClick:this.handleCancel,startIcon:g.jsx(qs,{}),children:b.I18n.t("Cancel")})]})]})}}class _x extends Y.Component{constructor(s){super(s),this.state={name:s.name,id:s.id}}handleCancel=()=>{this.props.onClose()};handleOk=()=>{this.props.onDelete(this.state.id),this.props.onClose()};render(){return g.jsxs(Gt,{onClose:()=>!1,maxWidth:"md",open:!0,"aria-labelledby":"confirmation-dialog-title",children:[g.jsx(as,{id:"confirmation-dialog-title",children:b.I18n.t("Are you sure?")}),g.jsxs(Vt,{children:[g.jsx(dc,{}),g.jsx("span",{style:{fontSize:14,fontWeight:"bold"},children:b.I18n.t("Delete %s",this.state.name)})]}),g.jsxs(Kt,{children:[g.jsx(De,{variant:"contained",onClick:this.handleOk,color:"primary",startIcon:g.jsx(zo,{}),children:b.I18n.t("Ok")}),g.jsx(De,{color:"grey",variant:"contained",onClick:this.handleCancel,startIcon:g.jsx(qs,{}),children:b.I18n.t("Cancel")})]})]})}}const wx=""+new URL("tileJS-C48gYbHw.png",import.meta.url).href,Cx=""+new URL("tileTS-CsXmgy4B.png",import.meta.url).href,Tx=""+new URL("tileBlockly-BMpdinN3.png",import.meta.url).href,kx=""+new URL("tileRules-BkbaFIhs.png",import.meta.url).href,Pt={card:{maxWidth:345,minWidth:250,display:"inline-block",margin:"0 10px 0 10px"},media:{height:122},text:{maxWidth:218,minHeight:30},complexity:{fontWeight:"bold",fontStyle:"italic",marginBottom:8}};class Cn extends Y.Component{handleCancel=()=>{this.props.onClose()};static openHtml(s){const i=b.I18n.getLanguage();!s.includes("javascript.md")&&(i==="de"||i==="ru")&&(s=s.replace(/\/en\//,`/${i}/`));const r=window.open(s,"_blank");r==null||r.focus()}getJSCard(){return g.jsxs(Yl,{style:Pt.card,children:[g.jsxs(Jl,{onClick:()=>this.props.onClose&&this.props.onClose("Javascript/js"),children:[g.jsx(ql,{style:Pt.media,image:wx,title:"JavaScript"}),g.jsxs(Xl,{children:[g.jsx("h2",{children:"JavaScript"}),g.jsx("div",{style:Pt.complexity,children:b.I18n.t("for programmers")}),g.jsx("div",{style:Pt.text,children:b.I18n.t("JS description")})]})]}),g.jsxs(Zl,{children:[g.jsx(De,{size:"small",color:"primary",variant:"contained",onClick:()=>this.props.onClose&&this.props.onClose("Javascript/js"),children:b.I18n.t("Add")}),g.jsx(De,{size:"small",color:"secondary",onClick:()=>Cn.openHtml("https://github.com/ioBroker/ioBroker.javascript/blob/master/docs/en/javascript.md"),children:b.I18n.t("Learn More")})]})]})}getTSCard(){return g.jsxs(Yl,{style:Pt.card,children:[g.jsxs(Jl,{onClick:()=>this.props.onClose&&this.props.onClose("TypeScript/ts"),children:[g.jsx(ql,{style:Pt.media,image:Cx,title:"TypeScript"}),g.jsxs(Xl,{children:[g.jsx("h2",{children:"TypeScript"}),g.jsx("div",{style:Pt.complexity,children:b.I18n.t("for professionals")}),g.jsx("div",{style:Pt.text,children:b.I18n.t("TS description")})]})]}),g.jsxs(Zl,{children:[g.jsx(De,{size:"small",color:"primary",variant:"contained",onClick:()=>this.props.onClose&&this.props.onClose("TypeScript/ts"),children:b.I18n.t("Add")}),g.jsx(De,{size:"small",color:"secondary",onClick:()=>Cn.openHtml("https://github.com/ioBroker/ioBroker.javascript/blob/master/docs/en/javascript.md"),children:b.I18n.t("Learn More")})]})]})}getBlocklyCard(){return g.jsxs(Yl,{style:Pt.card,children:[g.jsxs(Jl,{onClick:()=>this.props.onClose&&this.props.onClose("Blockly"),children:[g.jsx(ql,{style:Pt.media,image:Tx,title:"Blockly"}),g.jsxs(Xl,{children:[g.jsx("h2",{children:"Blockly"}),g.jsx("div",{style:Pt.complexity,children:b.I18n.t("normal")}),g.jsx("div",{style:Pt.text,children:b.I18n.t("Blockly description")})]})]}),g.jsxs(Zl,{children:[g.jsx(De,{size:"small",color:"primary",variant:"contained",onClick:()=>this.props.onClose&&this.props.onClose("Blockly"),children:b.I18n.t("Add")}),g.jsx(De,{size:"small",color:"secondary",onClick:()=>Cn.openHtml("https://github.com/ioBroker/ioBroker.javascript/blob/master/docs/en/blockly.md"),children:b.I18n.t("Learn More")})]})]})}getRulesCard(){return g.jsxs(Yl,{style:Pt.card,children:[g.jsxs(Jl,{onClick:()=>this.props.onClose&&this.props.onClose("Rules"),children:[g.jsx(ql,{style:Pt.media,image:kx,title:"Rules"}),g.jsxs(Xl,{children:[g.jsx("h2",{children:"Rules"}),g.jsx("div",{style:Pt.complexity,children:b.I18n.t("easy")}),g.jsx("div",{style:Pt.text,children:b.I18n.t("Rules description")})]})]}),g.jsxs(Zl,{children:[g.jsx(De,{size:"small",color:"primary",variant:"contained",onClick:()=>this.props.onClose&&this.props.onClose("Rules"),children:b.I18n.t("Add")}),g.jsx(De,{size:"small",color:"secondary",onClick:()=>Cn.openHtml("https://github.com/ioBroker/ioBroker.javascript/blob/master/docs/en/javascript.md"),children:b.I18n.t("Learn More")})]})]})}render(){return g.jsxs(Gt,{onClose:()=>!1,maxWidth:"lg",fullWidth:!0,open:!0,"aria-labelledby":"confirmation-dialog-title",children:[g.jsx(as,{id:"confirmation-dialog-title",children:b.I18n.t("Add new script")}),g.jsxs(Vt,{style:{textAlign:"center"},children:[this.getRulesCard(),this.getBlocklyCard(),this.getJSCard(),this.getTSCard()]}),g.jsx(Kt,{children:g.jsx(De,{color:"grey",onClick:this.handleCancel,startIcon:g.jsx(qs,{}),children:b.I18n.t("Cancel")})})]})}}class tg extends Y.Component{isShowInstance;constructor(s){super(s),this.state={name:s.name||"Script",instance:s.instance||0,parent:s.parent,error:"",id:""},this.isShowInstance=!s.folder&&!!s.instances&&(!!s.instance||!!s.instances[0]||s.instances.length>1)}getId(s){return s=s||this.state.name||"",s=s.replace(/[\\/\][.*,;'"`<>?\s]/g,"_").trim().replace(/\.$/,"_"),`${this.state?this.state.parent:this.props.parent}.${s}`}handleOk=()=>{this.props.onAdd(this.getId(this.state.name),this.state.name,this.state.instance,this.props.type),this.props.onClose()};render(){var s;return g.jsxs(Gt,{onClose:()=>!1,maxWidth:"md",fullWidth:!0,open:!0,"aria-labelledby":"confirmation-dialog-title",children:[g.jsx(as,{id:"confirmation-dialog-title",children:this.props.title||b.I18n.t("Create new")}),g.jsx(Vt,{children:g.jsxs("form",{noValidate:!0,autoComplete:"off",children:[g.jsx(vo,{variant:"standard",style:{width:"100%"},id:"standard-name",autoFocus:!0,error:!!this.state.error,label:b.I18n.t("Name"),value:this.state.name||"",helperText:this.state.error,slotProps:{input:{endAdornment:this.state.name?g.jsx(Me,{size:"small",onClick:()=>this.setState({name:""}),children:g.jsx(Jk,{})}):void 0}},onKeyUp:i=>{i.preventDefault(),i.key==="Enter"&&!this.state.error&&setTimeout(()=>this.handleOk(),200)},onChange:i=>{var u;const r=i.target.value,l=this.getId(r);r?(u=this.props.existingItems)!=null&&u.includes(l)?this.setState({name:r,id:l,error:b.I18n.t("Duplicate name")}):this.setState({name:r,id:l,error:""}):this.setState({name:r,id:l,error:b.I18n.t("Empty name is not allowed")})},margin:"normal"}),g.jsxs(_i,{variant:"standard",style:{width:"100%"},children:[g.jsx(Eg,{htmlFor:"parent",children:b.I18n.t("Folder")}),g.jsx(wi,{variant:"standard",style:{width:"100%"},value:this.state.parent,onChange:i=>this.setState({parent:i.target.value}),inputProps:{name:"parent",id:"parent"},children:this.props.parents.map(i=>{const r=i.id.split(".");r.splice(0,2);const l=[];let u="script.js";return r.forEach(d=>{u+=`.${d}`;const p=this.props.parents.find(m=>m.id===u);p?l.push(p.name):l.push(d)}),l.length||l.push(i.name),g.jsx(Ge,{value:i.id,children:l.join(" / ")},i.id)})})]}),g.jsx(vo,{variant:"standard",id:"standard-name-id",style:{width:"100%"},label:b.I18n.t("ID"),value:this.getId(),disabled:!0,margin:"normal"}),this.isShowInstance&&g.jsxs(_i,{variant:"standard",children:[g.jsx(Eg,{htmlFor:"instance",children:b.I18n.t("Instance")}),g.jsx(wi,{variant:"standard",value:this.state.instance,onChange:i=>this.setState({instance:parseInt(i.target.value,10)}),inputProps:{name:"instance",id:"instance"},children:(s=this.props.instances)==null?void 0:s.map(i=>g.jsx(Ge,{value:i,children:i||"0"},`instance${i}`))})]})]})}),g.jsxs(Kt,{children:[g.jsx(De,{variant:"contained",onClick:this.handleOk,disabled:!!this.state.error,color:"primary",startIcon:g.jsx(zo,{}),children:b.I18n.t("Ok")}),g.jsx(De,{color:"grey",variant:"contained",onClick:()=>this.props.onClose(),startIcon:g.jsx(qs,{}),children:b.I18n.t("Cancel")})]})]})}}const Sx={title:a=>({background:a.palette.error.main,color:a.palette.error.contrastText,"&>h2":{color:a.palette.error.contrastText}})};class Zc extends Y.Component{handleOk=()=>{this.props.onClose()};render(){return g.jsxs(Gt,{open:!0,maxWidth:"sm",fullWidth:!0,onClose:()=>this.handleOk(),"aria-labelledby":"alert-dialog-title","aria-describedby":"alert-dialog-description",children:[g.jsx(as,{sx:Sx.title,id:"alert-dialog-title",children:this.props.title||b.I18n.t("Error")}),g.jsx(Vt,{children:g.jsx(Iw,{id:"alert-dialog-description",children:this.props.text||b.I18n.t("Unknown error!")})}),g.jsx(Kt,{children:g.jsx(De,{variant:"contained",onClick:()=>this.handleOk(),color:"primary",autoFocus:!0,startIcon:g.jsx(zo,{}),children:b.I18n.t("Ok")})})]})}}const Mr={icon:{width:24,height:24},filterWithButton:{width:"100%"},title:{fontWeight:"bold",marginTop:16}};class Ex extends Y.Component{constructor(s){super(s),this.state={instances:[],filter:window.localStorage.getItem("javascript.debug.filter")||"",showAskForStop:!1,jsInstance:window.localStorage.getItem("javascript.debug.instance")||"",jsInstanceHost:"",adapterToDebug:window.localStorage.getItem("javascript.debug.adapter")||""}}componentDidMount(){this.props.socket.getAdapterInstances().then(s=>{const i=s.filter(p=>{var m;return p&&!((m=p.common)!=null&&m.onlyWWW)}).map(p=>{var v,_,y;const m=p._id.replace(/^system\.adapter\./,""),[f]=m.split(".");return{id:m,enabled:(v=p.common)==null?void 0:v.enabled,host:(_=p.common)==null?void 0:_.host,icon:(y=p.common)!=null&&y.icon?`../../adapter/${f}/${p.common.icon}`:""}});i.sort((p,m)=>p.id>m.id?1:p.idp.id===this.state.jsInstance):null;let u;if(!this.state.jsInstance||!l){const p=i.find(m=>m.id.startsWith("javascript."));u=(p==null?void 0:p.host)||"",r=(p==null?void 0:p.id)||""}else u=(l==null?void 0:l.host)||"";let d=this.state.adapterToDebug||"";d&&!i.find(p=>p.id===d)&&(d=""),this.setState({instances:i,jsInstance:r,adapterToDebug:d,jsInstanceHost:u})})}handleOk=()=>{var s;if((s=this.state.instances.find(i=>i.id===this.state.adapterToDebug))!=null&&s.enabled){this.props.socket.getObject(`system.adapter.${this.state.adapterToDebug}`).then(i=>{i&&(i.common.enabled=!1,this.props.socket.setObject(i._id,i).then(()=>this.props.onDebug(this.state.jsInstance,this.state.adapterToDebug)))});return}this.props.onDebug(this.state.jsInstance,this.state.adapterToDebug)};renderJavascriptList(){const s=this.state.instances.filter(i=>i.id.startsWith("javascript."));return s.length<2?null:g.jsxs($i,{children:[g.jsx("div",{style:Mr.title,children:b.I18n.t("Host")}),g.jsx(Ig,{component:"nav",children:s.map(i=>g.jsxs(Qy,{component:"div",selected:this.state.jsInstance===i.id,onClick:()=>this.setState({jsInstance:i.id,jsInstanceHost:i.host}),children:[g.jsx(xg,{children:g.jsx("img",{src:i.icon,alt:i.id,style:Mr.icon})}),g.jsx(Dg,{primary:i.id})]},i.id))})]})}renderInstances(){if(!this.state.jsInstance)return g.jsx($i,{});const s=this.state.instances.filter(i=>i.id!==this.state.jsInstance&&i.host===this.state.jsInstanceHost&&(!this.state.filter||i.id.includes(this.state.filter.toLowerCase())));return g.jsxs($i,{children:[g.jsx("div",{style:Mr.title,children:b.I18n.t("Instances")}),g.jsx(Ig,{component:"nav",children:s.map(i=>g.jsxs(Qy,{selected:this.state.adapterToDebug===i.id,onDoubleClick:()=>this.setState({adapterToDebug:i.id},()=>this.handleOk()),onClick:()=>this.setState({adapterToDebug:i.id}),children:[g.jsx(xg,{children:g.jsx("img",{src:i.icon,alt:i.id,style:Mr.icon})}),g.jsx(Dg,{primary:i.id})]},i.id))})]})}render(){return g.jsxs(Gt,{maxWidth:"md",fullWidth:!1,open:!0,onClose:()=>!1,"aria-labelledby":"confirmation-dialog-title",children:[g.jsx(as,{id:"confirmation-dialog-title",children:this.props.title||b.I18n.t("Debug instance")}),g.jsx(Vt,{children:g.jsxs($i,{container:!0,direction:"column",children:[g.jsx($i,{children:g.jsx(Dn,{style:Mr.filterWithButton,value:this.state.filter,placeholder:b.I18n.t("Filter"),onChange:s=>{this.setState({filter:s.target.value}),window.localStorage.setItem("javascript.debug.filter",s.target.value)},endAdornment:g.jsx(xw,{position:"end",children:this.state.filter?g.jsx(Me,{size:"small","aria-label":"toggle password visibility",onClick:()=>this.setState({filter:""}),children:g.jsx(Ow,{})}):""})})}),g.jsx($i,{children:g.jsxs($i,{container:!0,children:[this.renderJavascriptList(),this.renderInstances()]})})]})}),g.jsxs(Kt,{children:[g.jsx(De,{variant:"contained",onClick:this.handleOk,disabled:!this.state.jsInstance||!this.state.adapterToDebug,color:"primary",startIcon:g.jsx(zo,{}),children:b.I18n.t("Start")}),g.jsx(De,{color:"grey",variant:"contained",onClick:()=>this.props.onClose(),startIcon:g.jsx(qs,{}),children:b.I18n.t("Close")})]})]})}}function mC(a){if(!a)throw new Error("Password must be a non-empty string.")}function zg(a){return new TextEncoder().encode(a)}function Ix(a){return new TextDecoder().decode(a)}function xx(a){let s="";for(let i=0;i({height:a.toolbar.height}),toolbarButtons:a=>({color:a.palette.mode==="dark"?"white !important":"black !important"}),iconButtonsDisabled:{filter:"grayscale(100%)",opacity:.5},toolbarSearch:{width:"calc(100% - 105px)",lineHeight:"34px",marginLeft:5},iconButtons:{width:32,height:32,padding:2},iconDropdownMenu:{paddingRight:5},menu:{width:"100%",height:"100%"},innerMenu:{width:"100%",height:"calc(100% - 76px)",overflowX:"hidden",overflowY:"auto"},listItemIcon:{minWidth:32},scriptIcon:{width:18,height:18,borderRadius:2,marginTop:4,marginBottom:4,marginLeft:8,marginRight:4},folder:{cursor:"pointer",padding:0,userSelect:"none"},folderReorder:{opacity:.3,transitionDuration:"0.5s",transitionProperty:"opacity"},folderIcon:{width:20,height:20},folderIconReorder:{paddingTop:4,paddingBottom:4,paddingLeft:8,paddingRight:4},folderIconNoReorder:{cursor:"pointer",paddingTop:4,paddingBottom:4,paddingLeft:8,paddingRight:4},script:{cursor:"pointer",padding:0,userSelect:"none"},scriptReorder:{opacity:1,transitionDuration:"0.5s",transitionProperty:"opacity"},reorder:{},selected:window.vendorPrefix?a=>({backgroundColor:a.palette.primary.main,color:a.palette.text.primary}):{backgroundColor:"#164477",color:"white"},instances:{color:"gray",fontSize:"smaller"},childrenCount:{fontSize:10,opacity:.4},footer:{height:24,display:"flex"},footerButtons:a=>({"& img":{color:a.palette.mode==="dark"?"#ffffff":"#111111",cursor:"pointer",mt:"1px",mr:"2px",height:22,width:22,"&:hover":{backgroundColor:"#dbdbdb"}},"& svg":{color:a.palette.mode==="dark"?"#ffffff":"#111111",cursor:"pointer",mt:"1px",mr:"2px",height:22,width:22,"&:hover":{backgroundColor:"#dbdbdb"}}}),footerButtonsRight:{float:"right"}},$n={Blockly:hC,"Javascript/js":_c,def:_c,Rules:gC,"TypeScript/ts":pC};function Hg(a,s,i){var r;return i=i||b.I18n.getLanguage(),(r=s==null?void 0:s.common)!=null&&r.name?typeof s.common.name=="object"?(s.common.name[i]||s.common.name.en||a.replace(/^script\.js./,"")).toString():s.common.name.toString():a.replace(/^script\.js./,"")}function S_(a){var l;const s=[{id:Wt,depth:0,index:0,parent:null,title:"root",type:"folder",parentIndex:null}],i=Object.keys(a);for(let u=0;u1?p.join("."):null,instance:d.common.engine?parseInt(d.common.engine.split(".").pop(),10)||0:null,index:0,parentIndex:0}):s.push({id:i[u],title:Hg(i[u],d),depth:p.length-1,type:"folder",parent:p.length>1?p.join("."):null,index:0,parentIndex:null})}let r;do r=!1,s.forEach(u=>{if(u.parent&&!s.find(p=>p.id===u.parent)){const p=u.parent.split(".");p.pop(),s.push({id:u.parent,title:u.parent.split(".").pop()||"",depth:p.length-1,type:"folder",parent:p.length>1?p.join("."):null,index:0,parentIndex:null}),r=!0}});while(r);return s.sort((u,d)=>{const p=u.id.toLowerCase(),m=d.id.toLowerCase();return u.type==="folder"&&d.type!=="folder"?-1:d.type==="folder"&&u.type!=="folder"||p>m?1:pu.index=d),s.forEach(u=>{if(u.parent){const d=s.find(p=>p.id===u.parent);d&&(u.parentIndex=d.index)}}),s}function Ox(a){const{onDrop:s}=a,[{isOver:i,isOverAny:r},l]=zI({accept:"script",drop:u=>i?s(u):void 0,collect:u=>({isOver:u.isOver({shallow:!0}),isOverAny:u.isOver()})});return g.jsx("div",{ref:l,style:{background:i?"#40adff":void 0,opacity:r?.7:void 0},children:a.children},a.folderName)}function E_(a){const{name:s}=a,[{opacity:i},r]=OI({type:"script",item:()=>({name:s}),collect:l=>({opacity:l.isDragging()?.3:1})});return g.jsx("div",{ref:r,style:{opacity:i,transform:"translate3d(0, 0, 0)"},children:a.children},s)}class bo extends Y.Component{inputRef;filterTimer;problems;problemsTimer;onProblemUpdatedBound;parent=null;constructor(s){super(s);const i=window.localStorage?window.localStorage.getItem("SideMenu.expanded"):"[]";let r;try{r=JSON.parse(i||"[]")||[]}catch{r=[]}this.inputRef=Y.createRef(),this.state={listItems:S_(s.scripts||{}),expanded:r,problems:[],reorder:!1,themeName:this.props.themeName,selected:window.localStorage&&window.localStorage.getItem("SideMenu.selected")||null,creatingScript:null,creatingFolder:!1,copingScript:"",renaming:null,deleting:null,choosingType:!1,errorText:"",instances:s.instances||[],menuOpened:!1,menuAnchorEl:null,menuAnchorFilterEl:null,searchMode:!1,expertMode:this.props.expertMode,searchText:"",width:this.props.width||300,typeFilter:window.localStorage&&window.localStorage.getItem("SideMenu.typeFilter")||"",statusFilter:window.localStorage&&window.localStorage.getItem("SideMenu.statusFilter")||"",runningInstances:this.props.runningInstances||{},scriptsHash:s.scriptsHash,showAdapterDebug:!1,isAllZeroInstances:!1};const l=this.ensureSelectedIsVisible();l&&Object.assign(this.state,{expanded:l}),this.filterTimer=null,Object.assign(this.state,{isAllZeroInstances:this.getIsAllZeroInstances()}),this.problems=null,this.problemsTimer=null,this.onProblemUpdatedBound=this.onProblemUpdated.bind(this)}readProblems(s,i){var r,l;if(i||(i=Object.keys(this.props.scripts)),!i||!i.length)s&&s();else{const u=i.shift(),d=this.props.scripts[u];if(((r=this.props.scripts)==null?void 0:r[u].type)==="script"&&((l=d.common)!=null&&l.enabled)&&!u.match(/^script\.js\.global\./)){const p=d.common.engine.split(".").pop(),m=this,f=`javascript.${p}.scriptProblem.${u.substring(Wt.length+1)}`;this.props.socket.getState(f).then(v=>{m.onProblemUpdated(f,v),setTimeout(()=>m.readProblems(s,i),0)})}else setTimeout(()=>this.readProblems(s,i),0)}}componentDidMount(){this.readProblems(()=>{this.props.instances.forEach(s=>{this.props.socket.subscribeState(`javascript.${s}.scriptProblem.*`,this.onProblemUpdatedBound)})})}componentWillUnmount(){this.props.instances.forEach(s=>{this.props.socket.unsubscribeState(`javascript.${s}.scriptProblem.*`,this.onProblemUpdatedBound)})}onProblemUpdated(s,i){if(!i||!s)return;s=`${Wt}.${s.replace(/^javascript\.\d+\.scriptProblem\./,"")}`,this.problems||(this.problems=JSON.parse(JSON.stringify(this.state.problems))||[]);let r=!1;if(i.val)this.problems.includes(s)||(this.problems.push(s),r=!0);else{const l=this.problems.indexOf(s);l!==-1&&(this.problems.splice(l,1),r=!0)}r&&!this.problemsTimer&&(this.problemsTimer=setTimeout(()=>{this.problemsTimer=null,this.setState({problems:this.problems}),this.problems=null},300))}static filterListStatic(s,i,r,l,u){i=JSON.parse(JSON.stringify(i));let d=!1;const p={listItems:i};if(s&&r&&l){const m=l.toLowerCase();if(i.forEach(f=>{var k;const v=f.title.toLowerCase();f.filteredPartly=!1;let _=v.includes(m);const y=(k=u==null?void 0:u[f.id])==null?void 0:k.common;if(!_&&(y!=null&&y.source))if(y.engineType==="Blockly"){const C=y.source.lastIndexOf("//");_=y.source.substring(0,C).toLowerCase().includes(m)}else _=y.source.toLowerCase().includes(m);_?f.filtered&&(f.filtered=!1,d=!0):f.filtered||(f.filtered=!0,d=!0)}),d)for(let f=i.length-1;f>=0;f--){const v=i[f];if(!v.filtered||v.filteredPartly){let _=v;do _!=null&&_.parent&&i[_.parentIndex]&&(d=!0,i[_.parentIndex].filteredPartly=!0),_=_!=null&&_.parent&&i[_.parentIndex]?i[_.parentIndex]:null;while(_)}}}else i.forEach(m=>{(m.filtered||m.filteredPartly)&&(m.filtered=!1,m.filteredPartly=!1,d=!0)}),s||(p.searchText="",p.searchMode=!1,d=!0);return d?p:null}filterList(s,i){const r=bo.filterListStatic(s,this.state.listItems,this.state.searchMode,this.state.searchText,this.props.scripts);r?this.setState(r,()=>i&&i()):i&&i()}static ensureSelectedIsVisibleStatic(s,i,r){i=JSON.parse(JSON.stringify(i));let l=!1,u=typeof s=="object"?s:r.find(d=>d.id===s);do{if(u!=null&&u.parent){const d=u.parent;u=r.find(p=>p.id===d)}else u=void 0;u&&(i.includes(u.id)||(i.push(u.id),l=!0))}while(u);return l?i:null}ensureSelectedIsVisible(s,i){return bo.ensureSelectedIsVisibleStatic(s||this.state.selected,i||this.state.expanded,this.state.listItems)}static getDerivedStateFromProps(s,i){const r={};let l=!1;if(i.expertMode!==s.expertMode&&(l=!0,r.expertMode=s.expertMode),i.scriptsHash!==s.scriptsHash&&s.scripts){const u=S_(s.scripts||{});if(r.listItems=u,i.searchText){const m=bo.filterListStatic(!0,u,i.searchMode,i.searchText,s.scripts);m&&Object.assign(r,m)}const d=bo.getIsAllZeroInstancesStatic(u,s.instances||[]),p=bo.ensureSelectedIsVisibleStatic(i.selected,i.expanded,i.listItems);r.isAllZeroInstances=d,p&&(r.expanded=p),l=!0}if(i.width!==s.width&&(l=!0,r.width=s.width),i.themeName!==s.themeName&&(l=!0,r.themeName=s.themeName),s.selectId&&i.selected!==s.selectId){const u=i.listItems.find(d=>d.id===s.selectId);if(!i.reorder&&u){const d=bo.ensureSelectedIsVisibleStatic(u,i.expanded,i.listItems);r.selected=u.id,d&&(r.expanded=d),l=!0,window.localStorage&&window.localStorage.setItem("SideMenu.selected",u.id)}}return l?r:null}static getIsAllZeroInstancesStatic(s,i){let r=!i[0]&&i.length<=1;return r&&s.forEach(l=>{l.type!=="folder"&&l.instance!==0&&(r=!1)}),r}getIsAllZeroInstances(s,i){return s=s||this.state.listItems,i=i||this.state.instances,bo.getIsAllZeroInstancesStatic(s||this.state.listItems,i||this.state.instances)}saveExpanded(s){window.localStorage.setItem("SideMenu.expanded",JSON.stringify(s||this.state.expanded))}showError(s){this.setState({errorText:s})}onToggle(s,i){if(i==null||i.stopPropagation(),s===Wt)return;const r=[...this.state.expanded],l=r.indexOf(s);l!==-1?(r.splice(l,1),this.state.selected&&this.state.selected.startsWith(`${s}.`)&&window.localStorage&&window.localStorage.setItem("SideMenu.selected",s)):(r.push(s),r.sort()),this.setState({expanded:r}),this.saveExpanded(r)}renderItemButtonsOnEnd(s,i){if(this.state.reorder)return null;if(s.type!=="folder"){let r=s.enabled?C_:k_;return s.enabled&&this.state.problems.includes(s.id)&&(r=T_),[g.jsx(Me,{onClick:l=>{l.stopPropagation(),this.props.onEnableDisable&&this.props.onEnableDisable(s.id,!s.enabled)},title:s.enabled?b.I18n.t("Pause script"):b.I18n.t("Run script"),disabled:this.props.debugMode,style:{...fe.iconButtons,...this.props.debugMode?fe.iconButtonsDisabled:void 0,color:r},size:"medium",children:s.enabled?g.jsx(gc,{}):g.jsx(Fg,{})},"startStop"),this.state.width>Nr?g.jsx(Me,{style:this.props.debugMode?fe.iconButtonsDisabled:void 0,title:b.I18n.t("Delete script"),disabled:s.id===$o||s.id===fn||this.props.debugMode,onClick:l=>this.onDelete(s,l),size:"medium",children:g.jsx(dc,{})},"delete"):null,g.jsx(Me,{style:this.props.debugMode?fe.iconButtonsDisabled:void 0,disabled:this.props.debugMode,title:b.I18n.t("Edit script or just double click"),onClick:l=>this.onEdit(s,l),size:"medium",children:g.jsx(ux,{})},"openInEdit")]}return this.state.width>Nr&&s.id!==Wt&&s.id!==fn&&s.id!==$o&&!(i!=null&&i.length)?g.jsx(Me,{style:this.props.debugMode?fe.iconButtonsDisabled:void 0,title:b.I18n.t("Delete folder"),disabled:s.id===$o||s.id===fn||this.props.debugMode,onClick:r=>this.onDelete(s,r),size:"medium",children:g.jsx(dc,{})},"delete"):null}onDelete(s,i){return i==null||i.stopPropagation(),new Promise(r=>{if(!s){r();return}typeof s!="object"?this.setState({deleting:s},()=>r()):this.setState({deleting:s.id},()=>r())})}onEdit(s,i){this.onClick(s,i),this.props.onEdit&&this.props.onEdit(s.id)}getTextStyle(s){return!this.state.reorder&&s.type!=="folder"?{width:`calc(100% - ${this.state.width>Nr?185:137}px)`,overflow:"hidden",whiteSpace:"nowrap",flex:"none",padding:"0 16px 0 0"}:{whiteSpace:"nowrap",padding:"0 16px 0 0"}}onClick(s,i){if(i==null||i.stopPropagation(),!this.state.reorder&&s){const r=this.ensureSelectedIsVisible(s),l={selected:s.id};r&&(l.expanded=r),this.setState(l),window.localStorage&&window.localStorage.setItem("SideMenu.selected",s.id)}}onDblClick(s,i){i==null||i.stopPropagation(),!this.state.reorder&&(s.type==="folder"?this.onToggle(s.id):this.onEdit(s))}isFilteredOut(s){var i,r;return s.filtered&&!s.filteredPartly||this.state.typeFilter&&s.type!=="folder"&&s.type.toLowerCase()!==this.state.typeFilter.toLowerCase()||!this.state.expertMode&&((r=(i=this.props.scripts[s.id])==null?void 0:i.native)!=null&&r.protected)||this.state.statusFilter&&s.type!=="folder"&&(this.state.statusFilter==="running"&&!s.enabled||this.state.statusFilter==="paused"&&s.enabled||this.state.statusFilter==="problems"&&(!s.enabled||this.state.problems.indexOf(s.id)===-1))?!0:s.id===$o&&!this.state.expertMode}renderListItem(s,i,r){var y,k;if(s.id===Wt&&!this.state.reorder)return null;const l=(this.state.reorder?s.depth:s.depth-1)*Rx;let u=s.title;if(this.state.searchText){const C=u.toLowerCase().indexOf(this.state.searchText.toLowerCase());C!==-1&&(u=[g.jsx("span",{children:u.substring(0,C)},"first"),g.jsx("span",{style:{color:"orange"},children:u.substring(C,C+this.state.searchText.length)},"second"),g.jsx("span",{children:u.substring(C+this.state.searchText.length)},"third")])}!this.state.isAllZeroInstances&&s.type!=="folder"&&(u=[g.jsx("span",{children:u},"title"),g.jsxs("span",{title:b.I18n.t("Instance"),style:fe.instances,children:["[",s.instance,"]"]},"instance")]);const d=this.state.reorder&&!this.props.debugMode,p={marginLeft:l,cursor:s.type==="folder"&&d?"default":"inherit",width:`calc(100% - ${l}px)`};d||(p.opacity=s.filteredPartly?.5:1),s.id===$o&&s.id!==this.state.selected&&(p.color="#00a200");let m=s.id===Wt;!m&&i&&(m=this.state.expanded.includes(s.id));let f;s.type==="folder"?f={...fe.folderIcon,...d?fe.folderIconReorder:fe.folderIconNoReorder}:f={...fe.scriptIcon},s.id===$o?f.color="#356956":s.id===fn&&(f.color="#4899e1");let v=null;(r&&r.length||i&&i.length)&&(v=g.jsx("span",{style:fe.childrenCount,children:r&&r.length!==i.length?`${r.length}(${i.length})`:i.length}));const _={...s.type==="folder"?fe.folder:fe.script,...d?fe.reorder:void 0,...d&&s.type!=="folder"?fe.scriptReorder:void 0,...d&&s.type==="folder"?fe.folderReorder:void 0,...p};return g.jsxs(Ok,{style:_,sx:s.id===this.state.selected&&!d?fe.selected:void 0,className:b.Utils.clsx(d&&s.type==="folder"&&"folder-reorder",d&&s.type!=="folder"&&"script-reorder"),onClick:C=>this.onClick(s,C),onDoubleClick:C=>this.onDblClick(s,C),secondaryAction:this.renderItemButtonsOnEnd(s,i),children:[(k=(y=this.props.scripts[s.id])==null?void 0:y.native)!=null&&k.protected?g.jsx(w_,{style:{color:"orange",position:"absolute",right:5,width:10,height:10}}):null,g.jsx(xg,{style:fe.listItemIcon,children:s.type==="folder"?d||m?g.jsx(qk,{style:f,onClick:C=>!d&&this.onToggle(s.id,C)}):g.jsx(Xk,{style:f,onClick:C=>!d&&this.onToggle(s.id,C)}):g.jsx("img",{style:f,alt:s.type,src:$n[s.type]||$n.def})}),g.jsx(Dg,{sx:{"& .MuiListItemText-primary":s.id===this.state.selected&&!d?fe.selected:void 0},style:this.getTextStyle(s),primary:g.jsxs("span",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[u,v]})})]},s.id)}onDragFinish(s,i){let r=`${i}.${s.split(".").pop()}`;r!==s&&(this.state.listItems.find(l=>l.id===r)&&(r+=`_${b.I18n.t("copy")}`),this.props.onRename&&this.props.onRename(s,r))}renderOneItem(s,i){const r=this.state.statusFilter||this.state.typeFilter?s.filter(f=>f.parent===i.id?!this.isFilteredOut(f):!1):[],l=s.filter(f=>f.parent===i.id);if(this.isFilteredOut(i)||i.type==="folder"&&(this.state.statusFilter||this.state.typeFilter)&&!r.length)return null;const u=this.state.reorder&&!this.props.debugMode,d=this.renderListItem(i,l,r),p=[];let m;return l&&(u||this.state.expanded.includes(i.id)||i.id===Wt)&&(m=l.map(f=>this.renderOneItem(s,f))),u?i.type==="folder"?p.push(g.jsxs(Ox,{onDrop:f=>this.onDragFinish(f.name,i.id),folderName:i.id,children:[g.jsx(E_,{name:i.id,children:d},`draggable_${i.id}`),m||null]},`droppable_${i.id}`)):p.push(g.jsxs(E_,{name:i.id,children:[d,m||null]},`draggable_${i.id}`)):(p.push(d),m==null||m.forEach(f=>p.push(f))),p}renderAllItems(s){const i=s.filter(r=>!r.parent).map(r=>this.renderOneItem(s,r));return g.jsx(Ig,{dense:!0,disablePadding:!0,sx:fe.mainList,children:i})}onAddNew(s){s==null||s.stopPropagation();let i=this.state.listItems.find(l=>l.id===this.state.selected),r=Wt;for(;i&&i.type!=="folder";)i=this.state.listItems[i.parentIndex];i&&(r=i.id),this.parent=r,this.setState({choosingType:!0})}onCopy(s,i){s==null||s.stopPropagation();let r=this.state.listItems.find(u=>u.id===i),l=Wt;for(;r&&r.type!=="folder";)r=this.state.listItems[r.parentIndex];r&&(l=r.id),this.parent=l,this.setState({copingScript:i||""})}onAddNewFolder(s){s==null||s.stopPropagation();let i=this.state.listItems.find(l=>l.id===this.state.selected),r=Wt;for(;i&&i.type!=="folder";)i=this.state.listItems[i.parentIndex];i&&(r=i.id),this.parent=r,this.setState({creatingFolder:!0})}onRename(s){s==null||s.stopPropagation(),this.setState({renaming:this.state.selected})}getUniqueName(s){let i=1,r=`${b.I18n.t("Script")} `;if(s){const l=Hg(s,this.props.scripts[s]),u=l.match(/\d+$/);u?(r=l.replace(/\d+$/,""),i=parseInt(u[0],10)+1):r=l}for(;this.state.listItems.find(l=>l.id===`${this.parent}.${r.replace(/\.\s/g,"_")}${i}`);)i++;return r+i}getUniqueFolderName(){let s=1;for(;this.state.listItems.find(i=>i.id===`${this.parent}.${b.I18n.t("Folder")}_${s}`);)s++;return`${b.I18n.t("Folder")} ${s}`}onCloseMenu(s){this.setState({menuOpened:!1,menuAnchorEl:null,menuAnchorFilterEl:null},s)}getMainMenu(s,i){var l,u,d,p;const r=this.state.expertMode&&!!Object.keys(this.props.changedScripts).find(m=>{var f,v;return this.props.changedScripts[m]&&((v=(f=this.props.scripts[m])==null?void 0:f.native)==null?void 0:v.protected)});return g.jsxs(cm,{id:"long-menu",anchorEl:this.state.menuAnchorEl,open:this.state.menuOpened,onClose:()=>this.setState({menuOpened:!1,menuAnchorEl:null}),slotProps:{paper:{style:{maxHeight:Ax*7.5}}},children:[this.state.width<=Nr?g.jsxs(Ge,{disabled:this.props.debugMode||!this.state.selected||this.state.selected===$o||this.state.selected===fn||!!(s!=null&&s.length),onClick:m=>{if(m.stopPropagation(),m.preventDefault(),this.state.listItems.find(f=>f.parent===this.state.selected)){this.showError(b.I18n.t("Cannot delete non empty item!"));return}this.setState({menuOpened:!1,menuAnchorEl:null},()=>this.onDelete(this.state.selected).then(()=>{}))},children:[g.jsx(dc,{style:{...fe.iconDropdownMenu,color:"red"}}),b.I18n.t("Delete")]},"delete"):null,g.jsxs(Ge,{disabled:this.props.debugMode||r,selected:this.state.expertMode,onClick:m=>{m.stopPropagation(),m.preventDefault(),this.onCloseMenu(()=>this.props.onExpertModeChange&&this.props.onExpertModeChange(!this.state.expertMode))},children:[g.jsx(b.IconExpert,{style:{...fe.iconDropdownMenu,color:this.state.expertMode?"orange":"inherit"}}),b.I18n.t("Expert mode")]},"expertMode"),this.props.onExport&&g.jsxs(Ge,{onClick:m=>{m.stopPropagation(),m.preventDefault(),this.onCloseMenu(()=>this.props.onExport())},children:[g.jsx(vc,{style:fe.iconDropdownMenu}),b.I18n.t("Export all scripts")]},"exportAll"),this.props.onImport&&g.jsxs(Ge,{disabled:this.props.debugMode,onClick:m=>{m.stopPropagation(),m.preventDefault(),this.onCloseMenu(()=>this.props.onImport())},children:[g.jsx(Rg,{style:fe.iconDropdownMenu}),b.I18n.t("Import scripts")]},"import"),this.props.onThemeChange&&g.jsxs(Ge,{onClick:()=>this.onCloseMenu(()=>{this.props.onThemeChange&&this.props.onThemeChange(b.Utils.toggleTheme(this.state.themeName))}),children:[g.jsx(hx,{style:fe.iconDropdownMenu}),b.I18n.t('Change theme (actual "%s")',this.state.themeName)]},"dark"),this.props.onAddNew&&g.jsxs(Ge,{disabled:!this.state.selected||!i||i.type==="folder",onClick:m=>{const f=this.state.selected;this.onCloseMenu(()=>this.onCopy(m,f))},children:[g.jsx(Zk,{style:fe.iconDropdownMenu}),b.I18n.t("Copy script")]},"copy"),this.state.expertMode&&g.jsxs(Ge,{disabled:this.props.debugMode,onClick:m=>{m.stopPropagation(),m.preventDefault(),this.onCloseMenu(()=>this.setState({showAdapterDebug:!0}))},children:[g.jsx(nx,{style:fe.iconDropdownMenu}),b.I18n.t("Debug instance")]},"debugInstance"),this.state.selected&&this.props.password&&this.props.scripts[this.state.selected].type==="script"?g.jsxs(Ge,{disabled:this.props.debugMode||this.props.changedScripts[this.state.selected],onClick:m=>{m.stopPropagation(),m.preventDefault(),this.onCloseMenu(async()=>{var v;const f=await this.props.socket.getObject(this.state.selected);f&&((v=f.native)!=null&&v.protected?(delete f.native.protected,f.common.source=Ug(this.props.password,f.common.source||"")):(f.native||={},f.native.protected=!0,f.common.source=mc(this.props.password,f.common.source||"")),await this.props.socket.setObject(f._id,f))})},children:[g.jsx(w_,{style:{...fe.iconDropdownMenu,color:"orange"}}),(u=(l=this.props.scripts[this.state.selected])==null?void 0:l.native)!=null&&u.protected?g.jsx("span",{style:{color:(p=(d=this.props.scripts[this.state.selected])==null?void 0:d.native)!=null&&p.protected?"orange":void 0},children:b.I18n.t("Unprotect script")}):b.I18n.t("Protect script")]},"encrypt"):null]},"menu")}getToolbarButtons(){const s=[],i=this.state.reorder&&!this.props.debugMode;if(this.state.searchMode&&!this.props.debugMode)s.push(g.jsx(Dn,{value:this.state.searchText,style:fe.toolbarSearch,ref:this.inputRef,autoFocus:!0,placeholder:b.I18n.t("Search..."),onChange:r=>{this.setState({searchText:r.target.value}),this.filterTimer&&clearTimeout(this.filterTimer),this.filterTimer=setTimeout(()=>{this.filterTimer=null,this.filterList(!0),this.props.onSearch&&this.props.onSearch(this.state.searchText)},400)}},"searchInput")),s.push(g.jsx(Me,{sx:fe.toolbarButtons,style:{float:"right"},title:b.I18n.t("End search mode"),onClick:r=>{r.stopPropagation(),this.filterList(!1,()=>this.props.onSearch&&this.props.onSearch(this.state.searchText))},size:"medium",children:g.jsx(lx,{})},"disableSearch")),this.state.searchText&&s.push(g.jsx(Me,{title:b.I18n.t("Clear search input"),sx:fe.toolbarButtons,style:{marginTop:7,float:"right"},onClick:r=>{r.stopPropagation(),this.setState({searchText:""},()=>{this.filterList(!0),this.props.onSearch&&this.props.onSearch(this.state.searchText)})},size:"medium",children:g.jsx(Ow,{fontSize:"small"})},"cleanSearch"));else{if(!i){s.push(g.jsx(Me,{"aria-label":"More","aria-owns":this.state.menuOpened?"long-menu":void 0,title:b.I18n.t("Menu"),"aria-haspopup":"true",onClick:u=>{u.stopPropagation(),u.preventDefault(),this.setState({menuOpened:!0,menuAnchorEl:u.currentTarget})},size:"medium",children:g.jsx(dx,{})},"menuButton"));const r=this.state.listItems.find(u=>u.id===this.state.selected);let l;r&&this.state.width<=Nr&&r.type==="folder"&&(l=this.state.listItems.filter(u=>u.parent===this.state.selected)),s.push(this.getMainMenu(l,r)),s.push(g.jsx(Me,{disabled:this.props.debugMode,title:b.I18n.t("Create new script"),sx:{...fe.toolbarButtons,...this.props.debugMode?fe.iconButtonsDisabled:void 0},style:{color:i?"red":"inherit"},onClick:u=>this.onAddNew(u),size:"medium",children:g.jsx(Qk,{})},"new-script")),s.push(g.jsx(Me,{disabled:this.props.debugMode,title:b.I18n.t("Create new folder"),sx:{...fe.toolbarButtons,...this.props.debugMode?fe.iconButtonsDisabled:void 0},style:{color:i?"red":"inherit"},onClick:u=>this.onAddNewFolder(u),size:"medium",children:g.jsx(eS,{})},"new-folder"))}s.push(g.jsx(Me,{disabled:i||this.props.debugMode,sx:{...fe.toolbarButtons,...this.props.debugMode?fe.iconButtonsDisabled:void 0},title:b.I18n.t("Search in scripts"),style:{float:"right",opacity:this.props.debugMode?.5:i?0:1},onClick:r=>{r.stopPropagation(),this.setState({searchMode:!0})},size:"medium",children:g.jsx(gx,{})},"search")),s.push(g.jsx(Me,{disabled:this.props.debugMode,title:b.I18n.t("Reorder scripts in folders"),sx:{...fe.toolbarButtons,...this.props.debugMode?fe.iconButtonsDisabled:void 0},style:{color:i?"red":"inherit",float:"right"},onClick:r=>{r.stopPropagation(),this.setState({reorder:!this.state.reorder})},size:"medium",children:g.jsx(bx,{})},"reorder")),!i&&this.state.selected&&this.state.selected!==$o&&this.state.selected!==fn&&s.push(g.jsx(Me,{sx:{...fe.toolbarButtons,...this.props.debugMode?fe.iconButtonsDisabled:void 0},disabled:this.props.debugMode,title:b.I18n.t("Rename"),onClick:r=>this.onRename(r),size:"medium",children:g.jsx(tS,{})},"rename")),s.push(g.jsxs("span",{style:{opacity:.5,fontSize:10},children:["v",this.props.version]},"version"))}return s}getFolders(){const s=[{id:Wt,name:b.I18n.t("Root folder")}];return this.state.listItems.forEach(i=>{i.type==="folder"&&i.id!==Wt&&(!i.id.startsWith($o)||this.state.expertMode)&&s.push({id:i.id,name:i.title})}),s}onCollapseAll(){this.setState({expanded:[]}),this.saveExpanded([])}onExpandAll(){const s=[];this.state.listItems.forEach(i=>this.state.listItems.find(r=>r.parent===i.id)&&s.push(i.id)),this.setState({expanded:s}),this.saveExpanded(s)}getBottomButtons(){return this.state.reorder||this.props.debugMode?null:[g.jsx($t,{sx:fe.footerButtons,title:b.I18n.t("Show only running scripts"),onClick:s=>{s.stopPropagation(),s.preventDefault();const i=this.state.statusFilter==="running"?"":"running";window.localStorage&&window.localStorage.setItem("SideMenu.statusFilter",i),this.setState({statusFilter:i})},children:g.jsx(gc,{style:{color:C_,opacity:this.state.statusFilter==="running"?1:.3,background:this.state.statusFilter==="running"?"gray":"inherit"}})},"filterByRunning"),g.jsx($t,{sx:fe.footerButtons,title:b.I18n.t("Show only paused scripts"),onClick:()=>{const s=this.state.statusFilter==="paused"?"":"paused";window.localStorage&&window.localStorage.setItem("SideMenu.statusFilter",s),this.setState({statusFilter:s})},children:g.jsx(Fg,{style:{color:k_,opacity:this.state.statusFilter==="paused"?1:.3,background:this.state.statusFilter==="paused"?"gray":"inherit"}})},"filterByPaused"),g.jsx($t,{sx:fe.footerButtons,style:{marginRight:16},title:b.I18n.t("Show only scripts with problems"),onClick:()=>{const s=this.state.statusFilter==="problems"?"":"problems";window.localStorage&&window.localStorage.setItem("SideMenu.statusFilter",s),this.setState({statusFilter:s})},children:g.jsx(gc,{style:{color:T_,opacity:this.state.statusFilter==="problems"?1:.3,background:this.state.statusFilter==="problems"?"gray":"inherit"}})},"filterByProblem"),g.jsx($t,{sx:fe.footerButtons,children:g.jsx("img",{alt:"Blockly",style:{opacity:this.state.typeFilter==="Blockly"?1:.3,background:this.state.typeFilter==="Blockly"?"gray":"inherit"},src:$n.Blockly,onClick:()=>{const s=this.state.typeFilter==="Blockly"?"":"Blockly";window.localStorage&&window.localStorage.setItem("SideMenu.typeFilter",s),this.setState({typeFilter:s})}})},"filterBlockly"),g.jsx($t,{sx:fe.footerButtons,children:g.jsx("img",{alt:"Javascript",style:{opacity:this.state.typeFilter==="Javascript/js"?1:.3,background:this.state.typeFilter==="Javascript/js"?"gray":"inherit"},src:$n["Javascript/js"],onClick:()=>{const s=this.state.typeFilter==="Javascript/js"?"":"Javascript/js";window.localStorage&&window.localStorage.setItem("SideMenu.typeFilter",s),this.setState({typeFilter:s})}})},"filterJS"),g.jsx($t,{sx:fe.footerButtons,children:g.jsx("img",{alt:"TypeScript",style:{opacity:this.state.typeFilter==="TypeScript/ts"?1:.3,background:this.state.typeFilter==="TypeScript/ts"?"gray":"inherit"},src:$n["TypeScript/ts"],onClick:()=>{const s=this.state.typeFilter==="TypeScript/ts"?"":"TypeScript/ts";window.localStorage&&window.localStorage.setItem("SideMenu.typeFilter",s),this.setState({typeFilter:s})}})},"filterTS"),g.jsx($t,{sx:fe.footerButtons,children:g.jsx("img",{alt:"Rules",style:{opacity:this.state.typeFilter==="Rules"?1:.3,background:this.state.typeFilter==="Rules"?"gray":"inherit"},src:$n.Rules,onClick:()=>{const s=this.state.typeFilter==="Rules"?"":"Rules";window.localStorage&&window.localStorage.setItem("SideMenu.typeFilter",s),this.setState({typeFilter:s})}})},"filterRules"),g.jsx("div",{style:{flexGrow:1}},"padding"),g.jsx($t,{sx:fe.footerButtons,onClick:()=>this.onExpandAll(),title:b.I18n.t("Expand all"),children:g.jsx(yx,{style:fe.footerButtonsRight})},"expandAll"),this.state.expanded.length?g.jsx($t,{sx:fe.footerButtons,onClick:()=>this.onCollapseAll(),title:b.I18n.t("Collapse all"),children:g.jsx(vx,{style:fe.footerButtonsRight})},"collapseAll"):g.jsx("div",{style:{height:22,width:24}})]}getAdapterDebugDialog(){return this.state.showAdapterDebug?g.jsx(Ex,{socket:this.props.socket,onClose:()=>this.setState({showAdapterDebug:!1}),onDebug:(s,i)=>this.setState({showAdapterDebug:!1},()=>this.props.onDebugInstance({instance:s,adapter:i}))},"debug"):null}render(){var r,l,u;const s=this.state.renaming?this.state.listItems.find(d=>d.id===this.state.renaming):void 0,i=this.state.copingScript&&this.props.scripts[this.state.copingScript].type==="script"?this.props.scripts[this.state.copingScript]:void 0;return[g.jsxs(Mk,{variant:"permanent",style:fe.menu,sx:{"& .MuiDrawer-paper":fe.drawerPaper},anchor:"left",onClick:()=>this.onClick({id:""}),children:[g.jsx($t,{sx:fe.toolbar,children:this.getToolbarButtons()}),g.jsx(e_,{}),g.jsx(Zw,{backend:uC,children:g.jsx("div",{style:fe.innerMenu,children:this.renderAllItems(this.state.listItems)})}),g.jsx(e_,{}),g.jsx("div",{style:fe.footer,children:this.getBottomButtons()})]},"drawer"),s?g.jsx($m,{name:s.title,id:this.state.renaming||"",folder:s.type==="folder",instance:s.instance,instances:this.props.instances,onClose:()=>this.setState({renaming:null}),onRename:(d,p,m,f)=>this.props.onRename&&this.props.onRename(d,p,m,f)},"dialog-rename"):null,this.state.deleting?g.jsx(_x,{name:this.state.listItems.find(d=>d.id===this.state.deleting).title,id:this.state.deleting,onClose:()=>this.setState({deleting:null}),onDelete:d=>this.props.onDelete&&this.props.onDelete(d)},"dialog-delete"):null,this.state.choosingType?g.jsx(Cn,{onClose:d=>{const p={choosingType:!1};d&&(p.creatingScript=d),this.setState(p)}},"dialog-script-type"):null,this.state.creatingScript?g.jsx(tg,{onClose:()=>this.setState({creatingScript:null}),title:b.I18n.t("Create new script"),name:this.getUniqueName(),parents:this.getFolders(),folder:!1,existingItems:this.state.listItems.map(d=>d.id),instance:this.props.instances[0]||0,instances:this.props.instances,type:this.state.creatingScript,parent:this.parent,onAdd:(d,p,m,f)=>this.props.onAddNew&&this.props.onAddNew(d,p,!1,m,f)},"dialog-new-script"):null,this.state.copingScript?g.jsx(tg,{onClose:()=>this.setState({copingScript:""}),title:b.I18n.t("Copy script"),name:this.getUniqueName(this.state.copingScript),parents:this.getFolders(),folder:!1,instance:parseInt((l=(r=i==null?void 0:i.common)==null?void 0:r.engine)==null?void 0:l.split(".").pop(),10)||0,instances:this.props.instances,type:((u=i==null?void 0:i.common)==null?void 0:u.engineType)||"Javascript/js",parent:this.parent,onAdd:(d,p,m,f)=>{var _;const v=this.state.copingScript&&this.props.scripts[this.state.copingScript].type==="script"?this.props.scripts[this.state.copingScript]:void 0;v!=null&&v.common&&(v.common.enabled=!1),this.props.onAddNew&&this.props.onAddNew(d,p,!1,m,f,(_=v==null?void 0:v.common)==null?void 0:_.source)}},"dialog-copy-script"):null,this.state.creatingFolder?g.jsx(tg,{onClose:()=>this.setState({creatingFolder:!1}),title:b.I18n.t("Create new folder"),parents:this.getFolders(),name:this.getUniqueFolderName(),parent:this.parent,onAdd:(d,p)=>this.props.onAddNew&&this.props.onAddNew(d,p,!0)},"dialog-new-folder"):null,this.state.errorText?g.jsx(Zc,{onClose:()=>this.setState({errorText:""}),text:this.state.errorText},"error"):null,this.getAdapterDebugDialog()]}}const Mx="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGAAAABgAQMAAADYVuV7AAAABlBMVEUAAAAzMzPI8eYgAAAAAXRSTlMAQObYZgAAACFJREFUeAFjAIJRwP////8PYIKWHCigNQdKj/pn1D+jAABTG16wVQqVpQAAAABJRU5ErkJggg==",Nx="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGAAAABgAQMAAADYVuV7AAAABlBMVEUAAAAzMzPI8eYgAAAAAXRSTlMAQObYZgAAABtJREFUeAFjAIJRwP8fCj7QkENn/4z6Z5QzCgBjbWaoyx1PqQAAAABJRU5ErkJggg==";function Lx(a){let s,i=a.getHours();return i<10&&(i=`0${i.toString()}`),s=`${i}:`,i=a.getMinutes(),i<10&&(i=`0${i.toString()}`),s+=`${i}:`,i=a.getSeconds(),i<10&&(i=`0${i.toString()}`),s+=`${i}.`,i=a.getMilliseconds(),i<10?i=`00${i.toString()}`:i<100&&(i=`0${i.toString()}`),s+=i,s}const I_=34,Bt={logBox:{width:"100%",height:"100%",position:"relative",overflow:"hidden"},logBoxInner:a=>({display:"inline-block",color:a.palette.mode==="dark"?"white":"black",width:`calc(100% - ${I_}px)`,height:"100%",overflow:"auto",position:"relative",verticalAlign:"top"}),info:a=>({background:a.palette.mode==="dark"?"darkgrey":"lightgrey",color:(a.palette.mode==="dark","black")}),error:a=>({background:"#FF0000",color:a.palette.mode==="dark"?"black":"white"}),warn:a=>({background:"#FF8000",color:a.palette.mode==="dark"?"black":"white"}),debug:a=>({background:"gray",opacity:.8,color:a.palette.mode==="dark"?"black":"white"}),silly:a=>({background:"gray",opacity:.6,color:a.palette.mode==="dark"?"black":"white"}),table:{fontFamily:"monospace",width:"100%"},toolbox:{width:I_,height:"100%",boxShadow:"2px 0px 4px -1px rgba(0, 0, 0, 0.2), 4px 0px 5px 0px rgba(0, 0, 0, 0.14), 1px 0px 10px 0px rgba(0, 0, 0, 0.12)",display:"inline-block",verticalAlign:"top",overflow:"hidden"},trFrom:{width:90},trTime:{width:90},trSeverity:{width:40,fontWeight:"bold"},trPreMessage:{padding:0,margin:0},iconButtons:{width:32,height:32,padding:4},layoutIcon:a=>({"& img":{width:24,height:24,background:a.palette.mode==="dark"?"#9d9d9d":void 0,borderRadius:a.palette.mode==="dark"?"30px":void 0}})};function Px(a){return a<10?`00${a}`:a<100?`0${a}`:a.toString()}const Ks={};class bm extends Y.Component{messagesEnd;constructor(s){super(s),this.state={lines:{},goBottom:!0,selected:null,editing:this.props.editing||[]},this.messagesEnd=Y.createRef()}static generateLine(s,i){let r=s.message||"";if(typeof r!="object"){const l=new RegExp(`${s.from.replace(".","\\.").replace(")","\\)").replace("(","\\(")} \\(\\d+\\) `,"g"),u=r.match(l);u?r=r.replace(u[0],""):r=r.replace(`${s.from} `,"")}return r.startsWith(`${i}: `)&&(r=r.substring(i.length+2)),g.jsxs($t,{component:"tr",sx:Bt[s.severity],children:[g.jsx("td",{style:Bt.trFrom,children:s.from}),g.jsx("td",{style:Bt.trTime,children:Lx(new Date(s.ts))}),g.jsx("td",{style:Bt.trSeverity,children:s.severity}),g.jsx("td",{children:g.jsx("pre",{style:Bt.trPreMessage,children:r})})]},`tr_${s.ts}_${s.message.substring(s.message.length-10)}`)}scrollToBottom(){var s,i;(i=(s=this.messagesEnd)==null?void 0:s.current)==null||i.scrollIntoView({behavior:"smooth"})}logHandler=s=>{const i=this.state.lines,r=this.state.editing.filter(f=>s.message.includes(f));let l=null;if(!r.length||(r.length===1?l=r[0]:(r.sort(),l=r[r.length-1]),!l))return;const u=i[l]||[],d=Ks[l]||[];u.push(bm.generateLine(s,l));let p=s.severity;(p==="info"||p==="warn")&&(p+=" ");const m=new Date(s.ts);d.push(`${m.toLocaleString()}.${Px(m.getMilliseconds())} [${p}]: ${s.message}`),u.length>300&&(u.splice(0,u.length-300),d.splice(0,u.length-300)),Ks[l]=d,i[l]=u,this.setState({lines:i})};componentDidMount(){this.props.socket.registerLogHandler(this.logHandler)}componentWillUnmount(){this.props.socket.unregisterLogHandler(this.logHandler)}componentDidUpdate(){this.state.goBottom&&this.scrollToBottom()}static getDerivedStateFromProps(s,i){let r=!1;const l={};if(s.selected!==i.selected){const u=s.selected,d=i.lines;u&&(d[u]=d[u]||[],Ks[u]=Ks[u]||[]),l.selected=u,r=!0}if(JSON.stringify(s.editing)!==JSON.stringify(i.editing)){const u=JSON.parse(JSON.stringify(s.editing));r=!0;const d=i.lines;for(const p in Ks)Object.prototype.hasOwnProperty.call(Ks,p)&&(u.includes(p)||(delete Ks[p],delete d[p]));l.editing=u}return r?l:null}onCopy(){b.Utils.copyToClipboard((Ks[this.state.selected]||[]).join(` -`))}clearLog(){const s=this.state.lines;s[this.state.selected]&&(s[this.state.selected]=[]),Ks[this.state.selected]&&(Ks[this.state.selected]=[]),this.setState({lines:s})}renderLogList(s){return this.state.selected&&(s!=null&&s.length)?g.jsxs($t,{sx:Bt.logBoxInner,children:[g.jsx("table",{style:Bt.table,children:g.jsx("tbody",{children:s})},"logTable"),g.jsx("div",{ref:this.messagesEnd,style:{float:"left",clear:"both"}},"logScrollPoint")]},"logList"):g.jsx($t,{sx:Bt.logBoxInner,style:{paddingLeft:10},children:b.I18n.t("Log outputs")},"logList")}render(){const s=this.state.selected?this.state.lines[this.state.selected]:null;return g.jsxs("div",{style:Bt.logBox,children:[g.jsxs("div",{style:Bt.toolbox,children:[g.jsx(Me,{style:Bt.iconButtons,onClick:()=>this.setState({goBottom:!this.state.goBottom}),color:this.state.goBottom?"secondary":void 0,size:"medium",children:g.jsx(sS,{})}),s!=null&&s.length?g.jsx(Me,{style:Bt.iconButtons,onClick:()=>this.clearLog(),size:"medium",children:g.jsx(oS,{})}):null,s!=null&&s.length?g.jsx(Me,{style:Bt.iconButtons,onClick:()=>this.onCopy(),size:"medium",children:g.jsx(iS,{})}):null,this.props.onLayoutChange?g.jsx(Me,{style:Bt.iconButtons,onClick:()=>this.props.onLayoutChange&&this.props.onLayoutChange(),title:b.I18n.t("Change layout"),size:"medium",sx:Bt.layoutIcon,children:g.jsx("img",{alt:"split",src:this.props.verticalLayout?Mx:Nx})}):null,g.jsx(Me,{style:Bt.iconButtons,onClick:()=>this.props.onHideLog(),title:b.I18n.t("Hide logs"),size:"medium",children:g.jsx(nS,{})})]},"toolbox"),this.renderLogList(s)]})}}var x_="focus-outline-hidden";function $C(){var a=this;document.addEventListener("keydown",function(s){a.focusByKeyboard=!0},!0),document.addEventListener("mousedown",function(s){a.focusByKeyboard=!1},!0),document.addEventListener("focus",function(s){a.updateVisibility()},!0),document.addEventListener("focusout",function(s){window.setTimeout(function(){document.hasFocus()||(a.focusByKeyboard=!0,a.updateVisibility())},0)}),this.updateVisibility()}$C.prototype={focusByKeyboard:!0,updateVisibility:function(){this.hidden=!this.focusByKeyboard},set hidden(a){document.documentElement.classList.toggle(x_,a)},get hidden(){return document.documentElement.classList.contains(x_)}};new $C;var bC={exports:{}};(function(a){(function(){var s={}.hasOwnProperty;function i(){for(var r=[],l=0;l4&&arguments[4]!==void 0?arguments[4]:"easeInOutCubic";return r>l?i:s+(i-s)*jx[u](r/l)};Ei.calcEndPoint=function(s){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:window,r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0;if(Fx(s))return parseInt(s)+r;var l=i===window||i===document.documentElement?window.pageYOffset:i.scrollTop-i.getBoundingClientRect().top,u=s.nodeName.toLowerCase()==="html"?-l:s.getBoundingClientRect().top+l;return u+r};(function(a,s){Object.defineProperty(s,"__esModule",{value:!0});var i=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(l){return typeof l}:function(l){return l&&typeof Symbol=="function"&&l.constructor===Symbol&&l!==Symbol.prototype?"symbol":typeof l},r=Ei;s.default=function(l){var u=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},d=u.duration,p=d===void 0?500:d,m=u.context,f=m===void 0?window:m,v=u.offset,_=v===void 0?0:v,y=u.ease,k=y===void 0?"easeInOutCubic":y,C=u.callback;if((typeof window>"u"?"undefined":i(window))==="object"){var w=f.scrollTop!==null&&f.scrollTop!==void 0?f.scrollTop:window.pageYOffset,E=(0,r.calcEndPoint)(l,f,_),R=performance.now(),D=window.requestAnimationFrame,A=function J(){var ie=performance.now()-R,se=(0,r.setPosition)(w,E,ie,p,k);f!==window?f.scrollTop=se:window.scroll(0,se),ie>p?typeof C=="function"&&C(l):D(J)};A()}},a.exports=s.default})(Gg,Gg.exports);var vC=Gg.exports,Vg={exports:{}};(function(a,s){Object.defineProperty(s,"__esModule",{value:!0});var i=Object.assign||function(d){for(var p=1;p0&&arguments[0]!==void 0?arguments[0]:{},p=d.query,m=p===void 0?'[href^="#"]:not([href="#"]':p,f=d.match,v=f===void 0?function(E){return document.getElementById(E.hash.substring(1))}:f,_=d.hashChange,y=_===void 0?!0:_,k=d.scrollSmoothConfig,C=document.querySelectorAll(m),w=function(R){R.preventDefault();var D=v(R.target);D&&(y&&history.replaceState(null,null,"#"+D.id),(0,l.default)(D,i({},k)))};Array.from(C).map(function(E){E.addEventListener("click",w,!1)})},a.exports=s.default})(Vg,Vg.exports);var zx=Vg.exports,Kg={exports:{}};(function(a,s){Object.defineProperty(s,"__esModule",{value:!0});function i(r){if(Array.isArray(r)){for(var l=0,u=Array(r.length);l0&&arguments[0]!==void 0?arguments[0]:{},l=r.activeClass,u=l===void 0?"active":l,d=r.query,p=d===void 0?'[href^="#"]:not([href="#"]):not([href="#0"])':d,m=r.threshold,f=m===void 0?[.25,.5,.75]:m,v=r.detectType,_=v===void 0?"max":v,y={threshold:f},k=function(se){return se.classList.remove(u)},C=function(se){return se.classList.add(u)},w=function(){document.querySelectorAll("."+u).forEach(k)},E=function(se){w(),C(document.querySelector('a[href="#'+se.id+'"]'))},R=function(se){se.forEach(function(me){me.intersectionRatio>=Math[_].apply(Math,i(f))&&E(me.target)})},D=document.querySelectorAll(p),A=new IntersectionObserver(R,y),J=function(se){var me=document.querySelector("#"+se.hash.slice(1));A.observe(me)};D.forEach(J)},a.exports=s.default})(Kg,Kg.exports);var Ux=Kg.exports;(function(a,s){Object.defineProperty(s,"__esModule",{value:!0});var i=vC,r=f(i),l=Ei,u=zx,d=f(u),p=Ux,m=f(p);function f(v){return v&&v.__esModule?v:{default:v}}s.default={to:r.default,calcEndPoint:l.calcEndPoint,anchorScroll:d.default,observe:m.default},a.exports=s.default})(Wg,Wg.exports);var Hx=Wg.exports;const Wx=Si(Hx);var vm={exports:{}},Gx=vm.exports;(function(a){(function(s,i){a.exports?a.exports=i():s.Scrollparent=i()})(Gx,function(){var s=/(auto|scroll)/,i=function(p,m){return p.parentNode===null?m:i(p.parentNode,m.concat([p]))},r=function(p,m){return getComputedStyle(p,null).getPropertyValue(m)},l=function(p){return r(p,"overflow")+r(p,"overflow-y")+r(p,"overflow-x")},u=function(p){return s.test(l(p))},d=function(p){if(p instanceof HTMLElement||p instanceof SVGElement){for(var m=i(p.parentNode,[]),f=0;f=s||me<0||_&&z>=u}function R(){var se=sg();if(E(se))return D(se);p=setTimeout(R,w(se))}function D(se){return p=void 0,y&&r?k(se):(r=l=void 0,d)}function A(){p!==void 0&&clearTimeout(p),f=0,r=m=l=p=void 0}function J(){return p===void 0?d:D(sg())}function ie(){var se=sg(),me=E(se);if(r=arguments,l=this,m=se,me){if(p===void 0)return C(m);if(_)return p=setTimeout(R,s),k(m)}return p===void 0&&(p=setTimeout(R,s)),d}return ie.cancel=A,ie.flush=J,ie}function Yg(a){var s=typeof a;return!!a&&(s=="object"||s=="function")}function cD(a){return!!a&&typeof a=="object"}function uD(a){return typeof a=="symbol"||cD(a)&&nD.call(a)==Jx}function R_(a){if(typeof a=="number")return a;if(uD(a))return A_;if(Yg(a)){var s=typeof a.valueOf=="function"?a.valueOf():a;a=Yg(s)?s+"":s}if(typeof a!="string")return a===0?a:+a;a=a.replace(qx,"");var i=Zx.test(a);return i||Qx.test(a)?eD(a.slice(2),i?2:8):Xx.test(a)?A_:+a}var dD=lD;const hD=Si(dD);var Jg="data-focus-lock",yC="data-focus-lock-disabled",pD="data-no-focus-lock",gD="data-autofocus-inside",mD="data-no-autofocus";function og(a,s){return typeof a=="function"?a(s):a&&(a.current=s),a}function fD(a,s){var i=vt(function(){return{value:a,callback:s,facade:{get current(){return i.value},set current(r){var l=i.value;l!==r&&(i.value=r,i.callback(r,l))}}}})[0];return i.callback=s,i.facade}var $D=typeof window<"u"?lm:Mt,O_=new WeakMap;function bD(a,s){var i=fD(null,function(r){return a.forEach(function(l){return og(l,r)})});return $D(function(){var r=O_.get(i);if(r){var l=new Set(r),u=new Set(a),d=i.current;l.forEach(function(p){u.has(p)||og(p,null)}),u.forEach(function(p){l.has(p)||og(p,d)})}O_.set(i,a)},[a]),i}var ig={width:"1px",height:"0px",padding:0,overflow:"hidden",position:"fixed",top:"1px",left:"1px"};function _C(a){return a}function wC(a,s){s===void 0&&(s=_C);var i=[],r=!1,l={read:function(){if(r)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return i.length?i[i.length-1]:a},useMedium:function(u){var d=s(u,r);return i.push(d),function(){i=i.filter(function(p){return p!==d})}},assignSyncMedium:function(u){for(r=!0;i.length;){var d=i;i=[],d.forEach(u)}i={push:function(p){return u(p)},filter:function(){return i}}},assignMedium:function(u){r=!0;var d=[];if(i.length){var p=i;i=[],p.forEach(u),d=i}var m=function(){var v=d;d=[],v.forEach(u)},f=function(){return Promise.resolve().then(m)};f(),i={push:function(v){d.push(v),f()},filter:function(v){return d=d.filter(v),i}}}};return l}function ym(a,s){return s===void 0&&(s=_C),wC(a,s)}function vD(a){a===void 0&&(a={});var s=wC(null);return s.options=rS({async:!0,ssr:!1},a),s}var CC=ym({},function(a){var s=a.target,i=a.currentTarget;return{target:s,currentTarget:i}}),TC=ym(),yD=ym(),_D=vD({async:!0,ssr:typeof document<"u"}),wD=rm(void 0),CD=[],_m=Sw(function(s,i){var r,l=vt(),u=l[0],d=l[1],p=Bo(),m=Bo(!1),f=Bo(null),v=vt({}),_=v[1],y=s.children,k=s.disabled,C=k===void 0?!1:k,w=s.noFocusGuards,E=w===void 0?!1:w,R=s.persistentFocus,D=R===void 0?!1:R,A=s.crossFrame,J=A===void 0?!0:A,ie=s.autoFocus,se=ie===void 0?!0:ie;s.allowTextSelection;var me=s.group,z=s.className,Oe=s.whiteList,Ne=s.hasPositiveIndices,Ze=s.shards,ae=Ze===void 0?CD:Ze,ce=s.as,K=ce===void 0?"div":ce,ye=s.lockProps,he=ye===void 0?{}:ye,je=s.sideCar,V=s.returnFocus,tt=V===void 0?!1:V,q=s.focusOptions,ee=s.onActivation,B=s.onDeactivation,H=vt({}),U=H[0],re=_n(function(ke){var $e=ke.captureFocusRestore;if(!f.current){var Pe,bt=(Pe=document)==null?void 0:Pe.activeElement;f.current=bt,bt!==document.body&&(f.current=$e(bt))}p.current&&ee&&ee(p.current),m.current=!0,_()},[ee]),I=_n(function(){m.current=!1,B&&B(p.current),_()},[B]),de=_n(function(ke){var $e=f.current;if($e){var Pe=(typeof $e=="function"?$e():$e)||document.body,bt=typeof tt=="function"?tt(Pe):tt;if(bt){var X=typeof bt=="object"?bt:void 0;f.current=null,ke?Promise.resolve().then(function(){return Pe.focus(X)}):Pe.focus(X)}}},[tt]),W=_n(function(ke){m.current&&CC.useMedium(ke)},[]),Ce=TC.useMedium,be=_n(function(ke){p.current!==ke&&(p.current=ke,d(ke))},[]),Se=Tg((r={},r[yC]=C&&"disabled",r[Jg]=me,r),he),pe=E!==!0,Ve=pe&&E!=="tail",Je=bD([i,be]),_e=rs(function(){return{observed:p,shards:ae,enabled:!C,active:m.current}},[C,m.current,ae,u]);return Y.createElement(Sg,null,pe&&[Y.createElement("div",{key:"guard-first","data-focus-guard":!0,tabIndex:C?-1:0,style:ig}),Ne?Y.createElement("div",{key:"guard-nearest","data-focus-guard":!0,tabIndex:C?-1:1,style:ig}):null],!C&&Y.createElement(je,{id:U,sideCar:_D,observed:u,disabled:C,persistentFocus:D,crossFrame:J,autoFocus:se,whiteList:Oe,shards:ae,onActivation:re,onDeactivation:I,returnFocus:de,focusOptions:q,noFocusGuards:E}),Y.createElement(K,Tg({ref:Je},Se,{className:z,onBlur:Ce,onFocus:W}),Y.createElement(wD.Provider,{value:_e},y)),Ve&&Y.createElement("div",{"data-focus-guard":!0,tabIndex:C?-1:0,style:ig}))});_m.propTypes={};function TD(a,s){function i(r){return r.displayName||r.name||"Component"}return function(l){var u=[],d;function p(){d=a(u.map(function(f){return f.props})),s(d)}var m=(function(f){ES(v,f);function v(){return f.apply(this,arguments)||this}v.peek=function(){return d};var _=v.prototype;return _.componentDidMount=function(){u.push(this),p()},_.componentDidUpdate=function(){p()},_.componentWillUnmount=function(){var k=u.indexOf(this);u.splice(k,1),p()},_.render=function(){return Y.createElement(l,this.props)},v})(Dk);return KS(m,"displayName","SideEffect("+i(l)+")"),m}}var Xs=function(a){for(var s=Array(a.length),i=0;i=0}).sort(OD)},ND=["button:enabled","select:enabled","textarea:enabled","input:enabled","a[href]","area[href]","summary","iframe","object","embed","audio[controls]","video[controls]","[tabindex]","[contenteditable]","[autofocus]"],Tm=ND.join(","),LD="".concat(Tm,", [data-focus-guard]"),OC=function(a,s){return Xs((a.shadowRoot||a).children).reduce(function(i,r){return i.concat(r.matches(s?LD:Tm)?[r]:[],OC(r))},[])},PD=function(a,s){var i;return a instanceof HTMLIFrameElement&&(!((i=a.contentDocument)===null||i===void 0)&&i.body)?An([a.contentDocument.body],s):[a]},An=function(a,s){return a.reduce(function(i,r){var l,u=OC(r,s),d=(l=[]).concat.apply(l,u.map(function(p){return PD(p,s)}));return i.concat(d,r.parentNode?Xs(r.parentNode.querySelectorAll(Tm)).filter(function(p){return p===r}):[])},[])},BD=function(a){var s=a.querySelectorAll("[".concat(gD,"]"));return Xs(s).map(function(i){return An([i])}).reduce(function(i,r){return i.concat(r)},[])},km=function(a,s){return Xs(a).filter(function(i){return IC(s,i)}).filter(function(i){return DD(i)})},M_=function(a,s){return s===void 0&&(s=new Map),Xs(a).filter(function(i){return xC(s,i)})},Sm=function(a,s,i){return Cm(km(An(a,i),s),!0,i)},Kr=function(a,s){return Cm(km(An(a),s),!1)},jD=function(a,s){return km(BD(a),s)},yi=function(a,s){return a.shadowRoot?yi(a.shadowRoot,s):Object.getPrototypeOf(a).contains!==void 0&&Object.getPrototypeOf(a).contains.call(a,s)?!0:Xs(a.children).some(function(i){var r;if(i instanceof HTMLIFrameElement){var l=(r=i.contentDocument)===null||r===void 0?void 0:r.body;return l?yi(l,s):!1}return yi(i,s)})},FD=function(a){for(var s=new Set,i=a.length,r=0;r0&&s.add(l),(u&Node.DOCUMENT_POSITION_CONTAINS)>0&&s.add(r)}return a.filter(function(d,p){return!s.has(p)})},MC=function(a){return a.parentNode?MC(a.parentNode):a},Em=function(a){var s=Ti(a);return s.filter(Boolean).reduce(function(i,r){var l=r.getAttribute(Jg);return i.push.apply(i,l?FD(Xs(MC(r).querySelectorAll("[".concat(Jg,'="').concat(l,'"]:not([').concat(yC,'="disabled"])')))):[r]),i},[])},zD=function(a){try{return a()}catch{return}},Yr=function(a){if(a===void 0&&(a=document),!(!a||!a.activeElement)){var s=a.activeElement;return s.shadowRoot?Yr(s.shadowRoot):s instanceof HTMLIFrameElement&&zD(function(){return s.contentWindow.document})?Yr(s.contentWindow.document):s}},UD=function(a,s){return a===s},HD=function(a,s){return!!Xs(a.querySelectorAll("iframe")).some(function(i){return UD(i,s)})},NC=function(a,s){return s===void 0&&(s=Yr(kC(a).ownerDocument)),!s||s.dataset&&s.dataset.focusGuard?!1:Em(a).some(function(i){return yi(i,s)||HD(i,s)})},WD=function(a){a===void 0&&(a=document);var s=Yr(a);return s?Xs(a.querySelectorAll("[".concat(pD,"]"))).some(function(i){return yi(i,s)}):!1},GD=function(a,s){return s.filter(RC).filter(function(i){return i.name===a.name}).filter(function(i){return i.checked})[0]||a},Im=function(a,s){return RC(a)&&a.name?GD(a,s):a},VD=function(a){var s=new Set;return a.forEach(function(i){return s.add(Im(i,a))}),a.filter(function(i){return s.has(i)})},N_=function(a){return a[0]&&a.length>1?Im(a[0],a):a[0]},L_=function(a,s){return a.indexOf(Im(s,a))},Xg="NEW_FOCUS",KD=function(a,s,i,r,l){var u=a.length,d=a[0],p=a[u-1],m=wm(r);if(!(r&&a.indexOf(r)>=0)){var f=r!==void 0?i.indexOf(r):-1,v=l?i.indexOf(l):f,_=l?a.indexOf(l):-1;if(f===-1)return _!==-1?_:Xg;if(_===-1)return Xg;var y=f-v,k=i.indexOf(d),C=i.indexOf(p),w=VD(i),E=r!==void 0?w.indexOf(r):-1,R=l?w.indexOf(l):E,D=w.filter(function(z){return z.tabIndex>=0}),A=r!==void 0?D.indexOf(r):-1,J=l?D.indexOf(l):A,ie=A>=0&&J>=0?J-A:R-E;if(!y&&_>=0||s.length===0)return _;var se=L_(a,s[0]),me=L_(a,s[s.length-1]);if(f<=k&&m&&Math.abs(y)>1)return me;if(f>=C&&m&&Math.abs(y)>1)return se;if(y&&Math.abs(ie)>1)return _;if(f<=k)return me;if(f>C)return se;if(y)return Math.abs(y)>1?_:(u+_+y)%u}},YD=function(a){return function(s){var i,r=(i=DC(s))===null||i===void 0?void 0:i.autofocus;return s.autofocus||r!==void 0&&r!=="false"||a.indexOf(s)>=0}},P_=function(a,s,i){var r=a.map(function(u){var d=u.node;return d}),l=M_(r.filter(YD(i)));return l&&l.length?N_(l):N_(M_(s))},Zg=function(a,s){return s===void 0&&(s=[]),s.push(a),a.parentNode&&Zg(a.parentNode.host||a.parentNode,s),s},ng=function(a,s){for(var i=Zg(a),r=Zg(s),l=0;l=0)return u}return!1},LC=function(a,s,i){var r=Ti(a),l=Ti(s),u=r[0],d=!1;return l.filter(Boolean).forEach(function(p){d=ng(d||p,p)||d,i.filter(Boolean).forEach(function(m){var f=ng(u,m);f&&(!d||yi(f,d)?d=f:d=ng(f,d))})}),d},B_=function(a,s){return a.reduce(function(i,r){return i.concat(jD(r,s))},[])},JD=function(a,s){var i=new Map;return s.forEach(function(r){return i.set(r.node,r)}),a.map(function(r){return i.get(r)}).filter(RD)},qD=function(a,s){var i=Yr(Ti(a).length>0?document:kC(a).ownerDocument),r=Em(a).filter(qg),l=LC(i||a,a,r),u=new Map,d=Kr(r,u),p=d.filter(function(C){var w=C.node;return qg(w)});if(p[0]){var m=Kr([l],u).map(function(C){var w=C.node;return w}),f=JD(m,p),v=f.map(function(C){var w=C.node;return w}),_=f.filter(function(C){var w=C.tabIndex;return w>=0}).map(function(C){var w=C.node;return w}),y=KD(v,_,m,i,s);if(y===Xg){var k=P_(d,_,B_(r,u))||P_(d,v,B_(r,u));if(k)return{node:k};console.warn("focus-lock: cannot find any node to move focus into");return}return y===void 0?y:f[y]}},XD=function(a){var s=Em(a).filter(qg),i=LC(a,a,s),r=Cm(An([i],!0),!0,!0),l=An(s,!1);return r.map(function(u){var d=u.node,p=u.index;return{node:d,index:p,lockItem:l.indexOf(d)>=0,guard:wm(d)}})},xm=function(a,s){a&&("focus"in a&&a.focus(s),"contentWindow"in a&&a.contentWindow&&a.contentWindow.focus())},rg=0,ag=!1,PC=function(a,s,i){i===void 0&&(i={});var r=qD(a,s);if(!ag&&r){if(rg>2){console.error("FocusLock: focus-fighting detected. Only one focus management system could be active. See https://github.com/theKashey/focus-lock/#focus-fighting"),ag=!0,setTimeout(function(){ag=!1},1);return}rg++,xm(r.node,i.focusOptions),rg--}};function Lr(a){if(!a)return null;if(typeof WeakRef>"u")return function(){return a||null};var s=a?new WeakRef(a):null;return function(){return(s==null?void 0:s.deref())||null}}var ZD=function(a){if(!a)return null;for(var s=[],i=a;i&&i!==document.body;)s.push({current:Lr(i),parent:Lr(i.parentElement),left:Lr(i.previousElementSibling),right:Lr(i.nextElementSibling)}),i=i.parentElement;return{element:Lr(a),stack:s,ownerDocument:a.ownerDocument}},QD=function(a){var s,i,r,l,u;if(a)for(var d=a.stack,p=a.ownerDocument,m=new Map,f=0,v=d;f-1&&(E.filter(function(D){var A=D.guard,J=D.node;return A&&J.dataset.focusAutoGuard}).forEach(function(D){var A=D.node;return A.removeAttribute("tabIndex")}),F_(R,E.length,1,E),F_(R,-1,-1,E))}}}return s},HC=function(s){wc()&&s&&(s.stopPropagation(),s.preventDefault())},Rm=function(){return Dm(wc)},$A=function(s){var i=s.target,r=s.currentTarget;r.contains(i)||dA(r,i)},bA=function(){return null},WC=function(){Am=!0},GC=function(){Am=!1,Jr="just",Dm(function(){Jr="meanwhile"})},vA=function(){document.addEventListener("focusin",HC),document.addEventListener("focusout",Rm),window.addEventListener("focus",WC),window.addEventListener("blur",GC)},yA=function(){document.removeEventListener("focusin",HC),document.removeEventListener("focusout",Rm),window.removeEventListener("focus",WC),window.removeEventListener("blur",GC)};function _A(a){return a.filter(function(s){var i=s.disabled;return!i})}var VC={moveFocusInside:PC,focusInside:NC,focusNextElement:oA,focusPrevElement:iA,focusFirstElement:nA,focusLastElement:rA,captureFocusRestore:BC};function wA(a){var s=a.slice(-1)[0];s&&!Sn&&vA();var i=Sn,r=i&&s&&s.id===i.id;Sn=s,i&&!r&&(i.onDeactivation(),a.filter(function(l){var u=l.id;return u===i.id}).length||i.returnFocus(!s)),s?(Zt=null,(!r||i.observed!==s.observed)&&s.onActivation(VC),wc(),Dm(wc)):(yA(),Zt=null)}CC.assignSyncMedium($A);TC.assignMedium(Rm);yD.assignMedium(function(a){return a(VC)});const CA=TD(_A,wA)(bA);var KC=Sw(function(s,i){return Y.createElement(_m,Tg({sideCar:CA,ref:i},s))}),YC=_m.propTypes||{};YC.sideCar;IS(YC,["sideCar"]);KC.propTypes={};var JC={exports:{}},et={};var Om=Symbol.for("react.element"),Mm=Symbol.for("react.portal"),Qc=Symbol.for("react.fragment"),eu=Symbol.for("react.strict_mode"),tu=Symbol.for("react.profiler"),su=Symbol.for("react.provider"),ou=Symbol.for("react.context"),TA=Symbol.for("react.server_context"),iu=Symbol.for("react.forward_ref"),nu=Symbol.for("react.suspense"),ru=Symbol.for("react.suspense_list"),au=Symbol.for("react.memo"),lu=Symbol.for("react.lazy"),kA=Symbol.for("react.offscreen"),qC;qC=Symbol.for("react.module.reference");function _s(a){if(typeof a=="object"&&a!==null){var s=a.$$typeof;switch(s){case Om:switch(a=a.type,a){case Qc:case tu:case eu:case nu:case ru:return a;default:switch(a=a&&a.$$typeof,a){case TA:case ou:case iu:case lu:case au:case su:return a;default:return s}}case Mm:return s}}}et.ContextConsumer=ou;et.ContextProvider=su;et.Element=Om;et.ForwardRef=iu;et.Fragment=Qc;et.Lazy=lu;et.Memo=au;et.Portal=Mm;et.Profiler=tu;et.StrictMode=eu;et.Suspense=nu;et.SuspenseList=ru;et.isAsyncMode=function(){return!1};et.isConcurrentMode=function(){return!1};et.isContextConsumer=function(a){return _s(a)===ou};et.isContextProvider=function(a){return _s(a)===su};et.isElement=function(a){return typeof a=="object"&&a!==null&&a.$$typeof===Om};et.isForwardRef=function(a){return _s(a)===iu};et.isFragment=function(a){return _s(a)===Qc};et.isLazy=function(a){return _s(a)===lu};et.isMemo=function(a){return _s(a)===au};et.isPortal=function(a){return _s(a)===Mm};et.isProfiler=function(a){return _s(a)===tu};et.isStrictMode=function(a){return _s(a)===eu};et.isSuspense=function(a){return _s(a)===nu};et.isSuspenseList=function(a){return _s(a)===ru};et.isValidElementType=function(a){return typeof a=="string"||typeof a=="function"||a===Qc||a===tu||a===eu||a===nu||a===ru||a===kA||typeof a=="object"&&a!==null&&(a.$$typeof===lu||a.$$typeof===au||a.$$typeof===su||a.$$typeof===ou||a.$$typeof===iu||a.$$typeof===qC||a.getModuleId!==void 0)};et.typeOf=_s;JC.exports=et;var XC=JC.exports;function SA(a){function s(B,H,U,re,I){for(var de=0,W=0,Ce=0,be=0,Se,pe,Ve=0,Je=0,_e,ke=_e=Se=0,$e=0,Pe=0,bt=0,X=0,ct=U.length,ze=ct-1,kt,ve="",st="",Zs="",St="",Et;$eSe)&&(X=(ve=ve.replace(" ",":")).length),0re&&(re=(H=H.trim()).charCodeAt(0)),re){case 38:return H.replace(R,"$1"+B.trim());case 58:return B.trim()+H.replace(R,"$1"+B.trim());default:if(0<1*U&&0W.charCodeAt(8))break;case 115:I=I.replace(W,"-webkit-"+W)+";"+I;break;case 207:case 102:I=I.replace(W,"-webkit-"+(102U.charCodeAt(0)&&(U=U.trim()),ee=U,U=[ee],01?s-1:0),r=1;r0?" Args: "+i.join(", "):""))}var DA=(function(){function a(i){this.groupSizes=new Uint32Array(512),this.length=512,this.tag=i}var s=a.prototype;return s.indexOfGroup=function(i){for(var r=0,l=0;l=this.groupSizes.length){for(var l=this.groupSizes,u=l.length,d=u;i>=d;)(d<<=1)<0&&aa(16,""+i);this.groupSizes=new Uint32Array(d),this.groupSizes.set(l),this.length=d;for(var p=u;p=this.length||this.groupSizes[i]===0)return r;for(var l=this.groupSizes[i],u=this.indexOfGroup(i),d=u+l,p=u;p=zr&&(zr=s+1),fc.set(a,s),Tc.set(s,a)},OA="style["+Rn+'][data-styled-version="5.3.11"]',MA=new RegExp("^"+Rn+'\\.g(\\d+)\\[id="([\\w\\d-]+)"\\].*?"([^"]*)'),NA=function(a,s,i){for(var r,l=i.split(","),u=0,d=l.length;u=0;f--){var v=m[f];if(v&&v.nodeType===1&&v.hasAttribute(Rn))return v}})(i),u=l!==void 0?l.nextSibling:null;r.setAttribute(Rn,"active"),r.setAttribute("data-styled-version","5.3.11");var d=PA();return d&&r.setAttribute("nonce",d),i.insertBefore(r,u),r},BA=(function(){function a(i){var r=this.element=ZC(i);r.appendChild(document.createTextNode("")),this.sheet=(function(l){if(l.sheet)return l.sheet;for(var u=document.styleSheets,d=0,p=u.length;d=0){var l=document.createTextNode(r),u=this.nodes[i];return this.element.insertBefore(l,u||null),this.length++,!0}return!1},s.deleteRule=function(i){this.element.removeChild(this.nodes[i]),this.length--},s.getRule=function(i){return i0&&(_+=y+",")})),u+=""+f+v+'{content:"'+_+`"}/*!sc*/ -`}}}return u})(this)},a})(),UA=/(a)(d)/gi,W_=function(a){return String.fromCharCode(a+(a>25?39:97))};function em(a){var s,i="";for(s=Math.abs(a);s>52;s=s/52|0)i=W_(s%52)+i;return(W_(s%52)+i).replace(UA,"$1-$2")}var Tn=function(a,s){for(var i=s.length;i;)a=33*a^s.charCodeAt(--i);return a},QC=function(a){return Tn(5381,a)};function eT(a){for(var s=0;s>>0);if(!i.hasNameForId(l,p)){var m=r(d,"."+p,void 0,l);i.insertRules(l,p,m)}u.push(p),this.staticRulesId=p}else{for(var f=this.rules.length,v=Tn(this.baseHash,r.hash),_="",y=0;y>>0);if(!i.hasNameForId(l,E)){var R=r(_,"."+E,void 0,l);i.insertRules(l,E,R)}u.push(E)}}return u.join(" ")},a})(),GA=/^\s*\/\/.*$/gm,VA=[":","[",".","#"];function KA(a){var s,i,r,l,u=jo,d=u.options,p=d===void 0?jo:d,m=u.plugins,f=m===void 0?Cc:m,v=new SA(p),_=[],y=(function(w){function E(R){if(R)try{w(R+"}")}catch{}}return function(R,D,A,J,ie,se,me,z,Oe,Ne){switch(R){case 1:if(Oe===0&&D.charCodeAt(0)===64)return w(D+";"),"";break;case 2:if(z===0)return D+"/*|*/";break;case 3:switch(z){case 102:case 112:return w(A[0]+D),"";default:return D+(Ne===0?"/*|*/":"")}case-2:D.split("/*|*/}").forEach(E)}}})((function(w){_.push(w)})),k=function(w,E,R){return E===0&&VA.indexOf(R[i.length])!==-1||R.match(l)?w:"."+s};function C(w,E,R,D){D===void 0&&(D="&");var A=w.replace(GA,""),J=E&&R?R+" "+E+" { "+A+" }":A;return s=D,i=E,r=new RegExp("\\"+i+"\\b","g"),l=new RegExp("(\\"+i+"\\b){2,}"),v(R||!E?"":E,J)}return v.use([].concat(f,[function(w,E,R){w===2&&R.length&&R[0].lastIndexOf(i)>0&&(R[0]=R[0].replace(r,k))},y,function(w){if(w===-2){var E=_;return _=[],E}}])),C.hash=f.length?f.reduce((function(w,E){return E.name||aa(15),Tn(w,E.name)}),5381).toString():"",C}var tT=Y.createContext();tT.Consumer;var sT=Y.createContext(),YA=(sT.Consumer,new kc),tm=KA();function oT(){return Xr(tT)||YA}function iT(){return Xr(sT)||tm}var JA=(function(){function a(s,i){var r=this;this.inject=function(l,u){u===void 0&&(u=tm);var d=r.name+u.hash;l.hasNameForId(r.id,d)||l.insertRules(r.id,d,u(r.rules,d,"@keyframes"))},this.toString=function(){return aa(12,String(r.name))},this.name=s,this.id="sc-keyframes-"+s,this.rules=i}return a.prototype.getName=function(s){return s===void 0&&(s=tm),this.name+s.hash},a})(),qA=/([A-Z])/,XA=/([A-Z])/g,ZA=/^ms-/,QA=function(a){return"-"+a.toLowerCase()};function G_(a){return qA.test(a)?a.replace(XA,QA).replace(ZA,"-ms-"):a}var V_=function(a){return a==null||a===!1||a===""};function ki(a,s,i,r){if(Array.isArray(a)){for(var l,u=[],d=0,p=a.length;d1?s-1:0),r=1;r?@[\\\]^`{|}~-]+/g,t0=/(^-|-$)/g;function lg(a){return a.replace(e0,"-").replace(t0,"")}var aT=function(a){return em(QC(a)>>>0)};function ic(a){return typeof a=="string"&&!0}var sm=function(a){return typeof a=="function"||typeof a=="object"&&a!==null&&!Array.isArray(a)},s0=function(a){return a!=="__proto__"&&a!=="constructor"&&a!=="prototype"};function o0(a,s,i){var r=a[i];sm(s)&&sm(r)?lT(r,s):a[i]=s}function lT(a){for(var s=arguments.length,i=new Array(s>1?s-1:0),r=1;r=0||(Ne[z]=se[z]);return Ne})(s,["componentId"]),ie=A&&A+"-"+(ic(D)?D:lg(U_(D)));return cT(D,Js({},J,{attrs:y,componentId:ie}),i)},Object.defineProperty(C,"defaultProps",{get:function(){return this._foldedDefaultProps},set:function(D){this._foldedDefaultProps=r?lT({},a.defaultProps,D):D}}),Object.defineProperty(C,"toString",{value:function(){return"."+C.styledComponentId}}),l&&xS(C,a,{attrs:!0,componentStyle:!0,displayName:!0,foldedComponentIds:!0,shouldForwardProp:!0,styledComponentId:!0,target:!0,withComponent:!0}),C}var ys=function(a){return(function s(i,r,l){if(l===void 0&&(l=jo),!XC.isValidElementType(r))return aa(1,String(r));var u=function(){return i(r,l,nT.apply(void 0,arguments))};return u.withConfig=function(d){return s(i,r,Js({},l,{},d))},u.attrs=function(d){return s(i,r,Js({},l,{attrs:Array.prototype.concat(l.attrs,d).filter(Boolean)}))},u})(cT,a)};["a","abbr","address","area","article","aside","audio","b","base","bdi","bdo","big","blockquote","body","br","button","canvas","caption","cite","code","col","colgroup","data","datalist","dd","del","details","dfn","dialog","div","dl","dt","em","embed","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","iframe","img","input","ins","kbd","keygen","label","legend","li","link","main","map","mark","marquee","menu","menuitem","meta","meter","nav","noscript","object","ol","optgroup","option","output","p","param","picture","pre","progress","q","rp","rt","ruby","s","samp","script","section","select","small","source","span","strong","style","sub","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","title","tr","track","u","ul","var","video","wbr","circle","clipPath","defs","ellipse","foreignObject","g","image","line","linearGradient","marker","mask","path","pattern","polygon","polyline","radialGradient","rect","stop","svg","text","textPath","tspan"].forEach((function(a){ys[a]=ys(a)}));var i0=(function(){function a(i,r){this.rules=i,this.componentId=r,this.isStatic=eT(i),kc.registerId(this.componentId+1)}var s=a.prototype;return s.createStyles=function(i,r,l,u){var d=u(ki(this.rules,r,l,u).join(""),""),p=this.componentId+i;l.insertRules(p,p,d)},s.removeStyles=function(i,r){r.clearRules(this.componentId+i)},s.renderStyles=function(i,r,l,u){i>2&&kc.registerId(this.componentId+i),this.removeStyles(i,l),this.createStyles(i,r,l,u)},a})();function n0(a){for(var s=arguments.length,i=new Array(s>1?s-1:0),r=1;ra.length)&&(s=a.length);for(var i=0,r=Array(s);i=a.length?{done:!0}:{done:!1,value:a[r++]}},e:function(m){throw m},f:l}}throw new TypeError(`Invalid attempt to iterate non-iterable instance. -In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var u,d=!0,p=!1;return{s:function(){i=i.call(a)},n:function(){var m=i.next();return d=m.done,m},e:function(m){p=!0,u=m},f:function(){try{d||i.return==null||i.return()}finally{if(p)throw u}}}}function fs(a,s,i){return(s=dT(s))in a?Object.defineProperty(a,s,{value:i,enumerable:!0,configurable:!0,writable:!0}):a[s]=i,a}function Sc(a){return Sc=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(s){return s.__proto__||Object.getPrototypeOf(s)},Sc(a)}function h0(a,s){if(typeof s!="function"&&s!==null)throw new TypeError("Super expression must either be null or a function");a.prototype=Object.create(s&&s.prototype,{constructor:{value:a,writable:!0,configurable:!0}}),Object.defineProperty(a,"prototype",{writable:!1}),s&&om(a,s)}function uT(){try{var a=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(uT=function(){return!!a})()}function p0(a,s){var i=a==null?null:typeof Symbol<"u"&&a[Symbol.iterator]||a["@@iterator"];if(i!=null){var r,l,u,d,p=[],m=!0,f=!1;try{if(u=(i=i.call(a)).next,s!==0)for(;!(m=(r=u.call(i)).done)&&(p.push(r.value),p.length!==s);m=!0);}catch(v){f=!0,l=v}finally{try{if(!m&&i.return!=null&&(d=i.return(),Object(d)!==d))return}finally{if(f)throw l}}return p}}function g0(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. -In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function J_(a,s){var i=Object.keys(a);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(a);s&&(r=r.filter(function(l){return Object.getOwnPropertyDescriptor(a,l).enumerable})),i.push.apply(i,r)}return i}function Ec(a){for(var s=1;si.right&&(i.right=p.right),p.bottom>i.bottom&&(i.bottom=p.bottom),p.left=0+m&&l>=0+m&&r<=d-m&&i<=u-m}function w0(a){return a===document.querySelector("body")||a===document.querySelector("html")}var C0=function(s){return/(left|right)/.test(s)},ug=function(s,i){return s>i},dg=function(s,i){return s>i},Ys=function(s){return s<0?0:s};function T0(a){return Object.keys(a).map(function(s){return{position:s,value:a[s]}}).sort(function(s,i){return i.value-s.value}).map(function(s){return s.position})}var sw,k0=ys.div(sw||(sw=Os([` - --reactour-accent: `,`; - `,` - position: fixed; - transition: transform 0.3s; - top: 0; - left: 0; - z-index: 1000000; - - transform: `,`; -`])),function(a){return a.accentColor},function(a){return a.defaultStyles?` - max-width: 331px; - min-width: 150px; - padding-right: 40px; - border-radius: `.concat(a.rounded,`px; - background-color: #fff; - padding: 24px 30px; - box-shadow: 0 0.5em 3em rgba(0, 0, 0, 0.3); - color: inherit; - `):""},function(a){var s=a.targetTop,i=a.targetRight,r=a.targetBottom,l=a.targetLeft,u=a.windowWidth,d=a.windowHeight,p=a.helperWidth,m=a.helperHeight,f=a.helperPosition,v=a.padding,_={left:l,right:u-i,top:s,bottom:d-r},y=function(R){return _[R]>(C0(R)?p+v*2:m+v*2)},k=function(R){for(var D=T0(_),A=0;Av?ie:v,me=dg(s+m,d)?dg(r+v,d)?r-m:r-m+v:s-v,z=me>v?me:v,Oe={top:[se,s-m-v*2],right:[i+v*2,z],bottom:[se,r+v*2],left:[l-p-v*2,z],center:[u/2-p/2,d/2-m/2]};return R==="center"||y(R)?Oe[R]:k(Oe)},w=C(f);return"translate(".concat(Math.round(w[0]),"px, ").concat(Math.round(w[1]),"px)")}),ow,S0=ys.span(ow||(ow=Os([` - position: absolute; - font-family: monospace; - background: var(--reactour-accent); - background: `,`; - height: 1.875em; - line-height: 2; - padding-left: 0.8125em; - padding-right: 0.8125em; - font-size: 1em; - border-radius: 1.625em; - color: white; - text-align: center; - box-shadow: 0 0.25em 0.5em rgba(0, 0, 0, 0.3); - top: -0.8125em; - left: -0.8125em; -`])),function(a){return a.accentColor}),iw,E0=ys.div(iw||(iw=Os([` - display: flex; - margin-top: 24px; - align-items: center; - justify-content: center; -`]))),nw,I0=ys.nav(nw||(nw=Os([` - counter-reset: dot; - display: flex; - justify-content: center; - align-items: center; - flex-wrap: wrap; -`]))),rw,x0=ys.button(rw||(rw=Os([` - counter-increment: dot; - width: 8px; - height: 8px; - border: `,`; - - border-radius: 100%; - padding: 0; - display: block; - margin: 4px; - transition: opacity 0.3s, transform 0.3s; - cursor: `,`; - transform: scale(`,`); - - color: `,`; - background: `,`; - - color: `,`; - background: `,`; - - &:before { - content: counter(dot); - position: absolute; - bottom: calc(100% + 0.25em); - left: 50%; - opacity: 0; - transform: translate(-50%, 1em); - transition: 0.3s; - display: `,`; - } - - &:hover { - background-color: currentColor; - - &:before { - opacity: 0.5; - transform: translate(-50%, -2px); - } - } -`])),function(a){return a.current===a.index?"0":"1px solid #caccce"},function(a){return a.disabled?"not-allowed":"pointer"},function(a){return a.current===a.index?1.25:1},function(a){return a.current===a.index?"var(--reactour-accent)":"#caccce"},function(a){return a.current===a.index?"var(--reactour-accent)":"none"},function(a){return a.current===a.index?a.accentColor:"#caccce"},function(a){return a.current===a.index?a.accentColor:"none"},function(a){return a.showNumber?"block":"none"}),aw,D0=ys.div(aw||(aw=Os([` - opacity: `,`; - color: `,`; - width: 100%; - left: 0; - top: 0; - height: 100%; - position: fixed; - z-index: 99999; - pointer-events: none; -`])),function(a){return!a.maskClassName&&.7},function(a){return!a.maskClassName&&"#000"});function $T(a){var s=a.windowWidth,i=a.windowHeight,r=a.targetWidth,l=a.targetHeight,u=a.targetTop,d=a.targetLeft,p=a.padding,m=a.rounded,f=a.roundedStep,v=a.disableInteraction,_=a.disableInteractionClassName,y=a.className,k=a.onClick,C=a.highlightedBorder,w=Ys(r+p*2),E=Ys(l+p*2),R=Ys(u-p),D=Ys(d-p),A=f?Math.min(w/2,E/2):m;return Y.createElement(D0,{onClick:k,maskClassName:y},Y.createElement("svg",{width:s,height:i,xmlns:"http://www.w3.org/2000/svg",className:y},Y.createElement("defs",null,Y.createElement("mask",{id:"mask-main"},Y.createElement("rect",{x:0,y:0,width:s,height:i,fill:"white"}),Y.createElement("rect",{x:D,y:R,width:w,height:E,fill:"black"}),Y.createElement("rect",{x:D-1,y:R-1,width:A,height:A,fill:"white"}),Y.createElement("circle",{cx:D+A,cy:R+A,r:A,fill:"black"}),Y.createElement("rect",{x:D+w-A+1,y:R-1,width:A,height:A,fill:"white"}),Y.createElement("circle",{cx:D+w-A,cy:R+A,r:A,fill:"black"}),Y.createElement("rect",{x:D-1,y:R+E-A+1,width:A,height:A,fill:"white"}),Y.createElement("circle",{cx:D+A,cy:R+E-A,r:A,fill:"black"}),Y.createElement("rect",{x:D+w-A+1,y:R+E-A+1,width:A,height:A,fill:"white"}),Y.createElement("circle",{cx:D+w-A,cy:R+E-A,r:A,fill:"black "})),Y.createElement("clipPath",{id:"clip-path"},Y.createElement("rect",{x:0,y:0,width:s,height:R}),Y.createElement("rect",{x:0,y:R,width:D,height:E}),Y.createElement("rect",{x:d+r+p,y:R,width:Ys(s-r-D),height:E}),Y.createElement("rect",{x:0,y:u+l+p,width:s,height:Ys(i-l-R)}))),Y.createElement("rect",{x:0,y:0,width:s,height:i,fill:"currentColor",mask:"url(#mask-main)"}),Y.createElement("rect",{x:0,y:0,width:s,height:i,fill:"currentColor",clipPath:"url(#clip-path)",pointerEvents:"auto"}),Y.createElement("rect",{x:D,y:R,width:w,height:E,pointerEvents:"auto",fill:"transparent",display:v?"block":"none",className:_}),C&&Y.createElement("rect",{x:Ys(D+C.width/2),y:Ys(R+C.width/2),width:Ys(w-C.width),height:Ys(E-C.width),pointerEvents:"auto",fill:"none",strokeWidth:C.width,stroke:C.color,rx:A-2})))}$T.propTypes={windowWidth:Z.number.isRequired,windowHeight:Z.number.isRequired,targetWidth:Z.number.isRequired,targetHeight:Z.number.isRequired,targetTop:Z.number.isRequired,targetLeft:Z.number.isRequired,padding:Z.number.isRequired,rounded:Z.number.isRequired,roundedStep:Z.bool,disableInteraction:Z.bool.isRequired,disableInteractionClassName:Z.string.isRequired,highlightedBorder:Z.shape({color:Z.string.isRequired,width:Z.number.isRequired})};var A0=(function(a){var s=a.step,i=a.refresh,r=vt(0),l=f0(r,2),u=l[0],d=l[1];return Mt(function(){if(s.resizeObservables){var p=function(y){var k=In(y),C;try{var w=function(){var R=C.value;if(!R.attributes)return 1;var D=s.resizeObservables.find(function(A){return R.matches(A)||R.querySelector(A)!=null});D&&d(u+1)};for(k.s();!(C=k.n()).done;)w()}catch(E){k.e(E)}finally{k.f()}},m=new MutationObserver(function(_){var y=In(_),k;try{for(y.s();!(k=y.n()).done;){var C=k.value;C.addedNodes.length!==0&&p(C.addedNodes),C.removedNodes.length!==0&&p(C.removedNodes)}}catch(w){y.e(w)}finally{y.f()}}),f=document.documentElement||document.body,v={childList:!0,subtree:!0};return m.observe(f,v),function(){m.disconnect()}}},[s,u]),Mt(function(){if(s.resizeObservables){var p=new ResizeObserver(function(y){i()}),m=In(s.resizeObservables),f;try{for(m.s();!(f=m.n()).done;){var v=f.value,_=document.querySelector(v);_&&p.observe(_)}}catch(y){m.e(y)}finally{m.f()}return function(){p.disconnect()}}},[s,u]),null}),R0=(function(a){var s=a.step,i=a.refresh;return Mt(function(){if(s.mutationObservables){var r=function(m){var f=In(m),v;try{var _=function(){var k=v.value;if(!k.attributes)return 1;var C=s.mutationObservables.find(function(w){return k.matches(w)||k.querySelector(w)!=null});C&&i()};for(f.s();!(v=f.n()).done;)_()}catch(y){f.e(y)}finally{f.f()}},l=new MutationObserver(function(p){var m=In(p),f;try{for(m.s();!(f=m.n()).done;){var v=f.value;v.addedNodes.length!==0&&r(v.addedNodes),v.removedNodes.length!==0&&r(v.removedNodes)}}catch(_){m.e(_)}finally{m.f()}}),u=document.documentElement||document.body,d={childList:!0,subtree:!0};return l.observe(u,d),function(){l.disconnect()}}},[s]),null});function O0(a){var s=a.children,i=Bo(null);return i.current===null&&(i.current=document.createElement("div"),i.current.setAttribute("id","___reactour")),Mt(function(){return document.body.appendChild(i.current),function(){document.body.removeChild(i.current)}},[i]),DS(s,i.current)}var M0={disableFocusLock:Z.bool,badgeContent:Z.func,highlightedMaskClassName:Z.string,children:Z.oneOfType([Z.node,Z.element]),className:Z.string,closeButtonAriaLabel:Z.string,closeWithMask:Z.bool,inViewThreshold:Z.number,isOpen:Z.bool.isRequired,lastStepNextButton:Z.node,maskClassName:Z.string,maskSpace:Z.number,nextButton:Z.node,onAfterOpen:Z.func,onBeforeClose:Z.func,onRequestClose:Z.func,prevButton:Z.node,scrollDuration:Z.number,scrollOffset:Z.number,showButtons:Z.bool,showCloseButton:Z.bool,showNavigation:Z.bool,showNavigationNumber:Z.bool,showNumber:Z.bool,startAt:Z.number,goToStep:Z.number,getCurrentStep:Z.func,nextStep:Z.func,prevStep:Z.func,steps:Z.arrayOf(Z.shape({selector:Z.string,content:Z.oneOfType([Z.node,Z.element,Z.func]).isRequired,position:Z.oneOfType([Z.arrayOf(Z.number),Z.oneOf(["top","right","bottom","left","center"])]),action:Z.func,style:Z.object,stepInteraction:Z.bool,navDotAriaLabel:Z.string,roundedStep:Z.bool})),update:Z.string,updateDelay:Z.number,disableInteraction:Z.bool,disableDotsNavigation:Z.bool,disableKeyboardNavigation:Z.oneOfType([Z.arrayOf(Z.oneOf(["esc","right","left"])),Z.bool]),rounded:Z.number,accentColor:Z.string,highlightedBorder:Z.shape({color:Z.string.isRequired,width:Z.number.isRequired})},N0={disableFocusLock:!1,showNavigation:!0,showNavigationNumber:!0,showButtons:!0,showCloseButton:!0,closeButtonAriaLabel:"Close",showNumber:!0,scrollDuration:1,maskSpace:10,updateDelay:1,disableInteraction:!1,rounded:0,accentColor:"#007aff",closeWithMask:!0},bn={mask:{disableInteraction:"reactour__mask--disable-interaction"},helper:{base:"reactour__helper",isOpen:"reactour__helper--is-open"},dot:{base:"reactour__dot",active:"reactour__dot--is-active"}},Bm=(function(a){function s(){var i;return c0(this,s),i=l0(this,s),fs(i,"unlockFocus",function(r){i.setState({focusUnlocked:!0},r())}),fs(i,"showStep",function(){if(!(!i.helper||!i.helper.current)){var r=i.props.steps,l=i.state,u=l.current,d=l.focusUnlocked;d&&i.setState({focusUnlocked:!1});var p=r[u],m=p.selector?document.querySelector(p.selector):null,f=function(C){p.action&&typeof p.action=="function"&&i.unlockFocus(function(){return p.action(C)})};if(p.observe){var v=document.querySelector(p.observe),_={attributes:!0,childList:!0,characterData:!0};i.setState(function(k){return k.observer&&setTimeout(function(){k.observer.disconnect()},0),{observer:new MutationObserver(function(C){C.forEach(function(w){if(w.type==="childList"&&w.addedNodes.length>0){var E=function(){return f(w.addedNodes[0])};setTimeout(function(){return i.calculateNode(w.addedNodes[0],p,E)},100)}else if(w.type==="childList"&&w.removedNodes.length>0){var R=function(){return f(m)};i.calculateNode(m,p,R)}})})}},function(){return i.state.observer.observe(v,_)})}else i.state.observer&&(i.state.observer.disconnect(),i.setState({observer:null}));if(m){var y=function(){return f(m)};i.calculateNode(m,p,y)}else i.setState(hg(null,p,i.helper.current),f),p.selector&&console.warn("Doesn't find a DOM node '".concat(p.selector,"'. Please check the 'steps' Tour prop Array at position ").concat(u,"."))}}),fs(i,"calculateNode",function(r,l,u){var d=i.props,p=d.scrollDuration,m=d.inViewThreshold,f=d.scrollOffset,v=fT(r,l),_=Math.max(document.documentElement.clientWidth,window.innerWidth||0),y=Math.max(document.documentElement.clientHeight,window.innerHeight||0);if(_0(Ec(Ec({},v),{},{w:_,h:y,threshold:m})))i.setState(hg(r,l,i.helper.current),u);else{var k=Kx(r),C=f||(v.height>y?-25:-(y/2)+v.height/2);Wx.to(r,{context:w0(k)?window:k,duration:p,offset:C,callback:function(E){i.setState(hg(E,l,i.helper.current),u)}})}}),fs(i,"recalculateNode",function(r){var l=document.querySelector(r.selector),u=function(p){r.action&&typeof r.action=="function"&&i.unlockFocus(function(){return r.action(p)})};i.calculateNode(l,r,function(){return u(l)})}),fs(i,"maskClickHandler",function(r){var l=i.props,u=l.closeWithMask,d=l.onRequestClose;u&&!r.target.classList.contains(bn.mask.disableInteraction)&&d(r)}),fs(i,"nextStep",function(){var r=i.props,l=r.steps,u=r.getCurrentStep;i.setState(function(d){var p=d.current0?l.current-1:l.current;return typeof r=="function"&&r(u),{current:u}},i.showStep)}),fs(i,"gotoStep",function(r){var l=i.props,u=l.steps,d=l.getCurrentStep;i.setState(function(p){var m=u[r]?r:p.current;return typeof d=="function"&&d(m),{current:m}},i.showStep)}),fs(i,"keyDownHandler",function(r){var l=i.props,u=l.onRequestClose,d=l.nextStep,p=l.prevStep,m=l.disableKeyboardNavigation;if(r.stopPropagation(),m!==!0){var f,v,_;m&&(f=m.includes("esc"),v=m.includes("right"),_=m.includes("left")),r.keyCode===27&&!f&&(r.preventDefault(),u()),r.keyCode===39&&!v&&(r.preventDefault(),typeof d=="function"?d():i.nextStep()),r.keyCode===37&&!_&&(r.preventDefault(),typeof p=="function"?p():i.prevStep())}}),i.state={isOpen:!1,current:0,top:0,right:0,bottom:0,left:0,width:0,height:0,w:0,h:0,inDOM:!1,observer:null,focusUnlocked:!1},i.helper=Rk(),i.helperElement=null,i.debouncedShowStep=hD(i.showStep,70),i}return h0(s,a),d0(s,[{key:"componentDidMount",value:function(){var r=this.props,l=r.isOpen,u=r.startAt;l&&this.open(u)}},{key:"UNSAFE_componentWillReceiveProps",value:function(r){var l=this.props,u=l.isOpen,d=l.update,p=l.updateDelay;!u&&r.isOpen?this.open(r.startAt):u&&!r.isOpen&&this.close(),u&&d!==r.update&&(r.steps[this.state.current]?setTimeout(this.showStep,p):this.props.onRequestClose()),u&&r.isOpen&&this.state.current!==r.goToStep&&this.gotoStep(r.goToStep)}},{key:"componentWillUnmount",value:function(){var r=this.props.isOpen;r&&this.close(),this.state.observer&&this.state.observer.disconnect()}},{key:"open",value:function(r){var l=this,u=this.props.onAfterOpen;this.setState(function(d){return{isOpen:!0,current:r!==void 0?r:d.current}},function(){setTimeout(l.showStep,1),l.helperElement=l.helper.current,l.props.disableFocusLock||l.helper.current.focus(),u&&u(l.helperElement)}),window.addEventListener("resize",this.debouncedShowStep,!1),window.addEventListener("keydown",this.keyDownHandler,!1)}},{key:"close",value:function(){this.setState(function(r){return r.observer&&r.observer.disconnect(),{isOpen:!1,observer:null}},this.onBeforeClose),window.removeEventListener("resize",this.debouncedShowStep),window.removeEventListener("keydown",this.keyDownHandler)}},{key:"onBeforeClose",value:function(){var r=this.props.onBeforeClose;r&&r(this.helperElement)}},{key:"render",value:function(){var r=this,l=this.props,u=l.className,d=l.steps,p=l.maskClassName,m=l.showButtons,f=l.showCloseButton,v=l.closeButtonAriaLabel,_=l.showNavigation,y=l.showNavigationNumber,k=l.showNumber,C=l.onRequestClose,w=l.maskSpace,E=l.lastStepNextButton,R=l.nextButton,D=l.prevButton,A=l.badgeContent,J=l.highlightedMaskClassName,ie=l.disableInteraction,se=l.disableDotsNavigation,me=l.nextStep,z=l.prevStep,Oe=l.rounded,Ne=l.accentColor,Ze=l.CustomHelper,ae=l.disableFocusLock,ce=l.highlightedBorder,K=this.state,ye=K.isOpen,he=K.current,je=K.inDOM,V=K.top,tt=K.right,q=K.bottom,ee=K.left,B=K.width,H=K.height,U=K.w,re=K.h,I=K.helperWidth,de=K.helperHeight,W=K.helperPosition;return ye?Y.createElement(O0,null,Y.createElement(b0,null),Y.createElement(A0,{step:d[he],refresh:function(){return r.recalculateNode(d[he])}}),Y.createElement(R0,{step:d[he],refresh:function(){return r.recalculateNode(d[he])}}),Y.createElement($T,{onClick:this.maskClickHandler,forwardRef:function(be){return r.mask=be},windowWidth:U,windowHeight:re,targetWidth:B,targetHeight:H,targetTop:V,targetLeft:ee,padding:w,rounded:Oe,roundedStep:d[he].roundedStep,className:p,disableInteraction:d[he].stepInteraction===!1||ie?!d[he].stepInteraction:ie,disableInteractionClassName:"".concat(bn.mask.disableInteraction," ").concat(J),highlightedBorder:ce}),Y.createElement(KC,{disabled:ae,autoFocus:!1},Y.createElement(k0,{ref:this.helper,targetHeight:H,targetWidth:B,targetTop:V,targetRight:tt,targetBottom:q,targetLeft:ee,windowWidth:U,windowHeight:re,helperWidth:I,helperHeight:de,helperPosition:W,padding:w,tabIndex:-1,current:he,style:d[he].style?d[he].style:{},rounded:Oe,className:D_(bn.helper.base,u,fs({},bn.helper.isOpen,ye)),accentColor:Ne,defaultStyles:!Ze,role:"dialog"},Ze?Y.createElement(Ze,{current:he,totalSteps:d.length,gotoStep:this.gotoStep,close:C,content:d[he]&&(typeof d[he].content=="function"?d[he].content({close:C,goTo:this.gotoStep,inDOM:je,step:he+1}):d[he].content)},this.props.children):Y.createElement(Y.Fragment,null,this.props.children,d[he]&&(typeof d[he].content=="function"?d[he].content({close:C,goTo:this.gotoStep,inDOM:je,step:he+1}):d[he].content),k&&Y.createElement(S0,{"data-tour-elem":"badge",accentColor:Ne},typeof A=="function"?A(he+1,d.length):he+1),(m||_)&&Y.createElement(E0,{"data-tour-elem":"controls"},m&&Y.createElement(ew,{onClick:typeof z=="function"?z:this.prevStep,disabled:he===0,label:D||null}),_&&Y.createElement(I0,{"data-tour-elem":"navigation"},d.map(function(Ce,be){return Y.createElement(x0,{key:"".concat(Ce.selector?Ce.selector:"undef","_").concat(be),onClick:function(){return r.gotoStep(be)},current:he,index:be,accentColor:Ne,disabled:he===be||se,showNumber:y,"data-tour-elem":"dot",className:D_(bn.dot.base,fs({},bn.dot.active,he===be)),"aria-label":Ce.navDotAriaLabel})})),m&&Y.createElement(ew,{onClick:he===d.length-1?E?C:function(){}:typeof me=="function"?me:this.nextStep,disabled:!E&&he===d.length-1,inverted:!0,label:E&&he===d.length-1?E:R||null})),f&&Y.createElement(y0,{onClick:C,className:"reactour__close",ariaLabel:v}))))):null}}])})(Ew),hg=function(s,i,r){if(r){var l=Math.max(document.documentElement.clientWidth,window.innerWidth||0),u=Math.max(document.documentElement.clientHeight,window.innerHeight||0),d=$c(r),p=d.width,m=d.height,f={top:u+10,right:l/2+9,bottom:u/2+9,left:l/2-p/2,width:0,height:0,w:l,h:u,helperPosition:"center"};return s&&(f=fT(s,i)),function(){return Ec(Ec({w:l,h:u,helperWidth:p,helperHeight:m,helperPosition:i.position},f),{},{inDOM:!!s})}}};Bm.propTypes=M0;Bm.defaultProps=N0;const L0=""+new URL("blockly2js-B3Jxf2e-.svg",import.meta.url).href,P0=""+new URL("rules2js-DnYyR8mI.svg",import.meta.url).href,As={selectTriggers:0,addScheduleByDoubleClick:1,openTagsMenu:2,selectIntervalTag:3,selectActions:4,addActionPrintText:5,showJavascript:6,switchBackToRules:7,saveTheScript:8},B0=[{selector:".blocks-triggers",content:"Select triggers"},{selector:".block-TriggerScheduleBlock",content:"Double click to add the block"},{selector:".tag-card",content:"Open drop down menu"},{selector:".tag-card-interval",content:"Select interval"},{selector:".blocks-actions",content:"Select action blocks"},{selector:".block-ActionPrintText",content:"Double click to add the block"},{selector:".button-js-code",content:"Check the script"},{selector:".button-js-code",content:"Switch back to rules"},{selector:".button-save",content:"Save the script"}],pg=187,nc={root:{left:0,top:0,width:"100%",height:"100%",position:"fixed",background:"rgba(0, 0, 0, .3)",zIndex:2e4},connecting:{left:"40%",top:"40%",width:"20%",height:"20%",position:"absolute"},spinner:{animation:"admin-connecting-rotator 1.4s linear infinite"},path:{strokeDasharray:187,strokeDashoffset:0,transformOrigin:"center",animation:"admin-connecting-dash 1.4s ease-in-out infinite, $colors 5.6s ease-in-out infinite"}};function vn(){return g.jsxs("div",{style:nc.root,children:[g.jsx("style",{children:` -' @keyframes admin-connecting-colors { - 0% { - stroke: #4285F4; - } - 25% { - stroke: #DE3E35; - } - 50% { - stroke: #F7C223; - } - 75% { - stroke: #1B9A59; - } - 100% { - stroke: #4285F4; - } - } - @keyframes admin-connecting-dash { - 0% { - stroke-dashoffset: ${pg}; - } - 50% { - stroke-dashoffset: ${pg/4}; - transform: rotate(135deg); - } - 100% { - stroke-dashoffset: ${pg}; - transform: 'rotate(450deg); - } - } - @keyframes admin-connecting-rotator { - 0% { - transform: rotate(0deg); - } - 100% { - transform: rotate(270deg); - } - } -`}),g.jsx("div",{style:nc.connecting,children:g.jsx("svg",{style:nc.spinner,width:"100%",height:"100%",viewBox:"0 0 66 66",xmlns:"http://www.w3.org/2000/svg",children:g.jsx("circle",{style:nc.path,fill:"none",strokeWidth:"6",strokeLinecap:"round",cx:"33",cy:"33",r:"30"})})})]})}const j0=Y.lazy(()=>On(()=>Promise.resolve().then(()=>fR),void 0,import.meta.url)),F0=Y.lazy(()=>On(()=>import("./index-Cd8FZ0ou.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13]),import.meta.url)),z0=Y.lazy(()=>On(()=>import("./index-CZzmETwg.js"),__vite__mapDeps([14,1,2,3,4,6,7,5,15,8,9,10,11,12]),import.meta.url)),U0=Y.lazy(()=>On(()=>import("./ScriptEditorVanillaMonaco-DSYvOslZ.js"),__vite__mapDeps([15,1,2,3,4,6,7,5]),import.meta.url)),H0=Y.lazy(()=>On(()=>import("./ScriptEditor-C-fO5h68.js"),__vite__mapDeps([16,1,2,3,4,6,5,15,7,17]),import.meta.url)),W0=Y.lazy(()=>On(()=>import("./OpenAiDialog-BliYIniL.js"),__vite__mapDeps([18,1,2,3,4,6,5,9,19,15,7,8,10,11,12]),import.meta.url)),lw={Blockly:hC,"Javascript/js":_c,Rules:gC,def:_c,"TypeScript/ts":pC},G0=48,cw="#02a102",gg="#70aae9",V0=Cw[400],K0=Tw[400],Te={toolbar:a=>({minHeight:38,boxShadow:"0px 2px 4px -1px rgba(0, 0, 0, 0.2), 0px 4px 5px 0px rgba(0, 0, 0, 0.14), 0px 1px 10px 0px rgba(0, 0, 0, 0.12)",backgroundColor:a.palette.mode==="dark"?"#1e1e1e":"#E2E2E2"}),toolbarButtons:{padding:4,marginLeft:4},toolbarButtonsDisabled:{filter:"grayscale(100%)",opacity:.5},editorDiv:a=>({height:`calc(100% - ${(parseInt(a.toolbar.height,10)||48)+38+10}px)`,width:"100%",overflow:"hidden",position:"relative"}),textButton:{marginRight:10,minHeight:24,padding:"6px 16px",height:32},saveButton:{background:"#ff9900"},tabIcon:{width:24,height:24,verticalAlign:"middle",marginBottom:2,marginRight:2,borderRadius:3},hintIcon:{padding:"0 8px 0 8px"},hintButton:{marginTop:8,marginLeft:20},tabMenuButton:{position:"absolute",top:0,right:0},tabChanged:a=>({color:a.palette.secondary.main}),tabText:{maxWidth:130,textOverflow:"ellipsis",whiteSpace:"nowrap",overflow:"hidden",display:"inline-block",verticalAlign:"middle"},tabChangedIcon:{color:"#FF0000",fontSize:16,marginLeft:5},closeButton:{marginLeft:5},notRunning:{color:"#ffbc00",marginRight:8,marginLeft:8},tabButton:{minHeight:48},tabButtonWrapper:{display:"inline-block"},menuIcon:{width:18,height:18,borderRadius:2,marginRight:5}};class kn extends Y.Component{getSelect=null;changedMirror={};cron={initValue:null,callback:null};scriptDialog={initValue:null,callback:null,args:null,isReturn:!1};objects;scripts;selectId={initValue:null,callback:null};confirmCallback=null;constructor(s){var u,d;super(s);let i=window.localStorage.getItem("Editor.selected")||"";const r=window.localStorage.getItem("Editor.editing")||"[]";let l;try{l=JSON.parse(r)}catch{l=[]}i&&!l.includes(i)&&l.push(i),i&&!this.props.password&&((d=(u=this.props.objects[i])==null?void 0:u.native)!=null&&d.protected)&&(i=l.find(p=>{var m,f;return!((f=(m=this.props.objects[p])==null?void 0:m.native)!=null&&f.protected)})||""),!i&&l.length&&(this.props.password?i=l[0]:i=l.find(p=>{var m,f;return!((f=(m=this.props.objects[p])==null?void 0:m.native)!=null&&f.protected)})||""),this.state={askAboutDebug:!1,astroEvents:null,blockly:null,changed:{},cmdToBlockly:"",cmdToRules:"",confirm:"",debugEnabled:!1,editing:l,insert:"",instancesLoaded:!1,isTourOpen:window.localStorage.getItem("tour")!=="true",menuDebugAnchorEl:null,menuOpened:!!this.props.menuOpened,menuTabsOpened:!1,openAiDialog:!1,triggerPrettier:1,rules:null,runningInstances:this.props.runningInstances||{},searchText:"",selected:i,showAdapterDebug:!1,showAstro:!1,showCompiledCode:!1,showCron:!1,showDebugMenu:!1,showScript:!1,showSelectId:!1,themeType:this.props.themeType,toast:"",tourStep:As.selectTriggers,verboseEnabled:!1,visible:s.visible},this.setChangedInAdmin(),window.systemLang=b.I18n.getLanguage(),window.main={objects:{},getObject:(p,m)=>this.props.socket.getObject(p).then(f=>m==null?void 0:m(null,f)).catch(f=>m==null?void 0:m(f)),instances:[],selectIdDialog:(p,m,f)=>{typeof m=="function"&&(f=m,m=null),this.selectId.callback=f,this.selectId.initValue=p,this.selectId.type=m,this.setState({showSelectId:!0})},cronDialog:(p,m)=>{this.cron.callback=m,this.cron.initValue=p,this.setState({showCron:!0})},showScriptDialog:(p,m,f,v)=>{this.scriptDialog.callback=v,this.scriptDialog.initValue=p,this.scriptDialog.args=m,this.scriptDialog.isReturn=f||!1,this.setState({showScript:!0})}},this.objects=s.objects,this.scripts={},this.getAllAdapterInstances().then(()=>{this.props.onSelectedChange&&this.state.selected&&setTimeout(()=>this.props.onSelectedChange(this.state.selected,this.state.editing),100)})}async getAllAdapterInstances(){const s=await this.props.socket.getAdapterInstances(!0),i={},r=s.map(l=>(i[l._id]=l,l._id));window.main.objects=i,window.main.instances=r,this.setState({instancesLoaded:!0})}static onInstanceChanged(s,i){if(s)if(!i&&window.main.instances.includes(s)){delete window.main.objects[s];const r=window.main.instances.indexOf(s);window.main.instances.splice(r,1)}else(i==null?void 0:i.type)==="instance"&&(window.main.instances.includes(s)||(window.main.instances.push(s),window.main.instances.sort()),window.main.objects[s]=i)}setChangedInAdmin(){const s=Object.keys(this.state.changed).find(i=>this.state.changed[i]);Object.keys(this.state.changed).forEach(i=>{this.changedMirror[i]=this.state.changed[i]}),Object.keys(this.changedMirror).forEach(i=>{this.state.changed[i]===void 0&&delete this.changedMirror[i]}),this.props.onChangedChanged(this.changedMirror),typeof window.parent<"u"&&window.parent&&(window.parent.configNotSaved=!!s)}componentDidMount(){window.addEventListener("beforeunload",this.onBrowserClose,!1),this.props.socket.subscribeObject("system.adapter.*",kn.onInstanceChanged)}componentWillUnmount(){window.removeEventListener("beforeunload",this.onBrowserClose),this.props.socket.unsubscribeObject("system.adapter.*",kn.onInstanceChanged)}onBrowserClose=s=>{const i=Object.keys(this.scripts).find(r=>JSON.stringify(this.scripts[r])!==JSON.stringify(this.getScriptFromObject(r)));if(i){console.log(`Script ${JSON.stringify(this.scripts[i])}`);const r=b.I18n.t("Configuration not saved.");return s=s||window.event,s&&(s.returnValue=r),r}};removeNonExistingScripts(s,i){s=s||this.props,i=i||{};let r=!1;if(this.state.editing&&this.state.editing.find(u=>s&&!s.objects[u])){const u=[...this.state.editing];for(let d=u.length-1;d>=0;d--)this.objects[u[d]]||(r=!0,u.splice(d,1));r&&(i.editing=u),this.state.selected&&!this.objects[this.state.selected]&&(r=!0,i.selected=u[0]||"",i.selected&&this.scripts[i.selected]&&(this.state.blockly!==(this.scripts[i.selected].engineType==="Blockly")&&(i.blockly=this.scripts[i.selected].engineType==="Blockly",r=!0),this.state.rules!==(this.scripts[i.selected].engineType==="Rules")&&(i.rules=this.scripts[i.selected].engineType==="Rules",r=!0),this.state.verboseEnabled!==this.scripts[i.selected].verbose&&(i.verboseEnabled=this.scripts[i.selected].verbose,r=!0),this.state.debugEnabled!==this.scripts[i.selected].debug&&(i.debugEnabled=this.scripts[i.selected].debug,r=!0)))}return r}UNSAFE_componentWillReceiveProps(s){var l,u,d;const i={};let r=!1;if(JSON.stringify(s.runningInstances)!==JSON.stringify(this.state.runningInstances)&&(r=!0,i.runningInstances=s.runningInstances),this.state.menuOpened!==s.menuOpened&&(i.menuOpened=s.menuOpened,r=!0),this.state.themeType!==s.themeType&&(i.themeType=s.themeType,r=!0),this.removeNonExistingScripts(s,i)&&(r=!0),this.state.searchText!==s.searchText&&(i.searchText=s.searchText,r=!0),this.objects!==s.objects){this.objects=s.objects,window.main.objects=s.objects,Object.keys(this.scripts).forEach(m=>{const f=this.scripts[m].source;this.scripts[m]=JSON.parse(JSON.stringify(this.objects[m].common)),this.scripts[m].source=f}),this.state.selected&&this.objects[this.state.selected]&&(this.scripts[this.state.selected]||=JSON.parse(JSON.stringify(this.objects[this.state.selected].common)),this.state.blockly!==(this.scripts[this.state.selected].engineType==="Blockly")&&(i.blockly=this.scripts[this.state.selected].engineType==="Blockly",r=!0),this.state.rules!==(this.scripts[this.state.selected].engineType==="Rules")&&(i.rules=this.scripts[this.state.selected].engineType==="Rules",r=!0),this.state.verboseEnabled!==this.scripts[this.state.selected].verbose&&(i.verboseEnabled=this.scripts[this.state.selected].verbose,r=!0),this.state.debugEnabled!==this.scripts[this.state.selected].debug&&(i.debugEnabled=this.scripts[this.state.selected].debug,r=!0));const p=[...this.state.editing];for(let m=p.length-1;m>=0;m--)this.objects[p[m]]||(r=!0,p.splice(m,1),this.state.changed[p[m]]!==void 0&&(i.changed||={...this.state.changed},i.changed&&delete i.changed[p[m]]));this.state.selected&&!this.objects[this.state.selected]&&(i.selected=p[0]||""),r&&(i.editing=p)}else for(const p in this.scripts)if(Object.prototype.hasOwnProperty.call(this.scripts,p)){if((l=this.objects[p])!=null&&l.common){if(this.objects[p].type==="script"){const m=this.scripts[p].source,f=JSON.parse(JSON.stringify(this.scripts[p]));f.source=this.objects[p].common.source,JSON.stringify(f)!==JSON.stringify(this.objects[p].common)&&(this.scripts[p]=JSON.parse(JSON.stringify(this.objects[p].common)),this.scripts[p].source=m),m!==this.objects[p].common.source?this.state.changed[p]?(d=this.objects[p].from)!=null&&d.startsWith("system.adapter.javascript.")&&(this.objects[p].from="system.adapter.admin.0",this.setState({toast:b.I18n.t("Script %s was modified on disk.",p.split(".").pop())})):this.props.password&&((u=this.objects[p].native)!=null&&u.protected)?this.scripts[p].source=Ug(this.props.password,this.objects[p].common.source):this.scripts[p].source=this.objects[p].common.source:this.state.changed[p]&&(i.changed||={...this.state.changed},i.changed&&(i.changed[p]=!1),r=!0)}}else if(this.scripts[p]&&(delete this.scripts[p],this.state.selected===p)){if(this.state.editing.indexOf(p)!==-1){const m=[...this.state.editing],f=m.indexOf(p);f!==-1&&(m.splice(f,1),i.editing=m,r=!0)}i.selected=this.state.editing[0]||"",r=!0}}if(s.selected&&this.state.selected!==s.selected){const p=this.getScriptFromObject(s.selected);this.scripts[s.selected]||=p;const m=p&&JSON.stringify(this.scripts[s.selected])!==JSON.stringify(p),f=[...this.state.editing];s.selected&&!f.includes(s.selected)&&(f.push(s.selected),this.props.onSelectedChange(s.selected,f),window.localStorage.setItem("Editor.editing",JSON.stringify(f))),r=!0,i.changed||={...this.state.changed},i.changed[s.selected]=!!m,i.editing=f,i.selected=s.selected,i.blockly=this.scripts[s.selected].engineType==="Blockly",i.rules=this.scripts[s.selected].engineType==="Rules",i.verboseEnabled=this.scripts[s.selected].verbose,i.debugEnabled=this.scripts[s.selected].debug,i.showCompiledCode=!1}this.state.visible!==s.visible&&(r=!0,i.visible=s.visible),r&&this.setState(i,()=>this.setChangedInAdmin())}onRestart(){var s,i;(i=(s=this.props).onRestart)==null||i.call(s,this.state.selected)}onStartStop(){var i,r,l;const s=JSON.parse(JSON.stringify(this.scripts[this.state.selected]));s.enabled=!s.enabled,this.props.password&&((i=this.props.objects[this.state.selected].native)!=null&&i.protected)&&(s.source=mc(this.props.password,s.source)),(l=(r=this.props).onChange)==null||l.call(r,this.state.selected,s)}onSave(){if(this.state.isTourOpen&&this.state.tourStep===As.saveTheScript&&(this.setState({isTourOpen:!1}),window.localStorage.setItem("tour","true")),this.state.changed[this.state.selected]){const s={...this.state.changed};s[this.state.selected]=!1,this.setState({changed:s},()=>{var r,l,u;this.setChangedInAdmin();const i=JSON.parse(JSON.stringify(this.scripts[this.state.selected]));this.props.password&&((r=this.props.objects[this.state.selected].native)!=null&&r.protected)&&(i.source=mc(this.props.password,i.source)),(u=(l=this.props).onChange)==null||u.call(l,this.state.selected,i)})}}onSaveAll(){const s={...this.state.changed};Object.keys(s).forEach(i=>{var r,l,u;if(s[i]){s[i]=!1;const d=JSON.parse(JSON.stringify(this.scripts[i]));this.props.password&&((r=this.props.objects[i].native)!=null&&r.protected)&&(d.source=mc(this.props.password,d.source)),(u=(l=this.props).onChange)==null||u.call(l,i,d)}}),this.setState({changed:s},()=>this.setChangedInAdmin())}onCancel(){this.scripts[this.state.selected]=this.getScriptFromObject(this.state.selected);const s={...this.state.changed};s[this.state.selected]=!1,this.setState({changed:s},()=>this.setChangedInAdmin())}onRegisterSelect(s){this.getSelect=s}onConvertBlockly2JS(){this.showConfirmDialog(b.I18n.t("It will not be possible to revert this operation."),s=>{if(s){this.scripts[this.state.selected].engineType="Javascript/js";const r=this.scripts[this.state.selected].source.split(` -`);r.pop(),this.scripts[this.state.selected].source=r.join(` -`);const l=this.state.selected,u={...this.state.changed};u[this.state.selected]=!0,this.setState({changed:u,blockly:!1,selected:""},()=>{this.setChangedInAdmin(),setTimeout(()=>this.setState({selected:l}),100)})}})}onChange(s){if(s.script!==void 0){if(s.script===this.scripts[this.state.selected].source)return;this.scripts[this.state.selected].source=s.script}s.debug!==void 0&&(this.scripts[this.state.selected].debug=s.debug),s.verbose!==void 0&&(this.scripts[this.state.selected].verbose=s.verbose);const i=JSON.stringify(this.scripts[this.state.selected])!==JSON.stringify(this.getScriptFromObject(this.state.selected));if(i!==!!this.state.changed[this.state.selected]){const r={...this.state.changed};r[this.state.selected]=i,this.objects[this.state.selected].from="system.adapter.admin.0",this.setState({changed:r},()=>this.setChangedInAdmin())}}onTabChange(s){var r,l;if(this.props.debugMode)return;window.localStorage.setItem("Editor.selected",s);const i=this.scripts[s]||this.getScriptFromObject(s);this.setState({selected:s,rules:i.engineType==="Rules",blockly:i.engineType==="Blockly",showCompiledCode:!1,verboseEnabled:i.verbose,debugEnabled:i.debug}),(l=(r=this.props).onSelectedChange)==null||l.call(r,s,this.state.editing)}isScriptChanged(s){return!!(this.scripts[s]&&this.props.objects[s]&&JSON.stringify(this.scripts[s])!==JSON.stringify(this.getScriptFromObject(s)))}onTabClose(s,i){i==null||i.stopPropagation();const r=this.state.editing.indexOf(s);if(this.state.editing.includes(s))if(this.isScriptChanged(s))this.showConfirmDialog(b.I18n.t("Discard changes for %s",this.props.objects[s].common.name),l=>{l&&(delete this.scripts[s],this.onTabClose(s))});else{const l=[...this.state.editing];l.splice(r,1);const u={editing:l};if(s===this.state.selected?l.length?r===0||l.length===1?u.selected=l[0]:u.selected=l[r-1]:u.selected="":this.state.selected&&!l.length&&(u.selected=""),window.localStorage.setItem("Editor.editing",JSON.stringify(l)),u.selected!==void 0){u.changed||={...this.state.changed},u.changed[u.selected]=this.isScriptChanged(u.selected);const d=u.selected?this.scripts[u.selected]||this.getScriptFromObject(u.selected):void 0;u.blockly=(d==null?void 0:d.engineType)==="Blockly",u.rules=(d==null?void 0:d.engineType)==="Rules",u.verboseEnabled=!!(d!=null&&d.verbose),u.debugEnabled=!!(d!=null&&d.debug),u.showCompiledCode=!1}this.setState(u,()=>{var d,p,m,f;this.setChangedInAdmin(),u.selected!==void 0?((p=(d=this.props).onSelectedChange)==null||p.call(d,u.selected,this.state.editing),window.localStorage.setItem("Editor.selected",u.selected)):(f=(m=this.props).onSelectedChange)==null||f.call(m,this.state.selected,this.state.editing)})}}showConfirmDialog(s,i){this.confirmCallback=i,this.setState({confirm:s})}sendCommandToBlockly(s){this.setState({cmdToBlockly:s},()=>setTimeout(()=>this.setState({cmdToBlockly:""}),200))}sendCommandToRules(s){this.setState({cmdToRules:s},()=>setTimeout(()=>this.setState({cmdToRules:""}),200))}static getText(s){return typeof s=="object"?s[b.I18n.getLanguage()]||s.en:s}getScriptFullName(s){var u;const i=s.split(".");i.shift(),i.shift();const r=[];let l="script.js";for(let d=0;dthis.onTabChange(i),indicatorColor:"primary",style:{position:"relative",marginLeft:10,width:this.state.editing.length>1?"calc(100% - 50px)":"100%",display:"inline-block"},textColor:"primary",variant:"scrollable",scrollButtons:"auto",allowScrollButtonsMobile:!0,children:[this.state.editing.map(s=>{var p,m;if(!this.props.objects[s]){const f=[g.jsx($t,{sx:this.isScriptChanged(s)?Te.tabChanged:void 0,style:Te.tabText,children:s.split(".").pop()},"text"),g.jsx(Me,{onClick:v=>this.onTabClose(s,v),style:Te.closeButton,size:"small",component:"span",children:g.jsx(Ql,{})},"icon")];return g.jsx(Yp,{wrapped:!0,href:`#${s}`,label:f,value:s,sx:{"& .MuiTab-wrapper":Te.tabButtonWrapper}},s)}if(!this.props.password&&((p=this.props.objects[s].native)!=null&&p.protected))return null;let i=kn.getText(this.props.objects[s].common.name)||"";const r=this.getScriptFullName(s);i.length>18&&(i=`${i.substring(0,15)}...`);const l=(m=this.getScriptFromObject(s))==null?void 0:m.source,u=this.scripts[s]&&l!==this.scripts[s].source,d=[g.jsx($t,{sx:this.isScriptChanged(s)?Te.tabChanged:void 0,style:Te.tabText,children:i},"text"),u?g.jsx("span",{style:Te.tabChangedIcon,children:"▣"},"changedSign"):null,!this.props.debugInstance&&(!this.props.debugMode||this.state.selected!==s)&&g.jsx(Me,{onClick:f=>this.onTabClose(s,f),style:Te.closeButton,size:"small",component:"span",children:g.jsx(Ql,{})},"icon")];return g.jsx(Yp,{disabled:!!this.props.debugInstance||this.state.selected!==s&&this.props.debugMode,wrapped:!0,iconPosition:"start",icon:g.jsx("img",{alt:"",src:lw[this.props.objects[s].common.engineType]||lw.def,style:Te.tabIcon},"icon"),href:`#${s}`,label:d,style:Te.tabButton,value:s,title:r,sx:{"& .MuiTab-wrapper":Te.tabButtonWrapper}},s)}),this.props.debugInstance?g.jsx(Yp,{disabled:!1,wrapped:!0,href:`#${this.props.debugInstance.adapter}`,label:this.props.debugInstance.adapter,style:Te.tabButton,value:this.props.debugInstance.adapter,title:this.props.debugInstance.adapter,sx:{"& .MuiTab-wrapper":Te.tabButtonWrapper}},this.props.debugInstance.adapter):""]},"tabs1"),this.state.editing.length>1?g.jsx(Me,{href:"#","aria-label":"Close all but current",style:Te.tabMenuButton,title:b.I18n.t("Close all but current"),"aria-haspopup":"false",onClick:s=>{const i=[this.state.selected];Object.keys(this.scripts).forEach(r=>r!==this.state.selected&&JSON.stringify(this.scripts[r])!==JSON.stringify(this.getScriptFromObject(r))&&i.push(r)),window.localStorage.setItem("Editor.editing",JSON.stringify(i)),this.setState({menuTabsOpened:!1,editing:i})},size:"medium",children:g.jsx(aS,{})},"menuButton"):null]:g.jsx($t,{sx:Te.toolbar,children:g.jsxs(De,{color:"grey",disabled:!0,style:Te.hintButton,href:"",children:[g.jsx("span",{children:b.I18n.t("Click on this icon")},"select2"),g.jsx(lS,{style:Te.hintIcon},"select3"),g.jsx("span",{children:b.I18n.t("for edit or create script")},"select4")]},"select1")},"tabs2")}getDebugMenu(){return this.state.showDebugMenu?g.jsxs(cm,{id:"menu-debug",anchorEl:this.state.menuDebugAnchorEl,open:this.state.showDebugMenu,onClose:()=>this.setState({showDebugMenu:!1,menuDebugAnchorEl:null}),slotProps:{root:{style:{maxHeight:G0*7.5}}},children:[g.jsxs(Ge,{title:b.I18n.t("debug_help"),onClick:s=>{s.stopPropagation(),s.preventDefault(),this.setState({showDebugMenu:!1,menuDebugAnchorEl:null,debugEnabled:!this.state.debugEnabled},()=>this.onChange({debug:this.state.debugEnabled}))},children:[g.jsx(bc,{checked:this.state.debugEnabled}),g.jsx(ec,{style:{...Te.menuIcon,color:cw}}),b.I18n.t("debug_label")]},"debugEnabled"),g.jsxs(Ge,{title:b.I18n.t("verbose_help"),onClick:s=>{s.stopPropagation(),s.preventDefault(),this.setState({showDebugMenu:!1,menuDebugAnchorEl:null,verboseEnabled:!this.state.verboseEnabled},()=>this.onChange({verbose:this.state.verboseEnabled}))},children:[g.jsx(bc,{checked:this.state.verboseEnabled}),g.jsx(s_,{style:{...Te.menuIcon,color:gg}}),b.I18n.t("verbose_label")]},"verboseEnabled")]},"menuDebug"):null}getDebugBadge(){return[this.state.debugEnabled&&this.state.verboseEnabled?g.jsx(ec,{style:{...Te.menuIcon,color:gg}},"DebugVerbose"):null,this.state.debugEnabled&&!this.state.verboseEnabled?g.jsx(ec,{style:{...Te.menuIcon,color:cw}},"DebugNoVerbose"):null,!this.state.debugEnabled&&this.state.verboseEnabled?g.jsx(s_,{style:{...Te.menuIcon,color:gg}},"noDebugVerbose"):null]}getAskAboutDebug(){return this.state.askAboutDebug?g.jsx(b.DialogConfirm,{onClose:()=>{this.setState({askAboutDebug:!1},()=>this.props.onDebugModeChange(!0))},ok:b.I18n.t("Yes"),cancel:b.I18n.t("Cancel"),text:b.I18n.t("The script will be stopped and must be activated manually after debugging. Continue?")}):null}renderOpenAiDialog(){return this.state.openAiDialog?g.jsx(pn,{fallback:g.jsx(vn,{}),children:g.jsx(W0,{adapterName:this.props.adapterName,socket:this.props.socket,runningInstances:this.state.runningInstances,themeType:this.state.themeType,onClose:()=>this.setState({openAiDialog:!1}),language:this.scripts[this.state.selected].engineType==="TypeScript/ts"?"typescript":"javascript",onAddCode:s=>this.setState({insert:s})})}):null}getToolbar(){var r,l;const s=!!(this.state.selected&&((r=this.scripts[this.state.selected])!=null&&r.engine)&&this.state.runningInstances[this.scripts[this.state.selected].engine]),i=!!(this.state.selected&&((l=this.scripts[this.state.selected])!=null&&l.enabled));if(this.state.selected){const u=Object.keys(this.state.changed).filter(p=>this.state.changed[p]).length,d=this.state.changed[this.state.selected];return g.jsxs(Lk,{variant:"dense",sx:Te.toolbar,children:[!this.props.debugInstance&&this.state.menuOpened&&this.props.onLocate&&g.jsx(Me,{style:Te.toolbarButtons,title:b.I18n.t("Locate file"),onClick:()=>this.props.onLocate(this.state.selected),size:"medium",children:g.jsx(cS,{})},"locate"),!this.props.debugInstance&&!d&&s?g.jsx(Me,{disabled:this.props.debugMode,style:Te.toolbarButtons,onClick:()=>this.onRestart(),title:b.I18n.t("Restart"),size:"medium",children:g.jsx(uS,{})},"restart"):null,!this.props.debugInstance&&!d?g.jsx(Me,{disabled:this.props.debugMode,onClick:()=>this.onStartStop(),title:i?b.I18n.t("Pause script"):b.I18n.t("Run script"),size:"medium",style:{...Te.toolbarButtons,color:i?V0:K0},children:i?g.jsx(dS,{}):g.jsx(hS,{})},"start-stop"):null,!this.props.debugInstance&&!d&&!i?g.jsx("span",{style:Te.notRunning,children:b.I18n.t("Script is not running")}):null,!d&&i&&!s?g.jsx("span",{style:Te.notRunning,children:b.I18n.t("Instance is disabled")}):null,d?g.jsx(De,{color:"grey",variant:"contained",style:{...Te.textButton,...Te.saveButton},className:"button-save",onClick:()=>this.onSave(),endIcon:g.jsx(o_,{}),children:b.I18n.t("Save")},"save"):null,u>1||u===1&&!d?g.jsx(De,{color:"grey",variant:"contained",style:Te.textButton,onClick:()=>this.onSaveAll(),endIcon:g.jsx(o_,{}),children:b.I18n.t("Save all")},"saveall"):null,d?g.jsx(De,{color:"grey",variant:"contained",style:Te.textButton,onClick:()=>this.onCancel(),endIcon:g.jsx(Wc,{}),children:b.I18n.t("Cancel")},"cancel"):null,g.jsx("div",{style:{flex:2}}),!this.props.debugInstance&&!this.state.showCompiledCode&&g.jsx(Me,{style:Te.toolbarButtons,title:b.I18n.t("Prettify the script"),onClick:()=>this.setState({triggerPrettier:this.state.triggerPrettier+1}),size:"medium",children:g.jsx(pS,{})},"prettier"),this.state.blockly&&!this.state.showCompiledCode?g.jsx(Me,{"aria-label":"Export Blocks",title:b.I18n.t("Export blocks"),style:Te.toolbarButtons,onClick:()=>this.sendCommandToBlockly("export"),size:"medium",children:g.jsx(vc,{})},"export"):null,this.state.blockly&&!this.state.showCompiledCode&&g.jsx(Me,{"aria-label":"Import Blocks",title:b.I18n.t("Import blocks"),style:Te.toolbarButtons,onClick:()=>this.sendCommandToBlockly("import"),size:"medium",children:g.jsx(Rg,{})},"import"),this.state.blockly&&!this.state.showCompiledCode&&g.jsx(Me,{"aria-label":"Check code",title:b.I18n.t("Check blocks"),style:Te.toolbarButtons,onClick:()=>this.sendCommandToBlockly("check"),size:"medium",children:g.jsx(gS,{})},"check"),!this.props.debugMode&&!this.state.blockly&&!this.state.rules&&!this.state.showCompiledCode?g.jsx(Me,{"aria-label":"create CRON",title:b.I18n.t("Create or edit CRON or time wizard"),style:Te.toolbarButtons,onClick:()=>this.setState({showCron:!0}),size:"medium",children:g.jsx(mS,{})},"select-cron"):null,this.scripts[this.state.selected]&&this.scripts[this.state.selected].engineType!=="Blockly"&&this.scripts[this.state.selected].engineType!=="Rules"?g.jsx(Me,{"aria-label":"AI",title:b.I18n.t("AI code generator"),style:Te.toolbarButtons,size:"medium",onClick:()=>this.setState({openAiDialog:!0}),children:g.jsx(fS,{})},"ai"):null,g.jsx(Me,{"aria-label":"Show astronomical events",title:b.I18n.t("Show astronomical events"),style:Te.toolbarButtons,disabled:!s,onClick:()=>{this.setState({showAstro:!0,astroEvents:null}),this.props.socket.sendTo(this.scripts[this.state.selected].engine.replace("system.adapter.",""),"calcAstroAll",{}).then(p=>this.setState({astroEvents:p}))},size:"medium",children:g.jsx($S,{})},"show-astro"),!this.props.debugMode&&!this.state.blockly&&!this.state.rules&&!this.state.showCompiledCode&&g.jsx(Me,{"aria-label":"select ID",title:b.I18n.t("Insert object ID"),style:Te.toolbarButtons,onClick:()=>this.setState({showSelectId:!0}),size:"medium",children:g.jsx(bS,{})},"select-id"),this.state.blockly&&!this.state.rules&&this.state.showCompiledCode&&g.jsx(De,{color:"grey","aria-label":"convert to javascript",title:b.I18n.t("Convert blockly to javascript for ever."),onClick:()=>this.onConvertBlockly2JS(),children:"Blockly=>JS"},"convert2js"),this.state.rules&&!this.state.showCompiledCode&&g.jsx(Me,{"aria-label":"Export Blocks",title:b.I18n.t("Export blocks"),style:Te.toolbarButtons,onClick:()=>this.sendCommandToRules("export"),size:"medium",children:g.jsx(vc,{})},"export"),this.state.rules&&!this.state.showCompiledCode&&g.jsx(Me,{"aria-label":"Import Blocks",title:b.I18n.t("Import blocks"),style:Te.toolbarButtons,onClick:()=>this.sendCommandToRules("import"),size:"medium",children:g.jsx(Rg,{})},"import"),this.props.expertMode&&!d&&(this.props.debugMode||!this.state.blockly&&!this.state.rules||(this.state.blockly||this.state.rules)&&this.state.showCompiledCode)&&g.jsx(Me,{style:Te.toolbarButtons,color:this.props.debugMode?"primary":"default",disabled:!this.props.debugMode&&!s,onClick:()=>{!this.props.debugMode&&i?this.setState({askAboutDebug:!0}):this.props.onDebugModeChange(!this.props.debugMode)},size:"medium",children:g.jsx(ec,{style:{fontSize:32}})}),(this.state.blockly||this.state.rules)&&g.jsx(De,{"aria-label":"blockly",title:b.I18n.t("Show javascript code"),className:"button-js-code",color:this.state.showCompiledCode?"secondary":"inherit",disabled:this.props.debugMode,style:{...Te.toolbarButtons,...this.props.debugMode?Te.toolbarButtonsDisabled:void 0,padding:"0 5px"},onClick:()=>{this.props.debugMode||(this.setState({showCompiledCode:!this.state.showCompiledCode}),this.state.isTourOpen&&this.state.tourStep===As.showJavascript&&this.setState({tourStep:As.switchBackToRules}),this.state.isTourOpen&&this.state.tourStep===As.switchBackToRules&&this.setState({tourStep:As.saveTheScript}))},children:g.jsx("img",{alt:this.state.blockly?"blockly2js":"rules2js",src:this.state.blockly?L0:P0})},"blockly-code"),g.jsx(Me,{disabled:this.props.debugMode,"aria-label":"Debug menu",title:b.I18n.t("Debug options"),style:Te.toolbarButtons,onClick:p=>this.setState({showDebugMenu:!0,menuDebugAnchorEl:p.currentTarget}),size:"medium",children:g.jsx(Pk,{style:Te.badgeMargin,badgeContent:this.getDebugBadge(),children:g.jsx(vS,{})})},"debug")]},"toolbar1")}return null}getScriptEditor(){return!this.props.debugMode&&this.state.selected&&this.props.objects[this.state.selected]&&this.state.blockly!==null&&(!this.state.blockly||this.state.showCompiledCode)&&(!this.state.rules||this.state.showCompiledCode)?(this.scripts[this.state.selected]||=this.getScriptFromObject(this.state.selected),g.jsx($t,{sx:Te.editorDiv,children:g.jsx(pn,{fallback:g.jsx(vn,{}),children:g.jsx(U0,{name:this.state.selected,adapterName:this.props.adapterName,insert:this.state.insert,onInserted:()=>this.setState({insert:""}),onForceSave:()=>this.onSave(),searchText:this.state.searchText,onRegisterSelect:s=>this.onRegisterSelect(s),readOnly:this.state.showCompiledCode,changed:this.state.changed[this.state.selected],code:this.scripts[this.state.selected].source||"",isDark:this.state.themeType==="dark",socket:this.props.socket,runningInstances:this.state.runningInstances,triggerPrettier:this.state.triggerPrettier,onChange:s=>this.onChange({script:s}),language:this.scripts[this.state.selected].engineType==="TypeScript/ts"?"typescript":"javascript"},"scriptEditor1")})},"scriptEditorDiv")):null}getBlocklyEditor(){return!this.props.debugMode&&this.state.instancesLoaded&&this.state.selected&&this.props.objects[this.state.selected]&&this.state.blockly&&!this.state.showCompiledCode&&this.state.visible?(this.scripts[this.state.selected]||=this.getScriptFromObject(this.state.selected),g.jsx($t,{sx:Te.editorDiv,children:g.jsx(pn,{fallback:g.jsx(vn,{}),children:g.jsx(j0,{command:this.state.cmdToBlockly,themeType:this.state.themeType,searchText:this.state.searchText,code:this.scripts[this.state.selected].source||"",scriptId:this.state.selected,onChange:s=>this.onChange({script:s})},"BlocklyEditor")})},"blocklyEditorDiv")):null}getRulesEditor(){var s,i;if(!this.props.debugMode&&this.state.instancesLoaded&&this.state.selected&&this.props.objects[this.state.selected]&&this.state.rules&&!this.state.showCompiledCode&&this.state.visible){this.scripts[this.state.selected]||=this.getScriptFromObject(this.state.selected);const r=!!this.state.selected&&!!((s=this.scripts[this.state.selected])!=null&&s.engine)&&this.state.runningInstances[this.scripts[this.state.selected].engine],l=!!this.state.selected&&((i=this.scripts[this.state.selected])==null?void 0:i.enabled);return g.jsx($t,{sx:Te.editorDiv,children:g.jsx(pn,{fallback:g.jsx(vn,{}),children:g.jsx(F0,{scriptId:this.state.selected,setTourStep:this.setTourStep,tourStep:this.state.tourStep,isTourOpen:this.state.isTourOpen,changed:this.state.changed[this.state.selected],running:r&&l,command:this.state.cmdToRules,themeType:this.state.themeType,themeName:this.props.themeName,theme:this.props.theme,searchText:this.state.searchText,resizing:this.props.resizing,code:this.scripts[this.state.selected].source||"",onChange:u=>this.onChange({script:u})},"flowEditor")})},"flowEditorDiv")}return null}getConfirmDialog(){return this.state.confirm?g.jsx(b.DialogConfirm,{text:this.state.confirm,onClose:s=>{if(this.confirmCallback){const i=this.confirmCallback;this.confirmCallback=null,i(s)}this.setState({confirm:""})}},"dialogConfirm1"):null}getSelectIdDialog(){var s;if(this.state.showSelectId){const i=["state","channel","device","adapter","instance","enum","host","config","script","user","group"],r=["adapter","instance","enum","host","config","script","user","group"];let l=this.selectId.callback?this.selectId.initValue||"":this.getSelect&&this.getSelect()||"",u=l.indexOf("/*");u!==-1&&(l=l.substring(0,u)),u=l.indexOf("//"),u!==-1&&(l=l.substring(0,u));let d=l.match(/"([^"]+)"/);return d&&(l=d[1]),d=l.match(/'([^']+)'/),d&&(l=d[1]),g.jsx(b.DialogSelectID,{theme:this.props.theme,imagePrefix:"../..",themeName:this.props.themeName,themeType:this.state.themeType,socket:this.props.socket,selected:l,expertMode:this.selectId.type&&this.selectId.type!=="all"&&r.includes(this.selectId.type)?!0:void 0,types:((s=this.selectId)==null?void 0:s.type)==="all"?i:[this.selectId.type||"state"],onClose:()=>{this.setState({showSelectId:!1}),this.selectId.callback&&(this.selectId.callback=null)},onOk:(p,m)=>{this.selectId.initValue=null,this.selectId.callback?(this.selectId.callback(p),this.selectId.callback=null):this.setState({insert:`'${p}'/*${m}*/`})}},"dialogSelectID1")}return null}getCronDialog(){return this.state.showCron?g.jsx(b.DialogCron,{theme:this.props.theme,cron:this.cron.callback?this.cron.initValue||"":this.getSelect?this.getSelect():"* * * * *",onClose:()=>this.setState({showCron:!1}),onOk:s=>{this.cron.initValue=null,this.cron.callback?(this.cron.callback(s),this.cron.callback=null):this.setState({insert:`'${s}'`})}},"dialogCron1"):null}getAstroDialog(){return this.state.showAstro?g.jsxs(Gt,{open:!0,onClose:()=>this.setState({showAstro:!1}),children:[g.jsx(as,{children:b.I18n.t("Astronomical events today")}),g.jsx(Vt,{children:this.state.astroEvents?g.jsx(jk,{component:Dw,children:g.jsxs(Fk,{size:"small",children:[g.jsx(zk,{children:g.jsxs(t_,{children:[g.jsx(gn,{children:b.I18n.t("Name")}),g.jsx(gn,{children:b.I18n.t("Server time")}),g.jsx(gn,{children:b.I18n.t("Description")})]})}),g.jsx(Uk,{children:Object.keys(this.state.astroEvents).map(s=>{var i,r,l,u;return g.jsxs(t_,{children:[g.jsx(gn,{component:"th",scope:"row",children:s.startsWith("next")?"":s}),g.jsx(Hk,{title:`${b.I18n.t("Local time")}: ${(i=this.state.astroEvents)!=null&&i[s].isValidDate?new Date((r=this.state.astroEvents)==null?void 0:r[s].date).toLocaleTimeString():"n/a"}`,children:g.jsx(gn,{align:"right",children:(l=this.state.astroEvents)!=null&&l[s].isValidDate?(u=this.state.astroEvents)==null?void 0:u[s].serverTime:"n/a"})}),g.jsx(gn,{children:b.I18n.t(s)})]},s)})})]})}):g.jsx(Bk,{})}),g.jsx(Kt,{children:g.jsx(De,{variant:"contained",onClick:()=>this.setState({showAstro:!1}),color:"primary",startIcon:g.jsx(Ql,{}),children:b.I18n.t("Close")})})]},"dialogAstro"):null}getEditorDialog(){return this.state.showScript?g.jsx(pn,{fallback:g.jsx(vn,{}),children:g.jsx(H0,{adapterName:this.props.adapterName,source:this.scriptDialog.initValue||"",args:this.scriptDialog.args?this.scriptDialog.args.join(", "):"",isReturn:this.scriptDialog.isReturn,socket:this.props.socket,runningInstances:this.state.runningInstances,themeType:this.state.themeType,onClose:s=>{this.scriptDialog.initValue=null,this.scriptDialog.callback&&(s!==!1&&this.scriptDialog.callback(s||""),this.scriptDialog.callback=null),this.setState({showScript:!1})}},"scriptEditorDialog")}):null}getToast(){return g.jsx(Wk,{anchorOrigin:{vertical:"bottom",horizontal:"left"},open:!!this.state.toast,autoHideDuration:6e3,onClose:()=>this.setState({toast:""}),slotProps:{content:{"aria-describedby":"message-id"}},message:g.jsx("span",{id:"message-id",children:this.state.toast}),action:[g.jsx(Me,{"aria-label":"close",color:"inherit",style:Te.closeToast,onClick:()=>this.setState({toast:""}),size:"medium",children:g.jsx(Ql,{})},"close")]},"toast")}setTourStep=s=>this.setState({tourStep:s});getTour(){return this.state.instancesLoaded&&this.state.selected&&this.props.isAnyRulesExists===1&&this.props.objects[this.state.selected]&&this.state.rules&&this.state.visible?g.jsx(Bm,{steps:B0,isOpen:this.state.isTourOpen,onRequestClose:()=>{this.setState({isTourOpen:!1}),window.localStorage.setItem("tour","true"),this.props.socket.setState("javascript.0.variables.rulesTour",{val:!0,ack:!0})},goToStep:this.state.tourStep},"tour"):null}getDebug(){return this.props.debugMode?this.state.selected&&this.scripts[this.state.selected]&&this.scripts[this.state.selected].engine&&this.state.runningInstances[this.scripts[this.state.selected].engine]?g.jsx(pn,{fallback:g.jsx(vn,{}),children:g.jsx(z0,{runningInstances:this.state.runningInstances,adapterName:this.props.adapterName,socket:this.props.socket,themeName:this.props.themeName,themeType:this.props.themeType,src:this.props.debugInstance?this.props.debugInstance.adapter:this.state.selected,debugInstance:this.props.debugInstance},"debugger")}):(setTimeout(()=>this.props.onDebugModeChange(!1)),null):null}getScriptFromObject(s){var r,l;if(!((r=this.props.objects[s])!=null&&r.common))return;const i=JSON.parse(JSON.stringify(this.props.objects[s].common));return(l=this.props.objects[s].native)!=null&&l.protected&&this.props.password&&(i.source=Ug(this.props.password,i.source)),i}render(){var s,i;return this.state.selected&&this.props.objects[this.state.selected]&&this.state.blockly===null&&this.state.rules===null&&(this.scripts[this.state.selected]||=this.getScriptFromObject(this.state.selected),setTimeout(()=>{const r={blockly:this.scripts[this.state.selected].engineType==="Blockly",rules:this.scripts[this.state.selected].engineType==="Rules",showCompiledCode:!1,debugEnabled:this.scripts[this.state.selected].debug,verboseEnabled:this.scripts[this.state.selected].verbose};this.removeNonExistingScripts(null,r),this.setState(r)},100)),this.state.selected&&!this.props.password&&((i=(s=this.props.objects[this.state.selected])==null?void 0:s.native)!=null&&i.protected)&&setTimeout(()=>{const r=this.state.editing.find(l=>{var u,d;return!((d=(u=this.props.objects[l])==null?void 0:u.native)!=null&&d.protected)})||"";Object.keys(this.scripts).forEach(l=>{var u,d;(d=(u=this.props.objects[l])==null?void 0:u.native)!=null&&d.protected&&delete this.scripts[l]}),this.setState({selected:r},()=>{var l,u;(u=(l=this.props).onSelectedChange)==null||u.call(l,r,this.state.editing),this.state.selected?window.localStorage.setItem("Editor.selected",this.state.selected):window.localStorage.removeItem("Editor.selected")})},50),!this.state.selected&&this.props.password&&this.state.editing.length&&setTimeout(()=>{const r=this.state.editing[0];this.setState({selected:r},()=>{var l,u;(u=(l=this.props).onSelectedChange)==null||u.call(l,r,this.state.editing),window.localStorage.setItem("Editor.selected",this.state.selected)})},50),[this.getTabs(),this.getToolbar(),this.getScriptEditor(),this.getAskAboutDebug(),this.getBlocklyEditor(),this.getRulesEditor(),this.getDebug(),this.getConfirmDialog(),this.getSelectIdDialog(),this.getCronDialog(),this.getEditorDialog(),this.getAstroDialog(),this.getDebugMenu(),this.renderOpenAiDialog(),this.getToast(),this.getTour()]}}const Ht={dialog:{height:"95%"},dropzone:{marginTop:20,width:"100%",borderWidth:5,borderStyle:"dashed",borderColor:"#d0cccc",textAlign:"center",boxSizing:"border-box",paddingTop:45,borderRadius:10,height:"calc(100% - 10px)"},dropzoneDiv:{width:"100%",height:"100%"},dropzoneRejected:{borderColor:"#970000"},dropzoneAccepted:{borderColor:"#17cd02"},icon:{height:"30%",width:"30%",color:"#eeeeee",position:"absolute",top:"50%",left:"50%",transform:"translate(-50%,-50%)",zIndex:0},iconError:{color:"#ffc3c6"},iconOk:{color:"#aaeebc"},text:{top:"50%",left:"50%",transform:"translate(-50%,-50%)",color:"#868686",position:"absolute",zIndex:1}};class jm extends Y.Component{constructor(s){super(s),this.state={error:"",imageStatus:""}}componentDidMount(){setTimeout(()=>{var s;try{(s=window.document.getElementById("import-text-area"))==null||s.focus()}catch{}},100)}handleCancel(){this.props.onClose()}static readFileDataUrl(s,i){const r=new FileReader;r.onload=()=>{i(null,{data:r.result,name:s.name})},r.onabort=()=>{console.error("file reading was aborted"),i(b.I18n.t("file reading was aborted"))},r.onerror=l=>{console.error("file reading has failed"),i(b.I18n.t("file reading has failed: %s",l))},r.readAsDataURL(s)}handleDropFile(s){if(!(s!=null&&s.length))return;const i=s[s.length-1];i&&jm.readFileDataUrl(i,(r,l)=>{var u;r||!l?this.setState({error:r||"No data"}):this.props.onClose(((u=l.data)==null?void 0:u.toString())||"")})}render(){const s={...Ht.dropzone,...this.state.imageStatus==="accepted"?Ht.dropzoneAccepted:this.state.imageStatus==="rejected"?Ht.dropzoneRejected:void 0};return g.jsxs(Gt,{onClose:()=>!1,maxWidth:"lg",sx:{"& .MuiDialog-paper":Ht.dialog},fullWidth:!0,open:!0,"aria-labelledby":"import-dialog-title",PaperProps:{style:{minHeight:"90%",maxHeight:"90%"}},children:[g.jsx(as,{id:"import-dialog-title",children:b.I18n.t("Import scripts")}),g.jsxs(Vt,{children:[g.jsx(Mw,{maxSize:5e7,onDrop:(i,r)=>{var l,u,d;i.length?this.handleDropFile(i):window.alert(((d=(u=(l=r==null?void 0:r[0])==null?void 0:l.errors)==null?void 0:u[0])==null?void 0:d.message)||b.I18n.t("ra_Cannot upload"))},multiple:!1,accept:{"application/zip":[],"application/x-zip-compressed":[]},children:({getRootProps:i,getInputProps:r,isDragActive:l,isDragReject:u})=>u?(this.state.imageStatus!=="rejected"&&this.setState({imageStatus:"rejected"}),g.jsxs("div",{style:{...s,...Ht.dropzoneDiv},...i(),children:[g.jsx("input",{...r()}),g.jsx("span",{style:Ht.text,children:b.I18n.t("Some files will be rejected")},"text"),g.jsx(Wc,{style:{...Ht.icon,...Ht.iconError}},"icon")]})):l?(this.state.imageStatus!=="accepted"&&this.setState({imageStatus:"accepted"}),g.jsxs("div",{style:{...s,...Ht.dropzoneDiv},...i(),children:[g.jsx("input",{...r()}),g.jsx("span",{style:Ht.text,children:b.I18n.t("All files will be accepted")},"text"),g.jsx(Nw,{style:{...Ht.icon,...Ht.iconOk}},"icon")]})):(this.state.imageStatus!=="wait"&&this.setState({imageStatus:"wait"}),g.jsxs("div",{style:{...s,...Ht.dropzoneDiv},...i(),children:[g.jsx("input",{...r()}),g.jsx("span",{style:Ht.text,children:b.I18n.t("Drop some files here or click...")},"text"),g.jsx(Lw,{style:Ht.icon},"icon")]}))},"image-drop"),this.state.error?g.jsx(Zc,{text:this.state.error,onClose:()=>this.setState({error:""})}):null]}),g.jsx(Kt,{children:g.jsx(De,{color:"grey",variant:"contained",onClick:()=>this.handleCancel(),startIcon:g.jsx(qs,{}),children:b.I18n.t("Close")})})]})}}var Fm={exports:{}},Y0=Fm.exports;(function(a,s){(function(i,r){a.exports=r()})(Y0,function(){var i={},r,l,u,d,p,m,f,v,_,y,k,C,w,E,R,D,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$,Co,Va,Ka,kd,A$,Sd,Ya,Ed,Id,R$,xd,O$,Ja,M$,N$,L$,P$,B$,Dd,j$,Qn,er,F$,Ad,Rd,Od,Md,qa,Nd,z$,U$,H$,zi,Ld,W$,Xa,ls,G$,To,Pd,V$,tr,Bd,jd,Fd,zd,Ud,Hd,Wd,Gd,Vd,Kd,K$,Y$,J$,q$,X$,Z$,Za,Q$,eb,Yd,Jd,qd,Xd,Zd,Qd,eh,Qa,sr,th,tb,sh,oh,ih,nh,rh,ah,lh,ch,uh,dh,sb,ob,ib,hh,nb,rb,ab,lb,cb,j;r=function(e,t,o,n){if(!(e instanceof F)&&typeof e!="string"||`${e}`.trim()==="")throw Error('Invalid type "'+e+'". The type must be a non-empty string or a Blockly.registry.Type.');if(e=`${e}`.toLowerCase(),typeof t!="string"||t.trim()==="")throw Error('Invalid name "'+t+'". The name must be a non-empty string.');const c=t.toLowerCase();if(!o)throw Error("Can not register a null value");let h=ko[e],$=el[e];if(h||(h=ko[e]=Object.create(null),$=el[e]=Object.create(null)),l(e,o),!n&&h[c]&&h[c]!==o)throw Error('Name "'+c+'" with type "'+e+'" already registered.');h[c]=o,$[c]=t},l=function(e,t){switch(e){case String(F.FIELD):if(typeof t.fromJson!="function")throw Error('Type "'+e+'" must have a fromJson function')}},u=function(e,t){e=`${e}`.toLowerCase(),t=t.toLowerCase();const o=ko[e];o&&o[t]?(delete ko[e][t],delete el[e][t]):console.warn("Unable to unregister ["+t+"]["+e+"] from the registry.")},d=function(e,t,o){e=`${e}`.toLowerCase(),t=t.toLowerCase();const n=ko[e];if(!n||!n[t]){if(t="Unable to find ["+t+"]["+e+"] in the registry.",o)throw Error(t+" You must require or register a "+e+" plugin.");return console.warn(t),null}return n[t]},p=function(e,t){return e=`${e}`.toLowerCase(),t=t.toLowerCase(),(e=ko[e])?!!e[t]:!1},m=function(e,t,o){return d(e,t,o)},f=function(e,t,o){return d(e,t,o)},v=function(e,t,o){e=`${e}`.toLowerCase();var n=ko[e];if(!n){if(n=`Unable to find [${e}] in the registry.`,o)throw Error(`${n} You must require or register a ${e} plugin.`);return console.warn(n),null}if(!t)return n;e=el[e],o=Object.create(null);for(const c of Object.keys(n))o[e[c]]=n[c];return o},_=function(e,t,o){return t=t.plugins[String(e)]||js,typeof t=="function"?t:m(e,t,o)},y=function(e,t,o,n){e=e+" was deprecated in "+t+" and will be deleted in "+o+".",n&&(e+=` -Use `+n+" instead."),db.has(e)||(db.add(e),console.warn(e))},k=function(){return"blockly-"+(OT++).toString(36)},C=function(){return gb.genUid()},w=function(e){return e.type===O.BLOCK_CREATE},E=function(e){return e.type===O.BLOCK_DELETE},R=function(e){return e.type===O.BLOCK_CHANGE},D=function(e){return e.type===O.BLOCK_FIELD_INTERMEDIATE_CHANGE},A=function(e){return e.type===O.BLOCK_MOVE},J=function(e){return e.type===O.CLICK},ie=function(e){return e.type===O.BUBBLE_OPEN},se=function(e){return e.type===O.VIEWPORT_CHANGE},i.setRecordUndo$$module$build$src$core$events$utils=function(e){or=e},me=function(){return or},z=function(e){fb.fireInternal(e)},Oe=function(e){if(K()){if(!io.length)try{requestAnimationFrame(()=>{setTimeout(Ne,0)})}catch{setTimeout(Ne,0)}Ze(e)}},Ne=function(){const e=ae(io,!0);io.length=0;for(const t of e){if(!t.workspaceId)continue;let o;(o=q(t.workspaceId))==null||o.fireChangeListener(t)}},Ze=function(e){if(R(e)&&e.element==="mutation"){let t;for(t=io.length;0!n.isNull()),t||e.reverse(),e},ce=function(){for(let e=0,t;t=io[e];e++)t.recordUndo=!1},i.disable$$module$build$src$core$events$utils=function(){gh++},i.enable$$module$build$src$core$events$utils=function(){gh--},K=function(){return gh===0},i.getGroup$$module$build$src$core$events$utils=function(){return mb},i.setGroup$$module$build$src$core$events$utils=function(e){fb.setGroupInternal(e)},ye=function(e){mb=typeof e=="boolean"?e?C():"":e},he=function(e){const t=[];e=e.getDescendants(!1);for(let o=0,n;n=e[o];o++)t[o]=n.id;return t},je=function(e,t){const o=V(e.type);if(!o)throw Error("Unknown event type.");return o.fromJson(e,t)},V=function(e){const t=m(F.EVENT,e);if(!t)throw Error(`Event type ${e} not found in registry.`);return t},tt=function(e){if((A(e)||w(e))&&e.workspaceId){var t=q(e.workspaceId);if(!e.blockId)throw Error("Encountered a blockEvent without a proper blockId");if(e=t.getBlockById(e.blockId)){const o=or;try{or=!1;const n=e.getParent();if(n&&!n.hasDisabledReason(mh)){const c=e.getDescendants(!1);for(let h=0,$;$=c[h];h++)$.setDisabledReason(!1,mh)}else if((e.outputConnection||e.previousConnection)&&!t.isDragging())do e.setDisabledReason(!0,mh),e=e.getNextBlock();while(e)}finally{or=o}}}},q=function(e){return ir[e]||null},ee=function(){const e=[];for(const t in ir)e.push(ir[t]);return e},B=function(e){ir[e.id]=e},H=function(e){delete ir[e.id]},U=function(){return $b},re=function(e){$b=e},I=function(){return Zo},i.setSelected$$module$build$src$core$common=function(e){if(Zo!==e){var t,o,n,c,h,$,T=new(V(O.SELECTED))((n=(t=Zo)==null?void 0:t.id)!=null?n:null,(c=e==null?void 0:e.id)!=null?c:null,($=(h=e==null?void 0:e.workspace.id)!=null?h:(o=Zo)==null?void 0:o.workspace.id)!=null?$:"");z(T);var L;(L=Zo)==null||L.unselect(),Zo=e;var te;(te=Zo)==null||te.select()}},de=function(){return bb},W=function(e){bb=e},Ce=function(e){for(;e.options.parentWorkspace;)e=e.options.parentWorkspace;const t=e.getParentSvg(),o=e.getCachedParentSvgSize();var n=t.parentElement;if(n instanceof HTMLElement){var c=n.offsetWidth;n=n.offsetHeight,o.width!==c&&(t.setAttribute("width",c+"px"),e.setCachedParentSvgSize(c,null)),o.height!==n&&(t.setAttribute("height",n+"px"),e.setCachedParentSvgSize(null,n)),e.resize()}},be=function(e,t){const o=Object.create(null),n=e.getDescendants(!0);t&&(e=e.getNextBlock())&&(e=n.indexOf(e),n.splice(e,n.length-e));for(let c=0,h;h=n[c];c++)o[h.type]?o[h.type]++:o[h.type]=1;return o},Se=function(e){return function(){this.jsonInit(e)}},pe=function(e){vb.defineBlocksWithJsonArrayInternal(e)},Ve=function(e){i.defineBlocks$$module$build$src$core$common(i.createBlockDefinitionsFromJsonArray$$module$build$src$core$common(e))},i.createBlockDefinitionsFromJsonArray$$module$build$src$core$common=function(e){const t={};for(let o=0;o>>/g,e),Ch="",e=document.createElement("style"),e.id="blockly-common-style",t=document.createTextNode(t),e.appendChild(t),document.head.insertBefore(e,document.head.firstChild)))},N=function(e,t,o){e=document.createElementNS(rr,`${e}`);for(const n in t)e.setAttribute(n,`${t[n]}`);return o&&o.appendChild(e),e},ge=function(e,t){return t=t.split(" "),t.every(o=>e.classList.contains(o))?!1:(e.classList.add(...t),!0)},la=function(e,t){e.classList.remove(...t.split(" "))},ot=function(e,t){return t=t.split(" "),t.every(o=>!e.classList.contains(o))?!1:(e.classList.remove(...t),!0)},Hm=function(e,t){return e.classList.contains(t)},Ke=function(e){return e&&e.parentNode?e.parentNode.removeChild(e):null},Uo=function(e,t){const o=t.nextSibling;if(t=t.parentNode,!t)throw Error("Reference node has no parent.");o?t.insertBefore(e,o):t.appendChild(e)},ca=function(e,t){e.style.transform=t,e.style["-webkit-transform"]=t},Ho=function(){kh++,Ts||(Ts=Object.create(null))},Wo=function(){kh--,kh||(Ts=null)},uu=function(e){const t=e.textContent+` -`+e.className.baseVal;let o;if(Ts&&(o=Ts[t]))return o;try{o=e.getComputedTextLength()}catch{return 8*e.textContent.length}return Ts&&(Ts[t]=o),o},Nn=function(e,t,o,n){return ua(e,t+"pt",o,n)},ua=function(e,t,o,n){const c=e.textContent;e=c+` -`+e.className.baseVal;var h;return Ts&&(h=Ts[e])||(rl||(h=document.createElement("canvas"),h.className="blocklyComputeCanvas",document.body.appendChild(h),rl=h.getContext("2d")),rl.font=o+" "+t+" "+n,h=c?rl.measureText(c).width:0,Ts&&(Ts[e]=h)),h},da=function(e,t,o,n){const c=document.createElement("span");c.style.font=o+" "+t+" "+n,c.textContent=e,e=document.createElement("div"),e.style.width="1px",e.style.height="0",t=document.createElement("div"),t.style.display="flex",t.style.position="fixed",t.style.top="0",t.style.left="0",t.appendChild(c),t.appendChild(e),document.body.appendChild(t),o={height:0,baseline:0};try{t.style.alignItems="baseline",o.baseline=e.offsetTop-c.offsetTop,t.style.alignItems="flex-end",o.height=e.offsetTop-c.offsetTop}finally{document.body.removeChild(t)}return o},Ln=function(e){return Mb.getSizeInternal(e)},Wm=function(e){if(Ms(e,"display")!=="none")return du(e);const t=e.style,o=t.display,n=t.visibility,c=t.position;t.visibility="hidden",t.position="absolute",t.display="inline";const h=e.offsetWidth;return e=e.offsetHeight,t.display=o,t.position=c,t.visibility=n,new Le(h,e)},du=function(e){return new Le(e.offsetWidth,e.offsetHeight)},Ms=function(e,t){return e=window.getComputedStyle(e),e[t]||e.getPropertyValue(t)},yo=function(e){const t=new G(0,0);e=e.getBoundingClientRect();var o=document.documentElement;return o=new G(window.pageXOffset||o.scrollLeft,window.pageYOffset||o.scrollTop),t.x=e.left+o.x,t.y=e.top+o.y,t},hu=function(){const e=document.body,t=document.documentElement;return new G(e.scrollLeft||t.scrollLeft,e.scrollTop||t.scrollTop)},pu=function(e){const t=parseFloat(Ms(e,"borderLeftWidth")),o=parseFloat(Ms(e,"borderRightWidth")),n=parseFloat(Ms(e,"borderTopWidth"));return e=parseFloat(Ms(e,"borderBottomWidth")),new qe(n,e,t,o)},ha=function(e,t,o){e=gu(e,t,o),t.scrollLeft=e.x,t.scrollTop=e.y},gu=function(e,t,o){var n=yo(e),c=yo(t),h=pu(t);const $=n.x-c.x-h.left;return n=n.y-c.y-h.top,c=du(e),e=t.clientWidth-c.width,c=t.clientHeight-c.height,h=t.scrollLeft,t=t.scrollTop,o?(h+=$-e/2,t+=n-c/2):(h+=Math.min($,Math.max($-e,0)),t+=Math.min(n,Math.max(n-c,0))),new G(h,t)},Pn=function(e){const t=new G(0,0);var o=e.x&&e.getAttribute("x");const n=e.y&&e.getAttribute("y");return o&&(t.x=parseInt(o)),n&&(t.y=parseInt(n)),(o=(o=e.getAttribute("transform"))&&o.match(Nb))&&(t.x+=Number(o[1]),o[3]&&(t.y+=Number(o[3]))),(e=e.getAttribute("style"))&&e.includes("translate")&&(e=e.match(Lb))&&(t.x+=Number(e[1]),e[3]&&(t.y+=Number(e[3]))),t},pa=function(e){let t=0,o=0;for(;e;){const n=Pn(e);if(t+=n.x,o+=n.y,(" "+(e.getAttribute("class")||"")+" ").includes(" injectionDiv "))break;e=e.parentNode}return new G(t,o)},mu=function(){const e=hu();return new qe(e.y,document.documentElement.clientHeight+e.y,e.x,document.documentElement.clientWidth+e.x)},fu=function(){const e=document.documentElement,t=window;return new G(t.pageXOffset||e.scrollLeft,t.pageYOffset||e.scrollTop)},Gm=function(e,t){var o=t.x;t=t.y;const n=e.getInjectionDiv().getBoundingClientRect();return o=new G(o-n.left,t-n.top),t=e.getOriginOffsetInPixels(),G.difference(o,t).scale(1/e.scale)},Vm=function(e,t){var o=t.scale(e.scale);t=o.x,o=o.y;const n=e.getInjectionDiv().getBoundingClientRect();return e=e.getOriginOffsetInPixels(),new G(t+n.left+e.x,o+n.top+e.y)},Km=function(e){({document:ll=ll,DOMParser:ar=ar,XMLSerializer:lr=lr}=e),al=new ar,Sh=new lr},i.createElement$$module$build$src$core$utils$xml=function(e){return ll.createElementNS(Pb,e)},i.createTextNode$$module$build$src$core$utils$xml=function(e){return ll.createTextNode(e)},i.textToDom$$module$build$src$core$utils$xml=function(e){let t=al.parseFromString(e,"text/xml");if(t&&t.documentElement&&!t.getElementsByTagName("parsererror").length)return t.documentElement;if((t=al.parseFromString(e,"text/html"))&&t.body.firstChild&&t.body.firstChild.nodeName.toLowerCase()==="xml")return t.body.firstChild;throw Error(`DOMParser was unable to parse: ${e}`)},Ii=function(e){return Ym(Sh.serializeToString(e))},Ym=function(e){return e.replace(BT,t=>`&#${t.charCodeAt(0)};`)},ga=function(e){return e?((e instanceof Element||typeof e=="string")&&(e=bu(e),e=Xm(e)),Jm(e),e):null},Jm=function(e){const t=e.kind;if(e=e.contents,t&&t!==Bb&&t!==Eh)throw Error("Invalid toolbox kind "+t+". Please supply either "+Bb+" or "+Eh);if(!e)throw Error("Toolbox must have a contents attribute.")},Bn=function(e){return e?e.contents?e.contents:Array.isArray(e)&&0o.kind.toUpperCase()==="CATEGORY").length},fa=function(e){return e&&e.contents?!!e.contents.filter(function(t){return t.kind.toUpperCase()==="CATEGORY"}).length:!1},Xm=function(e){const t={contents:$a(e)};return e instanceof Node&&$u(e,t),t},$a=function(e){const t=[];let o=e.childNodes;o||(o=e);for(let n=0,c;c=o[n];n++){if(!c.tagName)continue;e={};const h=c.tagName.toUpperCase();e.kind=h,h==="BLOCK"?e.blockxml=c:c.childNodes&&0 document.")}else e instanceof Element&&(t=e);return t},ba=function(e,t,o,n,c,h){const $=h.scrollbar&&h.scrollbar.canScrollVertically();return e.horizontal===Wi.LEFT?(o=c.absoluteMetrics.left+o,$&&h.RTL&&(o+=mt.scrollbarThickness)):(o=c.absoluteMetrics.left+c.viewMetrics.width-t.width-o,$&&!h.RTL&&(o-=mt.scrollbarThickness)),e.vertical===lo.TOP?e=c.absoluteMetrics.top+n:(e=c.absoluteMetrics.top+c.viewMetrics.height-t.height-n,h.scrollbar&&h.scrollbar.canScrollHorizontally()&&(e-=mt.scrollbarThickness)),new qe(e,e+t.height,o,o+t.width)},va=function(e,t){return{horizontal:t.toolboxMetrics.position===Ee.LEFT||e.horizontalLayout&&!e.RTL?Wi.RIGHT:Wi.LEFT,vertical:t.toolboxMetrics.position===Ee.BOTTOM?lo.TOP:lo.BOTTOM}},ya=function(e,t,o,n){const c=e.left,h=e.right-e.left,$=e.bottom-e.top;for(let T=0;Th.id!==e.id).map(h=>h.getRelativeToSurfaceXY());for(;tf(G.sum(o,n),c);)n.translate(t.RTL?-30:30,30);e.moveTo(G.sum(o,n))},tf=function(e,t){return t.some(o=>1>=Math.abs(o.x-e.x)&&1>=Math.abs(o.y-e.y))},_o=function(e,t){e.setAttribute(zT,t)},It=function(e,t,o){Array.isArray(o)&&(o=o.join(" ")),e.setAttribute(FT+t,`${o}`)},zn=function(e){return e.saveState!==void 0&&e.loadState!==void 0},vu=function(e){return yu(e),sf()?(wa(),Promise.resolve()):(Gi||(Gi=new Promise(t=>{Nh=t,Vb=window.requestAnimationFrame(()=>{wa(),t()})})),Gi)},ws=function(){return Gi||Promise.resolve()},Qs=function(e){e||window.cancelAnimationFrame(Vb),wa(e),!e&&Nh&&Nh()},sf=function(){return Eb},yu=function(e){Oh.add(e),Mh.set(e,i.getGroup$$module$build$src$core$events$utils());const t=e.getParent();t?yu(t):hl.add(e)},wa=function(e){const t=e?new Set([e]):new Set([...hl].map(h=>h.workspace)),o=[...hl].filter(of).filter(h=>t.has(h.workspace));for(var n of o)wu(n);for(const h of t)h.resizeContents();for(var c of o)n=c.getRelativeToSurfaceXY(),c.updateComponentLocations(n);for(const h of o)c=i.getGroup$$module$build$src$core$events$utils(),(n=Mh.get(h))&&i.setGroup$$module$build$src$core$events$utils(n),h.bumpNeighbours(),i.setGroup$$module$build$src$core$events$utils(c);for(const h of o)_u(h);e||(Gi=null)},_u=function(e){hl.delete(e),Oh.delete(e),Mh.delete(e);for(const t of e.getChildren(!1))_u(t)},of=function(e){return!e.isDisposed()&&!e.getParent()},wu=function(e){if(Oh.has(e)&&e.initialized){for(const t of e.getChildren(!1))wu(t);e.renderEfficiently()}},Un=function(e,t){Kb(e,t)},nf=function(e){Kb=e},Ca=function(e,t){qb.confirmInternal(e,t)},rf=function(e,t){Yb(e,t)},af=function(e){Yb=e},Ta=function(e,t,o){Jb(e,t,o)},lf=function(e){Jb=e},Di=function(e){return e.getProcedureDef!==void 0},cf=function(e){return e.getProcedureCall!==void 0&&e.renameProcedure!==void 0},Cu=function(e){return e.getVariableModel!==void 0},i.allUsedVarModels$$module$build$src$core$variables=function(e){e=e.getAllBlocks(!1);const t=new Set;for(let o=0;o1'),n.appendChild(o),t.push(n)),Jt.variables_get){e.sort(hr.compareByName);for(let c=0,h;h=e[c];c++)o=i.createElement$$module$build$src$core$utils$xml("block"),o.setAttribute("type","variables_get"),o.setAttribute("gap","8"),o.appendChild(Go(h)),t.push(o)}}return t},ku=function(e){return Zb.generateUniqueNameInternal(e)},uf=function(e){return Sa(jh.charAt(0),e.getAllVariableNames())},Sa=function(e,t){if(!t.length)return e;const o=jh;let n="",c=o.indexOf(e);for(;;){let h=!1;for(let $=0;$h.getVariableModel().name);if(n&&(o=n.some(h=>h.toLowerCase()===e),n=n.some(h=>h.toLowerCase()===t),o&&n))return c.getName()}return null},pf=function(e,t,o){e=e.toLowerCase(),t=t.toLowerCase(),o=o.getAllBlocks(!1);for(const c of o){if(!Di(c))continue;o=c.getProcedureDef();var n=o[1];const h=n.some($=>$.toLowerCase()===e);if(n=n.some($=>$.toLowerCase()===t),h&&n)return o[0]}return null},Go=function(e){const t=i.createElement$$module$build$src$core$utils$xml("field");return t.setAttribute("name","VAR"),t.setAttribute("id",e.getId()),t.setAttribute("variabletype",e.type),e=i.createTextNode$$module$build$src$core$utils$xml(e.name),t.appendChild(e),t},i.getOrCreateVariablePackage$$module$build$src$core$variables=function(e,t,o,n){let c=i.getVariable$$module$build$src$core$variables(e,t,o,n);return c||(c=gf(e,t,o,n)),c},i.getVariable$$module$build$src$core$variables=function(e,t,o,n){const c=e.getPotentialVariableMap();let h=null;if(t&&(h=e.getVariableById(t),!h&&c&&(h=c.getVariableById(t)),h))return h;if(o){if(n===void 0)throw Error("Tried to look up a variable by name without a type");h=e.getVariable(o,n),!h&&c&&(h=c.getVariable(o,n))}return h},gf=function(e,t,o,n){const c=e.getPotentialVariableMap();return o||(o=ku(e.isFlyout?e.targetWorkspace:e)),c?c.createVariable(o,n,t):e.createVariable(o,n,t)},Hn=function(e,t){e=e.getAllVariables();const o=[];if(t.length!==e.length)for(let n=0;n{L.disposed||L.setConnectionTracking(!0)},1)}return T},xu=function(e,t,{parentConnection:o,isShadow:n=!1}={}){if(!e.type)throw new Qb(e);const c=t.newBlock(e.type,e.id);return c.setShadow(n),Cf(c,e),Tf(c,e),kf(c,e),Sf(o,c,e),Ef(c,e),If(c,e),xf(c,e),Df(c,e),Af(c,t.rendered),c},wf=function(e,t){if(K())for(e=Hn(e,t),t=0;tt&&(t=o[n].length);var c=-1/0;let h,$=1;do{n=c,h=e,e=[],c=o.length/$;let T=1;for(let L=0;Ln);return h},Ra=function(e,t,o){const n=[0],c=[];for(var h=0;hn&&(n=T,c=$)}return c?Ku(e,c,o):t},Lf=function(e,t){const o=[];for(let n=0;ncv&&to()}else $r!==cs&&(clearTimeout(ci),Wh=e.pageX,Gh=e.pageY,ci=setTimeout(Vf,uv))},Xu=function(){$r=cs=null,to()},to=function(){fr&&(fr=!1,_t&&(_t.style.display="none")),ci&&(clearTimeout(ci),ci=0)},Zu=function(){to(),Xi=!0},Qu=function(){Xi=!1},Hf=function(){_t&&cs&&(typeof $l=="function"?$l(_t,cs):Wf())},Wf=function(){var e=Ni(cs);e=i.wrap$$module$build$src$core$utils$string(e,av),e=e.split(` -`);for(let t=0;to+window.scrollY&&(c-=_t.offsetHeight+2*Kh),e?n=Math.max(bl-window.scrollX,n):n+_t.offsetWidth>t+window.scrollX-2*bl&&(n=t-_t.offsetWidth-2*bl),{x:n,y:c}},Vf=function(){if(!Xi&&($r=cs,_t)){_t.textContent="",Hf();var e=cs.RTL;_t.style.direction=e?"rtl":"ltr",_t.style.display="block",fr=!0;var{x:t,y:o}=Gf(e);_t.style.left=t+"px",_t.style.top=o+"px"}},ed=function(){return Yh},Kf=function(e){Yh=e},td=function(){return Jh},Yf=function(e){Jh=e},Vo=function(e){e=`${e}`.toLowerCase().trim();var t=dv[e];if(t||(t=e.substring(0,2)==="0x"?"#"+e.substring(2):e,t=t[0]==="#"?t:"#"+t,/^#[0-9a-f]{6}$/.test(t)))return t;if(/^#[0-9a-f]{3}$/.test(t))return["#",t[1],t[1],t[2],t[2],t[3],t[3]].join("");var o=e.match(/^(?:rgb)?\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/);return o&&(e=Number(o[1]),t=Number(o[2]),o=Number(o[3]),0<=e&&256>e&&0<=t&&256>t&&0<=o&&256>o)?Kn(e,t,o):null},Kn=function(e,t,o){return t=e<<16|t<<8|o,16>e?"#"+(16777216|t).toString(16).substr(1):"#"+t.toString(16)},Ma=function(e){return e=Vo(e),e?(e=parseInt(e.substr(1),16),[e>>16,e>>8&255,e&255]):[0,0,0]},Na=function(e,t,o){let n=0,c=0,h=0;if(t===0)h=c=n=o;else{const $=Math.floor(e/60),T=e/60-$;e=o*(1-t);const L=o*(1-t*T);switch(t=o*(1-t*(1-T)),$){case 1:n=L,c=o,h=e;break;case 2:n=e,c=o,h=t;break;case 3:n=e,c=L,h=o;break;case 4:n=t,c=e,h=o;break;case 5:n=o,c=e,h=L;break;case 6:case 0:n=o,c=t,h=e}}return Kn(Math.floor(n),Math.floor(c),Math.floor(h))},Ko=function(e,t,o){return e=Vo(e),!e||(t=Vo(t),!t)?null:(e=Ma(e),t=Ma(t),Kn(Math.round(t[0]+o*(e[0]-t[0])),Math.round(t[1]+o*(e[1]-t[1])),Math.round(t[2]+o*(e[2]-t[2]))))},sd=function(e){return Na(e,Yh,255*Jh)},La=function(e,t,o){const n=[];var c=e.split("");c.push("");var h=0;e=[];let $=null;for(let te=0;te=T?(h=2,$=T,(T=e.join(""))&&n.push(T),e.length=0):T==="{"?h=3:(e.push("%",T),h=0);else if(h===2)if("0"<=T&&"9">=T)$+=T;else{var L=void 0;n.push(parseInt((L=$)!=null?L:"",10)),te--,h=0}else h===3&&(T===""?(e.splice(0,0,"%{"),te--,h=0):T!=="}"?e.push(T):(h=e.join(""),/[A-Z]\w*/i.test(h)?(T=h.toUpperCase(),(T=T.startsWith("BKY_")?T.substring(4):null)&&T in i.Msg$$module$build$src$core$msg?(h=i.Msg$$module$build$src$core$msg[T],typeof h=="string"?Array.prototype.push.apply(n,La(h,t,o)):t?n.push(`${h}`):n.push(h)):n.push("%{"+h+"}")):n.push("%{"+h+"}"),h=e.length=0))}for((t=e.join(""))&&n.push(t),L=[],e.length=0,c=0;c=o)return{hue:o,hex:Na(o,ed(),255*td())};if(o=Vo(t))return{hue:null,hex:o};throw o='Invalid colour: "'+t+'"',e!==t&&(o+=' (from "'+e+'")'),Error(o)},Yo=function(){return Ss},qf=function(e){if(Ss=e,e===null){let t;(t=document.querySelector("."+yl))==null||t.remove()}},id=function(){const e=de()||document.body;document.querySelector("."+yl)?Ss=document.querySelector("."+yl):(Ss=document.createElement("div"),Ss.className=yl),e.appendChild(Ss)},Pa=function(e,t,o,n){if(Bi(),Zi=e,vl=o,o=Ss){if(o.style.direction=t?"rtl":"ltr",o.style.display="block",!n&&e instanceof Qe){let $;n=($=e.getSourceBlock())==null?void 0:$.workspace}var c;qh=(c=n)!=null?c:null;var h;e=(h=n)!=null?h:U(),Qi=e.getRenderer().getClassName(),en=e.getTheme().getClassName(),Qi&&ge(o,Qi),en&&ge(o,en)}},Bi=function(){if(nd()){Zi=null;var e=Ss;e&&(e.style.display="none",e.style.left="",e.style.top="",vl&&vl(),vl=null,e.textContent="",Qi&&(ot(e,Qi),Qi=""),en&&(ot(e,en),en=""),U().markFocused())}},nd=function(){return!!Zi},Jo=function(e){Zi===e&&Bi()},Yn=function(e){qh!==null&&qh!==e||Bi()},rd=function(e,t,o){Ss.style.left=e+"px",Ss.style.top=t+"px",Ss.style.height=o+"px"},ad=function(e,t,o,n){const c=Zf(e,t,o);e=Xf(e,t,o,n),0>c?rd(e,0,o.height+c):rd(e,c,o.height)},Xf=function(e,t,o,n){return n?Math.min(Math.max(t.right-o.width,e.left),e.right-o.width):Math.max(Math.min(t.left,e.right-o.width),e.left)},Zf=function(e,t,o){return t.bottom+o.height>=e.bottom?t.top-o.height:t.bottom},Qf=function(e){return!(e==null||!e.repositionForWindowResize)},ld=function(){Qf(Zi)&&Zi.repositionForWindowResize()||Bi()},e$=function(){return _l},cd=function(e){_l=e},Jn=function(e,t,o,n){if(Pa(hv,o,ud,n),t.length){var c=t$(t,o,e);wl=c,s$(c,e,o),setTimeout(function(){c.focus()},1),_l=null}else qn()},t$=function(e,t,o){const n=new Ah;n.setRole(ks.MENU);for(let c=0;c{setTimeout(()=>{h.callback(h.scope,o)},0)})},{})}return n},s$=function(e,t,o){const n=mu();t=new qe(t.clientY+n.top,t.clientY+n.top,t.clientX+n.left,t.clientX+n.left),o$(e);const c=e.getSize();o&&(t.left+=c.width,t.right+=c.width,n.left+=c.width,n.right+=c.width),ad(n,t,c,o),e.focus()},o$=function(e){var t=Yo();if(!t)throw Error("Attempting to create a context menu when widget div is null");t=e.render(t),ge(t,"blocklyContextMenu"),X(t,"contextmenu",null,i$),e.focus()},i$=function(e){e.preventDefault(),e.stopPropagation()},qn=function(){Jo(hv),_l=null},ud=function(){wl&&(wl.dispose(),wl=null)},i.callbackFactory$$module$build$src$core$contextmenu=function(e,t){return()=>{i.disable$$module$build$src$core$events$utils();let o;try{o=t instanceof Element?qo(t,e.workspace):Ri(t,e.workspace);const n=e.getRelativeToSurfaceXY();n.x=e.RTL?n.x-i.config$$module$build$src$core$config.snapRadius:n.x+i.config$$module$build$src$core$config.snapRadius,n.y+=2*i.config$$module$build$src$core$config.snapRadius,o.moveBy(n.x,n.y)}finally{i.enable$$module$build$src$core$events$utils()}return K()&&!o.isShadow()&&z(new(V(O.BLOCK_CREATE))(o)),i.setSelected$$module$build$src$core$common(o),o}},dd=function(e,t){return t=st(t,e.getParentSvg(),e.getInverseScreenCTM()),t.x/=e.scale,t.y/=e.scale,t},Ba=function(e,t,o){t=dd(e,t),gv.set(e,G.difference(o,t))},ja=function(e,t){if(t=dd(e,t),e=gv.get(e),!e)throw Error("Drag not initialized");return G.sum(e,t)},n$=function(e,t=!1){const o=i.createElement$$module$build$src$core$utils$xml("xml");var n=hd(i.allUsedVarModels$$module$build$src$core$variables(e));n.hasChildNodes()&&o.appendChild(n);for(const c of e.getTopComments())o.appendChild(Xn(c,t));for(e=e.getTopBlocks(!0),n=0;n/g,"<$1$2>")},l$=function(e){e=Ls(e).split("<");let t="";for(let o=1;o"&&(t+=" ")}return e=e.join(` -`),e=e.replace(/(<(\w+)\b[^>]*>[^\n]*)\n *<\/\2>/g,"$1"),e.replace(/^\n/,"")},c$=function(e,t){return t.setResizesEnabled(!1),t.clear(),e=i.domToWorkspace$$module$build$src$core$xml(e,t),t.setResizesEnabled(!0),e},i.domToWorkspace$$module$build$src$core$xml=function(e,t){let o=0;t.RTL&&(o=t.getWidth());const n=[];Ho();const c=i.getGroup$$module$build$src$core$events$utils();c||i.setGroup$$module$build$src$core$events$utils(!0),t.setResizesEnabled&&t.setResizesEnabled(!1);let h=!0;try{for(let $=0,T;T=e.childNodes[$];$++){const L=T.nodeName.toLowerCase(),te=T;if(L==="block"||L==="shadow"&&!me()){const nt=qo(te,t);n.push(nt.id);let it;const Xt=parseInt((it=te.getAttribute("x"))!=null?it:"10",10);let hn;const Or=parseInt((hn=te.getAttribute("y"))!=null?hn:"10",10);isNaN(Xt)||isNaN(Or)||nt.moveBy(t.RTL?o-Xt:Xt,Or,["create"]),h=!1}else{if(L==="shadow")throw TypeError("Shadow block cannot be a top-level block.");if(L==="comment")gd(te,t);else if(L==="variables"){if(h)md(te,t);else throw Error("'variables' tag must exist once before block and shadow tag elements in the workspace XML, but it was found in another location.");h=!1}}}}finally{i.setGroup$$module$build$src$core$events$utils(c),t.setResizesEnabled&&t.setResizesEnabled(!0),t.rendered&&Qs(),Wo()}return z(new(V(O.FINISHED_LOADING))(t)),n},gd=function(e,t){var o;const n=(o=e.getAttribute("id"))!=null?o:void 0;o=t.rendered?new kl(t,n):new Tl(t,n);var c;o.setText((c=e.textContent)!=null?c:"");var h;c=parseInt((h=e.getAttribute("x"))!=null?h:"",10);let $;h=parseInt(($=e.getAttribute("y"))!=null?$:"",10),isNaN(c)||isNaN(h)||(c=t.RTL?t.getWidth()-c:c,o.moveTo(new G(c,h)));var T;t=parseInt((T=e.getAttribute("w"))!=null?T:"",10);let L;return T=parseInt((L=e.getAttribute("h"))!=null?L:"",10),isNaN(t)||isNaN(T)||o.setSize(new Le(t,T)),e.getAttribute("collapsed")==="true"&&o.setCollapsed(!0),e.getAttribute("editable")==="false"&&o.setEditable(!1),e.getAttribute("movable")==="false"&&o.setMovable(!1),e.getAttribute("deletable")==="false"&&o.setDeletable(!1),o},u$=function(e,t){if(!t.getBlocksBoundingBox)return i.domToWorkspace$$module$build$src$core$xml(e,t);var o=t.getBlocksBoundingBox();if(e=i.domToWorkspace$$module$build$src$core$xml(e,t),o&&o.top!==o.bottom){var n=o.bottom;o=t.RTL?o.right:o.left;var c=1/0;let h=-1/0,$=1/0;for(let T=0;Th&&(h=L.x)}for(n=n-$+10,o=t.RTL?o-h:o-c,c=0;cte.setBubbleVisible(h),1)}},g$=function(e,t){for(let o=0;oc}),bd(c,{x:n.x,y:n.y,width:e.width,height:e.height},t.RTL,new Date)}},bd=function(e,t,o,n){const c=(new Date().getTime()-n.getTime())/150;1o)){var n=t.getSvgXY(e.getSvgRoot());e.outputConnection?(n.x+=(e.RTL?3:-3)*o,n.y+=13*o):e.previousConnection&&(n.x+=(e.RTL?-23:23)*o,n.y+=3*o);var c=N(x.CIRCLE,{cx:n.x,cy:n.y,r:0,fill:"none",stroke:"#888","stroke-width":10},t.getParentSvg());e=N(x.ANIMATE,{id:"animationCircle",begin:"indefinite",attributeName:"r",dur:"150ms",from:0,to:25*o},c),t=N(x.ANIMATE,{id:"animationOpacity",begin:"indefinite",attributeName:"opacity",dur:"150ms",from:1,to:0},c),e.beginElement(),t.beginElement(),setTimeout(()=>{Ke(c)},150)}},vd=function(e){if(ji(),e.workspace.getAudioManager().play("disconnect"),!(1>e.workspace.scale)){var t=e.getHeightWidth().height;t=Math.atan(10/t)/Math.PI*180,e.RTL||(t*=-1),vr=e,yd(e,t,new Date,0)}},yd=function(e,t,o,n){const c=[.66,1,.66,0,-.66,-1,-.66,0];let h="";o.getTime()+200>new Date().getTime()&&(h=`skewX(${Math.round(c[n%c.length]*t)})`,Sl=setTimeout(yd,15,e,t,o,n+1)),e.getSvgRoot().setAttribute("transform",`${e.getTranslation()} ${h}`)},ji=function(){vr&&(Sl&&(clearTimeout(Sl),Sl=null),vr.getSvgRoot().setAttribute("transform",vr.getTranslation()),vr=null)},Xo=function(e){return e.getRelativeToSurfaceXY!==void 0&&e.isMovable!==void 0&&e.startDrag!==void 0&&e.drag!==void 0&&e.endDrag!==void 0&&e.revertDrag!==void 0},so=function(e,t){for(const o in t)e[o]=t[o]!==null&&typeof t[o]=="object"?so(e[o]||Object.create(null),t[o]):t[o];return e},Ps=function(e,t){r(F.FIELD,e,t)},y$=function(e){u(F.FIELD,e)},i.fromJson$$module$build$src$core$field_registry=function(e){return bv.fromJsonInternal(e)},_$=function(e){const t=f(F.FIELD,e.type);return t?t.fromJson(e):(console.warn("Blockly could not create a field of type "+e.type+". The field is probably not being registered. This could be because the file is not loaded, the field does not register itself (Issue #1584), or the registration is not being reached."),null)},i.register$$module$build$src$core$extensions=function(e,t){if(typeof e!="string"||e.trim()==="")throw Error('Error: Invalid extension name "'+e+'"');if(sn[e])throw Error('Error: Extension "'+e+'" is already registered.');if(typeof t!="function")throw Error('Error: Extension "'+e+'" must be a function');sn[e]=t},i.registerMixin$$module$build$src$core$extensions=function(e,t){if(!t||typeof t!="object")throw Error('Error: Mixin "'+e+'" must be a object');i.register$$module$build$src$core$extensions(e,function(){this.mixin(t)})},i.registerMutator$$module$build$src$core$extensions=function(e,t,o,n){const c='Error when registering mutator "'+e+'": ';Cd(c,t);const h=wd(t,c);if(o&&typeof o!="function")throw Error(c+'Extension "'+e+'" is not a function');i.register$$module$build$src$core$extensions(e,function(){h&&this.setMutator(new i.MutatorIcon$$module$build$src$core$icons$mutator_icon(n||[],this)),this.mixin(t),o&&o.apply(this)})},w$=function(e){_d(e)?delete sn[e]:console.warn('No extension mapping for name "'+e+'" found to unregister')},_d=function(e){return!!sn[e]},Ha=function(e,t,o){const n=sn[e];if(typeof n!="function")throw Error('Error: Extension "'+e+'" not found.');let c;if(o?C$(e,t):c=Ga(t),n.apply(t),o)Cd('Error after applying mutator "'+e+'": ',t);else if(!S$(c,t))throw Error('Error when applying extension "'+e+'": mutation properties changed when applying a non-mutator extension.')},C$=function(e,t){if(Ga(t).length)throw Error('Error: tried to apply mutation "'+e+'" to a block that already has mutator functions. Block id: '+t.id)},T$=function(e,t){return Wa(e.mutationToDom,e.domToMutation,t+" mutationToDom/domToMutation")},k$=function(e,t){return Wa(e.saveExtraState,e.loadExtraState,t+" saveExtraState/loadExtraState")},wd=function(e,t){return Wa(e.compose,e.decompose,t+" compose/decompose")},Wa=function(e,t,o){if(e&&t){if(typeof e!="function"||typeof t!="function")throw Error(o+" must be a function");return!0}if(!e&&!t)return!1;throw Error(o+"Must have both or neither functions")},Cd=function(e,t){const o=T$(t,e),n=k$(t,e);if(!o&&!n)throw Error(e+"Mutations must contain either XML hooks, or JSON hooks, or both");wd(t,e)},Ga=function(e){const t=[];return e.domToMutation!==void 0&&t.push(e.domToMutation),e.mutationToDom!==void 0&&t.push(e.mutationToDom),e.saveExtraState!==void 0&&t.push(e.saveExtraState),e.loadExtraState!==void 0&&t.push(e.loadExtraState),e.compose!==void 0&&t.push(e.compose),e.decompose!==void 0&&t.push(e.decompose),t},S$=function(e,t){if(t=Ga(t),t.length!==e.length)return!1;for(let o=0;o!n.getReturnTypes()).map(n=>[n.getName(),n.getParameters().map(c=>c.getName()),!1]);e.getBlocksByType("procedures_defnoreturn",!1).forEach(n=>{!Co(n)&&Di(n)&&t.push(n.getProcedureDef())});const o=e.getProcedureMap().getProcedures().filter(n=>!!n.getReturnTypes()).map(n=>[n.getName(),n.getParameters().map(c=>c.getName()),!0]);return e.getBlocksByType("procedures_defreturn",!1).forEach(n=>{!Co(n)&&Di(n)&&o.push(n.getProcedureDef())}),t.sort(kd),o.sort(kd),[t,o]},kd=function(e,t){return e[0].localeCompare(t[0],void 0,{sensitivity:"base"})},i.findLegalName$$module$build$src$core$procedures=function(e,t){if(t.isInFlyout)return e;for(e=e||i.Msg$$module$build$src$core$msg.UNNAMED_KEY||"unnamed";!A$(e,t.workspace,t);){const o=e.match(/^(.*?)(\d+)$/);e=o?o[1]+(parseInt(o[2])+1):e+"2"}return e},A$=function(e,t,o){return!Sd(e,t,o)},Sd=function(e,t,o){for(const n of t.getAllBlocks(!1))if(n!==o&&Di(n)&&i.Names$$module$build$src$core$names.equals(n.getProcedureDef()[0],e))return!0;o=o&&Co(o)?o==null?void 0:o.getProcedureModel():void 0;for(const n of t.getProcedureMap().getProcedures())if(n!==o&&i.Names$$module$build$src$core$names.equals(n.getName(),e))return!0;return!1},i.rename$$module$build$src$core$procedures=function(e){var t=this.getSourceBlock();if(!t)throw new ft;e=e.trim();const o=i.findLegalName$$module$build$src$core$procedures(e,t);Co(t)&&!t.isInsertionMarker()&&t.getProcedureModel().setName(o);const n=this.getValue();if(n!==e&&n!==o)for(e=t.workspace.getAllBlocks(!1),t=0;tO$(o,e)||cf(o)&&i.Names$$module$build$src$core$names.equals(o.getProcedureCall(),e))},O$=function(e,t){return Co(e)&&!e.isProcedureDef()&&e.getProcedureModel()&&i.Names$$module$build$src$core$names.equals(e.getProcedureModel().getName(),t)},i.mutateCallers$$module$build$src$core$procedures=function(e){const t=me();var o=e.getProcedureDef()[0];const n=e.mutationToDom(!0);e=xd(o,e.workspace);for(let h=0,$;$=e[h];h++){o=(o=$.mutationToDom())&&Ii(o),$.domToMutation&&$.domToMutation(n);var c=$.mutationToDom();c=c&&Ii(c),o!==c&&(i.setRecordUndo$$module$build$src$core$events$utils(!1),z(new(V(O.BLOCK_CHANGE))($,"mutation",null,o,c)),i.setRecordUndo$$module$build$src$core$events$utils(t))}},i.getDefinition$$module$build$src$core$procedures=function(e,t){for(const o of t.getAllBlocks(!1))if(Co(o)&&o.isProcedureDef()&&i.Names$$module$build$src$core$names.equals(o.getProcedureModel().getName(),e)||Di(o)&&i.Names$$module$build$src$core$names.equals(o.getProcedureDef()[0],e))return o;return null},Ja=function(e){return e.isDynamic},M$=function(e){return e.pathDown!==void 0&&e.pathUp!==void 0},N$=function(e){return e.pathLeft!==void 0&&e.pathRight!==void 0},L$=function(e,t){if(!e||!t)throw Error("Cannot connect null connections.");e.targetConnection=t,t.targetConnection=e},P$=function(e,t){let o=null;t=t.outputConnection;const n=t==null?void 0:t.getConnectionChecker();for(let c=0,h;h=e.inputList[c];c++){const $=h.connection;let T;if($&&((T=n)!=null&&T.canConnect(t,$,!1))){if(o)return null;o=$}}return o},B$=function(e,t){let o;for(;o=P$(e,t);)if(e=o.targetBlock(),!e||e.isShadow())return o;return null},Dd=function(e){return e.getType!==void 0&&e.initView!==void 0&&e.dispose!==void 0&&e.getWeight!==void 0&&e.getSize!==void 0&&e.applyColour!==void 0&&e.hideForInsertionMarker!==void 0&&e.updateEditable!==void 0&&e.updateCollapsed!==void 0&&e.isShownWhenCollapsed!==void 0&&e.setOffsetInBlock!==void 0&&e.onLocationChange!==void 0&&e.onClick!==void 0},j$=function(e){return Dd(e)&&Oi(e)&&zn(e)&&e.setText!==void 0&&e.getText!==void 0&&e.setBubbleSize!==void 0&&e.getBubbleSize!==void 0&&e.getType()===yt.COMMENT},Qn=function(e){let t=e.outputConnection;return(!t||e.previousConnection&&e.previousConnection.isConnected())&&(t=e.previousConnection),t},er=function(e,t){r(F.RENDERER,e,t)},F$=function(e){u(F.RENDERER,e)},Ad=function(e,t,o){return e=new(m(F.RENDERER,e))(e),e.init(t,o),e},Rd=function(e){Ai(e.getTargetWorkspace(),void 0,"String")},Od=function(e){Ai(e.getTargetWorkspace(),void 0,"Number")},Md=function(e){Ai(e.getTargetWorkspace(),void 0,"Colour")},qa=function(e){let t=[],o=document.createElement("button");return o.setAttribute("text",i.Msg$$module$build$src$core$msg.NEW_STRING_VARIABLE),o.setAttribute("callbackKey","CREATE_VARIABLE_STRING"),t.push(o),o=document.createElement("button"),o.setAttribute("text",i.Msg$$module$build$src$core$msg.NEW_NUMBER_VARIABLE),o.setAttribute("callbackKey","CREATE_VARIABLE_NUMBER"),t.push(o),o=document.createElement("button"),o.setAttribute("text",i.Msg$$module$build$src$core$msg.NEW_COLOUR_VARIABLE),o.setAttribute("callbackKey","CREATE_VARIABLE_COLOUR"),t.push(o),e.registerButtonCallback("CREATE_VARIABLE_STRING",Rd),e.registerButtonCallback("CREATE_VARIABLE_NUMBER",Od),e.registerButtonCallback("CREATE_VARIABLE_COLOUR",Md),e=Nd(e),t=t.concat(e)},Nd=function(e){e=e.getAllVariables();const t=[];if(0T.id!=e.id).map(T=>T.getRelativeToSurfaceXY());for(;U$(G.sum(t,h),$)||H$(e,G.sum(c,h),n);)o.RTL?h.translate(-n,2*n):h.translate(n,2*n);e.moveTo(G.sum(t,h))},U$=function(e,t){return t.some(o=>1>=Math.abs(o.x-e.x)&&1>=Math.abs(o.y-e.y))},H$=function(e,t,o){return e.getConnections_(!1).some(n=>!!n.closest(o,t).connection)},zi=function(e,t,o){const n=o.getBoundingRectangle(),c=n.right-n.left,h=Mi(t.top,n.top,t.top+t.height-(n.bottom-n.top))-n.top;let $=t.left;return t=t.left+t.width-c,e.RTL?$=Math.min(t,$):t=Math.max($,t),(e=Mi($,n.left,t)-n.left)||h?(o.moveBy(e,h,["inbounds"]),!0):!1},Ld=function(e){return t=>{var o=e.getMetricsManager();if(o.hasFixedEdges()&&!e.isDragging()){var n;if(ub.includes((n=t.type)!=null?n:"")){n=o.getScrollMetrics(!0);const c=W$(e,t);c&&(o=i.getGroup$$module$build$src$core$events$utils()||!1,i.setGroup$$module$build$src$core$events$utils(t.group),zi(e,n,c)&&!t.group&&console.warn("Moved object in bounds but there was no event group. This may break undo."),i.setGroup$$module$build$src$core$events$utils(o))}else se(t)&&t.scale&&t.oldScale&&t.scale>t.oldScale&&Xa(e)}}},W$=function(e,t){let o=null;switch(t.type){case O.BLOCK_CREATE:case O.BLOCK_MOVE:(o=e.getBlockById(t.blockId))&&(o=o.getRootBlock());break;case O.COMMENT_CREATE:case O.COMMENT_MOVE:case O.COMMENT_RESIZE:o=e.getCommentById(t.commentId)}return o},Xa=function(e){var t=e.getMetricsManager();if(t.hasFixedEdges()&&!e.isDragging()){t=t.getScrollMetrics(!0);var o=e.getTopBoundedElements();for(let n=0,c;c=o[n];n++)zi(e,t,c)}},ls=function(e){return e.isDeletable!==void 0&&e.dispose!==void 0&&e.setDeleteStyle!==void 0},G$=function(e){const t=e.toCopyData();Tp=t;let o;return kp=(o=e.workspace)!=null?o:null,t},To=function(e,t,o){return e&&t?Pd(e,t,o):Tp&&kp?Pd(Tp,kp):null},Pd=function(e,t,o){let n;t=t.isMutator?t:(n=t.getRootWorkspace())!=null?n:t;let c,h;return(h=(c=f(F.PASTER,e.paster,!1))==null?void 0:c.paste(e,t,o))!=null?h:null},V$=function(e){const t=e.toCopyData();return t?To(t,e.workspace):null},tr=function(e){return e.toCopyData!==void 0},Bd=function(){He.registry.register({name:Hs.ESCAPE,preconditionFn(e){return!e.options.readOnly},callback(e){return e.hideChaff(),!0},keyCodes:[Ae.ESC]})},jd=function(){He.registry.register({name:Hs.DELETE,preconditionFn(e){const t=I();return!e.options.readOnly&&t!=null&&ls(t)&&t.isDeletable()&&!co.inProgress()},callback(e,t){return t.preventDefault(),e=I(),e instanceof gs?e.checkAndDelete():ls(e)&&e.isDeletable()&&(i.setGroup$$module$build$src$core$events$utils(!0),e.dispose(),i.setGroup$$module$build$src$core$events$utils(!1)),!0},keyCodes:[Ae.DELETE,Ae.BACKSPACE]})},Fd=function(){const e=He.registry.createSerializedKey(Ae.C,[Ae.CTRL]),t=He.registry.createSerializedKey(Ae.C,[Ae.ALT]),o=He.registry.createSerializedKey(Ae.C,[Ae.META]);He.registry.register({name:Hs.COPY,preconditionFn(n){const c=I();return!n.options.readOnly&&!co.inProgress()&&c!=null&&ls(c)&&c.isDeletable()&&Xo(c)&&c.isMovable()&&tr(c)},callback(n,c){return c.preventDefault(),n.hideChaff(),c=I(),!c||!tr(c)?!1:(Mo=c.toCopyData(),No=c.workspace instanceof ns?c.workspace:n,cn=Xo(c)?c.getRelativeToSurfaceXY():null,!!Mo)},keyCodes:[e,t,o]})},zd=function(){const e=He.registry.createSerializedKey(Ae.X,[Ae.CTRL]),t=He.registry.createSerializedKey(Ae.X,[Ae.ALT]),o=He.registry.createSerializedKey(Ae.X,[Ae.META]);He.registry.register({name:Hs.CUT,preconditionFn(n){const c=I();return!n.options.readOnly&&!co.inProgress()&&c!=null&&ls(c)&&c.isDeletable()&&Xo(c)&&c.isMovable()&&!c.workspace.isFlyout},callback(n){const c=I();return c instanceof gs?(Mo=c.toCopyData(),No=n,cn=c.getRelativeToSurfaceXY(),c.checkAndDelete(),!0):ls(c)&&c.isDeletable()&&tr(c)?(Mo=c.toCopyData(),No=n,cn=Xo(c)?c.getRelativeToSurfaceXY():null,c.dispose(),!0):!1},keyCodes:[e,t,o]})},Ud=function(){const e=He.registry.createSerializedKey(Ae.V,[Ae.CTRL]),t=He.registry.createSerializedKey(Ae.V,[Ae.ALT]),o=He.registry.createSerializedKey(Ae.V,[Ae.META]);He.registry.register({name:Hs.PASTE,preconditionFn(n){return!n.options.readOnly&&!co.inProgress()},callback(){if(!Mo||!No)return!1;if(!cn)return!!To(Mo,No);const{left:n,top:c,width:h,height:$}=No.getMetricsManager().getViewMetrics(!0);if(new qe(c,c+$,n,n+h).contains(cn.x,cn.y))return!!To(Mo,No);const T=new G(n+h/2,c+$/2);return!!To(Mo,No,T)},keyCodes:[e,t,o]})},Hd=function(){const e=He.registry.createSerializedKey(Ae.Z,[Ae.CTRL]),t=He.registry.createSerializedKey(Ae.Z,[Ae.ALT]),o=He.registry.createSerializedKey(Ae.Z,[Ae.META]);He.registry.register({name:Hs.UNDO,preconditionFn(n){return!n.options.readOnly&&!co.inProgress()},callback(n,c){return n.hideChaff(),n.undo(!1),c.preventDefault(),!0},keyCodes:[e,t,o]})},Wd=function(){const e=He.registry.createSerializedKey(Ae.Z,[Ae.SHIFT,Ae.CTRL]),t=He.registry.createSerializedKey(Ae.Z,[Ae.SHIFT,Ae.ALT]),o=He.registry.createSerializedKey(Ae.Z,[Ae.SHIFT,Ae.META]),n=He.registry.createSerializedKey(Ae.Y,[Ae.CTRL]);He.registry.register({name:Hs.REDO,preconditionFn(c){return!co.inProgress()&&!c.options.readOnly},callback(c,h){return c.hideChaff(),c.undo(!0),h.preventDefault(),!0},keyCodes:[e,t,o,n]})},Gd=function(){Bd(),jd(),Fd(),zd(),Ud(),Hd(),Wd()},Vd=function(e){const t=e.saveState();return e.getParameters().length&&(t.parameters=e.getParameters().map(o=>o.saveState())),t},Kd=function(e,t,o,n){if(e=e.loadState(o,n),!o.parameters)return e;for(const[c,h]of o.parameters.entries())e.insertParameter(t.loadState(h,n),c);return e},K$=function(e){const t=Object.create(null),o=v(F.SERIALIZER,!0);for(const n in o){let c;const h=(c=o[n])==null?void 0:c.save(e);h&&(t[n]=h)}return t},Y$=function(e,t,{recordUndo:o=!1}={}){var n=v(F.SERIALIZER,!0);if(n){n=Object.entries(n).sort((h,$)=>$[1].priority-h[1].priority);var c=me();i.setRecordUndo$$module$build$src$core$events$utils(o),(o=i.getGroup$$module$build$src$core$events$utils())||i.setGroup$$module$build$src$core$events$utils(!0),Ho(),t instanceof ns&&t.setResizesEnabled(!1);for(const[,h]of n.reverse()){let $;($=h)==null||$.clear(t)}for(const[h,$]of n.reverse())if(e[h]){let T;(T=$)==null||T.load(e[h],t)}t instanceof ns&&t.setResizesEnabled(!0),Wo(),z(new(V(O.FINISHED_LOADING))(t)),i.setGroup$$module$build$src$core$events$utils(o),i.setRecordUndo$$module$build$src$core$events$utils(c)}},J$=function(e,t){let o=null;o=typeof e=="string"?document.getElementById(e)||document.querySelector(e):e;var n;if(!document.contains(o)&&document!==((n=o)==null?void 0:n.ownerDocument))throw Error("Error: container is not in current document");e=new ds(t||{}),n=document.createElement("div"),ge(n,"injectionDiv"),t!=null&&t.rtl&&ge(n,"blocklyRTL"),n.tabIndex=0,It(n,Ct.LABEL,i.Msg$$module$build$src$core$msg.WORKSPACE_ARIA_LABEL),o.appendChild(n),t=q$(n,e);const c=X$(n,t,e);return Z$(c),re(c),Ce(c),n.addEventListener("focusin",function(){re(c)}),X(n,"keydown",null,Za),X(Wn(),"keydown",null,Za),(t=Yo())&&X(t,"keydown",null,Za),c},q$=function(e,t){e.setAttribute("dir","LTR"),cu(t.hasCss,t.pathToMedia),e=N(x.SVG,{xmlns:rr,"xmlns:html":Fs,"xmlns:xlink":es,version:"1.1",class:"blocklySvg",tabindex:"0"},e);const o=N(x.DEFS,{},e),n=String(Math.random()).substring(2);return t.gridPattern=ep.createDom(n,t.gridOptions,o),e},X$=function(e,t,o){o.parentWorkspace=null,o=new ns(o);const n=o.options;o.scale=n.zoomOptions.startScale,t.appendChild(o.createDom("blocklyMainBackground",e));var c=o.getRenderer().getClassName();return c&&ge(e,c),(c=o.getTheme().getClassName())&&ge(e,c),!n.hasCategories&&n.languageTree&&(e=o.addFlyout(x.SVG),Uo(e,t)),n.hasTrashcan&&o.addTrashcan(),n.zoomOptions&&n.zoomOptions.controls&&o.addZoomControls(),o.getThemeManager().subscribe(t,"workspaceBackgroundColour","background-color"),o.translate(0,0),o.addChangeListener(Ld(o)),Ce(o),id(),Au(),Ju(),o},Z$=function(e){const t=e.options;var o=e.getParentSvg();if(X(o.parentNode,"contextmenu",null,function(n){kt(n)||n.preventDefault()}),o=X(window,"resize",null,function(){to(),e.hideComponents(!0),Wu(),ld(),Ce(e),Xa(e)}),e.setResizeHandlerWrapper(o),Q$(),t.languageTree){o=e.getToolbox();const n=e.getFlyout(!0);o?o.init():n&&(n.init(e),n.show(t.languageTree),typeof n.scrollToStart=="function"&&n.scrollToStart())}t.hasTrashcan&&e.trashcan.init(),t.zoomOptions&&t.zoomOptions.controls&&e.zoomControls_.init(),t.moveOptions&&t.moveOptions.scrollbars?(e.scrollbar=new Ep(e,t.moveOptions.scrollbars===!0||!!t.moveOptions.scrollbars.horizontal,t.moveOptions.scrollbars===!0||!!t.moveOptions.scrollbars.vertical,"blocklyMainWorkspaceScrollbar"),e.scrollbar.resize()):e.setMetrics({x:.5,y:.5}),t.hasSounds&&eb(t.pathToMedia,e)},Za=function(e){const t=U();t&&!(kt(e)||t.rendered&&!t.isVisible())&&He.registry.onKeyDown(t,e)},Q$=function(){oy||(X(document,"scroll",null,function(){const e=ee();for(let t=0,o;o=e[t];t++)o instanceof ns&&o.updateInverseScreenCTM()}),ct(document,"touchend",null,_e),ct(document,"touchcancel",null,_e)),oy=!0},eb=function(e,t){function o(){for(;c.length;){const h=c.pop();h&&ze(h)}n.preload()}const n=t.getAudioManager();n.load([e+"click.mp3",e+"click.wav",e+"click.ogg"],"click"),n.load([e+"disconnect.wav",e+"disconnect.mp3",e+"disconnect.ogg"],"disconnect"),n.load([e+"delete.mp3",e+"delete.ogg",e+"delete.wav"],"delete");const c=[];c.push(X(document,"pointermove",null,o,!0)),c.push(X(document,"touchstart",null,o,!0))},Yd=function(){xe.registry.register({displayText(){return i.Msg$$module$build$src$core$msg.UNDO},preconditionFn(e){return 0t.length?sr(t):Ca(i.Msg$$module$build$src$core$msg.DELETE_ALL_BLOCKS.replace("%1",String(t.length)),function(o){o&&sr(t)})}},scopeType:xe.ScopeType.WORKSPACE,id:"workspaceDelete",weight:6})},tb=function(){Yd(),Jd(),qd(),Zd(),Qd(),th()},sh=function(){xe.registry.register({displayText(){return i.Msg$$module$build$src$core$msg.DUPLICATE_BLOCK},preconditionFn(e){return e=e.block,!e.isInFlyout&&e.isDeletable()&&e.isMovable()?e.isDuplicatable()?"enabled":"disabled":"hidden"},callback(e){if(e.block){var t=e.block.toCopyData();t&&To(t,e.block.workspace)}},scopeType:xe.ScopeType.BLOCK,id:"blockDuplicate",weight:1})},oh=function(){xe.registry.register({displayText(e){return e.block.hasIcon(po.TYPE)?i.Msg$$module$build$src$core$msg.REMOVE_COMMENT:i.Msg$$module$build$src$core$msg.ADD_COMMENT},preconditionFn(e){return e=e.block,!e.isInFlyout&&e.workspace.options.comments&&!e.isCollapsed()&&e.isEditable()?"enabled":"hidden"},callback(e){e=e.block,e.hasIcon(po.TYPE)?e.setCommentText(null):e.setCommentText("")},scopeType:xe.ScopeType.BLOCK,id:"blockComment",weight:2})},ih=function(){xe.registry.register({displayText(e){return e.block.getInputsInline()?i.Msg$$module$build$src$core$msg.EXTERNAL_INPUTS:i.Msg$$module$build$src$core$msg.INLINE_INPUTS},preconditionFn(e){if(e=e.block,!e.isInFlyout&&e.isMovable()&&!e.isCollapsed()){for(let t=1;t(t.has(Ft)?1:0),e.getInheritedDisabled()||t?"disabled":"enabled"}return"hidden"},callback(e){e=e.block;const t=i.getGroup$$module$build$src$core$events$utils();t||i.setGroup$$module$build$src$core$events$utils(!0),e.setDisabledReason(!e.hasDisabledReason(Ft),Ft),i.setGroup$$module$build$src$core$events$utils(t)},scopeType:xe.ScopeType.BLOCK,id:"blockDisable",weight:5})},ah=function(){xe.registry.register({displayText(e){var t=e.block;return e=t.getDescendants(!1).length,(t=t.getNextBlock())&&(e-=t.getDescendants(!1).length),e===1?i.Msg$$module$build$src$core$msg.DELETE_BLOCK:i.Msg$$module$build$src$core$msg.DELETE_X_BLOCKS.replace("%1",`${e}`)},preconditionFn(e){return!e.block.isInFlyout&&e.block.isDeletable()?"enabled":"hidden"},callback(e){e.block&&e.block.checkAndDelete()},scopeType:xe.ScopeType.BLOCK,id:"blockDelete",weight:6})},lh=function(){xe.registry.register({displayText(){return i.Msg$$module$build$src$core$msg.HELP},preconditionFn(e){return e=e.block,(typeof e.helpUrl=="function"?e.helpUrl():e.helpUrl)?"enabled":"hidden"},callback(e){e.block.showHelp()},scopeType:xe.ScopeType.BLOCK,id:"blockHelp",weight:7})},ch=function(){xe.registry.register({displayText:()=>i.Msg$$module$build$src$core$msg.REMOVE_COMMENT,preconditionFn(e){let t;return(t=e.comment)!=null&&t.isDeletable()?"enabled":"hidden"},callback(e){i.setGroup$$module$build$src$core$events$utils(!0);let t;(t=e.comment)==null||t.dispose(),i.setGroup$$module$build$src$core$events$utils(!1)},scopeType:xe.ScopeType.COMMENT,id:"commentDelete",weight:6})},uh=function(){xe.registry.register({displayText:()=>i.Msg$$module$build$src$core$msg.DUPLICATE_COMMENT,preconditionFn(e){let t;return(t=e.comment)!=null&&t.isMovable()?"enabled":"hidden"},callback(e){if(e.comment){var t=e.comment.toCopyData();t&&To(t,e.comment.workspace)}},scopeType:xe.ScopeType.COMMENT,id:"commentDuplicate",weight:1})},dh=function(){xe.registry.register({displayText:()=>i.Msg$$module$build$src$core$msg.ADD_COMMENT,preconditionFn:e=>{let t;return(t=e.workspace)!=null&&t.isMutator?"hidden":"enabled"},callback:(e,t)=>{if(e=e.workspace){i.setGroup$$module$build$src$core$events$utils(!0);var o=new kl(e);o.setText(i.Msg$$module$build$src$core$msg.WORKSPACE_COMMENT_DEFAULT_TEXT),o.moveTo(sb(new G(t.clientX,t.clientY),e)),i.setSelected$$module$build$src$core$common(o),i.setGroup$$module$build$src$core$events$utils(!1)}},scopeType:xe.ScopeType.WORKSPACE,id:"commentCreate",weight:8})},sb=function(e,t){var o=t.getInjectionDiv().getBoundingClientRect();return e=new G(e.x-o.left,e.y-o.top),o=t.getOriginOffsetInPixels(),e=G.difference(e,o),e.scale(1/t.scale),e},ob=function(){sh(),oh(),ih(),nh(),rh(),ah(),lh()},ib=function(){uh(),ch(),dh()},hh=function(){tb(),ob()},nb=function(e){return e.paste!==void 0},rb=function(e){return e.getSvgRoot!==void 0},ab=function(e){return typeof e.id=="string"&&e.workspace!==void 0&&e.select!==void 0&&e.unselect!==void 0},lb=function(e){return e.isSelectable()},cb=function(e){U().hideChaff(e)},j=j||{},j.scope={},j.ASSUME_ES5=!1,j.ASSUME_NO_NATIVE_MAP=!1,j.ASSUME_NO_NATIVE_SET=!1,j.SIMPLE_FROUND_POLYFILL=!1,j.ISOLATE_POLYFILLS=!1,j.FORCE_POLYFILL_PROMISE=!1,j.FORCE_POLYFILL_PROMISE_WHEN_NO_UNHANDLED_REJECTION=!1,j.defineProperty=j.ASSUME_ES5||typeof Object.defineProperties=="function"?Object.defineProperty:function(e,t,o){return e==Array.prototype||e==Object.prototype||(e[t]=o.value),e},j.getGlobal=function(e){e=[typeof globalThis=="object"&&globalThis,e,typeof window=="object"&&window,typeof self=="object"&&self,typeof wn=="object"&&wn];for(var t=0;t>>0,j.propertyToPolyfillSymbol[c]=j.IS_SYMBOL_NATIVE?j.global.Symbol(c):j.POLYFILL_PREFIX+o+"$"+c),j.defineProperty(n,j.propertyToPolyfillSymbol[c],{configurable:!0,writable:!0,value:t})))},j.underscoreProtoCanBeSet=function(){var e={a:!0},t={};try{return t.__proto__=e,t.a}catch{}return!1},j.setPrototypeOf=j.TRUST_ES6_POLYFILLS&&typeof Object.setPrototypeOf=="function"?Object.setPrototypeOf:j.underscoreProtoCanBeSet()?function(e,t){if(e.__proto__=t,e.__proto__!==t)throw new TypeError(e+" is not extensible");return e}:null,j.arrayIteratorImpl=function(e){var t=0;return function(){return to&&(o=Math.max(o+c,0));o{const e=pb.length,t=[];for(let o=0;20>o;o++)t[o]=pb.charAt(Math.random()*e);return t.join("")}},OT=0,ph={TEST_ONLY:gb};ph.genUid=C,ph.getNextUniqueId=k;var mb="",or=!0,gh=0,mh="ORPHANED_BLOCK",io=[],fb={FIRE_QUEUE:io,enqueueEvent:Ze,fireNow:Ne,fireInternal:Oe,setGroupInternal:ye};i.disable$$module$build$src$core$events$utils,i.enable$$module$build$src$core$events$utils,i.getGroup$$module$build$src$core$events$utils,i.setGroup$$module$build$src$core$events$utils,i.setRecordUndo$$module$build$src$core$events$utils;var ir=Object.create(null),$b,Zo=null,bb,nr=[],vb={defineBlocksWithJsonArrayInternal:Ve},Dt={TEST_ONLY:vb};Dt.createBlockDefinitionsFromJsonArray=i.createBlockDefinitionsFromJsonArray$$module$build$src$core$common,Dt.defineBlocks=i.defineBlocks$$module$build$src$core$common,Dt.defineBlocksWithJsonArray=pe,Dt.draggingConnections=nr,Dt.getAllWorkspaces=ee,Dt.getBlockTypeCounts=be,Dt.getMainWorkspace=U,Dt.getParentContainer=de,Dt.getSelected=I,Dt.getWorkspaceById=q,Dt.registerWorkspace=B,Dt.setMainWorkspace=re,Dt.setParentContainer=W,Dt.setSelected=i.setSelected$$module$build$src$core$common,Dt.svgResize=Ce,Dt.unregisterWorkpace=H;var Ui=class{constructor(){this.workspaceId=void 0,this.isUiEvent=!1,this.type="",this.group=i.getGroup$$module$build$src$core$events$utils(),this.recordUndo=me()}toJson(){return{type:this.type,group:this.group}}static fromJson(e,t,o){return o.isBlank=!1,o.group=e.group||"",o.workspaceId=t.id,o}isNull(){return!1}run(e){}getEventWorkspace_(){let e;if(this.workspaceId&&(e=q(this.workspaceId)),!e)throw Error("Workspace is null. Event must have been generated from real Blockly events.");return e}},Cs=class extends Ui{constructor(e){super(),this.recordUndo=!1,this.isUiEvent=!0,this.isBlank=typeof e>"u",this.workspaceId=e||""}},fh=class extends Cs{constructor(e,t,o){t=e?e.workspace.id:t,t===null&&(t=void 0),super(t),this.type=O.CLICK,this.blockId=e?e.id:void 0,this.targetType=o}toJson(){const e=super.toJson();if(!this.targetType)throw Error("The click target type is undefined. Either pass a block to the constructor, or call fromJson");return e.targetType=this.targetType,e.blockId=this.blockId,e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new fh),t.targetType=e.targetType,t.blockId=e.blockId,t}},$h;(function(e){e.BLOCK="block",e.WORKSPACE="workspace",e.ZOOM_CONTROLS="zoom_controls"})($h||($h={})),r(F.EVENT,O.CLICK,fh);var MT=750,yb="ontouchstart"in globalThis||!!(globalThis.document&&document.documentElement&&"ontouchstart"in document.documentElement)||!(!globalThis.navigator||!globalThis.navigator.maxTouchPoints&&!globalThis.navigator.msMaxTouchPoints),tl=null,Qo={mousedown:["pointerdown"],mouseenter:["pointerenter"],mouseleave:["pointerleave"],mousemove:["pointermove"],mouseout:["pointerout"],mouseover:["pointerover"],mouseup:["pointerup","pointercancel"],touchend:["pointerup"],touchcancel:["pointercancel"]},sl=0,ei={TOUCH_ENABLED:yb,TOUCH_MAP:Qo};ei.checkTouchIdentifier=bt,ei.clearTouchIdentifier=ke,ei.getTouchIdentifierFromEvent=Pe,ei.longStart=Je,ei.longStop=_e,ei.shouldHandleEvent=$e;var bh,_b,wb,Cb,ol,il,vh,Tb,kb,Sb;(function(e){function t(n){return o.includes(n.toUpperCase())}bh=e;const o=bh.toUpperCase();_b=t("JavaFX"),wb=t("WebKit"),Cb=t("Gecko")&&!wb,ol=t("Android"),e=globalThis.navigator&&globalThis.navigator.maxTouchPoints,il=t("iPad")||t("Macintosh")&&0{n.push(this.componentData.get(c))}),n.sort(function(c,h){return c.weight-h.weight}),n.forEach(function(c){o.push(c.component)})}else e.forEach(n=>{o.push(this.componentData.get(n).component)});return o}};lt.Capability=ro,(function(e){e=e.ComponentWeight||(e.ComponentWeight={}),e[e.TOOLBOX_WEIGHT=0]="TOOLBOX_WEIGHT",e[e.FLYOUT_WEIGHT=1]="FLYOUT_WEIGHT",e[e.TRASHCAN_WEIGHT=2]="TRASHCAN_WEIGHT",e[e.ZOOM_CONTROLS_WEIGHT=3]="ZOOM_CONTROLS_WEIGHT"})(lt||(lt={})),lt.ComponentWeight;var wh=!1,Ch=` -.blocklySvg { - background-color: #fff; - outline: none; - overflow: hidden; /* IE overflows by default. */ - position: absolute; - display: block; -} - -.blocklyWidgetDiv { - display: none; - position: absolute; - z-index: 99999; /* big value for bootstrap3 compatibility */ -} - -.injectionDiv { - height: 100%; - position: relative; - overflow: hidden; /* So blocks in drag surface disappear at edges */ - touch-action: none; - user-select: none; - -webkit-user-select: none; -} - -.blocklyNonSelectable { - user-select: none; - -ms-user-select: none; - -webkit-user-select: none; -} - -.blocklyBlockCanvas.blocklyCanvasTransitioning, -.blocklyBubbleCanvas.blocklyCanvasTransitioning { - transition: transform .5s; -} - -.blocklyTooltipDiv { - background-color: #ffffc7; - border: 1px solid #ddc; - box-shadow: 4px 4px 20px 1px rgba(0,0,0,.15); - color: #000; - display: none; - font: 9pt sans-serif; - opacity: .9; - padding: 2px; - position: absolute; - z-index: 100000; /* big value for bootstrap3 compatibility */ -} - -.blocklyDropDownDiv { - position: absolute; - left: 0; - top: 0; - z-index: 1000; - display: none; - border: 1px solid; - border-color: #dadce0; - background-color: #fff; - border-radius: 2px; - padding: 4px; - box-shadow: 0 0 3px 1px rgba(0,0,0,.3); -} - -.blocklyDropDownDiv.blocklyFocused { - box-shadow: 0 0 6px 1px rgba(0,0,0,.3); -} - -.blocklyDropDownContent { - max-height: 300px; /* @todo: spec for maximum height. */ - overflow: auto; - overflow-x: hidden; - position: relative; -} - -.blocklyDropDownArrow { - position: absolute; - left: 0; - top: 0; - width: 16px; - height: 16px; - z-index: -1; - background-color: inherit; - border-color: inherit; -} - -.blocklyDropDownButton { - display: inline-block; - float: left; - padding: 0; - margin: 4px; - border-radius: 4px; - outline: none; - border: 1px solid; - transition: box-shadow .1s; - cursor: pointer; -} - -.blocklyArrowTop { - border-top: 1px solid; - border-left: 1px solid; - border-top-left-radius: 4px; - border-color: inherit; -} - -.blocklyArrowBottom { - border-bottom: 1px solid; - border-right: 1px solid; - border-bottom-right-radius: 4px; - border-color: inherit; -} - -.blocklyResizeSE { - cursor: se-resize; - fill: #aaa; -} - -.blocklyResizeSW { - cursor: sw-resize; - fill: #aaa; -} - -.blocklyResizeLine { - stroke: #515A5A; - stroke-width: 1; -} - -.blocklyHighlightedConnectionPath { - fill: none; - stroke: #fc3; - stroke-width: 4px; -} - -.blocklyPathLight { - fill: none; - stroke-linecap: round; - stroke-width: 1; -} - -.blocklySelected>.blocklyPathLight { - display: none; -} - -.blocklyDraggable { - cursor: grab; - cursor: -webkit-grab; -} - -.blocklyDragging { - cursor: grabbing; - cursor: -webkit-grabbing; - /* Drag surface disables events to not block the toolbox, so we have to - * reenable them here for the cursor values to work. */ - pointer-events: auto; -} - - /* Changes cursor on mouse down. Not effective in Firefox because of - https://bugzilla.mozilla.org/show_bug.cgi?id=771241 */ -.blocklyDraggable:active { - cursor: grabbing; - cursor: -webkit-grabbing; -} - -.blocklyDragging.blocklyDraggingDelete { - cursor: url("<<>>/handdelete.cur"), auto; -} - -.blocklyDragging>.blocklyPath, -.blocklyDragging>.blocklyPathLight { - fill-opacity: .8; - stroke-opacity: .8; -} - -.blocklyDragging>.blocklyPathDark { - display: none; -} - -.blocklyDisabled>.blocklyPath { - fill-opacity: .5; - stroke-opacity: .5; -} - -.blocklyDisabled>.blocklyPathLight, -.blocklyDisabled>.blocklyPathDark { - display: none; -} - -.blocklyInsertionMarker>.blocklyPath, -.blocklyInsertionMarker>.blocklyPathLight, -.blocklyInsertionMarker>.blocklyPathDark { - fill-opacity: .2; - stroke: none; -} - -.blocklyNonEditableText>text { - pointer-events: none; -} - -.blocklyFlyout { - position: absolute; - z-index: 20; -} - -.blocklyText text { - cursor: default; -} - -.blocklyHidden { - display: none; -} - -.blocklyFieldDropdown:not(.blocklyHidden) { - display: block; -} - -.blocklyIconGroup { - cursor: default; -} - -.blocklyIconGroup:not(:hover), -.blocklyIconGroupReadonly { - opacity: .6; -} - -.blocklyIconShape { - fill: #00f; - stroke: #fff; - stroke-width: 1px; -} - -.blocklyIconSymbol { - fill: #fff; -} - -.blocklyMinimalBody { - margin: 0; - padding: 0; - height: 100%; -} - -.blocklyHtmlInput { - border: none; - border-radius: 4px; - height: 100%; - margin: 0; - outline: none; - padding: 0; - width: 100%; - text-align: center; - display: block; - box-sizing: border-box; -} - -/* Remove the increase and decrease arrows on the field number editor */ -input.blocklyHtmlInput[type=number]::-webkit-inner-spin-button, -input.blocklyHtmlInput[type=number]::-webkit-outer-spin-button { - -webkit-appearance: none; - margin: 0; -} - -input[type=number] { - -moz-appearance: textfield; -} - -.blocklyMainBackground { - stroke-width: 1; - stroke: #c6c6c6; /* Equates to #ddd due to border being off-pixel. */ -} - -.blocklyMutatorBackground { - fill: #fff; - stroke: #ddd; - stroke-width: 1; -} - -.blocklyFlyoutBackground { - fill: #ddd; - fill-opacity: .8; -} - -.blocklyMainWorkspaceScrollbar { - z-index: 20; -} - -.blocklyFlyoutScrollbar { - z-index: 30; -} - -.blocklyScrollbarHorizontal, -.blocklyScrollbarVertical { - position: absolute; - outline: none; -} - -.blocklyScrollbarBackground { - opacity: 0; - pointer-events: none; -} - -.blocklyScrollbarHandle { - fill: #ccc; -} - -.blocklyScrollbarBackground:hover+.blocklyScrollbarHandle, -.blocklyScrollbarHandle:hover { - fill: #bbb; -} - -/* Darken flyout scrollbars due to being on a grey background. */ -/* By contrast, workspace scrollbars are on a white background. */ -.blocklyFlyout .blocklyScrollbarHandle { - fill: #bbb; -} - -.blocklyFlyout .blocklyScrollbarBackground:hover+.blocklyScrollbarHandle, -.blocklyFlyout .blocklyScrollbarHandle:hover { - fill: #aaa; -} - -.blocklyInvalidInput { - background: #faa; -} - -.blocklyVerticalMarker { - stroke-width: 3px; - fill: rgba(255,255,255,.5); - pointer-events: none; -} - -.blocklyComputeCanvas { - position: absolute; - width: 0; - height: 0; -} - -.blocklyNoPointerEvents { - pointer-events: none; -} - -.blocklyContextMenu { - border-radius: 4px; - max-height: 100%; -} - -.blocklyDropdownMenu { - border-radius: 2px; - padding: 0 !important; -} - -.blocklyDropdownMenu .blocklyMenuItem { - /* 28px on the left for icon or checkbox. */ - padding-left: 28px; -} - -/* BiDi override for the resting state. */ -.blocklyDropdownMenu .blocklyMenuItemRtl { - /* Flip left/right padding for BiDi. */ - padding-left: 5px; - padding-right: 28px; -} - -.blocklyWidgetDiv .blocklyMenu { - background: #fff; - border: 1px solid transparent; - box-shadow: 0 0 3px 1px rgba(0,0,0,.3); - font: normal 13px Arial, sans-serif; - margin: 0; - outline: none; - padding: 4px 0; - position: absolute; - overflow-y: auto; - overflow-x: hidden; - max-height: 100%; - z-index: 20000; /* Arbitrary, but some apps depend on it... */ -} - -.blocklyWidgetDiv .blocklyMenu.blocklyFocused { - box-shadow: 0 0 6px 1px rgba(0,0,0,.3); -} - -.blocklyDropDownDiv .blocklyMenu { - background: inherit; /* Compatibility with gapi, reset from goog-menu */ - border: inherit; /* Compatibility with gapi, reset from goog-menu */ - font: normal 13px "Helvetica Neue", Helvetica, sans-serif; - outline: none; - position: relative; /* Compatibility with gapi, reset from goog-menu */ - z-index: 20000; /* Arbitrary, but some apps depend on it... */ -} - -/* State: resting. */ -.blocklyMenuItem { - border: none; - color: #000; - cursor: pointer; - list-style: none; - margin: 0; - /* 7em on the right for shortcut. */ - min-width: 7em; - padding: 6px 15px; - white-space: nowrap; -} - -/* State: disabled. */ -.blocklyMenuItemDisabled { - color: #ccc; - cursor: inherit; -} - -/* State: hover. */ -.blocklyMenuItemHighlight { - background-color: rgba(0,0,0,.1); -} - -/* State: selected/checked. */ -.blocklyMenuItemCheckbox { - height: 16px; - position: absolute; - width: 16px; -} - -.blocklyMenuItemSelected .blocklyMenuItemCheckbox { - background: url(<<>>/sprites.png) no-repeat -48px -16px; - float: left; - margin-left: -24px; - position: static; /* Scroll with the menu. */ -} - -.blocklyMenuItemRtl .blocklyMenuItemCheckbox { - float: right; - margin-right: -24px; -} - -.blocklyBlockDragSurface, .blocklyAnimationLayer { - position: absolute; - top: 0; - left: 0; - right: 0; - bottom: 0; - overflow: visible !important; - z-index: 80; - pointer-events: none; -} -`,Th={};Th.inject=cu,Th.register=Et;var G=class{constructor(e,t){this.x=e,this.y=t}clone(){return new G(this.x,this.y)}scale(e){return this.x*=e,this.y*=e,this}translate(e,t){return this.x+=e,this.y+=t,this}static equals(e,t){return e===t?!0:e&&t?e.x===t.x&&e.y===t.y:!1}static distance(e,t){const o=e.x-t.x;return e=e.y-t.y,Math.sqrt(o*o+e*e)}static magnitude(e){return Math.sqrt(e.x*e.x+e.y*e.y)}static difference(e,t){return new G(e.x-t.x,e.y-t.y)}static sum(e,t){return new G(e.x+t.x,e.y+t.y)}},rr="http://www.w3.org/2000/svg",Fs="http://www.w3.org/1999/xhtml",es="http://www.w3.org/1999/xlink",ao;(function(e){e[e.ELEMENT_NODE=1]="ELEMENT_NODE",e[e.TEXT_NODE=3]="TEXT_NODE",e[e.COMMENT_NODE=8]="COMMENT_NODE"})(ao||(ao={}));var Ts=null,kh=0,rl=null,xt={HTML_NS:Fs};xt.NodeType=ao,xt.SVG_NS=rr,xt.XLINK_NS=es,xt.addClass=ge,xt.createSvgElement=N,xt.getFastTextWidth=Nn,xt.getFastTextWidthWithSizeString=ua,xt.getTextWidth=uu,xt.hasClass=Hm,xt.insertAfter=Uo,xt.measureFontMetrics=da,xt.removeClass=ot,xt.removeClasses=la,xt.removeNode=Ke,xt.setCssTransform=ca,xt.startTextWidthCache=Ho,xt.stopTextWidthCache=Wo;var x=class{constructor(e){this.tagName=e}toString(){return this.tagName}};x.ANIMATE=new x("animate"),x.CIRCLE=new x("circle"),x.CLIPPATH=new x("clipPath"),x.DEFS=new x("defs"),x.FECOMPOSITE=new x("feComposite"),x.FECOMPONENTTRANSFER=new x("feComponentTransfer"),x.FEFLOOD=new x("feFlood"),x.FEFUNCA=new x("feFuncA"),x.FEGAUSSIANBLUR=new x("feGaussianBlur"),x.FEPOINTLIGHT=new x("fePointLight"),x.FESPECULARLIGHTING=new x("feSpecularLighting"),x.FILTER=new x("filter"),x.FOREIGNOBJECT=new x("foreignObject"),x.G=new x("g"),x.IMAGE=new x("image"),x.LINE=new x("line"),x.PATH=new x("path"),x.PATTERN=new x("pattern"),x.POLYGON=new x("polygon"),x.RECT=new x("rect"),x.SVG=new x("svg"),x.TEXT=new x("text"),x.TSPAN=new x("tspan");var qe=class{constructor(e,t,o,n){this.top=e,this.bottom=t,this.left=o,this.right=n}clone(){return new qe(this.top,this.bottom,this.left,this.right)}getHeight(){return this.bottom-this.top}getWidth(){return this.right-this.left}contains(e,t){return e>=this.left&&e<=this.right&&t>=this.top&&t<=this.bottom}intersects(e){return this.left<=e.right&&this.right>=e.left&&this.bottom>=e.top&&this.top<=e.bottom}static equals(e,t){return e===t?!0:e&&t?e.top===t.top&&e.bottom===t.bottom&&e.left===t.left&&e.right===t.right:!1}static createFromPoint(e,t,o){const n=e.x;return e=e.y,new qe(e,e+o,n,n+t)}},Le=class{constructor(e,t){this.width=e,this.height=t}static equals(e,t){return e===t?!0:e&&t?e.width===t.width&&e.height===t.height:!1}static max(e,t){return new Le(Math.max(e.width,t.width),Math.max(e.height,t.height))}static min(e,t){return new Le(Math.min(e.width,t.width),Math.min(e.height,t.height))}},Mb={getSizeInternal:Wm},So={TEST_ONLY:Mb};So.getBorderBox=pu,So.getComputedStyle=Ms,So.getContainerOffsetToScrollInto=gu,So.getPageOffset=yo,So.getSize=Ln,So.getViewportPageOffset=hu,So.scrollIntoContainerView=ha;var Nb=/translate\(\s*([-+\d.e]+)([ ,]\s*([-+\d.e]+)\s*)?/,Lb=/transform:\s*translate(?:3d)?\(\s*([-+\d.e]+)\s*px([ ,]\s*([-+\d.e]+)\s*px)?/,PT={XY_REGEX:Nb,XY_STYLE_REGEX:Lb},ti={TEST_ONLY:PT};ti.getDocumentScroll=fu,ti.getInjectionDivXY=pa,ti.getRelativeXY=Pn,ti.getViewportBBox=mu,ti.screenToWsCoordinates=Gm,ti.wsToScreenCoordinates=Vm;var mt=class{constructor(e,t,o,n,c){this.workspace=e,this.horizontal=t,this.oldHostMetrics=null,this.ratio=1,this.origin=new G(0,0),this.startDragHandle=this.handlePosition=this.handleLength=this.scrollbarLength=this.startDragMouse=0,this.containerVisible=this.isHandleVisible=!0,this.position=new G(0,0),this.onMouseMoveWrapper_=this.onMouseUpWrapper_=null,this.pair=o||!1,this.margin=c!==void 0?c:mt.DEFAULT_SCROLLBAR_MARGIN,e="blocklyScrollbar"+(this.horizontal?"Horizontal":"Vertical"),n&&(e+=" "+n),this.outerSvg=N(x.SVG,{class:e}),n=N(x.G,{},this.outerSvg),this.svgBackground=N(x.RECT,{class:"blocklyScrollbarBackground"},n),e=Math.floor((mt.scrollbarThickness-5)/2),this.svgHandle=N(x.RECT,{class:"blocklyScrollbarHandle",rx:e,ry:e},n),this.workspace.getThemeManager().subscribe(this.svgHandle,"scrollbarColour","fill"),this.workspace.getThemeManager().subscribe(this.svgHandle,"scrollbarOpacity","fill-opacity"),Uo(this.outerSvg,this.workspace.getParentSvg()),this.setInitialThickness(),t?(this.lengthAttribute_="width",this.positionAttribute_="x"):(this.lengthAttribute_="height",this.positionAttribute_="y"),this.onMouseDownBarWrapper_=X(this.svgBackground,"pointerdown",this,this.onMouseDownBar),this.onMouseDownHandleWrapper_=X(this.svgHandle,"pointerdown",this,this.onMouseDownHandle)}setInitialThickness(){const e=mt.scrollbarThickness;this.horizontal?(this.svgBackground.setAttribute("height",String(e)),this.outerSvg.setAttribute("height",String(e)),this.svgHandle.setAttribute("height",String(e-5)),this.svgHandle.setAttribute("y","2.5")):(this.svgBackground.setAttribute("width",String(e)),this.outerSvg.setAttribute("width",String(e)),this.svgHandle.setAttribute("width",String(e-5)),this.svgHandle.setAttribute("x","2.5"))}dispose(){this.cleanUp(),ze(this.onMouseDownBarWrapper_),ze(this.onMouseDownHandleWrapper_),Ke(this.outerSvg),this.workspace.getThemeManager().unsubscribe(this.svgHandle)}constrainHandleLength(e){return e=0>=e||isNaN(e)?0:Math.min(e,this.scrollbarLength)}setHandleLength(e){this.handleLength=e,this.svgHandle.setAttribute(this.lengthAttribute_,String(this.handleLength))}constrainHandlePosition(e){return e=0>=e||isNaN(e)?0:Math.min(e,this.scrollbarLength-this.handleLength)}setHandlePosition(e){this.handlePosition=e,this.svgHandle.setAttribute(this.positionAttribute_,String(this.handlePosition))}setScrollbarLength(e){this.scrollbarLength=e,this.outerSvg.setAttribute(this.lengthAttribute_,String(this.scrollbarLength)),this.svgBackground.setAttribute(this.lengthAttribute_,String(this.scrollbarLength))}setPosition(e,t){this.position.x=e,this.position.y=t,ca(this.outerSvg,"translate("+(this.position.x+this.origin.x)+"px,"+(this.position.y+this.origin.y)+"px)")}resize(e){!e&&(e=this.workspace.getMetrics(),!e)||this.oldHostMetrics&&mt.metricsAreEquivalent(e,this.oldHostMetrics)||(this.horizontal?this.resizeHorizontal(e):this.resizeVertical(e),this.oldHostMetrics=e,this.updateMetrics())}requiresViewResize(e){return this.oldHostMetrics?this.oldHostMetrics.viewWidth!==e.viewWidth||this.oldHostMetrics.viewHeight!==e.viewHeight||this.oldHostMetrics.absoluteLeft!==e.absoluteLeft||this.oldHostMetrics.absoluteTop!==e.absoluteTop:!0}resizeHorizontal(e){this.requiresViewResize(e)?this.resizeViewHorizontal(e):this.resizeContentHorizontal(e)}resizeViewHorizontal(e){var t=e.viewWidth-2*this.margin;this.pair&&(t-=mt.scrollbarThickness),this.setScrollbarLength(Math.max(0,t)),t=e.absoluteLeft+this.margin,this.pair&&this.workspace.RTL&&(t+=mt.scrollbarThickness),this.setPosition(t,e.absoluteTop+e.viewHeight-mt.scrollbarThickness-this.margin),this.resizeContentHorizontal(e)}resizeContentHorizontal(e){if(e.viewWidth>=e.scrollWidth)this.setHandleLength(this.scrollbarLength),this.setHandlePosition(0),this.pair||this.setVisible(!1);else{this.pair||this.setVisible(!0);var t=this.scrollbarLength*e.viewWidth/e.scrollWidth;t=this.constrainHandleLength(t),this.setHandleLength(t),t=e.scrollWidth-e.viewWidth;var o=this.scrollbarLength-this.handleLength;e=(e.viewLeft-e.scrollLeft)/t*o,e=this.constrainHandlePosition(e),this.setHandlePosition(e),this.ratio=o/t}}resizeVertical(e){this.requiresViewResize(e)?this.resizeViewVertical(e):this.resizeContentVertical(e)}resizeViewVertical(e){let t=e.viewHeight-2*this.margin;this.pair&&(t-=mt.scrollbarThickness),this.setScrollbarLength(Math.max(0,t)),this.setPosition(this.workspace.RTL?e.absoluteLeft+this.margin:e.absoluteLeft+e.viewWidth-mt.scrollbarThickness-this.margin,e.absoluteTop+this.margin),this.resizeContentVertical(e)}resizeContentVertical(e){if(e.viewHeight>=e.scrollHeight)this.setHandleLength(this.scrollbarLength),this.setHandlePosition(0),this.pair||this.setVisible(!1);else{this.pair||this.setVisible(!0);var t=this.scrollbarLength*e.viewHeight/e.scrollHeight;t=this.constrainHandleLength(t),this.setHandleLength(t),t=e.scrollHeight-e.viewHeight;var o=this.scrollbarLength-this.handleLength;e=(e.viewTop-e.scrollTop)/t*o,e=this.constrainHandlePosition(e),this.setHandlePosition(e),this.ratio=o/t}}isVisible(){return this.isHandleVisible}setContainerVisible(e){const t=e!==this.containerVisible;this.containerVisible=e,t&&this.updateDisplay_()}setVisible(e){if(this.pair)throw Error("Unable to toggle visibility of paired scrollbars.");this.setVisibleInternal(e)}setVisibleInternal(e){const t=e!==this.isVisible();this.isHandleVisible=e,t&&this.updateDisplay_()}updateDisplay_(){this.containerVisible&&this.isVisible()?this.outerSvg.setAttribute("display","block"):this.outerSvg.setAttribute("display","none")}onMouseDownBar(e){if(this.workspace.markFocused(),ke(),this.cleanUp(),ve(e))e.stopPropagation();else{var t=st(e,this.workspace.getParentSvg(),this.workspace.getInverseScreenCTM());t=this.horizontal?t.x:t.y;var o=pa(this.svgHandle);o=this.horizontal?o.x:o.y;var n=this.handlePosition,c=.95*this.handleLength;t<=o?n-=c:t>=o+this.handleLength&&(n+=c),this.setHandlePosition(this.constrainHandlePosition(n)),this.updateMetrics(),e.stopPropagation(),e.preventDefault()}}onMouseDownHandle(e){this.workspace.markFocused(),this.cleanUp(),ve(e)?e.stopPropagation():(this.startDragHandle=this.handlePosition,this.startDragMouse=this.horizontal?e.clientX:e.clientY,this.onMouseUpWrapper_=X(document,"pointerup",this,this.onMouseUpHandle),this.onMouseMoveWrapper_=X(document,"pointermove",this,this.onMouseMoveHandle),e.stopPropagation(),e.preventDefault())}onMouseMoveHandle(e){this.setHandlePosition(this.constrainHandlePosition(this.startDragHandle+((this.horizontal?e.clientX:e.clientY)-this.startDragMouse))),this.updateMetrics()}onMouseUpHandle(){ke(),this.cleanUp()}cleanUp(){this.workspace.hideChaff(!0),this.onMouseUpWrapper_&&(ze(this.onMouseUpWrapper_),this.onMouseUpWrapper_=null),this.onMouseMoveWrapper_&&(ze(this.onMouseMoveWrapper_),this.onMouseMoveWrapper_=null)}getRatio_(){let e=this.handlePosition/(this.scrollbarLength-this.handleLength);return isNaN(e)&&(e=0),e}updateMetrics(){const e=this.getRatio_();this.horizontal?this.workspace.setMetrics({x:e}):this.workspace.setMetrics({y:e})}set(e,t){this.setHandlePosition(this.constrainHandlePosition(e*this.ratio)),(t||t===void 0)&&this.updateMetrics()}setOrigin(e,t){this.origin=new G(e,t)}static metricsAreEquivalent(e,t){return e.viewWidth===t.viewWidth&&e.viewHeight===t.viewHeight&&e.viewLeft===t.viewLeft&&e.viewTop===t.viewTop&&e.absoluteTop===t.absoluteTop&&e.absoluteLeft===t.absoluteLeft&&e.scrollWidth===t.scrollWidth&&e.scrollHeight===t.scrollHeight&&e.scrollLeft===t.scrollLeft&&e.scrollTop===t.scrollTop}};mt.scrollbarThickness=yb?25:15,mt.DEFAULT_SCROLLBAR_MARGIN=.5;var al={parseFromString:function(){throw Error("DOMParser was not found in the global scope and was not properly injected using injectDependencies")}},Sh={serializeToString:function(){throw Error("XMLSerializer was not foundin the global scope and was not properly injected using injectDependencies")}},{document:ll,DOMParser:ar,XMLSerializer:lr}=globalThis;ar&&(al=new ar),lr&&(Sh=new lr);var Pb="https://developers.google.com/blockly/xml",BT=/[\x00-\x09\x0B\x0C\x0E-\x1F]/g,Hi={NAME_SPACE:Pb};Hi.createElement=i.createElement$$module$build$src$core$utils$xml,Hi.createTextNode=i.createTextNode$$module$build$src$core$utils$xml,Hi.domToText=Ii,Hi.injectDependencies=Km,Hi.textToDom=i.textToDom$$module$build$src$core$utils$xml;var Eh="categoryToolbox",Bb="flyoutToolbox",Ee;(function(e){e[e.TOP=0]="TOP",e[e.BOTTOM=1]="BOTTOM",e[e.LEFT=2]="LEFT",e[e.RIGHT=3]="RIGHT"})(Ee||(Ee={}));var jb={hasCategoriesInternal:qm},Eo={};Eo.Position=Ee,Eo.TEST_ONLY=jb,Eo.convertFlyoutDefToJsonArray=Bn,Eo.convertToolboxDefToJson=ga,Eo.hasCategories=ma,Eo.isCategoryCollapsible=fa,Eo.parseToolboxTree=bu;var lo;(function(e){e[e.TOP=0]="TOP",e[e.BOTTOM=1]="BOTTOM"})(lo||(lo={}));var Wi;(function(e){e[e.LEFT=0]="LEFT",e[e.RIGHT=1]="RIGHT"})(Wi||(Wi={}));var Io;(function(e){e[e.UP=0]="UP",e[e.DOWN=1]="DOWN"})(Io||(Io={}));var si={};si.bumpDirection=Io,si.bumpPositionRect=ya,si.getCornerOppositeToolbox=va,si.getStartPositionRect=ba,si.horizontalPosition=Wi,si.verticalPosition=lo;var jt={width:96,height:124,url:"sprites.png"},Fb=class{constructor(e){this.workspace=e,this.id="zoomControls",this.boundEvents=[],this.zoomResetGroup=this.zoomOutGroup=this.zoomInGroup=null,this.HEIGHT=this.WIDTH=32,this.SMALL_SPACING=2,this.LARGE_SPACING=11,this.MARGIN_HORIZONTAL=this.MARGIN_VERTICAL=20,this.svgGroup=null,this.top=this.left=0,this.initialized=!1}createDom(){this.svgGroup=N(x.G,{});const e=String(Math.random()).substring(2);return this.createZoomOutSvg(e),this.createZoomInSvg(e),this.workspace.isMovable()&&this.createZoomResetSvg(e),this.svgGroup}init(){this.workspace.getComponentManager().addComponent({component:this,weight:lt.ComponentWeight.ZOOM_CONTROLS_WEIGHT,capabilities:[lt.Capability.POSITIONABLE]}),this.initialized=!0}dispose(){this.workspace.getComponentManager().removeComponent("zoomControls"),this.svgGroup&&Ke(this.svgGroup);for(const e of this.boundEvents)ze(e);this.boundEvents.length=0}getBoundingRectangle(){let e=this.SMALL_SPACING+2*this.HEIGHT;return this.zoomResetGroup&&(e+=this.LARGE_SPACING+this.HEIGHT),new qe(this.top,this.top+e,this.left,this.left+this.WIDTH)}position(e,t){if(this.initialized){var o=va(this.workspace,e),n=this.SMALL_SPACING+2*this.HEIGHT;if(this.zoomResetGroup&&(n+=this.LARGE_SPACING+this.HEIGHT),e=ba(o,new Le(this.WIDTH,n),this.MARGIN_HORIZONTAL,this.MARGIN_VERTICAL,e,this.workspace),o=o.vertical,t=ya(e,this.MARGIN_VERTICAL,o===lo.TOP?Io.DOWN:Io.UP,t),o===lo.TOP){var c=this.SMALL_SPACING+this.HEIGHT,h;(h=this.zoomInGroup)==null||h.setAttribute("transform","translate(0, "+c+")"),this.zoomResetGroup&&this.zoomResetGroup.setAttribute("transform","translate(0, "+(c+this.LARGE_SPACING+this.HEIGHT)+")")}else{h=this.zoomResetGroup?this.LARGE_SPACING+this.HEIGHT:0;let T;(T=this.zoomInGroup)==null||T.setAttribute("transform","translate(0, "+h+")"),h=h+this.SMALL_SPACING+this.HEIGHT,(c=this.zoomOutGroup)==null||c.setAttribute("transform","translate(0, "+h+")")}this.top=t.top,this.left=t.left;var $;($=this.svgGroup)==null||$.setAttribute("transform","translate("+this.left+","+this.top+")")}}createZoomOutSvg(e){this.zoomOutGroup=N(x.G,{class:"blocklyZoom blocklyZoomOut"},this.svgGroup);const t=N(x.CLIPPATH,{id:"blocklyZoomoutClipPath"+e},this.zoomOutGroup);N(x.RECT,{width:32,height:32},t),N(x.IMAGE,{width:jt.width,height:jt.height,x:-64,y:-92,"clip-path":"url(#blocklyZoomoutClipPath"+e+")"},this.zoomOutGroup).setAttributeNS(es,"xlink:href",this.workspace.options.pathToMedia+jt.url),this.boundEvents.push(X(this.zoomOutGroup,"pointerdown",null,this.zoom.bind(this,-1)))}createZoomInSvg(e){this.zoomInGroup=N(x.G,{class:"blocklyZoom blocklyZoomIn"},this.svgGroup);const t=N(x.CLIPPATH,{id:"blocklyZoominClipPath"+e},this.zoomInGroup);N(x.RECT,{width:32,height:32},t),N(x.IMAGE,{width:jt.width,height:jt.height,x:-32,y:-92,"clip-path":"url(#blocklyZoominClipPath"+e+")"},this.zoomInGroup).setAttributeNS(es,"xlink:href",this.workspace.options.pathToMedia+jt.url),this.boundEvents.push(X(this.zoomInGroup,"pointerdown",null,this.zoom.bind(this,1)))}zoom(e,t){this.workspace.markFocused(),this.workspace.zoomCenter(e),this.fireZoomEvent(),ke(),t.stopPropagation(),t.preventDefault()}createZoomResetSvg(e){this.zoomResetGroup=N(x.G,{class:"blocklyZoom blocklyZoomReset"},this.svgGroup);const t=N(x.CLIPPATH,{id:"blocklyZoomresetClipPath"+e},this.zoomResetGroup);N(x.RECT,{width:32,height:32},t),N(x.IMAGE,{width:jt.width,height:jt.height,y:-92,"clip-path":"url(#blocklyZoomresetClipPath"+e+")"},this.zoomResetGroup).setAttributeNS(es,"xlink:href",this.workspace.options.pathToMedia+jt.url),this.boundEvents.push(X(this.zoomResetGroup,"pointerdown",null,this.resetZoom.bind(this)))}resetZoom(e){this.workspace.markFocused();const t=Math.log(this.workspace.options.zoomOptions.startScale/this.workspace.scale)/Math.log(this.workspace.options.zoomOptions.scaleSpeed);this.workspace.beginCanvasTransition(),this.workspace.zoomCenter(t),this.workspace.scrollCenter(),setTimeout(this.workspace.endCanvasTransition.bind(this.workspace),500),this.fireZoomEvent(),ke(),e.stopPropagation(),e.preventDefault()}fireZoomEvent(){const e=new(V(O.CLICK))(null,this.workspace.id,"zoom_controls");z(e)}};Et(` -.blocklyZoom>image, .blocklyZoom>svg>image { - opacity: .4; -} - -.blocklyZoom>image:hover, .blocklyZoom>svg>image:hover { - opacity: .6; -} - -.blocklyZoom>image:active, .blocklyZoom>svg>image:active { - opacity: .8; -} -`);var zb=100,Ub=75,Hb=50,Wb=25,jT={BLOCKS:Hb,PROCEDURES:Ub,VARIABLES:zb,WORKSPACE_COMMENTS:Wb},Ih={};Ih.register=jn,Ih.unregister=Zm;var Gb=class{constructor(){this.priority=Wb}save(e){const t=[];for(const o of e.getTopComments())(e=xi(o,{addCoordinates:!0,saveIds:!0}))&&t.push(e);return t.length?t:null}load(e,t){for(const o of e)Fn(o,t,{recordUndo:me()})}clear(e){for(const t of e.getTopComments())t.dispose()}};jn("workspaceComments",new Gb);var cl={};cl.WorkspaceCommentSerializer=Gb,cl.append=Fn,cl.save=xi;var xh={};xh.register=_a,xh.unregister=Qm;var ul=class{paste(e,t,o){e=e.commentState,o&&(e.x=o.x,e.y=o.y),i.disable$$module$build$src$core$events$utils();let n;try{n=Fn(e,t),ef(n)}finally{i.enable$$module$build$src$core$events$utils()}return n?(K()&&z(new(V(O.COMMENT_CREATE))(n)),i.setSelected$$module$build$src$core$common(n),n):null}};ul.TYPE="workspace-comment",_a(ul.TYPE,new ul);var Dh;Dh=28,i.config$$module$build$src$core$config={dragRadius:5,flyoutDragRadius:10,snapRadius:Dh,connectingSnapRadius:Dh,currentConnectionPreference:8,bumpDelay:250},i.config$$module$build$src$core$config;var FT="aria-",zT="role",ks;(function(e){e.GRID="grid",e.GRIDCELL="gridcell",e.GROUP="group",e.LISTBOX="listbox",e.MENU="menu",e.MENUITEM="menuitem",e.MENUITEMCHECKBOX="menuitemcheckbox",e.OPTION="option",e.PRESENTATION="presentation",e.ROW="row",e.TREE="tree",e.TREEITEM="treeitem"})(ks||(ks={}));var Ct;(function(e){e.ACTIVEDESCENDANT="activedescendant",e.COLCOUNT="colcount",e.DISABLED="disabled",e.EXPANDED="expanded",e.INVALID="invalid",e.LABEL="label",e.LABELLEDBY="labelledby",e.LEVEL="level",e.ORIENTATION="orientation",e.POSINSET="posinset",e.ROWCOUNT="rowcount",e.SELECTED="selected",e.SETSIZE="setsize",e.VALUEMAX="valuemax",e.VALUEMIN="valuemin"})(Ct||(Ct={}));var cr={};cr.Role=ks,cr.State=Ct,cr.setRole=_o,cr.setState=It;var Ah=class{constructor(){this.menuItems=[],this.roleName=this.element=this.onKeyDownHandler=this.pointerLeaveHandler=this.pointerEnterHandler=this.clickHandler=this.pointerMoveHandler=this.highlightedItem=this.openingCoords=null}addChild(e){this.menuItems.push(e)}render(e){const t=document.createElement("div");t.className="blocklyMenu goog-menu blocklyNonSelectable",t.tabIndex=0,this.roleName&&_o(t,this.roleName),this.element=t;for(let o=0,n;n=this.menuItems[o];o++)t.appendChild(n.createDom());return this.pointerMoveHandler=X(t,"pointermove",this,this.handlePointerMove,!0),this.clickHandler=X(t,"pointerup",this,this.handleClick,!0),this.pointerEnterHandler=X(t,"pointerenter",this,this.handlePointerEnter,!0),this.pointerLeaveHandler=X(t,"pointerleave",this,this.handlePointerLeave,!0),this.onKeyDownHandler=X(t,"keydown",this,this.handleKeyEvent),e.appendChild(t),t}getElement(){return this.element}focus(){const e=this.getElement();e&&(e.focus({preventScroll:!0}),ge(e,"blocklyFocused"))}blur(){const e=this.getElement();e&&(e.blur(),ot(e,"blocklyFocused"))}setRole(e){this.roleName=e}dispose(){this.pointerMoveHandler&&(ze(this.pointerMoveHandler),this.pointerMoveHandler=null),this.clickHandler&&(ze(this.clickHandler),this.clickHandler=null),this.pointerEnterHandler&&(ze(this.pointerEnterHandler),this.pointerEnterHandler=null),this.pointerLeaveHandler&&(ze(this.pointerLeaveHandler),this.pointerLeaveHandler=null),this.onKeyDownHandler&&(ze(this.onKeyDownHandler),this.onKeyDownHandler=null);for(let e=0,t;t=this.menuItems[e];e++)t.dispose();this.element=null}getMenuItem(e){const t=this.getElement();for(;e&&e!==t;){if(e.classList.contains("blocklyMenuItem")){for(let o=0,n;n=this.menuItems[o];o++)if(n.getElement()===e)return n}e=e.parentElement}return null}setHighlighted(e){var t=this.highlightedItem;if(t&&(t.setHighlighted(!1),this.highlightedItem=null),e){e.setHighlighted(!0),this.highlightedItem=e,t=this.getElement();const o=t==null?void 0:t.parentElement,n=e.getElement();o&&n&&(ha(n,o),It(t,Ct.ACTIVEDESCENDANT,e.getId()))}}highlightNext(){const e=this.highlightedItem?this.menuItems.indexOf(this.highlightedItem):-1;this.highlightHelper(e,1)}highlightPrevious(){const e=this.highlightedItem?this.menuItems.indexOf(this.highlightedItem):-1;this.highlightHelper(0>e?this.menuItems.length:e,-1)}highlightFirst(){this.highlightHelper(-1,1)}highlightLast(){this.highlightHelper(this.menuItems.length,-1)}highlightHelper(e,t){e+=t;let o;for(;o=this.menuItems[e];){if(o.isEnabled()){this.setHighlighted(o);break}e+=t}}handlePointerMove(e){Math.max(Math.abs(e.movementX),Math.abs(e.movementY))!==0&&(e=this.getMenuItem(e.target))&&(e.isEnabled()?this.highlightedItem!==e&&this.setHighlighted(e):this.setHighlighted(null))}handleClick(e){const t=this.openingCoords;if(this.openingCoords=null,t&&typeof e.clientX=="number"){const o=new G(e.clientX,e.clientY);if(1>G.distance(t,o))return}(e=this.getMenuItem(e.target))&&e.performAction()}handlePointerEnter(e){this.focus()}handlePointerLeave(e){this.getElement()&&this.setHighlighted(null)}handleKeyEvent(e){if(this.menuItems.length&&!(e.shiftKey||e.ctrlKey||e.metaKey||e.altKey)){var t=this.highlightedItem;switch(e.key){case"Enter":case" ":t&&t.performAction();break;case"ArrowUp":this.highlightPrevious();break;case"ArrowDown":this.highlightNext();break;case"PageUp":case"Home":this.highlightFirst();break;case"PageDown":case"End":this.highlightLast();break;default:return}e.preventDefault(),e.stopPropagation()}}getSize(){const e=this.getElement(),t=Ln(e);return t.height=e.scrollHeight,t}},Rh=class{constructor(e,t){this.content=e,this.opt_value=t,this.enabled=!0,this.element=null,this.rightToLeft=!1,this.roleName=null,this.highlight=this.checked=this.checkable=!1,this.actionHandler=null}createDom(){const e=document.createElement("div");e.id=k(),this.element=e,e.className="blocklyMenuItem goog-menuitem "+(this.enabled?"":"blocklyMenuItemDisabled goog-menuitem-disabled ")+(this.checked?"blocklyMenuItemSelected goog-option-selected ":"")+(this.highlight?"blocklyMenuItemHighlight goog-menuitem-highlight ":"")+(this.rightToLeft?"blocklyMenuItemRtl goog-menuitem-rtl ":"");const t=document.createElement("div");if(t.className="blocklyMenuItemContent goog-menuitem-content",this.checkable){var o=document.createElement("div");o.className="blocklyMenuItemCheckbox goog-menuitem-checkbox",t.appendChild(o)}return o=this.content,typeof this.content=="string"&&(o=document.createTextNode(this.content)),t.appendChild(o),e.appendChild(t),this.roleName&&_o(e,this.roleName),It(e,Ct.SELECTED,this.checkable&&this.checked||!1),It(e,Ct.DISABLED,!this.enabled),e}dispose(){this.element=null}getElement(){return this.element}getId(){return this.element.id}getValue(){let e;return(e=this.opt_value)!=null?e:null}setRightToLeft(e){this.rightToLeft=e}setRole(e){this.roleName=e}setCheckable(e){this.checkable=e}setChecked(e){this.checked=e}setHighlighted(e){this.highlight=e;const t=this.getElement();t&&this.isEnabled()&&(e?(ge(t,"blocklyMenuItemHighlight"),ge(t,"goog-menuitem-highlight")):(ot(t,"blocklyMenuItemHighlight"),ot(t,"goog-menuitem-highlight")))}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}performAction(){this.isEnabled()&&this.actionHandler&&this.actionHandler(this)}onAction(e,t){this.actionHandler=e.bind(t)}},ur="_TEMP_COLLAPSED_INPUT",dl="_TEMP_COLLAPSED_FIELD",Ft="MANUALLY_DISABLED",UT={COLLAPSED_FIELD_NAME:dl,COLLAPSED_INPUT_NAME:ur,MANUALLY_DISABLED:Ft};(function(e){e[e.VALUE=1]="VALUE",e[e.STATEMENT=3]="STATEMENT",e[e.DUMMY=5]="DUMMY",e[e.CUSTOM=6]="CUSTOM",e[e.END_ROW=7]="END_ROW"})(i.inputTypes$$module$build$src$core$inputs$input_types||(i.inputTypes$$module$build$src$core$inputs$input_types={})),i.inputTypes$$module$build$src$core$inputs$input_types;var hl=new Set,Oh=new WeakSet,Mh=new WeakMap,Gi=null,Nh=null,Vb=0,pl={};pl.finishQueuedRenders=ws,pl.queueRender=vu,pl.triggerQueuedRenders=Qs;var Kb=function(e,t){window.alert(e),t&&t()},Yb=function(e,t){t(window.confirm(e))},Jb=function(e,t,o){o(window.prompt(e,t))},qb={confirmInternal:rf},oi={TEST_ONLY:qb};oi.alert=Un,oi.confirm=Ca,oi.prompt=Ta,oi.setAlert=nf,oi.setConfirm=af,oi.setPrompt=lf;var Lh,Xb;i.Msg$$module$build$src$core$msg=Object.create(null),Lh=function(e){Object.keys(e).forEach(function(t){i.Msg$$module$build$src$core$msg[t]=e[t]})},Xb={Msg:i.Msg$$module$build$src$core$msg,setLocale:Lh};var dr=class extends Ui{constructor(e){super(),this.isBlank=typeof e>"u",e&&(this.varId=e.getId(),this.workspaceId=e.workspace.id)}toJson(){const e=super.toJson();if(!this.varId)throw Error("The var ID is undefined. Either pass a variable to the constructor, or call fromJson");return e.varId=this.varId,e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new dr),t.varId=e.varId,t}},Ph=class extends dr{constructor(e){super(e),this.type=O.VAR_CREATE,e&&(this.varType=e.type,this.varName=e.name)}toJson(){const e=super.toJson();if(this.varType===void 0)throw Error("The var type is undefined. Either pass a variable to the constructor, or call fromJson");if(!this.varName)throw Error("The var name is undefined. Either pass a variable to the constructor, or call fromJson");return e.varType=this.varType,e.varName=this.varName,e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new Ph),t.varType=e.varType,t.varName=e.varName,t}run(e){const t=this.getEventWorkspace_();if(!this.varId)throw Error("The var ID is undefined. Either pass a variable to the constructor, or call fromJson");if(!this.varName)throw Error("The var name is undefined. Either pass a variable to the constructor, or call fromJson");e?t.createVariable(this.varName,this.varType,this.varId):t.deleteVariableById(this.varId)}};r(F.EVENT,O.VAR_CREATE,Ph);var hr=class{constructor(e,t,o,n){this.workspace=e,this.name=t,this.type=o||"",this.id=n||C()}getId(){return this.id}static compareByName(e,t){return e.name.localeCompare(t.name,void 0,{sensitivity:"base"})}},Bh="VARIABLE",jh="ijkmnopqrstuvwxyzabcdefgh",Zb={generateUniqueNameInternal:uf},At={CATEGORY_NAME:Bh,TEST_ONLY:Zb,VAR_LETTER_OPTIONS:jh};At.allDeveloperVariables=i.allDeveloperVariables$$module$build$src$core$variables,At.allUsedVarModels=i.allUsedVarModels$$module$build$src$core$variables,At.createVariableButtonHandler=Ai,At.flyoutCategory=ka,At.flyoutCategoryBlocks=Tu,At.generateUniqueName=ku,At.generateUniqueNameFromOptions=Sa,At.generateVariableFieldDom=Go,At.getAddedVariables=Hn,At.getOrCreateVariablePackage=i.getOrCreateVariablePackage$$module$build$src$core$variables,At.getVariable=i.getVariable$$module$build$src$core$variables,At.nameUsedWithAnyType=Su,At.nameUsedWithConflictingParam=Eu,At.promptName=Ea,At.renameVariable=i.renameVariable$$module$build$src$core$variables;var Vi=class extends Error{},Qb=class extends Vi{constructor(e){super("Expected to find a 'type' property, defining the block type"),this.state=e}},pr=class extends Vi{constructor(e,t,o){super(`The block ${t.toDevString()} is missing a(n) ${e} -connection`),this.block=t,this.state=o}},ev=class extends Vi{constructor(e,t,o,n){super(`The block ${o.toDevString()} could not connect its -${t} to its parent, because: ${e}`),this.childBlock=o,this.childState=n}},tv=class extends Vi{constructor(e){super(`Encountered a real block which is defined as a child of a shadow -block. It is an invariant of Blockly that shadow blocks only have shadow -children`),this.state=e}},sv=class extends Vi{constructor(e,t,o){super(`Cannot add an icon of type '${e}' to the block ${t.toDevString()}, because there is no icon registered with type '${e}'. Make sure that all of your icons have been registered.`),this.block=t,this.state=o}},ii={};ii.BadConnectionCheck=ev,ii.DeserializationError=Vi,ii.MissingBlockType=Qb,ii.MissingConnection=pr,ii.RealChildOfShadow=tv,ii.UnregisteredIcon=sv;var ov=class{constructor(){this.priority=Hb}save(e){const t=[];for(const o of e.getTopBlocks(!1))(e=Qt(o,{addCoordinates:!0,doFullSerialization:!1}))&&t.push(e);return t.length?{languageVersion:0,blocks:t}:null}load(e,t){e=e.blocks;for(const o of e)eo(o,t,{recordUndo:me()})}clear(e){for(const t of e.getTopBlocks(!1))t.dispose(!1)}};jn("blocks",new ov);var gr={};gr.BlockSerializer=ov,gr.append=eo,gr.appendInternal=Ri,gr.save=Qt;var yt=class{constructor(e){this.name=e}toString(){return this.name}equals(e){return this.name===e.toString()}};yt.MUTATOR=new yt("mutator"),yt.WARNING=new yt("warning"),yt.COMMENT=new yt("comment");var ni=class extends Ui{constructor(e){super(),this.isBlank=!e,e&&(this.blockId=e.id,this.workspaceId=e.workspace.id)}toJson(){const e=super.toJson();if(!this.blockId)throw Error("The block ID is undefined. Either pass a block to the constructor, or call fromJson");return e.blockId=this.blockId,e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new ni),t.blockId=e.blockId,t}},ri=class extends ni{constructor(e,t,o,n,c){super(e),this.type=O.BLOCK_CHANGE,e&&(this.element=t,this.name=o||void 0,this.oldValue=n,this.newValue=c)}toJson(){const e=super.toJson();if(!this.element)throw Error("The changed element is undefined. Either pass an element to the constructor, or call fromJson");return e.element=this.element,e.name=this.name,e.oldValue=this.oldValue,e.newValue=this.newValue,this.disabledReason&&(e.disabledReason=this.disabledReason),e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new ri),t.element=e.element,t.name=e.name,t.oldValue=e.oldValue,t.newValue=e.newValue,e.disabledReason!==void 0&&(t.disabledReason=e.disabledReason),t}setDisabledReason(e){if(this.element!=="disabled")throw Error('Cannot set the disabled reason for a BlockChange event if the element is not "disabled".');this.disabledReason=e}isNull(){return this.oldValue===this.newValue}run(e){var t=this.getEventWorkspace_();if(!this.blockId)throw Error("The block ID is undefined. Either pass a block to the constructor, or call fromJson");if(t=t.getBlockById(this.blockId),!t)throw Error("The associated block is undefined. Either pass a block to the constructor, or call fromJson");const o=t.getIcon(yt.MUTATOR);switch(o&&Oi(o)&&o.bubbleIsVisible()&&o.setBubbleVisible(!1),e=e?this.newValue:this.oldValue,this.element){case"field":(t=t.getField(this.name))?t.setValue(e):console.warn("Can't set non-existent field: "+this.name);break;case"comment":t.setCommentText(e||null);break;case"collapsed":t.setCollapsed(!!e);break;case"disabled":var n;t.setDisabledReason(!!e,(n=this.disabledReason)!=null?n:Ft);break;case"inline":t.setInputsInline(!!e);break;case"mutation":n=ri.getExtraBlockState_(t),t.loadExtraState?t.loadExtraState(JSON.parse(e||"{}")):t.domToMutation&&t.domToMutation(i.textToDom$$module$build$src$core$utils$xml(e||"")),z(new ri(t,"mutation",null,n,e));break;default:console.warn("Unknown change type: "+this.element)}}static getExtraBlockState_(e){return e.saveExtraState?(e=e.saveExtraState(!0))?JSON.stringify(e):"":e.mutationToDom&&(e=e.mutationToDom())?Ls(e):""}};r(F.EVENT,O.BLOCK_CHANGE,ri);var gl={};gl.clamp=Mi,gl.toDegrees=Rf,gl.toRadians=Ia;var ml=16,iv=1,nv=12,Fh=16,fl=.25,zh=null,ai=null,Ki="",Yi="",Ue,Ji,li,Uh=null,xo=null,rv=null,Hh={getBoundsInfo:function(){const e=yo(Uh),t=Ln(Uh);return{left:e.x,right:e.x+t.width,top:e.y,bottom:e.y+t.height,width:t.width,height:t.height}},getPositionMetrics:function(e,t,o,n){const c=Hh.getBoundsInfo(),h=Ln(Ue);return t+h.heightc.top?zu(o,n,c,h):t+h.heightdocument.documentElement.clientTop?zu(o,n,c,h):Mf(e,c,h)}},Nt={ANIMATION_TIME:fl,ARROW_HORIZONTAL_PADDING:nv,ARROW_SIZE:ml,BORDER_SIZE:iv,PADDING_Y:Fh,TEST_ONLY:Hh};Nt.clearContent=xa,Nt.createDom=Au,Nt.getContentDiv=Wn,Nt.getOwner=Ou,Nt.getPositionX=Gn,Nt.hide=Aa,Nt.hideIfOwner=Da,Nt.hideWithoutAnimation=Ns,Nt.isVisible=Uu,Nt.repositionForWindowResize=Wu,Nt.setBoundsElement=Ru,Nt.setColour=Mu,Nt.show=ju,Nt.showPositionedByBlock=Of,Nt.showPositionedByField=Nu;var mr=class{constructor(e){this.workspace=e,this.cursorSvg=this.cursor=null,this.markers=new Map,this.markerSvg=null}registerMarker(e,t){this.markers.has(e)&&this.unregisterMarker(e),t.setDrawer(this.workspace.getRenderer().makeMarkerDrawer(this.workspace,t)),this.setMarkerSvg(t.getDrawer().createDom()),this.markers.set(e,t)}unregisterMarker(e){const t=this.markers.get(e);if(t)t.dispose(),this.markers.delete(e);else throw Error("Marker with ID "+e+" does not exist. Can only unregister markers that exist.")}getCursor(){return this.cursor}getMarker(e){return this.markers.get(e)||null}setCursor(e){this.cursor&&this.cursor.getDrawer()&&this.cursor.getDrawer().dispose(),(this.cursor=e)&&(e=this.workspace.getRenderer().makeMarkerDrawer(this.workspace,this.cursor),this.cursor.setDrawer(e),this.setCursorSvg(this.cursor.getDrawer().createDom()))}setCursorSvg(e){e?(this.workspace.getBlockCanvas().appendChild(e),this.cursorSvg=e):this.cursorSvg=null}setMarkerSvg(e){e?this.workspace.getBlockCanvas()&&(this.cursorSvg?this.workspace.getBlockCanvas().insertBefore(e,this.cursorSvg):this.workspace.getBlockCanvas().appendChild(e)):this.markerSvg=null}updateMarkers(){this.workspace.keyboardAccessibilityMode&&this.cursorSvg&&this.workspace.getCursor().draw()}dispose(){const e=Object.keys(this.markers);for(let t=0,o;o=e[t];t++)this.unregisterMarker(o);this.markers.clear(),this.cursor&&(this.cursor.dispose(),this.cursor=null)}};mr.LOCAL_MARKER="local_marker_1";var qi={};qi.commonWordPrefix=Gu,qi.commonWordSuffix=Vu,qi.isNumber=i.isNumber$$module$build$src$core$utils$string,qi.shortestStringLength=Vn,qi.wrap=i.wrap$$module$build$src$core$utils$string;var $l=void 0,fr=!1,Xi=!1,av=50,lv=0,ci=0,Wh=0,Gh=0,cs=null,$r=null,Vh=0,Kh=10,cv=10,uv=750,bl=5,_t=null,ts={HOVER_MS:uv,LIMIT:av,MARGINS:bl,OFFSET_X:Vh,OFFSET_Y:Kh,RADIUS_OK:cv};ts.bindMouseEvents=Li,ts.block=Zu,ts.createDom=Ju,ts.dispose=Xu,ts.getCustomTooltip=Bf,ts.getDiv=Ff,ts.getTooltipOfObject=Ni,ts.hide=to,ts.isVisible=jf,ts.setCustomTooltip=Pf,ts.unbindMouseEvents=Oa,ts.unblock=Qu;var Yh=.45,Jh=.65,dv={aqua:"#00ffff",black:"#000000",blue:"#0000ff",fuchsia:"#ff00ff",gray:"#808080",green:"#008000",lime:"#00ff00",maroon:"#800000",navy:"#000080",olive:"#808000",purple:"#800080",red:"#ff0000",silver:"#c0c0c0",teal:"#008080",white:"#ffffff",yellow:"#ffff00"},us={};us.blend=Ko,us.getHsvSaturation=ed,us.getHsvValue=td,us.hexToRgb=Ma,us.hsvToHex=Na,us.hueToHex=sd,us.names=dv,us.parse=Vo,us.rgbToHex=Kn,us.setHsvSaturation=Kf,us.setHsvValue=Yf;var br={};br.checkMessageReferences=Jf,br.parseBlockColour=Pi,br.replaceMessageReferences=pt,br.tokenizeInterpolation=od;var Qe=class{constructor(e,t,o){this.DEFAULT_VALUE=null,this.name=void 0,this.constants_=this.mouseDownWrapper=this.textContent_=this.textElement_=this.borderRect_=this.fieldGroup_=this.markerSvg=this.cursorSvg=this.tooltip=this.validator_=null,this.disposed=!1,this.maxDisplayLength=50,this.sourceBlock_=null,this.enabled_=this.visible_=this.isDirty_=!0,this.suffixField=this.prefixField=this.clickTarget_=null,this.EDITABLE=!0,this.SERIALIZABLE=!1,this.CURSOR="",this.value_="DEFAULT_VALUE"in new.target.prototype?new.target.prototype.DEFAULT_VALUE:this.DEFAULT_VALUE,this.size_=new Le(0,0),e!==Qe.SKIP_SETUP&&(o&&this.configure_(o),this.setValue(e),t&&this.setValidator(t))}configure_(e){e.tooltip&&this.setTooltip(pt(e.tooltip))}setSourceBlock(e){if(this.sourceBlock_)throw Error("Field already bound to a block");this.sourceBlock_=e}getConstants(){return!this.constants_&&this.sourceBlock_&&!this.sourceBlock_.isDeadOrDying()&&this.sourceBlock_.workspace.rendered&&(this.constants_=this.sourceBlock_.workspace.getRenderer().getConstants()),this.constants_}getSourceBlock(){return this.sourceBlock_}init(){this.fieldGroup_||(this.fieldGroup_=N(x.G,{}),this.isVisible()||(this.fieldGroup_.style.display="none"),this.sourceBlock_.getSvgRoot().appendChild(this.fieldGroup_),this.initView(),this.updateEditable(),this.setTooltip(this.tooltip),this.bindEvents_(),this.initModel(),this.applyColour())}initView(){this.createBorderRect_(),this.createTextElement_()}initModel(){}isFullBlockField(){return!this.borderRect_}createBorderRect_(){this.borderRect_=N(x.RECT,{rx:this.getConstants().FIELD_BORDER_RECT_RADIUS,ry:this.getConstants().FIELD_BORDER_RECT_RADIUS,x:0,y:0,height:this.size_.height,width:this.size_.width,class:"blocklyFieldRect"},this.fieldGroup_)}createTextElement_(){this.textElement_=N(x.TEXT,{class:"blocklyText"},this.fieldGroup_),this.getConstants().FIELD_TEXT_BASELINE_CENTER&&this.textElement_.setAttribute("dominant-baseline","central"),this.textContent_=document.createTextNode(""),this.textElement_.appendChild(this.textContent_)}bindEvents_(){const e=this.getClickTarget_();if(!e)throw Error("A click target has not been set.");Li(e),this.mouseDownWrapper=X(e,"pointerdown",this,this.onMouseDown_)}fromXml(e){this.setValue(e.textContent)}toXml(e){return e.textContent=this.getValue(),e}saveState(e){return e=this.saveLegacyState(Qe),e!==null?e:this.getValue()}loadState(e){this.loadLegacyState(Qe,e)||this.setValue(e)}saveLegacyState(e){return e.prototype.saveState===this.saveState&&e.prototype.toXml!==this.toXml?(e=i.createElement$$module$build$src$core$utils$xml("field"),e.setAttribute("name",this.name||""),Ii(this.toXml(e)).replace(' xmlns="https://developers.google.com/blockly/xml"',"")):null}loadLegacyState(e,t){return e.prototype.loadState===this.loadState&&e.prototype.fromXml!==this.fromXml?(this.fromXml(i.textToDom$$module$build$src$core$utils$xml(t)),!0):!1}dispose(){Da(this),Jo(this);let e;(e=this.getSourceBlock())!=null&&e.isDeadOrDying()||Ke(this.fieldGroup_),this.disposed=!0}updateEditable(){const e=this.fieldGroup_,t=this.getSourceBlock();this.EDITABLE&&e&&t&&(this.enabled_&&t.isEditable()?(ge(e,"blocklyEditableText"),ot(e,"blocklyNonEditableText"),e.style.cursor=this.CURSOR):(ge(e,"blocklyNonEditableText"),ot(e,"blocklyEditableText"),e.style.cursor=""))}setEnabled(e){this.enabled_=e,this.updateEditable()}isEnabled(){return this.enabled_}isClickable(){return this.enabled_&&!!this.sourceBlock_&&this.sourceBlock_.isEditable()&&this.showEditor_!==Qe.prototype.showEditor_}isClickableInFlyout(e){return!e}isCurrentlyEditable(){return this.enabled_&&this.EDITABLE&&!!this.sourceBlock_&&this.sourceBlock_.isEditable()}isSerializable(){let e=!1;return this.name&&(this.SERIALIZABLE?e=!0:this.EDITABLE&&(console.warn("Detected an editable field that was not serializable. Please define SERIALIZABLE property as true on all editable custom fields. Proceeding with serialization."),e=!0)),e}isVisible(){return this.visible_}setVisible(e){if(this.visible_!==e){this.visible_=e;var t=this.fieldGroup_;t&&(t.style.display=e?"block":"none")}}setValidator(e){this.validator_=e}getValidator(){return this.validator_}getSvgRoot(){return this.fieldGroup_}getBorderRect(){if(!this.borderRect_)throw Error(`The border rectangle is ${this.borderRect_}.`);return this.borderRect_}getTextElement(){if(!this.textElement_)throw Error(`The text element is ${this.textElement_}.`);return this.textElement_}getTextContent(){if(!this.textContent_)throw Error(`The text content is ${this.textContent_}.`);return this.textContent_}applyColour(){}render_(){this.textContent_&&(this.textContent_.nodeValue=this.getDisplayText_()),this.updateSize_()}showEditor(e){this.isClickable()&&this.showEditor_(e)}showEditor_(e){}repositionForWindowResize(){return!1}updateSize_(e){const t=this.getConstants();e=e!==void 0?e:this.isFullBlockField()?0:this.getConstants().FIELD_BORDER_RECT_X_PADDING;let o=2*e,n=t.FIELD_TEXT_HEIGHT,c=0;this.textElement_&&(c=Nn(this.textElement_,t.FIELD_TEXT_FONTSIZE,t.FIELD_TEXT_FONTWEIGHT,t.FIELD_TEXT_FONTFAMILY),o+=c),this.isFullBlockField()||(n=Math.max(n,t.FIELD_BORDER_RECT_HEIGHT)),this.size_.height=n,this.size_.width=o,this.positionTextElement_(e,c),this.positionBorderRect_()}positionTextElement_(e,t){if(this.textElement_){var o=this.getConstants(),n=this.size_.height/2,c;this.textElement_.setAttribute("x",String((c=this.getSourceBlock())!=null&&c.RTL?this.size_.width-t-e:e)),this.textElement_.setAttribute("y",String(o.FIELD_TEXT_BASELINE_CENTER?n:n-o.FIELD_TEXT_HEIGHT/2+o.FIELD_TEXT_BASELINE))}}positionBorderRect_(){this.borderRect_&&(this.borderRect_.setAttribute("width",String(this.size_.width)),this.borderRect_.setAttribute("height",String(this.size_.height)),this.borderRect_.setAttribute("rx",String(this.getConstants().FIELD_BORDER_RECT_RADIUS)),this.borderRect_.setAttribute("ry",String(this.getConstants().FIELD_BORDER_RECT_RADIUS)))}getSize(){return this.isVisible()?(this.isDirty_?(this.render_(),this.isDirty_=!1):this.visible_&&this.size_.width===0&&(this.render_(),this.size_.width!==0&&console.warn("Deprecated use of setting size_.width to 0 to rerender a field. Set field.isDirty_ to true instead.")),this.size_):new Le(0,0)}getScaledBBox(){let e;var t=this.getSourceBlock();if(!t)throw new ft;if(this.isFullBlockField()){var o=this.sourceBlock_.getHeightWidth();const n=t.workspace.scale;e=this.getAbsoluteXY_(),t=(o.width+1)*n,o=(o.height+1)*n,Ib?(e.x+=1.5*n,e.y+=1.5*n):(e.x-=.5*n,e.y-=.5*n)}else o=this.borderRect_.getBoundingClientRect(),e=yo(this.borderRect_),t=o.width,o=o.height;return new qe(e.y,e.y+o,e.x,e.x+t)}onLocationChange(e){}getDisplayText_(){let e=this.getText();return e?(e.length>this.maxDisplayLength&&(e=e.substring(0,this.maxDisplayLength-2)+"…"),e=e.replace(/\s/g,Qe.NBSP),this.sourceBlock_&&this.sourceBlock_.RTL&&(e+="‏"),e):Qe.NBSP}getText(){const e=this.getText_();return String(e!==null?e:this.getValue())}getText_(){return null}markDirty(){this.isDirty_=!0,this.constants_=null}forceRerender(){this.isDirty_=!0,this.sourceBlock_&&this.sourceBlock_.rendered&&this.sourceBlock_.queueRender()}setValue(e,t=!0){if(e!==null){var o=i.getGroup$$module$build$src$core$events$utils();o||i.setGroup$$module$build$src$core$events$utils(!0);try{const L=this.doClassValidation_(e),te=this.processValidation(e,L,t);if(!(te instanceof Error)){var n,c=(n=this.getValidator())==null?void 0:n.call(this,te),h=this.processValidation(te,c,t);if(!(h instanceof Error)){var $=this.sourceBlock_;if(!$||!$.disposed){var T=this.getValue();T===h?this.doValueUpdate_(h):(this.doValueUpdate_(h),t&&$&&K()&&z(new(V(O.BLOCK_CHANGE))($,"field",this.name||null,T,h)),this.isDirty_&&this.forceRerender())}}}}finally{i.setGroup$$module$build$src$core$events$utils(o)}}}processValidation(e,t,o){return t===null?(this.doValueInvalid_(e,o),this.isDirty_&&this.forceRerender(),Error()):t===void 0?e:t}getValue(){return this.value_}doClassValidation_(e){return e??null}doValueUpdate_(e){this.value_=e,this.isDirty_=!0}doValueInvalid_(e,t){}onMouseDown_(e){this.sourceBlock_&&!this.sourceBlock_.isDeadOrDying()&&(e=this.sourceBlock_.workspace.getGesture(e))&&e.setStartField(this)}setTooltip(e){e||e===""||(e=this.sourceBlock_);const t=this.getClickTarget_();t?t.tooltip=e:this.tooltip=e}getTooltip(){const e=this.getClickTarget_();return Ni(e||{tooltip:this.tooltip})}getClickTarget_(){return this.clickTarget_||this.getSvgRoot()}getAbsoluteXY_(){return yo(this.getClickTarget_())}referencesVariables(){return!1}refreshVariableName(){}getParentInput(){let e=null;const t=this.getSourceBlock();if(!t)throw new ft;const o=t.inputList;for(let n=0;n{o.stopPropagation()})}addModelUpdateBindings(){this.view.addTextChangeListener((e,t)=>{super.setText(t)}),this.view.addSizeChangeListener((e,t)=>{super.setSize(t)}),this.view.addOnCollapseListener(()=>{super.setCollapsed(this.view.isCollapsed())}),this.view.addDisposeListener(()=>{this.isDeadOrDying()||this.dispose()})}setText(e){this.view.setText(e)}setSize(e){this.view.setSize(e)}setCollapsed(e){this.view.setCollapsed(e)}setEditable(e){super.setEditable(e),this.view.setEditable(this.isEditable())}getSvgRoot(){return this.view.getSvgRoot()}getSize(){return super.getSize()}getBoundingRectangle(){const e=this.getRelativeToSurfaceXY();var t,o;const n=(o=(t=this.view)==null?void 0:t.getSize())!=null?o:this.getSize();return this.workspace.RTL?(t=e.x-n.width,o=e.x):(t=e.x,o=e.x+n.width),new qe(e.y,e.y+n.height,t,o)}moveBy(e,t,o){const n=this.getRelativeToSurfaceXY();e=new G(n.x+e,n.y+t),this.moveTo(e,o)}moveTo(e,t){super.moveTo(e,t),this.view.moveTo(e)}moveDuringDrag(e){this.location=e,this.view.moveTo(e)}setDragging(e){e?ge(this.getSvgRoot(),"blocklyDragging"):ot(this.getSvgRoot(),"blocklyDragging")}dispose(){this.disposing=!0,this.view.isDeadOrDying()||this.view.dispose(),super.dispose()}startGesture(e){const t=this.workspace.getGesture(e);if(t){if(kt(e))e.stopPropagation();else{t.handleCommentStart(e,this);let o;(o=this.workspace.getLayerManager())==null||o.append(this,Do)}i.setSelected$$module$build$src$core$common(this)}}setDeleteStyle(e){e?ge(this.getSvgRoot(),"blocklyDraggingDelete"):ot(this.getSvgRoot(),"blocklyDraggingDelete")}isMovable(){return this.dragStrategy.isMovable()}startDrag(){this.dragStrategy.startDrag()}drag(e){this.dragStrategy.drag(e)}endDrag(){this.dragStrategy.endDrag()}revertDrag(){this.dragStrategy.revertDrag()}select(){ge(this.getSvgRoot(),"blocklySelected")}unselect(){ot(this.getSvgRoot(),"blocklySelected")}toCopyData(){return{paster:ul.TYPE,commentState:xi(this,{addCoordinates:!0})}}showContextMenu(e){const t=xe.registry.getContextMenuOptions(xe.ScopeType.COMMENT,{comment:this});Jn(e,t,this.workspace.RTL,this.workspace)}snapToGrid(){if(!this.isDeadOrDying()){var e=this.workspace.getGrid();if(e!=null&&e.shouldSnap()){var t=this.getRelativeToSurfaceXY();e=e.alignXY(t),e!==t&&this.moveTo(e,["snap"])}}}},Lt={};Lt.appendDomToWorkspace=u$,Lt.blockToDom=wo,Lt.blockToDomWithXY=Zn,Lt.clearWorkspaceAndLoadFromXml=c$,Lt.deleteNext=v$,Lt.domToBlock=i.domToBlock$$module$build$src$core$xml,Lt.domToBlockInternal=qo,Lt.domToPrettyText=l$,Lt.domToText=Ls,Lt.domToVariables=md,Lt.domToWorkspace=i.domToWorkspace$$module$build$src$core$xml,Lt.loadWorkspaceComment=gd,Lt.saveWorkspaceComment=Xn,Lt.variablesToDom=hd,Lt.workspaceToDom=n$;var Xh=class extends ni{constructor(e){super(e),this.type=O.BLOCK_CREATE,e&&(e.isShadow()&&(this.recordUndo=!1),this.xml=Zn(e),this.ids=he(e),this.json=Qt(e,{addCoordinates:!0}))}toJson(){const e=super.toJson();if(!this.xml)throw Error("The block XML is undefined. Either pass a block to the constructor, or call fromJson");if(!this.ids)throw Error("The block IDs are undefined. Either pass a block to the constructor, or call fromJson");if(!this.json)throw Error("The block JSON is undefined. Either pass a block to the constructor, or call fromJson");return e.xml=Ls(this.xml),e.ids=this.ids,e.json=this.json,this.recordUndo||(e.recordUndo=this.recordUndo),e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new Xh),t.xml=i.textToDom$$module$build$src$core$utils$xml(e.xml),t.ids=e.ids,t.json=e.json,e.recordUndo!==void 0&&(t.recordUndo=e.recordUndo),t}run(e){const t=this.getEventWorkspace_();if(!this.json)throw Error("The block JSON is undefined. Either pass a block to the constructor, or call fromJson");if(!this.ids)throw Error("The block IDs are undefined. Either pass a block to the constructor, or call fromJson");if(!WT(t,this.ids))if(e)eo(this.json,t);else for(e=0;ee.getBlockById(o)).filter(o=>o&&o.isShadow()).length===t.length};r(F.EVENT,O.BLOCK_CREATE,Xh);var Zh=class extends Cs{constructor(e,t){super(t),this.type=O.THEME_CHANGE,this.themeName=e}toJson(){const e=super.toJson();if(!this.themeName)throw Error("The theme name is undefined. Either pass a theme name to the constructor, or call fromJson");return e.themeName=this.themeName,e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new Zh),t.themeName=e.themeName,t}};r(F.EVENT,O.THEME_CHANGE,Zh);var Qh=class extends Cs{constructor(e,t,o,n,c){super(n),this.type=O.VIEWPORT_CHANGE,this.viewTop=e,this.viewLeft=t,this.scale=o,this.oldScale=c}toJson(){const e=super.toJson();if(this.viewTop===void 0)throw Error("The view top is undefined. Either pass a value to the constructor, or call fromJson");if(this.viewLeft===void 0)throw Error("The view left is undefined. Either pass a value to the constructor, or call fromJson");if(this.scale===void 0)throw Error("The scale is undefined. Either pass a value to the constructor, or call fromJson");if(this.oldScale===void 0)throw Error("The old scale is undefined. Either pass a value to the constructor, or call fromJson");return e.viewTop=this.viewTop,e.viewLeft=this.viewLeft,e.scale=this.scale,e.oldScale=this.oldScale,e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new Qh),t.viewTop=e.viewTop,t.viewLeft=e.viewLeft,t.scale=e.scale,t.oldScale=e.oldScale,t}};r(F.EVENT,O.VIEWPORT_CHANGE,Qh);var oe;(function(e){e[e.INPUT_VALUE=1]="INPUT_VALUE",e[e.OUTPUT_VALUE=2]="OUTPUT_VALUE",e[e.NEXT_STATEMENT=3]="NEXT_STATEMENT",e[e.PREVIOUS_STATEMENT=4]="PREVIOUS_STATEMENT"})(oe||(oe={}));var tn=class{constructor(e){this.connectionChecker=e,this.connections=[]}addConnection(e,t){t=this.calculateIndexForYPos(t),this.connections.splice(t,0,e)}findIndexOfConnection(e,t){if(!this.connections.length)return-1;const o=this.calculateIndexForYPos(t);if(o>=this.connections.length)return-1;t=e.y;let n=o;for(;0<=n&&this.connections[n].y===t;){if(this.connections[n]===e)return n;n--}for(n=o;ne)o=n;else{t=n;break}}return t}removeConnection(e,t){if(e=this.findIndexOfConnection(e,t),e===-1)throw Error("Unable to find connection in connectionDB.");this.connections.splice(e,1)}getNeighbours(e,t){function o(te){const nt=c-n[te].x,it=h-n[te].y;return Math.sqrt(nt*nt+it*it)<=t&&L.push(n[te]),it(this.flyout?i.config$$module$build$src$core$config.flyoutDragRadius:i.config$$module$build$src$core$config.dragRadius)}updateIsDraggingFromFlyout(){let e;if(!this.targetBlock||(e=this.flyout)==null||!e.isBlockCreatable(this.targetBlock))return!1;if(!this.flyout.targetWorkspace)throw Error(`Cannot update dragging from the flyout because the ' + - 'flyout's target workspace is undefined`);return!this.flyout.isScrollable()||this.flyout.isDragTowardWorkspace(this.currentDragDeltaXY)?(this.startWorkspace_=this.flyout.targetWorkspace,this.startWorkspace_.updateScreenCalculationsIfScrolled(),i.getGroup$$module$build$src$core$events$utils()||i.setGroup$$module$build$src$core$events$utils(!0),this.startBlock=null,this.targetBlock=this.flyout.createBlock(this.targetBlock),i.setSelected$$module$build$src$core$common(this.targetBlock),!0):!1}updateIsDraggingWorkspace(){if(!this.startWorkspace_)throw Error("Cannot update dragging the workspace because the start workspace is undefined");(this.flyout?this.flyout.isScrollable():this.startWorkspace_&&this.startWorkspace_.isDraggable())&&(this.dragging=!0,this.workspaceDragger=new fv(this.startWorkspace_),this.workspaceDragger.startDrag())}updateIsDragging(e){if(!this.startWorkspace_)throw Error("Cannot update dragging because the start workspace is undefined");if(this.calledUpdateIsDragging)throw Error("updateIsDragging_ should only be called once per gesture.");this.calledUpdateIsDragging=!0,this.flyout&&this.updateIsDraggingFromFlyout();const t=I();t&&Xo(t)&&t.isMovable()?(this.dragging=!0,this.dragger=this.createDragger(t,this.startWorkspace_),this.dragger.onDragStart(e),this.dragger.onDrag(e,this.currentDragDeltaXY)):this.updateIsDraggingWorkspace()}createDragger(e,t){return new(_(F.BLOCK_DRAGGER,this.creatorWorkspace.options,!0))(e,t)}doStart(e){if(!this.startWorkspace_)throw Error("Cannot start the touch gesture becauase the start workspace is undefined");this.isPinchZoomEnabled=this.startWorkspace_.options.zoomOptions&&this.startWorkspace_.options.zoomOptions.pinch,kt(e)?this.cancel():(this.gestureHasStarted=!0,ji(),this.startWorkspace_.updateScreenCalculationsIfScrolled(),this.startWorkspace_.isMutator&&this.startWorkspace_.resize(),this.currentDropdownOwner=Ou(),this.startWorkspace_.hideChaff(!!this.flyout),this.startWorkspace_.markFocused(),this.mostRecentEvent=e,Zu(),ve(e)?this.handleRightClick(e):(e.type.toLowerCase()==="pointerdown"&&e.pointerType!=="mouse"&&Je(e,this),this.mouseDownXY=new G(e.clientX,e.clientY),this.bindMouseEvents(e),this.isEnding_||this.handleTouchStart(e)))}bindMouseEvents(e){this.boundEvents.push(X(document,"pointerdown",null,this.handleStart.bind(this),!0)),this.boundEvents.push(X(document,"pointermove",null,this.handleMove.bind(this),!0)),this.boundEvents.push(X(document,"pointerup",null,this.handleUp.bind(this),!0)),e.preventDefault(),e.stopPropagation()}handleStart(e){this.isDragging()||(this.handleTouchStart(e),this.isMultiTouch()&&_e())}handleMove(e){this.isDragging()&&$e(e)||!this.isMultiTouch()?(this.updateFromEvent(e),this.workspaceDragger?this.workspaceDragger.drag(this.currentDragDeltaXY):this.dragger&&this.dragger.onDrag(this.mostRecentEvent,this.currentDragDeltaXY),e.preventDefault(),e.stopPropagation()):this.isMultiTouch()&&(this.handleTouchMove(e),_e())}handleUp(e){if(this.isDragging()||this.handleTouchEnd(e),!this.isMultiTouch()||this.isDragging()){if(!$e(e))return;if(this.updateFromEvent(e),_e(),this.isEnding_){console.log("Trying to end a gesture recursively.");return}this.isEnding_=!0,this.dragger?this.dragger.onDragEnd(e,this.currentDragDeltaXY):this.workspaceDragger?this.workspaceDragger.endDrag(this.currentDragDeltaXY):this.isBubbleClick()||this.isCommentClick()||(this.isFieldClick()?this.doFieldClick():this.isIconClick()?this.doIconClick():this.isBlockClick()?this.doBlockClick():this.isWorkspaceClick()&&this.doWorkspaceClick(e))}e.preventDefault(),e.stopPropagation(),this.dispose()}handleTouchStart(e){var t=Pe(e);this.cachedPoints.set(t,this.getTouchPoint(e));var o=Array.from(this.cachedPoints.keys());o.length===2&&(t=this.cachedPoints.get(o[0]),o=this.cachedPoints.get(o[1]),this.startDistance=G.distance(t,o),this.multiTouch=!0,e.preventDefault())}handleTouchMove(e){const t=Pe(e);this.cachedPoints.set(t,this.getTouchPoint(e)),this.isPinchZoomEnabled&&this.cachedPoints.size===2?this.handlePinch(e):(this.updateFromEvent(e),this.workspaceDragger?this.workspaceDragger.drag(this.currentDragDeltaXY):this.dragger&&this.dragger.onDrag(this.mostRecentEvent,this.currentDragDeltaXY),e.preventDefault(),e.stopPropagation())}handlePinch(e){var t=Array.from(this.cachedPoints.keys()),o=this.cachedPoints.get(t[0]);if(t=this.cachedPoints.get(t[1]),o=G.distance(o,t)/this.startDistance,0this.previousScale){if(t=o-this.previousScale,t=0this.cachedPoints.size&&(this.cachedPoints.clear(),this.previousScale=0)}getTouchPoint(e){return this.startWorkspace_?new G(e.pageX,e.pageY):null}isMultiTouch(){return this.multiTouch}cancel(){this.isEnding_||(_e(),this.dragger?this.dragger.onDragEnd(this.mostRecentEvent,this.currentDragDeltaXY):this.workspaceDragger&&this.workspaceDragger.endDrag(this.currentDragDeltaXY),this.dispose())}handleRightClick(e){this.targetBlock?(this.bringBlockToFront(),this.targetBlock.workspace.hideChaff(!!this.flyout),this.targetBlock.showContextMenu(e)):this.startBubble?this.startBubble.showContextMenu(e):this.startComment?(this.startComment.workspace.hideChaff(),this.startComment.showContextMenu(e)):this.startWorkspace_&&!this.flyout&&(this.startWorkspace_.hideChaff(),this.startWorkspace_.showContextMenu(e)),e.preventDefault(),e.stopPropagation(),this.dispose()}handleWsStart(e,t){if(this.gestureHasStarted)throw Error("Tried to call gesture.handleWsStart, but the gesture had already been started.");this.setStartWorkspace(t),this.mostRecentEvent=e,this.startBlock||this.startBubble||this.startComment||i.setSelected$$module$build$src$core$common(null),this.doStart(e)}fireWorkspaceClick(e){z(new(V(O.CLICK))(null,e.id,"workspace"))}handleFlyoutStart(e,t){if(this.gestureHasStarted)throw Error("Tried to call gesture.handleFlyoutStart, but the gesture had already been started.");this.setStartFlyout(t),this.handleWsStart(e,t.getWorkspace())}handleBlockStart(e,t){if(this.gestureHasStarted)throw Error("Tried to call gesture.handleBlockStart, but the gesture had already been started.");this.setStartBlock(t),this.mostRecentEvent=e}handleBubbleStart(e,t){if(this.gestureHasStarted)throw Error("Tried to call gesture.handleBubbleStart, but the gesture had already been started.");this.setStartBubble(t),this.mostRecentEvent=e}handleCommentStart(e,t){if(this.gestureHasStarted)throw Error("Tried to call gesture.handleCommentStart, but the gesture had already been started.");this.setStartComment(t),this.mostRecentEvent=e}doFieldClick(){if(!this.startField)throw Error("Cannot do a field click because the start field is undefined");this.currentDropdownOwner!==this.startField&&this.startField.showEditor(this.mostRecentEvent),this.bringBlockToFront()}doIconClick(){if(!this.startIcon)throw Error("Cannot do an icon click because the start icon is undefined");this.bringBlockToFront(),this.startIcon.onClick()}doBlockClick(){if(this.flyout&&this.flyout.autoClose){if(!this.targetBlock)throw Error("Cannot do a block click because the target block is undefined");if(this.targetBlock.isEnabled()){i.getGroup$$module$build$src$core$events$utils()||i.setGroup$$module$build$src$core$events$utils(!0);var e=this.flyout.createBlock(this.targetBlock);e.snapToGrid(),e.bumpNeighbours()}}else{if(!this.startWorkspace_)throw Error("Cannot do a block click because the start workspace is undefined");e=new(V(O.CLICK))(this.startBlock,this.startWorkspace_.id,"block"),z(e)}this.bringBlockToFront(),i.setGroup$$module$build$src$core$events$utils(!1)}doWorkspaceClick(e){e=this.creatorWorkspace,I()&&I().unselect(),this.fireWorkspaceClick(this.startWorkspace_||e)}bringBlockToFront(){this.targetBlock&&!this.flyout&&this.targetBlock.bringToFront()}setStartField(e){if(this.gestureHasStarted)throw Error("Tried to call gesture.setStartField, but the gesture had already been started.");this.startField||(this.startField=e)}setStartIcon(e){if(this.gestureHasStarted)throw Error("Tried to call gesture.setStartIcon, but the gesture had already been started.");this.startIcon||(this.startIcon=e)}setStartBubble(e){this.startBubble||(this.startBubble=e)}setStartComment(e){this.startComment||(this.startComment=e)}setStartBlock(e){this.startBlock||this.startBubble||(this.startBlock=e,i.setSelected$$module$build$src$core$common(this.startBlock),e.isInFlyout&&e!==e.getRootBlock()?this.setTargetBlock(e.getRootBlock()):this.setTargetBlock(e))}setTargetBlock(e){e.isShadow()?this.setTargetBlock(e.getParent()):this.targetBlock=e}setStartWorkspace(e){this.startWorkspace_||(this.startWorkspace_=e)}setStartFlyout(e){this.flyout||(this.flyout=e)}isBubbleClick(){return!!this.startBubble&&!this.hasExceededDragRadius}isCommentClick(){return!!this.startComment&&!this.hasExceededDragRadius}isBlockClick(){return!!this.startBlock&&!this.hasExceededDragRadius&&!this.isFieldClick()&&!this.isIconClick()}isFieldClick(){return this.startField?this.startField.isClickable()&&!this.hasExceededDragRadius&&(!this.flyout||this.startField.isClickableInFlyout(this.flyout.autoClose)):!1}isIconClick(){if(!this.startIcon)return!1;const e=!this.flyout||!this.startIcon.isClickableInFlyout||this.startIcon.isClickableInFlyout(this.flyout.autoClose);return!this.hasExceededDragRadius&&e}isWorkspaceClick(){return!this.startBlock&&!this.startBubble&&!this.startField&&!this.hasExceededDragRadius}getCurrentDragger(){let e,t;return(t=(e=this.workspaceDragger)!=null?e:this.dragger)!=null?t:null}isDragging(){return this.dragging}hasStarted(){return this.gestureHasStarted}static inProgress(){const e=ee();for(let t=0,o;o=e[t];t++)if(o.currentGesture_)return!0;return!1}},ep=class{constructor(e,t){this.pattern=e,this.scale=1;let o;this.spacing=(o=t.spacing)!=null?o:0;let n;this.length=(n=t.length)!=null?n:1,this.line2=(this.line1=e.firstChild)&&this.line1.nextSibling;let c;this.snapToGrid=(c=t.snap)!=null?c:!1}setSpacing(e){this.spacing=e,this.update(this.scale)}getSpacing(){return this.spacing}setLength(e){this.length=e,this.update(this.scale)}getLength(){return this.length}setSnapToGrid(e){this.snapToGrid=e}shouldSnap(){return this.snapToGrid}getPatternId(){return this.pattern.id}update(e){this.scale=e;var t=this.spacing*e;this.pattern.setAttribute("width",`${t}`),this.pattern.setAttribute("height",`${t}`),t=Math.floor(this.spacing/2)+.5;let o=t-this.length/2,n=t+this.length/2;t*=e,o*=e,n*=e,this.setLineAttributes(this.line1,e,o,n,t,t),this.setLineAttributes(this.line2,e,t,t,o,n)}setLineAttributes(e,t,o,n,c,h){e&&(e.setAttribute("stroke-width",`${t}`),e.setAttribute("x1",`${o}`),e.setAttribute("y1",`${c}`),e.setAttribute("x2",`${n}`),e.setAttribute("y2",`${h}`))}moveTo(e,t){this.pattern.setAttribute("x",`${e}`),this.pattern.setAttribute("y",`${t}`)}alignXY(e){var t=this.getSpacing();const o=t/2,n=Math.round(Math.round((e.x-o)/t)*t+o);return t=Math.round(Math.round((e.y-o)/t)*t+o),n===e.x&&t===e.y?e:new G(n,t)}static createDom(e,t,o){e=N(x.PATTERN,{id:"blocklyGridPattern"+e,patternUnits:"userSpaceOnUse"},o);let n,c;if(0<((n=t.length)!=null?n:1)&&0<((c=t.spacing)!=null?c:0)){N(x.LINE,{stroke:t.colour},e);let h;(h=t.length)!=null&&h&&N(x.LINE,{stroke:t.colour},e)}else N(x.LINE,{},e);return e}},KT=class{constructor(e){this.workspace=e,this.layers=new Map,(e=e.getInjectionDiv())&&(this.dragLayer=this.createDragLayer(e),this.animationLayer=this.createAnimationLayer(e)),e=this.createLayer(Do),ge(e,"blocklyBlockCanvas"),e=this.createLayer(Cl),ge(e,"blocklyBubbleCanvas")}createDragLayer(e){const t=N(x.SVG,{class:"blocklyBlockDragSurface",xmlns:rr,"xmlns:html":Fs,"xmlns:xlink":es,version:"1.1"});return e.append(t),N(x.G,{},t)}createAnimationLayer(e){const t=N(x.SVG,{class:"blocklyAnimationLayer",xmlns:rr,"xmlns:html":Fs,"xmlns:xlink":es,version:"1.1"});return e.append(t),N(x.G,{},t)}appendToAnimationLayer(e){let t;const o=(t=this.dragLayer)==null?void 0:t.getAttribute("transform");if(o){let c;(c=this.animationLayer)==null||c.setAttribute("transform",o)}let n;(n=this.animationLayer)==null||n.appendChild(e.getSvgRoot())}translateLayers(e,t){e=`translate(${e.x}, ${e.y}) scale(${t})`;let o;(o=this.dragLayer)==null||o.setAttribute("transform",e);for(const[,n]of this.layers)n.setAttribute("transform",e)}moveToDragLayer(e){let t;(t=this.dragLayer)==null||t.appendChild(e.getSvgRoot())}moveOffDragLayer(e,t){this.append(e,t)}append(e,t){this.layers.has(t)||this.createLayer(t);let o;(o=this.layers.get(t))==null||o.appendChild(e.getSvgRoot())}createLayer(e){const t=this.workspace.getSvgGroup(),o=N(x.G,{});let n=!1;const c=[...this.layers].sort((h,$)=>h[0]-$[0]);for(const[h,$]of c)if(et[1]===e)?e:(this.sourceBlock_&&console.warn("Cannot set the dropdown's value to an unavailable option. Block type: "+this.sourceBlock_.type+", Field name: "+this.name+", Value: "+e),null)}doValueUpdate_(e){super.doValueUpdate_(e),e=this.getOptions(!0);for(let t=0,o;o=e[t];t++)o[1]===this.value_&&(this.selectedOption=o)}applyColour(){const e=this.sourceBlock_;this.borderRect_&&(this.borderRect_.setAttribute("stroke",e.getColourTertiary()),this.menu_?this.borderRect_.setAttribute("fill",e.getColourTertiary()):this.borderRect_.setAttribute("fill","transparent")),e&&this.arrow&&(e.isShadow()?this.arrow.style.fill=e.getColourSecondary():this.arrow.style.fill=e.getColour())}render_(){this.getTextContent().nodeValue="",this.imageElement.style.display="none";const e=this.selectedOption&&this.selectedOption[0];e&&typeof e=="object"?this.renderSelectedImage(e):this.renderSelectedText(),this.positionBorderRect_()}renderSelectedImage(e){const t=this.getSourceBlock();if(!t)throw new ft;this.imageElement.style.display="",this.imageElement.setAttributeNS(es,"xlink:href",e.src),this.imageElement.setAttribute("height",String(e.height)),this.imageElement.setAttribute("width",String(e.width));const o=Number(e.height);e=Number(e.width);var n=!!this.borderRect_;const c=Math.max(n?this.getConstants().FIELD_DROPDOWN_BORDER_RECT_HEIGHT:0,o+qt.IMAGE_Y_PADDING);n=n?this.getConstants().FIELD_BORDER_RECT_X_PADDING:0;let h;h=this.svgArrow?this.positionSVGArrow(e+n,c/2-this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE/2):Nn(this.arrow,this.getConstants().FIELD_TEXT_FONTSIZE,this.getConstants().FIELD_TEXT_FONTWEIGHT,this.getConstants().FIELD_TEXT_FONTFAMILY),this.size_.width=e+h+2*n,this.size_.height=c;let $=0;t.RTL?this.imageElement.setAttribute("x",`${n+h}`):($=e+h,this.getTextElement().setAttribute("text-anchor","end"),this.imageElement.setAttribute("x",`${n}`)),this.imageElement.setAttribute("y",String(c/2-o/2)),this.positionTextElement_($+n,e+h)}renderSelectedText(){this.getTextContent().nodeValue=this.getDisplayText_();var e=this.getTextElement();ge(e,"blocklyDropdownText"),e.setAttribute("text-anchor","start");var t=!!this.borderRect_;e=Math.max(t?this.getConstants().FIELD_DROPDOWN_BORDER_RECT_HEIGHT:0,this.getConstants().FIELD_TEXT_HEIGHT);const o=Nn(this.getTextElement(),this.getConstants().FIELD_TEXT_FONTSIZE,this.getConstants().FIELD_TEXT_FONTWEIGHT,this.getConstants().FIELD_TEXT_FONTFAMILY);t=t?this.getConstants().FIELD_BORDER_RECT_X_PADDING:0;let n=0;this.svgArrow&&(n=this.positionSVGArrow(o+t,e/2-this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE/2)),this.size_.width=o+n+2*t,this.size_.height=e,this.positionTextElement_(t,o)}positionSVGArrow(e,t){if(!this.svgArrow)return 0;const o=this.getSourceBlock();if(!o)throw new ft;const n=this.borderRect_?this.getConstants().FIELD_BORDER_RECT_X_PADDING:0,c=this.getConstants().FIELD_DROPDOWN_SVG_ARROW_PADDING,h=this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE;return this.svgArrow.setAttribute("transform","translate("+(o.RTL?n:e+c)+","+t+")"),h+c}getText_(){if(!this.selectedOption)return null;const e=this.selectedOption[0];return typeof e=="object"?e.alt:e}static fromJson(e){if(!e.options)throw Error("options are required for the dropdown field. The options property must be assigned an array of [humanReadableValue, languageNeutralValue] tuples.");return new this(e.options,void 0,e)}trimOptions(e){let t=!1;const o=e.map(([$,T])=>typeof $=="string"?[pt($),T]:(t=!0,[$.alt!==null?Object.assign({},$,{alt:pt($.alt)}):Object.assign({},$),T]));if(t||2>e.length)return{options:o};var n=o.map(([$])=>$),c=Vn(n);e=Gu(n,c);const h=Vu(n,c);return!e&&!h||c<=e+h?{options:o}:(c=e?n[0].substring(0,e-1):void 0,n=h?n[0].substr(1-h):void 0,{options:this.applyTrim(o,e,h),prefix:c,suffix:n})}applyTrim(e,t,o){return e.map(([n,c])=>[n.substring(t,n.length-o),c])}validateOptions(e){if(!Array.isArray(e))throw TypeError("FieldDropdown options must be an array.");if(!e.length)throw TypeError("FieldDropdown options must not be an empty array.");let t=!1;for(let o=0;oe.width)return t;if(e=this.getWorkspaceViewRect(e),this.workspace.RTL){var o=this.anchor.x-t;o-this.size.widthe.right&&(t=-(e.right-this.anchor.x))}else{o=t+this.anchor.x;const n=o+this.size.width;oe.right&&(t=e.right-this.anchor.x-this.size.width)}return t}getOptimalRelativeTop(e){let t=-this.size.height/4;if(this.size.height>e.height)return t;const o=this.anchor.y+t,n=o+this.size.height;return e=this.getWorkspaceViewRect(e),oe.bottom&&(t=e.bottom-this.anchor.y-this.size.height),t}getWorkspaceViewRect(e){const t=e.top;let o=e.top+e.height,n=e.left;return e=e.left+e.width,o-=this.getScrollbarThickness(),this.workspace.RTL?n-=this.getScrollbarThickness():e-=this.getScrollbarThickness(),new qe(t,o,n,e)}getScrollbarThickness(){return mt.scrollbarThickness/this.workspace.scale}renderTail(){const e=[];var t=this.size.width/2,o=this.size.height/2,n=-this.relativeLeft,c=-this.relativeTop;if(t===n&&o===c)e.push("M "+t+","+o);else{c-=o,n-=t,this.workspace.RTL&&(n*=-1);var h=Math.sqrt(c*c+n*n),$=Math.acos(n/h);0>c&&($=2*Math.PI-$);var T=$+Math.PI/2;T>2*Math.PI&&(T-=2*Math.PI);var L=Math.sin(T);const nt=Math.cos(T);let it=(this.size.width+this.size.height)/ss.TAIL_THICKNESS;it=Math.min(it,this.size.width,this.size.height)/4,T=1-ss.ANCHOR_RADIUS/h,n=t+T*n,c=o+T*c,T=t+it*nt;const Xt=o+it*L;t-=it*nt,o-=it*L,L=Ia(this.workspace.RTL?-ss.TAIL_ANGLE:ss.TAIL_ANGLE),L=$+L,L>2*Math.PI&&(L-=2*Math.PI),$=Math.sin(L)*h/ss.TAIL_BEND,h=Math.cos(L)*h/ss.TAIL_BEND,e.push("M"+T+","+Xt),e.push("C"+(T+h)+","+(Xt+$)+" "+n+","+c+" "+n+","+c),e.push("C"+n+","+c+" "+(t+h)+","+(o+$)+" "+t+","+o)}e.push("z");let te;(te=this.tail)==null||te.setAttribute("d",e.join(" "))}bringToFront(){let e;const t=(e=this.svgRoot)==null?void 0:e.parentNode;return this.svgRoot&&(t==null?void 0:t.lastChild)!==this.svgRoot?(t==null||t.appendChild(this.svgRoot),!0):!1}getRelativeToSurfaceXY(){return new G(this.workspace.RTL?-this.relativeLeft+this.anchor.x-this.size.width:this.anchor.x+this.relativeLeft,this.anchor.y+this.relativeTop)}getSvgRoot(){return this.svgRoot}moveDuringDrag(e){this.moveTo(e.x,e.y),this.relativeLeft=this.workspace.RTL?this.anchor.x-e.x-this.size.width:e.x-this.anchor.x,this.relativeTop=e.y-this.anchor.y,this.renderTail()}setDragging(e){}setDeleteStyle(e){}isDeletable(){return!1}showContextMenu(e){}isMovable(){return!0}startDrag(){this.dragStrategy.startDrag()}drag(e){this.dragStrategy.drag(e)}endDrag(){this.dragStrategy.endDrag()}revertDrag(){this.dragStrategy.revertDrag()}select(){}unselect(){}};ss=Ye,Ye.BORDER_WIDTH=6,Ye.DOUBLE_BORDER=2*ss.BORDER_WIDTH,Ye.MIN_SIZE=ss.DOUBLE_BORDER,Ye.TAIL_THICKNESS=1,Ye.TAIL_ANGLE=20,Ye.TAIL_BEND=4,Ye.ANCHOR_RADIUS=8;var uo=class extends Ye{constructor(e,t,o,n){super(t,o,n),this.workspace=t,this.anchor=o,this.ownerRect=n,this.autoLayout=!0,t=new ds(e),this.validateWorkspaceOptions(t),this.svgDialog=N(x.SVG,{x:Ye.BORDER_WIDTH,y:Ye.BORDER_WIDTH},this.contentContainer),e.parentWorkspace=this.workspace,this.miniWorkspace=this.newWorkspaceSvg(new ds(e)),this.miniWorkspace.internalIsMutator=!0,e=this.miniWorkspace.createDom("blocklyMutatorBackground"),this.svgDialog.appendChild(e),t.languageTree&&(e.insertBefore(this.miniWorkspace.addFlyout(x.G),this.miniWorkspace.getCanvas()),e=this.miniWorkspace.getFlyout(),e==null||e.init(this.miniWorkspace),e==null||e.show(t.languageTree)),this.miniWorkspace.addChangeListener(this.onWorkspaceChange.bind(this));let c,h;(c=this.miniWorkspace.getFlyout())==null||(h=c.getWorkspace())==null||h.addChangeListener(this.onWorkspaceChange.bind(this)),this.updateBubbleSize()}dispose(){this.miniWorkspace.dispose(),super.dispose()}getWorkspace(){return this.miniWorkspace}addWorkspaceChangeListener(e){this.miniWorkspace.addChangeListener(e)}validateWorkspaceOptions(e){if(e.hasCategories)throw Error("The miniworkspace bubble does not support toolboxes with categories");if(e.hasTrashcan)throw Error("The miniworkspace bubble does not support trashcans");if(e.zoomOptions.controls||e.zoomOptions.wheel||e.zoomOptions.pinch)throw Error("The miniworkspace bubble does not support zooming");if(e.moveOptions.scrollbars||e.moveOptions.wheel||e.moveOptions.drag)throw Error("The miniworkspace bubble does not scrolling/moving the workspace");if(e.horizontalLayout)throw Error("The miniworkspace bubble does not support horizontal layouts")}onWorkspaceChange(){this.bumpBlocksIntoBounds(),this.updateBubbleSize()}bumpBlocksIntoBounds(){if(!this.miniWorkspace.isDragging())for(const e of this.miniWorkspace.getTopBlocks(!1)){const t=e.getRelativeToSurfaceXY();if(20>t.y&&e.moveBy(0,20-t.y),e.RTL){let o=-20;const n=this.miniWorkspace.getFlyout();n&&(o-=n.getWidth()),t.x>o&&e.moveBy(o-t.x,0)}else 20>t.x&&e.moveBy(20-t.x,0)}}updateBubbleSize(){if(!this.miniWorkspace.isDragging()){var e=this.getSize(),t=this.calculateWorkspaceSize();Math.abs(e.width-t.width)({kind:"block",type:o}))}),t}getAnchorLocation(){const e=Dl/2;return G.sum(this.workspaceLocation,new G(e,e))}getBubbleOwnerRect(){const e=this.sourceBlock.getSvgRoot().getBBox();return new qe(e.y,e.y+e.height,e.x,e.x+e.width)}createRootBlock(){if(!this.sourceBlock.decompose)throw Error("Blocks with mutator icons must include a decompose method");this.rootBlock=this.sourceBlock.decompose(this.miniWorkspaceBubble.getWorkspace());for(var e of this.rootBlock.getDescendants(!1))e.queueRender();this.rootBlock.setMovable(!1),this.rootBlock.setDeletable(!1);let t,o,n,c;e=(c=(t=this.miniWorkspaceBubble)==null||(o=t.getWorkspace())==null||(n=o.getFlyout())==null?void 0:n.getWidth())!=null?c:0,this.rootBlock.moveBy(this.rootBlock.RTL?-(e+Al):Al,Al)}addSaveConnectionsListener(){this.sourceBlock.saveConnections&&this.rootBlock&&(this.saveConnectionsListener=()=>{this.sourceBlock.saveConnections&&this.rootBlock&&this.sourceBlock.saveConnections(this.rootBlock)},this.saveConnectionsListener(),this.sourceBlock.workspace.addChangeListener(this.saveConnectionsListener))}createMiniWorkspaceChangeListener(){return e=>{i.MutatorIcon$$module$build$src$core$icons$mutator_icon.isIgnorableMutatorEvent(e)||this.updateWorkspacePid||(this.updateWorkspacePid=setTimeout(()=>{this.updateWorkspacePid=null,this.recomposeSourceBlock()},0))}}static isIgnorableMutatorEvent(e){return e.isUiEvent||w(e)||R(e)&&e.element==="disabled"}recomposeSourceBlock(){if(this.rootBlock){if(!this.sourceBlock.compose)throw Error("Blocks with mutator icons must include a compose method");var e=i.getGroup$$module$build$src$core$events$utils();e||i.setGroup$$module$build$src$core$events$utils(!0);var t=ri.getExtraBlockState_(this.sourceBlock);this.sourceBlock.compose(this.rootBlock);var o=ri.getExtraBlockState_(this.sourceBlock);t!==o&&z(new(V(O.BLOCK_CHANGE))(this.sourceBlock,"mutation",null,t,o)),i.setGroup$$module$build$src$core$events$utils(e)}}getWorkspace(){let e;return(e=this.miniWorkspaceBubble)==null?void 0:e.getWorkspace()}},i.MutatorIcon$$module$build$src$core$icons$mutator_icon.TYPE=yt.MUTATOR,i.MutatorIcon$$module$build$src$core$icons$mutator_icon.WEIGHT=1,i.MutatorIcon$$module$build$src$core$icons$mutator_icon;var sn=Object.create(null),qT={allExtensions:sn};i.register$$module$build$src$core$extensions("parent_tooltip_when_inline",x$);var Is={TEST_ONLY:qT};Is.apply=Ha,Is.buildTooltipForDropdown=i.buildTooltipForDropdown$$module$build$src$core$extensions,Is.buildTooltipWithFieldText=i.buildTooltipWithFieldText$$module$build$src$core$extensions,Is.isRegistered=_d,Is.register=i.register$$module$build$src$core$extensions,Is.registerMixin=i.registerMixin$$module$build$src$core$extensions,Is.registerMutator=i.registerMutator$$module$build$src$core$extensions,Is.runAfterPageLoad=E$,Is.unregister=w$;var Ae;(function(e){e[e.WIN_KEY_FF_LINUX=0]="WIN_KEY_FF_LINUX",e[e.MAC_ENTER=3]="MAC_ENTER",e[e.BACKSPACE=8]="BACKSPACE",e[e.TAB=9]="TAB",e[e.NUM_CENTER=12]="NUM_CENTER",e[e.ENTER=13]="ENTER",e[e.SHIFT=16]="SHIFT",e[e.CTRL=17]="CTRL",e[e.ALT=18]="ALT",e[e.PAUSE=19]="PAUSE",e[e.CAPS_LOCK=20]="CAPS_LOCK",e[e.ESC=27]="ESC",e[e.SPACE=32]="SPACE",e[e.PAGE_UP=33]="PAGE_UP",e[e.PAGE_DOWN=34]="PAGE_DOWN",e[e.END=35]="END",e[e.HOME=36]="HOME",e[e.LEFT=37]="LEFT",e[e.UP=38]="UP",e[e.RIGHT=39]="RIGHT",e[e.DOWN=40]="DOWN",e[e.PLUS_SIGN=43]="PLUS_SIGN",e[e.PRINT_SCREEN=44]="PRINT_SCREEN",e[e.INSERT=45]="INSERT",e[e.DELETE=46]="DELETE",e[e.ZERO=48]="ZERO",e[e.ONE=49]="ONE",e[e.TWO=50]="TWO",e[e.THREE=51]="THREE",e[e.FOUR=52]="FOUR",e[e.FIVE=53]="FIVE",e[e.SIX=54]="SIX",e[e.SEVEN=55]="SEVEN",e[e.EIGHT=56]="EIGHT",e[e.NINE=57]="NINE",e[e.FF_SEMICOLON=59]="FF_SEMICOLON",e[e.FF_EQUALS=61]="FF_EQUALS",e[e.FF_DASH=173]="FF_DASH",e[e.FF_HASH=163]="FF_HASH",e[e.QUESTION_MARK=63]="QUESTION_MARK",e[e.AT_SIGN=64]="AT_SIGN",e[e.A=65]="A",e[e.B=66]="B",e[e.C=67]="C",e[e.D=68]="D",e[e.E=69]="E",e[e.F=70]="F",e[e.G=71]="G",e[e.H=72]="H",e[e.I=73]="I",e[e.J=74]="J",e[e.K=75]="K",e[e.L=76]="L",e[e.M=77]="M",e[e.N=78]="N",e[e.O=79]="O",e[e.P=80]="P",e[e.Q=81]="Q",e[e.R=82]="R",e[e.S=83]="S",e[e.T=84]="T",e[e.U=85]="U",e[e.V=86]="V",e[e.W=87]="W",e[e.X=88]="X",e[e.Y=89]="Y",e[e.Z=90]="Z",e[e.META=91]="META",e[e.WIN_KEY_RIGHT=92]="WIN_KEY_RIGHT",e[e.CONTEXT_MENU=93]="CONTEXT_MENU",e[e.NUM_ZERO=96]="NUM_ZERO",e[e.NUM_ONE=97]="NUM_ONE",e[e.NUM_TWO=98]="NUM_TWO",e[e.NUM_THREE=99]="NUM_THREE",e[e.NUM_FOUR=100]="NUM_FOUR",e[e.NUM_FIVE=101]="NUM_FIVE",e[e.NUM_SIX=102]="NUM_SIX",e[e.NUM_SEVEN=103]="NUM_SEVEN",e[e.NUM_EIGHT=104]="NUM_EIGHT",e[e.NUM_NINE=105]="NUM_NINE",e[e.NUM_MULTIPLY=106]="NUM_MULTIPLY",e[e.NUM_PLUS=107]="NUM_PLUS",e[e.NUM_MINUS=109]="NUM_MINUS",e[e.NUM_PERIOD=110]="NUM_PERIOD",e[e.NUM_DIVISION=111]="NUM_DIVISION",e[e.F1=112]="F1",e[e.F2=113]="F2",e[e.F3=114]="F3",e[e.F4=115]="F4",e[e.F5=116]="F5",e[e.F6=117]="F6",e[e.F7=118]="F7",e[e.F8=119]="F8",e[e.F9=120]="F9",e[e.F10=121]="F10",e[e.F11=122]="F11",e[e.F12=123]="F12",e[e.NUMLOCK=144]="NUMLOCK",e[e.SCROLL_LOCK=145]="SCROLL_LOCK",e[e.FIRST_MEDIA_KEY=166]="FIRST_MEDIA_KEY",e[e.LAST_MEDIA_KEY=183]="LAST_MEDIA_KEY",e[e.SEMICOLON=186]="SEMICOLON",e[e.DASH=189]="DASH",e[e.EQUALS=187]="EQUALS",e[e.COMMA=188]="COMMA",e[e.PERIOD=190]="PERIOD",e[e.SLASH=191]="SLASH",e[e.APOSTROPHE=192]="APOSTROPHE",e[e.TILDE=192]="TILDE",e[e.SINGLE_QUOTE=222]="SINGLE_QUOTE",e[e.OPEN_SQUARE_BRACKET=219]="OPEN_SQUARE_BRACKET",e[e.BACKSLASH=220]="BACKSLASH",e[e.CLOSE_SQUARE_BRACKET=221]="CLOSE_SQUARE_BRACKET",e[e.WIN_KEY=224]="WIN_KEY",e[e.MAC_FF_META=224]="MAC_FF_META",e[e.MAC_WK_CMD_LEFT=91]="MAC_WK_CMD_LEFT",e[e.MAC_WK_CMD_RIGHT=93]="MAC_WK_CMD_RIGHT",e[e.WIN_IME=229]="WIN_IME",e[e.VK_NONAME=252]="VK_NONAME",e[e.PHANTOM=255]="PHANTOM"})(Ae||(Ae={}));var ho={};ho.arc=gt,ho.curve=Yt,ho.line=Fi,ho.lineOnAxis=ne,ho.lineTo=Bs,ho.moveBy=at,ho.moveTo=wt,ho.point=ue;var ut={};ut.Coordinate=G,ut.KeyCodes=Ae,ut.Rect=qe,ut.Size=Le,ut.Svg=x,ut.aria=cr,ut.array=Ob,ut.browserEvents=no,ut.colour=us,ut.deprecation=hb,ut.dom=xt,ut.extensions=Is,ut.idGenerator=ph,ut.math=gl,ut.object=$v,ut.parsing=br,ut.string=qi,ut.style=So,ut.svgMath=ti,ut.svgPaths=ho,ut.toolbox=Eo,ut.userAgent=LT,ut.xml=Hi;var yv=class extends Ye{constructor(e,t,o){super(e,t,o),this.workspace=e,this.anchor=t,this.ownerRect=o,this.resizePointerMoveListener=this.resizePointerUpListener=null,this.textChangeListeners=[],this.sizeChangeListeners=[],this.text="",this.DEFAULT_SIZE=new Le(160+Ye.DOUBLE_BORDER,80+Ye.DOUBLE_BORDER),this.MIN_SIZE=new Le(45+Ye.DOUBLE_BORDER,20+Ye.DOUBLE_BORDER),this.editable=!0,ge(this.svgRoot,"blocklyTextInputBubble"),{inputRoot:this.inputRoot,textArea:this.textArea}=this.createEditor(this.contentContainer),this.resizeGroup=this.createResizeHandle(this.svgRoot,e),this.setSize(this.DEFAULT_SIZE,!0)}getText(){return this.text}setText(e){this.text=e,this.textArea.value=e,this.onTextChange()}setEditable(e){(this.editable=e)?this.textArea.removeAttribute("readonly"):this.textArea.setAttribute("readonly","")}isEditable(){return this.editable}addTextChangeListener(e){this.textChangeListeners.push(e)}addSizeChangeListener(e){this.sizeChangeListeners.push(e)}createEditor(e){e=N(x.FOREIGNOBJECT,{x:Ye.BORDER_WIDTH,y:Ye.BORDER_WIDTH},e);const t=document.createElementNS(Fs,"body");t.setAttribute("xmlns",Fs),t.className="blocklyMinimalBody";const o=document.createElementNS(Fs,"textarea");return o.className="blocklyTextarea blocklyText",o.setAttribute("dir",this.workspace.RTL?"RTL":"LTR"),t.appendChild(o),e.appendChild(t),this.bindTextAreaEvents(o),setTimeout(()=>{o.focus()},0),{inputRoot:e,textArea:o}}bindTextAreaEvents(e){X(e,"wheel",this,t=>{t.stopPropagation()}),X(e,"focus",this,this.onStartEdit,!0),X(e,"change",this,this.onTextChange)}createResizeHandle(e,t){return e=N(x.IMAGE,{class:"blocklyResizeHandle",href:`${t.options.pathToMedia}resize-handle.svg`},e),X(e,"pointerdown",this,this.onResizePointerDown),e}setSize(e,t=!1){e.width=Math.max(e.width,this.MIN_SIZE.width),e.height=Math.max(e.height,this.MIN_SIZE.height);const o=e.width-Ye.DOUBLE_BORDER,n=e.height-Ye.DOUBLE_BORDER;this.inputRoot.setAttribute("width",`${o}`),this.inputRoot.setAttribute("height",`${n}`),this.resizeGroup.setAttribute("y",`${n}`),this.workspace.RTL?this.resizeGroup.setAttribute("x",`${-Ye.DOUBLE_BORDER}`):this.resizeGroup.setAttribute("x",`${o}`),super.setSize(e,t),this.onSizeChange()}getSize(){return super.getSize()}onResizePointerDown(e){this.bringToFront(),ve(e)||(Ba(this.workspace,e,new G(this.workspace.RTL?-this.getSize().width:this.getSize().width,this.getSize().height)),this.resizePointerUpListener=X(document,"pointerup",this,this.onResizePointerUp),this.resizePointerMoveListener=X(document,"pointermove",this,this.onResizePointerMove),this.workspace.hideChaff()),e.stopPropagation()}onResizePointerUp(e){ke(),this.resizePointerUpListener&&(ze(this.resizePointerUpListener),this.resizePointerUpListener=null),this.resizePointerMoveListener&&(ze(this.resizePointerMoveListener),this.resizePointerMoveListener=null)}onResizePointerMove(e){e=ja(this.workspace,e),this.setSize(new Le(this.workspace.RTL?-e.x:e.x,e.y),!1),this.onSizeChange()}onStartEdit(){this.bringToFront()&&this.textArea.focus()}onTextChange(){this.text=this.textArea.value;for(const e of this.textChangeListeners)e()}onSizeChange(){for(const e of this.sizeChangeListeners)e()}};Et(` -.blocklyTextInputBubble .blocklyTextarea { - background-color: var(--commentFillColour); - border: 0; - box-sizing: border-box; - display: block; - outline: 0; - padding: 5px; - resize: none; - width: 100%; - height: 100%; -} -`);var tp={};tp.register=Td,tp.unregister=D$;var sp=17,_v=160,wv=80,po=class extends xl{constructor(e){super(e),this.sourceBlock=e,this.textInputBubble=null,this.text="",this.bubbleSize=new Le(_v,wv),this.bubbleVisiblity=!1}getType(){return po.TYPE}initView(e){this.svgRoot||(super.initView(e),N(x.CIRCLE,{class:"blocklyIconShape",r:"8",cx:"8",cy:"8"},this.svgRoot),N(x.PATH,{class:"blocklyIconSymbol",d:"m6.8,10h2c0.003,-0.617 0.271,-0.962 0.633,-1.266 2.875,-2.4050.607,-5.534 -3.765,-3.874v1.7c3.12,-1.657 3.698,0.118 2.336,1.25-1.201,0.998 -1.201,1.528 -1.204,2.19z"},this.svgRoot),N(x.RECT,{class:"blocklyIconSymbol",x:"6.8",y:"10.78",height:"2",width:"2"},this.svgRoot),ge(this.svgRoot,"blockly-icon-comment"))}dispose(){super.dispose();let e;(e=this.textInputBubble)==null||e.dispose()}getWeight(){return po.WEIGHT}getSize(){return new Le(sp,sp)}applyColour(){super.applyColour();const e=this.sourceBlock.getColour();let t;(t=this.textInputBubble)==null||t.setColour(e)}updateEditable(){const e=this,t=()=>super.updateEditable;return j.asyncExecutePromiseGeneratorFunction(function*(){t().call(e),e.bubbleIsVisible()&&(yield e.setBubbleVisible(!1),yield e.setBubbleVisible(!0))})}onLocationChange(e){super.onLocationChange(e),e=this.getAnchorLocation();let t;(t=this.textInputBubble)==null||t.setAnchorLocation(e)}setText(e){const t=this.text;z(new(V(O.BLOCK_CHANGE))(this.sourceBlock,"comment",null,t,e)),this.text=e;let o;(o=this.textInputBubble)==null||o.setText(this.text)}getText(){return this.text}setBubbleSize(e){this.bubbleSize=e;let t;(t=this.textInputBubble)==null||t.setSize(this.bubbleSize,!0)}getBubbleSize(){return this.bubbleSize}saveState(){return this.text?{text:this.text,pinned:this.bubbleIsVisible(),height:this.bubbleSize.height,width:this.bubbleSize.width}:null}loadState(e){let t;this.text=(t=e.text)!=null?t:"";let o,n;this.bubbleSize=new Le((o=e.width)!=null?o:_v,(n=e.height)!=null?n:wv);let c;this.bubbleVisiblity=(c=e.pinned)!=null?c:!1,this.setBubbleVisible(this.bubbleVisiblity)}onClick(){super.onClick(),this.setBubbleVisible(!this.bubbleIsVisible())}isClickableInFlyout(){return!1}onTextChange(){if(this.textInputBubble){var e=this.textInputBubble.getText();this.text!==e&&(z(new(V(O.BLOCK_CHANGE))(this.sourceBlock,"comment",null,this.text,e)),this.text=e)}}onSizeChange(){this.textInputBubble&&(this.bubbleSize=this.textInputBubble.getSize())}bubbleIsVisible(){return this.bubbleVisiblity}setBubbleVisible(e){const t=this;return j.asyncExecutePromiseGeneratorFunction(function*(){t.bubbleVisiblity!==e&&(t.bubbleVisiblity=e,yield ws(),!t.sourceBlock.rendered||t.sourceBlock.isInFlyout||t.sourceBlock.isInsertionMarker()||(e?(t.sourceBlock.isEditable()?t.showEditableBubble():t.showNonEditableBubble(),t.applyColour()):t.hideBubble(),z(new(V(O.BUBBLE_OPEN))(t.sourceBlock,e,"comment"))))})}showEditableBubble(){this.createBubble();let e;(e=this.textInputBubble)==null||e.addTextChangeListener(()=>this.onTextChange());let t;(t=this.textInputBubble)==null||t.addSizeChangeListener(()=>this.onSizeChange())}showNonEditableBubble(){this.createBubble();let e;(e=this.textInputBubble)==null||e.setEditable(!1)}createBubble(){this.textInputBubble=new yv(this.sourceBlock.workspace,this.getAnchorLocation(),this.getBubbleOwnerRect()),this.textInputBubble.setText(this.getText()),this.textInputBubble.setSize(this.bubbleSize,!0)}hideBubble(){let e;(e=this.textInputBubble)==null||e.dispose(),this.textInputBubble=null}getAnchorLocation(){const e=sp/2;return G.sum(this.workspaceLocation,new G(e,e))}getBubbleOwnerRect(){return this.sourceBlock.getBoundingRectangleWithoutChildren()}};po.TYPE=yt.COMMENT,po.WEIGHT=3,Td(po.TYPE,po);var Cv=class extends Error{constructor(e){super(`Tried to append an icon of type ${e.getType()} when an icon of that type already exists on the block. Use getIcon to access the existing icon.`),this.icon=e}},Tv={};Tv.DuplicateIconType=Cv;var kv=class extends Ye{constructor(e,t,o,n){super(t,o,n),this.text=e,this.workspace=t,this.anchor=o,this.ownerRect=n,this.paragraph=this.stringToSvg(e,this.contentContainer),this.updateBubbleSize()}getText(){return this.text}setText(e){this.text=e,Ke(this.paragraph),this.paragraph=this.stringToSvg(e,this.contentContainer),this.updateBubbleSize()}stringToSvg(e,t){return t=this.createParagraph(t),e=this.createTextFragments(t,e),this.workspace.RTL&&this.rightAlignTextFragments(t.getBBox().width,e),t}createParagraph(e){return N(x.G,{class:"blocklyText blocklyBubbleText blocklyNoPointerEvents",transform:`translate(0,${Ye.BORDER_WIDTH})`,style:`direction: ${this.workspace.RTL?"rtl":"ltr"}`},e)}createTextFragments(e,t){let o=1;return t.split(` -`).map(n=>{const c=N(x.TEXT,{y:`${o}em`,x:Ye.BORDER_WIDTH},e);return n=document.createTextNode(n),c.appendChild(n),o+=1,c})}rightAlignTextFragments(e,t){for(const o of t)o.setAttribute("text-anchor","start"),o.setAttribute("x",`${e+Ye.BORDER_WIDTH}`)}updateBubbleSize(){const e=this.paragraph.getBBox();this.setSize(new Le(e.width+2*Ye.BORDER_WIDTH,e.height+2*Ye.BORDER_WIDTH),!0)}},op=17,go=class extends xl{constructor(e){super(e),this.sourceBlock=e,this.textMap=new Map,this.textBubble=null}getType(){return go.TYPE}initView(e){this.svgRoot||(super.initView(e),N(x.PATH,{class:"blocklyIconShape",d:"M2,15Q-1,15 0.5,12L6.5,1.7Q8,-1 9.5,1.7L15.5,12Q17,15 14,15z"},this.svgRoot),N(x.PATH,{class:"blocklyIconSymbol",d:"m7,4.8v3.16l0.27,2.27h1.46l0.27,-2.27v-3.16z"},this.svgRoot),N(x.RECT,{class:"blocklyIconSymbol",x:"7",y:"11",height:"2",width:"2"},this.svgRoot),ge(this.svgRoot,"blockly-icon-warning"))}dispose(){super.dispose();let e;(e=this.textBubble)==null||e.dispose()}getWeight(){return go.WEIGHT}getSize(){return new Le(op,op)}applyColour(){super.applyColour();let e;(e=this.textBubble)==null||e.setColour(this.sourceBlock.getColour())}updateCollapsed(){}isShownWhenCollapsed(){return!0}onLocationChange(e){super.onLocationChange(e);let t;(t=this.textBubble)==null||t.setAnchorLocation(this.getAnchorLocation())}addMessage(e,t){if(this.textMap.get(t)===e)return this;e?this.textMap.set(t,e):this.textMap.delete(t);let o;return(o=this.textBubble)==null||o.setText(this.getText()),this}getText(){return[...this.textMap.values()].join(` -`)}onClick(){super.onClick(),this.setBubbleVisible(!this.bubbleIsVisible())}isClickableInFlyout(){return!1}bubbleIsVisible(){return!!this.textBubble}setBubbleVisible(e){const t=this;return j.asyncExecutePromiseGeneratorFunction(function*(){if(t.bubbleIsVisible()!==e){if(yield ws(),e)t.textBubble=new kv(t.getText(),t.sourceBlock.workspace,t.getAnchorLocation(),t.getBubbleOwnerRect()),t.applyColour();else{let o;(o=t.textBubble)==null||o.dispose(),t.textBubble=null}z(new(V(O.BUBBLE_OPEN))(t.sourceBlock,e,"warning"))}})}getAnchorLocation(){const e=op/2;return G.sum(this.workspaceLocation,new G(e,e))}getBubbleOwnerRect(){const e=this.sourceBlock.getSvgRoot().getBBox();return new qe(e.y,e.y+e.height,e.x,e.x+e.width)}};go.TYPE=yt.WARNING,go.WEIGHT=2;var Ao={};Ao.CommentIcon=po,Ao.Icon=xl,Ao.IconType=yt,Ao.MutatorIcon=i.MutatorIcon$$module$build$src$core$icons$mutator_icon,Ao.WarningIcon=go,Ao.exceptions=Tv,Ao.registry=tp,i.Names$$module$build$src$core$names=class{constructor(e,t){this.db=new Map,this.dbReverse=new Set,this.variableMap=null,this.variablePrefix=t||"",this.reservedWords=new Set(e?e.split(","):[])}reset(){this.db.clear(),this.dbReverse.clear(),this.variableMap=null}setVariableMap(e){this.variableMap=e}getNameForUserVariable(e){return this.variableMap?(e=this.variableMap.getVariableById(e))?e.name:null:(console.warn(`Deprecated call to Names.prototype.getName without defining a variable map. To fix, add the following code in your generator's init() function: -Blockly.YourGeneratorName.nameDB_.setVariableMap(workspace.getVariableMap());`),null)}populateVariables(e){e=i.allUsedVarModels$$module$build$src$core$variables(e);for(let t=0;trect,`,`${e} .blocklyEditableText>rect {`,`fill: ${this.FIELD_BORDER_RECT_COLOUR};`,"fill-opacity: .6;","stroke: none;","}",`${e} .blocklyNonEditableText>text,`,`${e} .blocklyEditableText>text {`,"fill: #000;","}",`${e} .blocklyFlyoutLabelText {`,"fill: #000;","}",`${e} .blocklyText.blocklyBubbleText {`,"fill: #000;","}",`${e} .blocklyEditableText:not(.editing):hover>rect {`,"stroke: #fff;","stroke-width: 2;","}",`${e} .blocklyHtmlInput {`,`font-family: ${this.FIELD_TEXT_FONTFAMILY};`,`font-weight: ${this.FIELD_TEXT_FONTWEIGHT};`,"}",`${e} .blocklySelected>.blocklyPath {`,"stroke: #fc3;","stroke-width: 3px;","}",`${e} .blocklyHighlightedConnectionPath {`,"stroke: #fc3;","}",`${e} .blocklyReplaceable .blocklyPath {`,"fill-opacity: .5;","}",`${e} .blocklyReplaceable .blocklyPathLight,`,`${e} .blocklyReplaceable .blocklyPathDark {`,"display: none;","}",`${e} .blocklyInsertionMarker>.blocklyPath {`,`fill-opacity: ${this.INSERTION_MARKER_OPACITY};`,"stroke: none;","}"]}},Nl=class{constructor(e,t){this.inlinePath_=this.outlinePath_="",this.block_=e,this.info_=t,this.topLeft_=e.getRelativeToSurfaceXY(),this.constants_=t.getRenderer().getConstants()}draw(){this.drawOutline_(),this.drawInternals_(),this.updateConnectionHighlights(),this.block_.pathObject.setPath(this.outlinePath_+` -`+this.inlinePath_),this.info_.RTL&&this.block_.pathObject.flipRTL(),this.recordSizeOnBlock_()}recordSizeOnBlock_(){this.block_.height=this.info_.height,this.block_.width=this.info_.widthWithChildren,this.block_.childlessWidth=this.info_.width}drawOutline_(){this.drawTop_();for(let e=1;ee||e>this.fieldRow.length)throw Error("index "+e+" out of bounds.");return(t||t===""&&o)&&(typeof t=="string"&&(t=i.fromJson$$module$build$src$core$field_registry({type:"field_label",text:t})),t.setSourceBlock(this.sourceBlock),this.sourceBlock.initialized&&this.initField(t),t.name=o,t.setVisible(this.isVisible()),t.prefixField&&(e=this.insertFieldAt(e,t.prefixField)),this.fieldRow.splice(e,0,t),e++,t.suffixField&&(e=this.insertFieldAt(e,t.suffixField)),this.sourceBlock.rendered&&this.sourceBlock.queueRender()),e}removeField(e,t){for(let o=0,n;n=this.fieldRow[o];o++)if(n.name===e)return n.dispose(),this.fieldRow.splice(o,1),this.sourceBlock.rendered&&this.sourceBlock.queueRender(),!0;if(t)return!1;throw Error('Field "'+e+'" not found.')}isVisible(){return this.visible}setVisible(e){let t=[];if(this.visible===e)return t;this.visible=e;for(let n=0,c;c=this.fieldRow[n];n++)c.setVisible(e);if(this.connection){var o=this.connection;e?t=o.startTrackingAll():o.stopTrackingAll(),(o=o.targetBlock())&&(o.getSvgRoot().style.display=e?"block":"none")}return t}markDirty(){for(let e=0,t;t=this.fieldRow[e];e++)t.markDirty()}setCheck(e){if(!this.connection)throw Error("This input does not have a connection.");return this.connection.setCheck(e),this}setAlign(e){return this.align=e,this.sourceBlock.rendered&&this.sourceBlock.queueRender(),this}setShadowDom(e){if(!this.connection)throw Error("This input does not have a connection.");return this.connection.setShadowDom(e),this}getShadowDom(){if(!this.connection)throw Error("This input does not have a connection.");return this.connection.getShadowDom()}init(){for(const e of this.fieldRow)e.init()}initModel(){for(const e of this.fieldRow)e.initModel()}initField(e){this.sourceBlock.rendered?e.init():e.initModel()}dispose(){for(let e=0,t;t=this.fieldRow[e];e++)t.dispose();this.connection&&this.connection.dispose()}makeConnection(e){return this.sourceBlock.makeConnection_(e)}},Us=class extends nn{constructor(e,t){super(e,t),this.name=e,this.type=i.inputTypes$$module$build$src$core$inputs$input_types.DUMMY}},fo=class extends nn{constructor(e,t){super(e,t),this.name=e,this.type=i.inputTypes$$module$build$src$core$inputs$input_types.END_ROW}},is=class extends nn{constructor(e,t){if(!e)throw Error("Statement inputs must have a non-empty name");super(e,t),this.name=e,this.type=i.inputTypes$$module$build$src$core$inputs$input_types.STATEMENT,this.connection=this.makeConnection(oe.NEXT_STATEMENT)}},Rv;i.ValueInput$$module$build$src$core$inputs$value_input=class extends nn{constructor(e,t){if(!e)throw Error("Value inputs must have a non-empty name");super(e,t),this.name=e,this.type=i.inputTypes$$module$build$src$core$inputs$input_types.VALUE,this.connection=this.makeConnection(oe.INPUT_VALUE)}},Rv={},Rv.ValueInput=i.ValueInput$$module$build$src$core$inputs$value_input;var kr=class{constructor(e,t){this.statementEdge=this.width=this.widthWithChildren=this.height=0,this.rows=[],this.inputRows=[],this.startY=this.startX=0,this.renderer_=e,this.block_=t,this.constants_=this.renderer_.getConstants(),this.outputConnection=t.outputConnection?new Dv(this.constants_,t.outputConnection):null,this.isInline=t.getInputsInline()&&!t.isCollapsed(),this.isCollapsed=t.isCollapsed(),this.isInsertionMarker=t.isInsertionMarker(),this.RTL=t.RTL,this.topRow=new cp(this.constants_),this.bottomRow=new ip(this.constants_)}getRenderer(){return this.renderer_}measure(){this.createRows_(),this.addElemSpacing_(),this.addRowSpacing_(),this.computeBounds_(),this.alignRowElements_(),this.finalize_()}createRows_(){this.populateTopRow_(),this.rows.push(this.topRow);let e=new ap(this.constants_);this.inputRows.push(e);var t=this.block_.getIcons();for(let o=0,n;n=t[o];o++){const c=new Ev(this.constants_,n);this.isCollapsed&&!n.isShownWhenCollapsed()||e.elements.push(c)}t=void 0;for(let o=0,n;n=this.block_.inputList[o];o++)if(n.isVisible()){this.shouldStartNewRow_(n,t)&&(this.rows.push(e),e=new ap(this.constants_),this.inputRows.push(e));for(let c=0,h;h=n.fieldRow[c];c++)e.elements.push(new on(this.constants_,h,n));this.addInput_(n,e),t=n}this.isCollapsed&&(e.hasJaggedEdge=!0,e.elements.push(new Iv(this.constants_))),(e.elements.length||e.hasDummyInput)&&this.rows.push(e),this.populateBottomRow_(),this.rows.push(this.bottomRow)}populateTopRow_(){var e=!!this.block_.previousConnection;const t=(this.block_.hat?this.block_.hat==="cap":this.constants_.ADD_START_HATS)&&!this.outputConnection&&!e;let o=this.topRow.hasLeftSquareCorner(this.block_)?Tr:Cr;this.topRow.elements.push(new o(this.constants_)),t?(e=new np(this.constants_),this.topRow.elements.push(e),this.topRow.capline=e.ascenderHeight):e&&(this.topRow.hasPreviousConnection=!0,this.topRow.connection=new Av(this.constants_,this.block_.previousConnection),this.topRow.elements.push(this.topRow.connection)),this.block_.inputList.length&&this.block_.inputList[0]instanceof is&&!this.block_.isCollapsed()?this.topRow.minHeight=this.constants_.TOP_ROW_PRECEDES_STATEMENT_MIN_HEIGHT:this.topRow.minHeight=this.constants_.TOP_ROW_MIN_HEIGHT,o=this.topRow.hasRightSquareCorner(this.block_)?Tr:Cr,this.topRow.elements.push(new o(this.constants_,"right"))}populateBottomRow_(){this.bottomRow.hasNextConnection=!!this.block_.nextConnection,this.bottomRow.minHeight=this.block_.inputList.length&&this.block_.inputList[this.block_.inputList.length-1]instanceof is?this.constants_.BOTTOM_ROW_AFTER_STATEMENT_MIN_HEIGHT:this.constants_.BOTTOM_ROW_MIN_HEIGHT,this.bottomRow.hasLeftSquareCorner(this.block_)?this.bottomRow.elements.push(new Tr(this.constants_)):this.bottomRow.elements.push(new Cr(this.constants_)),this.bottomRow.hasNextConnection&&(this.bottomRow.connection=new xv(this.constants_,this.block_.nextConnection),this.bottomRow.elements.push(this.bottomRow.connection)),this.bottomRow.hasRightSquareCorner(this.block_)?this.bottomRow.elements.push(new Tr(this.constants_,"right")):this.bottomRow.elements.push(new Cr(this.constants_,"right"))}addInput_(e,t){this.isInline&&e instanceof i.ValueInput$$module$build$src$core$inputs$value_input?(t.elements.push(new rp(this.constants_,e)),t.hasInlineInput=!0):e instanceof is?(t.elements.push(new wr(this.constants_,e)),t.hasStatement=!0):e instanceof i.ValueInput$$module$build$src$core$inputs$value_input?(t.elements.push(new Ol(this.constants_,e)),t.hasExternalInput=!0):(e instanceof Us||e instanceof fo)&&(t.minHeight=Math.max(t.minHeight,e.getSourceBlock()&&e.getSourceBlock().isShadow()?this.constants_.DUMMY_INPUT_SHADOW_MIN_HEIGHT:this.constants_.DUMMY_INPUT_MIN_HEIGHT),t.hasDummyInput=!0),t.align===null&&(t.align=e.align)}shouldStartNewRow_(e,t){return t?t instanceof fo||e instanceof is||t instanceof is?!0:e instanceof i.ValueInput$$module$build$src$core$inputs$value_input||e instanceof Us||t instanceof i.ValueInput$$module$build$src$core$inputs$value_input?!this.isInline:!1:!1}addElemSpacing_(){for(let e=0,t;t=this.rows[e];e++){const o=t.elements;if(t.elements=[],t.startsWithElemSpacer()&&t.elements.push(new os(this.constants_,this.getInRowSpacing_(null,o[0]))),o.length){for(let n=0;ne.disposeInternal()),this.inputList.forEach(e=>e.dispose()),this.inputList.length=0,this.getConnections_(!0).forEach(e=>e.dispose()),this.disposed=!0}isDeadOrDying(){return this.disposing||this.disposed}initModel(){if(!this.initialized){for(const e of this.inputList)e.initModel();this.initialized=!0}}unplug(e){this.outputConnection&&this.unplugFromRow(e),this.previousConnection&&this.unplugFromStack(e)}unplugFromRow(e){let t=null,o;(o=this.outputConnection)!=null&&o.isConnected()&&(t=this.outputConnection.targetConnection,this.outputConnection.disconnect()),t&&e&&(e=this.getOnlyValueConnection())&&e.isConnected()&&!e.targetBlock().isShadow()&&(e=e.targetConnection,e==null||e.disconnect(),this.workspace.connectionChecker.canConnect(e,t,!1)?t.connect(e):e==null||e.onFailedConnect(t))}getOnlyValueConnection(){let e=null;for(let t=0;t(n=n+(o==="("||c===")"?"":" ")+c,o=c[c.length-1],n),""),t=t.trim()||"???",e&&t.length>e&&(t=t.substring(0,e-3)+"..."),t}toTokens(e="?"){const t=[];for(const n of this.inputList)if(n.name!=ur){for(const c of n.fieldRow)t.push(c.getText());if(n.connection){const c=n.connection.targetBlock();if(c){var o=n.connection;let h=o.getCheck();!h&&o.targetConnection&&(h=o.targetConnection.getCheck()),(o=!!h&&(h.includes("Boolean")||h.includes("Number")))&&t.push("("),t.push(...c.toTokens(e)),o&&t.push(")")}else t.push(e)}}return t}appendValueInput(e){return this.appendInput(new i.ValueInput$$module$build$src$core$inputs$value_input(e,this))}appendStatementInput(e){return this.statementInputCount++,this.appendInput(new is(e,this))}appendDummyInput(e=""){return this.appendInput(new Us(e,this))}appendEndRowInput(e=""){return this.appendInput(new fo(e,this))}appendInput(e){return this.inputList.push(e),e}appendInputFromRegistry(e,t){return(e=m(F.INPUT,e,!1))?this.appendInput(new e(t,this)):null}jsonInit(e){var t=e.type?'Block "'+e.type+'": ':"";if(e.output&&e.previousStatement)throw Error(t+"Must not have both an output and a previousStatement.");for(var o=0;e["args"+o];){if(e["message"+o]===void 0)throw Error(t+`args${o} must have a corresponding message (message${o}).`);o++}if(e.style&&e.style.hat&&(this.hat=e.style.hat,e.style=null),e.style&&e.colour)throw Error(t+"Must not have both a colour and a style.");for(e.style?this.jsonInitStyle(e,t):this.jsonInitColour(e,t),o=0;e["message"+o]!==void 0;)this.interpolate(e["message"+o],e["args"+o]||[],e["implicitAlign"+o]||e["lastDummyAlign"+o],t),o++;if(e.inputsInline!==void 0&&(i.disable$$module$build$src$core$events$utils(),this.setInputsInline(e.inputsInline),i.enable$$module$build$src$core$events$utils()),e.output!==void 0&&this.setOutput(!0,e.output),e.outputShape!==void 0&&this.setOutputShape(e.outputShape),e.previousStatement!==void 0&&this.setPreviousStatement(!0,e.previousStatement),e.nextStatement!==void 0&&this.setNextStatement(!0,e.nextStatement),e.tooltip!==void 0&&(o=pt(e.tooltip),this.setTooltip(o)),e.enableContextMenu!==void 0&&(this.contextMenu=!!e.enableContextMenu),e.suppressPrefixSuffix!==void 0&&(this.suppressPrefixSuffix=!!e.suppressPrefixSuffix),e.helpUrl!==void 0&&(o=pt(e.helpUrl),this.setHelpUrl(o)),typeof e.extensions=="string"&&(console.warn(t+"JSON attribute 'extensions' should be an array of strings. Found raw string in JSON for '"+e.type+"' block."),e.extensions=[e.extensions]),e.mutator!==void 0&&Ha(e.mutator,this,!0),e=e.extensions,Array.isArray(e))for(t=0;th||h>t)throw Error('Block "'+this.type+'": Message index %'+h+" out of range.");if(o[h])throw Error('Block "'+this.type+'": Message index %'+h+" duplicated.");o[h]=!0,n++}}if(n!==t)throw Error('Block "'+this.type+'": Message does not reference all '+t+" arg(s).")}interpolateArguments(e,t,o){const n=[];for(let h=0;h=this.inputList.length)throw RangeError("Input index "+e+" out of bounds.");if(t>this.inputList.length)throw RangeError("Reference input "+t+" out of bounds.");const o=this.inputList[e];this.inputList.splice(e,1),et.getWeight()-o.getWeight()),e}removeIcon(e){if(!this.hasIcon(e))return!1;let t;return(t=this.getIcon(e))==null||t.dispose(),this.icons=this.icons.filter(o=>!o.getType().equals(e)),!0}hasIcon(e){return this.icons.some(t=>t.getType().equals(e))}getIcon(e){return e instanceof yt?this.icons.find(t=>t.getType().equals(e)):this.icons.find(t=>t.getType().toString()===e)}getIcons(){return[...this.icons]}getRelativeToSurfaceXY(){return this.xy}moveBy(e,t,o){if(this.parentBlock_)throw Error("Block has parent");const n=new(V(O.BLOCK_MOVE))(this);o&&n.setReason(o),this.xy.translate(e,t),n.recordNew(),z(n)}makeConnection_(e){return new Be(this,e)}allInputsFilled(e){if(e===void 0&&(e=!0),!e&&this.isShadow())return!1;for(let o=0,n;n=this.inputList[o];o++)if(n.connection){var t=n.connection.targetBlock();if(!t||!t.allInputsFilled(e))return!1}return(t=this.getNextBlock())?t.allInputsFilled(e):!0}toDevString(){let e=this.type?'"'+this.type+'" block':"Block";return this.id&&(e+=' (id="'+this.id+'")'),e}};Oo.COLLAPSED_INPUT_NAME=ur,Oo.COLLAPSED_FIELD_NAME=dl;var hs=class{constructor(e,t,o,n){this.workspace=e,this.targetWorkspace=t,this.isFlyoutLabel=n,this.onMouseUpWrapper=null,this.height=this.width=0,this.cursorSvg=this.svgText=this.svgGroup=null,this.text=o.text,this.position=new G(0,0),this.callbackKey=o.callbackKey||o.callbackkey,this.cssClass=o["web-class"]||null,this.info=o}createDom(){var e=this.isFlyoutLabel?"blocklyFlyoutLabel":"blocklyFlyoutButton";this.cssClass&&(e+=" "+this.cssClass),this.svgGroup=N(x.G,{class:e},this.workspace.getCanvas());let t;this.isFlyoutLabel||(t=N(x.RECT,{class:"blocklyFlyoutButtonShadow",rx:hs.BORDER_RADIUS,ry:hs.BORDER_RADIUS,x:1,y:1},this.svgGroup)),e=N(x.RECT,{class:this.isFlyoutLabel?"blocklyFlyoutLabelBackground":"blocklyFlyoutButtonBackground",rx:hs.BORDER_RADIUS,ry:hs.BORDER_RADIUS},this.svgGroup);const o=N(x.TEXT,{class:this.isFlyoutLabel?"blocklyFlyoutLabelText":"blocklyText",x:0,y:0,"text-anchor":"middle"},this.svgGroup);var n=pt(this.text);this.workspace.RTL&&(n+="‏"),o.textContent=n,this.isFlyoutLabel&&(this.svgText=o,this.workspace.getThemeManager().subscribe(this.svgText,"flyoutForegroundColour","fill"));const c=Ms(o,"fontSize"),h=Ms(o,"fontWeight"),$=Ms(o,"fontFamily");if(this.width=ua(o,c,h,$),n=da(n,c,h,$),this.height=n.height,!this.isFlyoutLabel){this.width+=2*hs.TEXT_MARGIN_X,this.height+=2*hs.TEXT_MARGIN_Y;let T;(T=t)==null||T.setAttribute("width",String(this.width));let L;(L=t)==null||L.setAttribute("height",String(this.height))}return e.setAttribute("width",String(this.width)),e.setAttribute("height",String(this.height)),o.setAttribute("x",String(this.width/2)),o.setAttribute("y",String(this.height/2-n.height/2+n.baseline)),this.updateTransform(),this.onMouseUpWrapper=X(this.svgGroup,"pointerup",this,this.onMouseUp),this.svgGroup}show(){this.updateTransform(),this.svgGroup.setAttribute("display","block")}updateTransform(){this.svgGroup.setAttribute("transform","translate("+this.position.x+","+this.position.y+")")}moveTo(e,t){this.position.x=e,this.position.y=t,this.updateTransform()}isLabel(){return this.isFlyoutLabel}getPosition(){return this.position}getButtonText(){return this.text}getTargetWorkspace(){return this.targetWorkspace}getWorkspace(){return this.workspace}dispose(){this.onMouseUpWrapper&&ze(this.onMouseUpWrapper),this.svgGroup&&Ke(this.svgGroup),this.svgText&&this.workspace.getThemeManager().unsubscribe(this.svgText)}setCursorSvg(e){e?this.svgGroup&&(this.svgGroup.appendChild(e),this.cursorSvg=e):this.cursorSvg=null}setMarkerSvg(){throw Error("Attempted to set a marker on a button.")}onMouseUp(e){(e=this.targetWorkspace.getGesture(e))&&e.cancel(),this.isFlyoutLabel&&this.callbackKey?console.warn("Labels should not have callbacks. Label text: "+this.text):this.isFlyoutLabel||this.callbackKey&&this.targetWorkspace.getButtonCallback(this.callbackKey)?this.isFlyoutLabel||(e=this.targetWorkspace.getButtonCallback(this.callbackKey))&&e(this):console.warn("Buttons should have callbacks. Button text: "+this.text)}};hs.TEXT_MARGIN_X=5,hs.TEXT_MARGIN_Y=2,hs.BORDER_RADIUS=4,Et(` -.blocklyFlyoutButton { - fill: #888; - cursor: default; -} - -.blocklyFlyoutButtonShadow { - fill: #666; -} - -.blocklyFlyoutButton:hover { - fill: #aaa; -} - -.blocklyFlyoutLabel { - cursor: default; -} - -.blocklyFlyoutLabelBackground { - opacity: 0; -} -`);var P=class{constructor(e,t,o){if(this.wsCoordinate=null,!t)throw Error("Cannot create a node without a location.");this.type=e,this.isConnectionLocation=P.isConnectionType(e),this.location=t,this.processParams(o||null)}processParams(e){e&&e.wsCoordinate&&(this.wsCoordinate=e.wsCoordinate)}getLocation(){return this.location}getType(){return this.type}getWsCoordinate(){return this.wsCoordinate}isConnection(){return this.isConnectionLocation}findNextForInput(){var e=this.location.getParentInput();const t=e.getSourceBlock();for(e=t.inputList.indexOf(e),e+=1;et instanceof Oo&&c.block===t||t instanceof hs&&c.button===t);return 0>n?null:(o=o?n+1:n-1,o===-1||o===e.length?null:e[o])}findTopASTNodeForBlock(e){const t=Qn(e);return t?P.createConnectionNode(t):P.createBlockNode(e)}getOutAstNodeForBlock(e){if(!e)return null;e=e.getTopStackBlock();const t=Qn(e);return t&&t.targetConnection&&t.targetConnection.getParentInput()?P.createInputNode(t.targetConnection.getParentInput()):P.createStackNode(e)}findFirstFieldOrInput(e){e=e.inputList;for(let t=0;t{Ua(o.getSourceBlock()),setTimeout(()=>{n.bringToFront()},0)})}}update(e,t){const o=this.getCandidate(e);((this.wouldDeleteBlock=this.shouldDelete(!!o,t))||this.shouldUpdatePreviews(o,e))&&(i.disable$$module$build$src$core$events$utils(),this.maybeHidePreview(o),this.maybeShowPreview(o),i.enable$$module$build$src$core$events$utils())}createMarkerBlock(e){i.disable$$module$build$src$core$events$utils();let t;try{const o=Qt(e,{addCoordinates:!1,addInputBlocks:!1,addNextBlocks:!1,doFullSerialization:!1});if(!o)throw Error(`Failed to serialize source block. ${e.toDevString()}`);t=eo(o,this.workspace);for(const n of t.getDescendants(!1))n.setInsertionMarker(!0);t.initSvg(),t.getSvgRoot().setAttribute("visibility","hidden")}finally{i.enable$$module$build$src$core$events$utils()}return t}initAvailableConnections(){const e=this.topBlock.getConnections_(!1),t=this.topBlock.lastConnectionInStack(!0);return t&&t!==this.topBlock.nextConnection&&(e.push(t),this.lastOnStack=t),e}shouldUpdatePreviews(e,t){if(!e)return!!this.activeCandidate;if(!this.activeCandidate)return!0;const{local:o,closest:n}=this.activeCandidate;if(n===e.closest&&o===e.local)return!1;const c=o.x+t.x-n.x;return t=o.y+t.y-n.y,e.radius{let L;(L=n)==null||L.positionNearConnection(T,h,$);let te;(te=n)==null||te.getSvgRoot().setAttribute("visibility","visible")}),this.markerConnection=c}hideInsertionMarker(){if(this.markerConnection){var e=this.markerConnection,t=e.getSourceBlock(),o=t.outputConnection,n;if((n=t.previousConnection)!=null&&n.targetConnection||o!=null&&o.targetConnection)t.unplug(!0);else{let c;(c=e.targetBlock())==null||c.unplug(!1)}if(e.targetConnection)throw Error("markerConnection still connected at the end of disconnectInsertionMarker");this.markerConnection=null,(e=t.getSvgRoot())&&e.setAttribute("visibility","hidden")}}showInsertionInputOutline(e){e=e.closest,this.highlightedBlock=e.getSourceBlock(),this.highlightedBlock.highlightShapeForInput(e,!0)}hideInsertionInputOutline(){if(this.highlightedBlock){if(!this.activeCandidate)throw Error("Cannot hide the insertion marker outline because there is no active candidate");this.highlightedBlock.highlightShapeForInput(this.activeCandidate.closest,!1),this.highlightedBlock=null}}showReplacementFade(e){if(this.fadedBlock=e.closest.targetBlock(),!this.fadedBlock)throw Error("Cannot show the replacement fade because the closest connection does not have a target block");this.fadedBlock.fadeForReplacement(!0)}hideReplacementFade(){this.fadedBlock&&(this.fadedBlock.fadeForReplacement(!1),this.fadedBlock=null)}getInsertionMarkers(){const e=[];return this.firstMarker&&e.push(this.firstMarker),this.lastMarker&&e.push(this.lastMarker),e}disposeInsertionMarker(e){if(e){i.disable$$module$build$src$core$events$utils();try{e.dispose()}finally{i.enable$$module$build$src$core$events$utils()}}}};(function(e){e=e.PREVIEW_TYPE||(e.PREVIEW_TYPE={}),e[e.INSERTION_MARKER=0]="INSERTION_MARKER",e[e.INPUT_OUTLINE=1]="INPUT_OUTLINE",e[e.REPLACEMENT_FADE=2]="REPLACEMENT_FADE"})(ps||(ps={})),ps.PREVIEW_TYPE;var Pl=class{constructor(e){this.overrides=null,this.name=e}getClassName(){return this.name+"-renderer"}init(e,t){this.constants_=this.makeConstants_(),t&&(this.overrides=t,Object.assign(this.constants_,t)),this.constants_.setTheme(e),this.constants_.init()}createDom(e,t){this.constants_.createDom(e,this.name+"-"+t.name,"."+this.getClassName()+"."+t.getClassName())}refreshDom(e,t){const o=this.getConstants();o.dispose(),this.constants_=this.makeConstants_(),this.overrides&&Object.assign(this.constants_,this.overrides),this.constants_.randomIdentifier=o.randomIdentifier,this.constants_.setTheme(t),this.constants_.init(),this.createDom(e,t)}dispose(){this.constants_&&this.constants_.dispose()}makeConstants_(){return new Ml}makeRenderInfo_(e){return new kr(this,e)}makeDrawer_(e,t){return new Nl(e,t)}makeMarkerDrawer(e,t){return new hp(e,this.getConstants(),t)}makePathObject(e,t){return new Ll(e,t,this.constants_)}getConstants(){return this.constants_}shouldHighlightConnection(e){return!0}orphanCanConnectAtEnd(e,t,o){return!!Be.getConnectionForOrphanedConnection(e,o===oe.OUTPUT_VALUE?t.outputConnection:t.previousConnection)}getConnectionPreviewMethod(e,t,o){return y("getConnectionPreviewMethod","v10","v12","an IConnectionPreviewer, if it fulfills your use case."),t.type===oe.OUTPUT_VALUE||t.type===oe.PREVIOUS_STATEMENT?!e.isConnected()||this.orphanCanConnectAtEnd(o,e.targetBlock(),t.type)?ps.PREVIEW_TYPE.INSERTION_MARKER:ps.PREVIEW_TYPE.REPLACEMENT_FADE:ps.PREVIEW_TYPE.INSERTION_MARKER}render(e){const t=this.makeRenderInfo_(e);t.measure(),this.makeDrawer_(e,t).draw()}},We={};We.BottomRow=ip,We.Connection=mo,We.ConstantProvider=Ml,We.Drawer=Nl,We.ExternalValueInput=Ol,We.Field=on,We.Hat=np,We.Icon=Ev,We.InRowSpacer=os,We.InlineInput=rp,We.InputConnection=Ro,We.InputRow=ap,We.JaggedEdge=Iv,We.MarkerSvg=hp,We.Measurable=zs,We.NextConnection=xv,We.OutputConnection=Dv,We.PathObject=Ll,We.PreviousConnection=Av,We.RenderInfo=kr,We.Renderer=Pl,We.RoundCorner=Cr,We.Row=_r,We.SpacerRow=lp,We.SquareCorner=Tr,We.StatementInput=wr,We.TopRow=cp,We.Types=S,We.init=Ad,We.register=er,We.unregister=F$;var Ov=class{constructor(e,t){this.workspace=e,this.theme=t,this.subscribedWorkspaces=[],this.componentDB=new Map}getTheme(){return this.theme}setTheme(e){var t=this.theme;this.theme=e,(e=this.workspace.getInjectionDiv())&&(t&&(t=t.getClassName())&&ot(e,t),(t=this.theme.getClassName())&&ge(e,t));for(let o=0,n;n=this.subscribedWorkspaces[o];o++)n.refreshTheme();for(const[o,n]of this.componentDB)for(const c of n){e=c.element,t=c.propertyName;const h=this.theme&&this.theme.getComponentStyle(o);e.style.setProperty(t,h||"")}for(const o of this.subscribedWorkspaces)o.hideChaff()}subscribeWorkspace(e){this.subscribedWorkspaces.push(e)}unsubscribeWorkspace(e){if(!St(this.subscribedWorkspaces,e))throw Error("Cannot unsubscribe a workspace that hasn't been subscribed.")}subscribe(e,t,o){this.componentDB.has(t)||this.componentDB.set(t,[]),this.componentDB.get(t).push({element:e,propertyName:o}),t=this.theme&&this.theme.getComponentStyle(t),e.style.setProperty(o,t||"")}unsubscribe(e){if(e)for(const[t,o]of this.componentDB){for(let n=o.length-1;0<=n;n--)o[n].element===e&&o.splice(n,1);o.length||this.componentDB.delete(t)}}dispose(){this.subscribedWorkspaces.length=0,this.componentDB.clear()}},pp="VARIABLE_DYNAMIC",pi={CATEGORY_NAME:pp};pi.flyoutCategory=qa,pi.flyoutCategoryBlocks=Nd,pi.onCreateVariableButtonClick_Colour=Md,pi.onCreateVariableButtonClick_Number=Od,pi.onCreateVariableButtonClick_String=Rd;var Mv=30,gi=[];gi[oe.INPUT_VALUE]=oe.OUTPUT_VALUE,gi[oe.OUTPUT_VALUE]=oe.INPUT_VALUE,gi[oe.NEXT_STATEMENT]=oe.PREVIOUS_STATEMENT,gi[oe.PREVIOUS_STATEMENT]=oe.NEXT_STATEMENT;var gp="RENAME_VARIABLE_ID",mp="DELETE_VARIABLE_ID",Nv=class{canConnect(e,t,o,n){return this.canConnectWithReason(e,t,o,n)===Be.CAN_CONNECT}canConnectWithReason(e,t,o,n){const c=this.doSafetyChecks(e,t);return c!==Be.CAN_CONNECT?c:this.doTypeChecks(e,t)?o&&!this.doDragChecks(e,t,n||0)?Be.REASON_DRAG_CHECKS_FAILED:Be.CAN_CONNECT:Be.REASON_CHECKS_FAILED}getErrorMessage(e,t,o){switch(e){case Be.REASON_SELF_CONNECTION:return"Attempted to connect a block to itself.";case Be.REASON_DIFFERENT_WORKSPACES:return"Blocks not on same workspace.";case Be.REASON_WRONG_TYPE:return"Attempt to connect incompatible types.";case Be.REASON_TARGET_NULL:return"Target connection is null.";case Be.REASON_CHECKS_FAILED:return"Connection checks failed. "+(t+" expected "+t.getCheck()+", found "+o.getCheck());case Be.REASON_SHADOW_PARENT:return"Connecting non-shadow to shadow block.";case Be.REASON_DRAG_CHECKS_FAILED:return"Drag checks failed.";case Be.REASON_PREVIOUS_AND_OUTPUT:return"Block would have an output and a previous connection.";default:return"Unknown connection failure: this should never happen!"}}doSafetyChecks(e,t){if(!e||!t)return Be.REASON_TARGET_NULL;let o,n,c;return e.isSuperior()?(o=e.getSourceBlock(),n=t.getSourceBlock(),c=t):(n=e.getSourceBlock(),o=t.getSourceBlock(),c=e,e=t),o===n?Be.REASON_SELF_CONNECTION:c.type!==gi[e.type]?Be.REASON_WRONG_TYPE:o.workspace!==n.workspace?Be.REASON_DIFFERENT_WORKSPACES:o.isShadow()&&!n.isShadow()?Be.REASON_SHADOW_PARENT:c.type===oe.OUTPUT_VALUE&&n.previousConnection&&n.previousConnection.isConnected()||c.type===oe.PREVIOUS_STATEMENT&&n.outputConnection&&n.outputConnection.isConnected()?Be.REASON_PREVIOUS_AND_OUTPUT:Be.CAN_CONNECT}doTypeChecks(e,t){if(e=e.getCheck(),t=t.getCheck(),!e||!t)return!0;for(let o=0;oo||t.getSourceBlock().isInsertionMarker())return!1;switch(t.type){case oe.PREVIOUS_STATEMENT:return this.canConnectToPrevious_(e,t);case oe.OUTPUT_VALUE:if(t.isConnected()&&!t.targetBlock().isInsertionMarker()||e.isConnected())return!1;break;case oe.INPUT_VALUE:if(t.isConnected()&&!t.targetBlock().isMovable()&&!t.targetBlock().isShadow())return!1;break;case oe.NEXT_STATEMENT:if(t.isConnected()&&!e.getSourceBlock().nextConnection&&!t.targetBlock().isShadow()&&t.targetBlock().nextConnection||t.targetBlock()&&!t.targetBlock().isMovable()&&!t.targetBlock().isShadow())return!1;break;default:return!1}return!nr.includes(t)}canConnectToPrevious_(e,t){return e.targetConnection||nr.includes(t)?!1:t.targetConnection?(e=t.targetBlock(),e.isInsertionMarker()?!e.getPreviousBlock():!1):!0}};r(F.CONNECTION_CHECKER,js,Nv);var fp=class extends dr{constructor(e){super(e),this.type=O.VAR_DELETE,e&&(this.varType=e.type,this.varName=e.name)}toJson(){const e=super.toJson();if(this.varType===void 0)throw Error("The var type is undefined. Either pass a variable to the constructor, or call fromJson");if(!this.varName)throw Error("The var name is undefined. Either pass a variable to the constructor, or call fromJson");return e.varType=this.varType,e.varName=this.varName,e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new fp),t.varType=e.varType,t.varName=e.varName,t}run(e){const t=this.getEventWorkspace_();if(!this.varId)throw Error("The var ID is undefined. Either pass a variable to the constructor, or call fromJson");if(!this.varName)throw Error("The var name is undefined. Either pass a variable to the constructor, or call fromJson");e?t.deleteVariableById(this.varId):t.createVariable(this.varName,this.varType,this.varId)}};r(F.EVENT,O.VAR_DELETE,fp);var $p=class extends dr{constructor(e,t){super(e),this.type=O.VAR_RENAME,e&&(this.oldName=e.name,this.newName=typeof t>"u"?"":t)}toJson(){const e=super.toJson();if(!this.oldName)throw Error("The old var name is undefined. Either pass a variable to the constructor, or call fromJson");if(!this.newName)throw Error("The new var name is undefined. Either pass a value to the constructor, or call fromJson");return e.oldName=this.oldName,e.newName=this.newName,e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new $p),t.oldName=e.oldName,t.newName=e.newName,t}run(e){const t=this.getEventWorkspace_();if(!this.varId)throw Error("The var ID is undefined. Either pass a variable to the constructor, or call fromJson");if(!this.oldName)throw Error("The old var name is undefined. Either pass a variable to the constructor, or call fromJson");if(!this.newName)throw Error("The new var name is undefined. Either pass a value to the constructor, or call fromJson");e?t.renameVariableById(this.varId,this.newName):t.renameVariableById(this.varId,this.oldName)}};r(F.EVENT,O.VAR_RENAME,$p);var bp=class{constructor(e){this.workspace=e,this.variableMap=new Map}clear(){for(const e of this.variableMap.values())for(;0{c&&t&&this.deleteVariableInternal(t,n)})):this.deleteVariableInternal(t,n)}else console.warn("Can't delete non-existent variable: "+e)}deleteVariableInternal(e,t){const o=i.getGroup$$module$build$src$core$events$utils();o||i.setGroup$$module$build$src$core$events$utils(!0);try{for(let n=0;ne.name)}getVariableUsesById(e){const t=[],o=this.workspace.getAllBlocks(!1);for(let n=0;n!o.isInsertionMarker())):[]}addTopComment(e){this.topComments.push(e),this.commentDB.has(e.id)&&console.warn('Overriding an existing comment on this workspace, with id "'+e.id+'"'),this.commentDB.set(e.id,e)}removeTopComment(e){if(!St(this.topComments,e))throw Error("Comment not present in workspace's list of top-most comments.");this.commentDB.delete(e.id)}getTopComments(e=!1){const t=[].concat(this.topComments);return e&&1!o.isInsertionMarker())}clear(){this.isClearing=!0;try{const e=i.getGroup$$module$build$src$core$events$utils();for(e||i.setGroup$$module$build$src$core$events$utils(!0);this.topBlocks.length;)this.topBlocks[0].dispose(!1);for(;this.topComments.length;)this.topComments[this.topComments.length-1].dispose();i.setGroup$$module$build$src$core$events$utils(e),this.variableMap.clear(),this.potentialVariableMap&&this.potentialVariableMap.clear()}finally{this.isClearing=!1}}renameVariableById(e,t){this.variableMap.renameVariableById(e,t)}createVariable(e,t,o){return this.variableMap.createVariable(e,t,o)}getVariableUsesById(e){return this.variableMap.getVariableUsesById(e)}deleteVariableById(e){this.variableMap.deleteVariableById(e)}getVariable(e,t){return this.variableMap.getVariable(e,t)}getVariableById(e){return this.variableMap.getVariableById(e)}getVariablesOfType(e){return this.variableMap.getVariablesOfType(e)}getVariableTypes(){return this.variableMap.getVariableTypes(this)}getAllVariables(){return this.variableMap.getAllVariables()}getAllVariableNames(){return this.variableMap.getAllVariableNames()}getWidth(){return 0}newBlock(e,t){throw Error("The implementation of newBlock should be monkey-patched in by blockly.ts")}newComment(e){throw Error("The implementation of newComment should be monkey-patched in by blockly.ts")}remainingCapacity(){return isNaN(this.options.maxBlocks)?1/0:this.options.maxBlocks-this.getAllBlocks(!1).length}remainingCapacityOfType(e){return this.options.maxInstances?(this.options.maxInstances[e]!==void 0?this.options.maxInstances[e]:1/0)-this.getBlocksByType(e,!1).length:1/0}isCapacityAvailable(e){if(!this.hasBlockLimits())return!0;let t=0;for(const o in e){if(e[o]>this.remainingCapacityOfType(o))return!1;t+=e[o]}return!(t>this.remainingCapacity())}hasBlockLimits(){return this.options.maxBlocks!==1/0||!!this.options.maxInstances}getUndoStack(){return this.undoStack_}getRedoStack(){return this.redoStack_}undo(e){var t=e?this.redoStack_:this.undoStack_,o=e?this.undoStack_:this.redoStack_;const n=t.pop();if(n){for(var c=[n];t.length&&n.group&&n.group===t[t.length-1].group;){const h=t.pop();h&&c.push(h)}for(t=0;tthis.MAX_UNDO&&0<=this.MAX_UNDO;)this.undoStack_.shift();for(let t=0;t!!t.getStyleName())),this.refreshToolboxSelection(),this.toolbox&&this.toolbox.refreshTheme(),this.isVisible()&&this.setVisible(!0);const e=new(V(O.THEME_CHANGE))(this.getTheme().name,this.id);z(e)}updateBlockStyles(e){for(let t=0,o;o=e[t];t++){const n=o.getStyleName();n&&o.setStyle(n)}}getInverseScreenCTM(){if(this.inverseScreenCTMDirty){const e=this.getParentSvg().getScreenCTM();e&&(this.inverseScreenCTM=e.inverse(),this.inverseScreenCTMDirty=!1)}return this.inverseScreenCTM}updateInverseScreenCTM(){this.inverseScreenCTMDirty=!0}isVisible(){return this.visible}getSvgXY(e){let t=0,o=0,n=1;(this.getCanvas().contains(e)||this.getBubbleCanvas().contains(e))&&(n=this.scale);do{const c=Pn(e);(e===this.getCanvas()||e===this.getBubbleCanvas())&&(n=1),t+=c.x*n,o+=c.y*n,e=e.parentNode}while(e&&e!==this.getParentSvg()&&e!==this.getInjectionDiv());return new G(t,o)}getCachedParentSvgSize(){const e=this.cachedParentSvgSize;return new Le(e.width,e.height)}getOriginOffsetInPixels(){return pa(this.getCanvas())}getInjectionDiv(){if(!this.injectionDiv){let e=this.svgGroup_;for(;e;){if((" "+(e.getAttribute("class")||"")+" ").includes(" injectionDiv ")){this.injectionDiv=e;break}e=e.parentNode}}return this.injectionDiv}getSvgGroup(){return this.svgGroup_}getBlockCanvas(){return this.getCanvas()}setResizeHandlerWrapper(e){this.resizeHandlerWrapper=e}createDom(e,t){return this.injectionDiv||(this.injectionDiv=t??null),this.svgGroup_=N(x.G,{class:"blocklyWorkspace"}),e&&(this.svgBackground_=N(x.RECT,{height:"100%",width:"100%",class:e},this.svgGroup_),e==="blocklyMainBackground"&&this.grid?this.svgBackground_.style.fill="url(#"+this.grid.getPatternId()+")":this.themeManager_.subscribe(this.svgBackground_,"workspaceBackgroundColour","fill")),this.layerManager=new KT(this),this.svgBlockCanvas_=this.layerManager.getBlockLayer(),this.svgBubbleCanvas_=this.layerManager.getBubbleLayer(),this.isFlyout||(X(this.svgGroup_,"pointerdown",this,this.onMouseDown,!1),this.dummyWheelListener=()=>{},document.body.addEventListener("wheel",this.dummyWheelListener),X(this.svgGroup_,"wheel",this,this.onMouseWheel)),this.options.hasCategories&&(this.toolbox=new(_(F.TOOLBOX,this.options,!0))(this)),this.grid&&this.grid.update(this.scale),this.recordDragTargets(),(e=_(F.CURSOR,this.options))&&this.markerManager.setCursor(new e),this.renderer.createDom(this.svgGroup_,this.getTheme()),this.svgGroup_}dispose(){if(this.rendered=!1,this.currentGesture_&&this.currentGesture_.cancel(),this.svgGroup_&&Ke(this.svgGroup_),this.toolbox&&(this.toolbox.dispose(),this.toolbox=null),this.flyout&&(this.flyout.dispose(),this.flyout=null),this.trashcan&&(this.trashcan.dispose(),this.trashcan=null),this.scrollbar&&(this.scrollbar.dispose(),this.scrollbar=null),this.zoomControls_&&this.zoomControls_.dispose(),this.audioManager&&this.audioManager.dispose(),this.grid&&(this.grid=null),this.renderer.dispose(),this.markerManager&&this.markerManager.dispose(),super.dispose(),this.themeManager_&&(this.themeManager_.unsubscribeWorkspace(this),this.themeManager_.unsubscribe(this.svgBackground_),this.options.parentWorkspace||this.themeManager_.dispose()),this.connectionDBList.length=0,this.toolboxCategoryCallbacks.clear(),this.flyoutButtonCallbacks.clear(),!this.options.parentWorkspace){const e=this.getParentSvg();e&&e.parentNode&&Ke(e.parentNode)}this.resizeHandlerWrapper&&(ze(this.resizeHandlerWrapper),this.resizeHandlerWrapper=null),this.dummyWheelListener&&(document.body.removeEventListener("wheel",this.dummyWheelListener),this.dummyWheelListener=null)}addTrashcan(){this.trashcan=ns.newTrashcan(this);const e=this.trashcan.createDom();this.svgGroup_.insertBefore(e,this.getCanvas())}static newTrashcan(e){throw Error("The implementation of newTrashcan should be monkey-patched in by blockly.ts")}addZoomControls(){this.zoomControls_=new Fb(this);const e=this.zoomControls_.createDom();this.svgGroup_.appendChild(e)}addFlyout(e){const t=new ds({parentWorkspace:this,rtl:this.RTL,oneBasedIndex:this.options.oneBasedIndex,horizontalLayout:this.horizontalLayout,renderer:this.options.renderer,rendererOverrides:this.options.rendererOverrides,move:{scrollbars:!0}});return t.toolboxPosition=this.options.toolboxPosition,this.flyout=this.horizontalLayout?new(_(F.FLYOUTS_HORIZONTAL_TOOLBOX,this.options,!0))(t):new(_(F.FLYOUTS_VERTICAL_TOOLBOX,this.options,!0))(t),this.flyout.autoClose=!1,this.flyout.getWorkspace().setVisible(!0),this.flyout.createDom(e)}getFlyout(e){return this.flyout||e?this.flyout:this.toolbox?this.toolbox.getFlyout():null}getToolbox(){return this.toolbox}updateScreenCalculations(){this.updateInverseScreenCTM(),this.recordDragTargets()}resizeContents(){this.resizesEnabled&&this.rendered&&(this.scrollbar&&this.scrollbar.resize(),this.updateInverseScreenCTM())}resize(){this.toolbox&&this.toolbox.position(),this.flyout&&this.flyout.position();const e=this.componentManager.getComponents(lt.Capability.POSITIONABLE,!0),t=this.getMetricsManager().getUiMetrics(),o=[];for(let n=0,c;c=e[n];n++){c.position(t,o);const h=c.getBoundingRectangle();h&&o.push(h)}this.scrollbar&&this.scrollbar.resize(),this.updateScreenCalculations()}updateScreenCalculationsIfScrolled(){const e=fu();G.equals(this.lastRecordedPageScroll,e)||(this.lastRecordedPageScroll=e,this.updateScreenCalculations())}getLayerManager(){return this.layerManager}getCanvas(){return this.layerManager.getBlockLayer()}setCachedParentSvgSize(e,t){const o=this.getParentSvg();e!=null&&(this.cachedParentSvgSize.width=e,o.setAttribute("data-cached-width",`${e}`)),t!=null&&(this.cachedParentSvgSize.height=t,o.setAttribute("data-cached-height",`${t}`))}getBubbleCanvas(){return this.layerManager.getBubbleLayer()}getParentSvg(){if(!this.cachedParentSvg){let e=this.svgGroup_;for(;e;){if(e.tagName==="svg"){this.cachedParentSvg=e;break}e=e.parentNode}}return this.cachedParentSvg}maybeFireViewportChangeEvent(){if(K()){var e=this.scale,t=-this.scrollY,o=-this.scrollX;if(!(e===this.oldScale&&1>Math.abs(t-this.oldTop)&&1>Math.abs(o-this.oldLeft))){var n=new(V(O.VIEWPORT_CHANGE))(t,o,e,this.id,this.oldScale);this.oldScale=e,this.oldTop=t,this.oldLeft=o,z(n)}}}translate(e,t){let o;(o=this.layerManager)==null||o.translateLayers(new G(e,t),this.scale);let n;(n=this.grid)==null||n.moveTo(e,t),this.maybeFireViewportChangeEvent()}getWidth(){const e=this.getMetrics();return e?e.viewWidth/this.scale:0}setVisible(e){this.visible=e,this.svgGroup_&&(this.scrollbar&&this.scrollbar.setContainerVisible(e),this.getFlyout()&&this.getFlyout().setContainerVisible(e),this.getParentSvg().style.display=e?"block":"none",this.toolbox&&this.toolbox.setVisible(e),e||this.hideChaff(!0))}render(){const e=this.getAllBlocks(!1);for(let t=e.length-1;0<=t;t--)e[t].queueRender();this.getTopBlocks().flatMap(t=>t.getDescendants(!1)).filter(t=>t.isInsertionMarker()).forEach(t=>t.queueRender()),ws().then(()=>{this.markerManager.updateMarkers()})}highlightBlock(e,t){if(t===void 0){for(let o=0,n;n=this.highlightedBlocks[o];o++)n.setHighlighted(!1);this.highlightedBlocks.length=0}(e=e?this.getBlockById(e):null)&&((t=t===void 0||t)?this.highlightedBlocks.includes(e)||this.highlightedBlocks.push(e):St(this.highlightedBlocks,e),e.setHighlighted(t))}refreshToolboxSelection(){const e=this.isFlyout?this.targetWorkspace:this;e&&!e.currentGesture_&&e.toolbox&&e.toolbox.getFlyout()&&e.toolbox.refreshSelection()}renameVariableById(e,t){super.renameVariableById(e,t),this.refreshToolboxSelection()}deleteVariableById(e){super.deleteVariableById(e),this.refreshToolboxSelection()}createVariable(e,t,o){return e=super.createVariable(e,t,o),this.refreshToolboxSelection(),e}recordDragTargets(){const e=this.componentManager.getComponents(lt.Capability.DRAG_TARGET,!0);this.dragTargetAreas=[];for(let t=0,o;o=e[t];t++){const n=o.getClientRect();n&&this.dragTargetAreas.push({component:o,clientRect:n})}}newBlock(e,t){throw Error("The implementation of newBlock should be monkey-patched in by blockly.ts")}newComment(e){throw Error("The implementation of newComment should be monkey-patched in by blockly.ts")}getDragTarget(e){for(let t=0,o;o=this.dragTargetAreas[t];t++)if(o.clientRect.contains(e.clientX,e.clientY))return o.component;return null}onMouseDown(e){const t=this.getGesture(e);t&&t.handleWsStart(e,this)}startDrag(e,t){Ba(this,e,t)}moveDrag(e){return ja(this,e)}isDragging(){return this.currentGesture_!==null&&this.currentGesture_.isDragging()}isDraggable(){return this.options.moveOptions&&this.options.moveOptions.drag}isMovable(){return this.options.moveOptions&&!!this.options.moveOptions.scrollbars||this.options.moveOptions&&this.options.moveOptions.wheel||this.options.moveOptions&&this.options.moveOptions.drag||this.options.zoomOptions&&this.options.zoomOptions.wheel||this.options.zoomOptions&&this.options.zoomOptions.pinch}isMovableHorizontally(){const e=!!this.scrollbar;return this.isMovable()&&(!e||e&&this.scrollbar.canScrollHorizontally())}isMovableVertically(){const e=!!this.scrollbar;return this.isMovable()&&(!e||e&&this.scrollbar.canScrollVertically())}onMouseWheel(e){if(co.inProgress())e.preventDefault(),e.stopPropagation();else{var t=this.options.zoomOptions&&this.options.zoomOptions.wheel,o=this.options.moveOptions&&this.options.moveOptions.wheel;if(t||o){var n=Zs(e);if(_h)var c=e.metaKey;t&&(e.ctrlKey||c||!o)?(n=-n.y/50,t=st(e,this.getParentSvg(),this.getInverseScreenCTM()),this.zoom(t.x,t.y,n)):(t=this.scrollX-n.x,o=this.scrollY-n.y,e.shiftKey&&!n.x&&(t=this.scrollX-n.y,o=this.scrollY),this.scroll(t,o)),e.preventDefault()}}}getBlocksBoundingBox(){const e=this.getTopBoundedElements();if(!e.length)return new qe(0,0,0,0);const t=e[0].getBoundingRectangle();for(let n=1;nt.bottom&&(t.bottom=o.bottom),o.leftt.right&&(t.right=o.right))}return t}cleanUp(){this.setResizesEnabled(!1),i.setGroup$$module$build$src$core$events$utils(!0);var e=this.getTopBlocks(!0),t=e.filter(h=>h.isMovable());const o=e.filter(h=>!h.isMovable()).map(h=>h.getBoundingRectangle());e=function(h){for(const $ of o)if(h.intersects($))return $;return null};var n=0;const c=this.renderer.getConstants().MIN_BLOCK_HEIGHT;for(const h of t){for(t=h.getBoundingRectangle(),h.moveBy(-t.left,n-t.top,["cleanup"]),h.snapToGrid(),t=h.getBoundingRectangle(),n=e(t);n!=null;)n=n.top+n.getHeight()+c,h.moveBy(0,n-t.top,["cleanup"]),h.snapToGrid(),t=h.getBoundingRectangle(),n=e(t);n=h.getRelativeToSurfaceXY().y+h.getHeightWidth().height+c}i.setGroup$$module$build$src$core$events$utils(!1),this.setResizesEnabled(!0)}showContextMenu(e){if(!this.options.readOnly&&!this.isFlyout){var t=xe.registry.getContextMenuOptions(xe.ScopeType.WORKSPACE,{workspace:this});this.configureContextMenu&&this.configureContextMenu(t,e),Jn(e,t,this.RTL,this)}}updateToolbox(e){if(e=ga(e)){if(!this.options.languageTree)throw Error("Existing toolbox is null. Can't create new toolbox.");if(ma(e)){if(!this.toolbox)throw Error("Existing toolbox has no categories. Can't change mode.");this.options.languageTree=e,this.toolbox.render(e)}else{if(!this.flyout)throw Error("Existing toolbox has categories. Can't change mode.");this.options.languageTree=e,this.flyout.show(e)}}else if(this.options.languageTree)throw Error("Can't nullify an existing toolbox.")}markFocused(){this.options.parentWorkspace?this.options.parentWorkspace.markFocused():(re(this),this.getParentSvg().focus({preventScroll:!0}))}zoom(e,t,o){o=Math.pow(this.options.zoomOptions.scaleSpeed,o);const n=this.scale*o;if(this.scale!==n){n>this.options.zoomOptions.maxScale?o=this.options.zoomOptions.maxScale/this.scale:nthis.options.zoomOptions.maxScale?e=this.options.zoomOptions.maxScale:this.options.zoomOptions.minScale&&et.autoHide(e))}static setTopLevelWorkspaceMetrics(e){const t=this.getMetrics();typeof e.x=="number"&&(this.scrollX=-(t.scrollLeft+(t.scrollWidth-t.viewWidth)*e.x)),typeof e.y=="number"&&(this.scrollY=-(t.scrollTop+(t.scrollHeight-t.viewHeight)*e.y)),this.translate(this.scrollX+t.absoluteLeft,this.scrollY+t.absoluteTop)}},vp=class extends Cs{constructor(e,t,o){super(o),this.type=O.SELECTED,this.oldElementId=e??void 0,this.newElementId=t??void 0}toJson(){const e=super.toJson();return e.oldElementId=this.oldElementId,e.newElementId=this.newElementId,e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new vp),t.oldElementId=e.oldElementId,t.newElementId=e.newElementId,t}};r(F.EVENT,O.SELECTED,vp);var Sr=class{paste(e,t,o){if(!t.isCapacityAvailable(e.typeCounts))return null;o&&(e.blockState.x=o.x,e.blockState.y=o.y),o=o||new G(e.blockState.x||0,e.blockState.y||0),i.disable$$module$build$src$core$events$utils();let n;try{n=eo(e.blockState,t),z$(n,o)}finally{i.enable$$module$build$src$core$events$utils()}return n&&(K()&&!n.isShadow()&&z(new(V(O.BLOCK_CREATE))(n)),i.setSelected$$module$build$src$core$common(n),n)}};Sr.TYPE="block",_a(Sr.TYPE,new Sr);var Bl={};Bl.bumpIntoBounds=zi,Bl.bumpIntoBoundsHandler=Ld,Bl.bumpTopObjectsIntoBounds=Xa;var Pv=class{constructor(e){this.block=e,this.connectionPreviewer=this.connectionCandidate=this.startLoc=this.startChildConn=this.startParentConn=null,this.dragging=!1,this.dragOffset=new G(0,0),this.inGroup=!1,this.workspace=e.workspace}isMovable(){if(this.block.isShadow()){let e,t;return(t=(e=this.block.getParent())==null?void 0:e.isMovable())!=null?t:!1}return this.block.isOwnMovable()&&!this.block.isDeadOrDying()&&!this.workspace.options.readOnly&&!this.block.isInFlyout}startDrag(e){if(this.block.isShadow())this.startDraggingShadow(e);else{this.dragging=!0,(this.inGroup=!!i.getGroup$$module$build$src$core$events$utils())||i.setGroup$$module$build$src$core$events$utils(!0),this.fireDragStartEvent(),this.startLoc=this.block.getRelativeToSurfaceXY(),this.connectionCandidate=null,this.connectionPreviewer=new(_(F.CONNECTION_PREVIEWER,this.workspace.options))(this.block),Ho(),this.workspace.setResizesEnabled(!1),ji(),e=!!e&&(e.altKey||e.ctrlKey||e.metaKey),this.shouldDisconnect(e)&&this.disconnectBlock(e),this.block.setDragging(!0);var t;(t=this.workspace.getLayerManager())==null||t.moveToDragLayer(this.block)}}startDraggingShadow(e){const t=this.block.getParent();if(!t)throw Error("Tried to drag a shadow block with no parent. Shadow blocks should always have parents.");this.dragOffset=G.difference(t.getRelativeToSurfaceXY(),this.block.getRelativeToSurfaceXY()),t.startDrag(e)}shouldDisconnect(e){return!!(this.block.getParent()||e&&this.block.nextConnection&&this.block.nextConnection.targetBlock())}disconnectBlock(e){let t,o,n;if(this.startParentConn=(n=(t=this.block.outputConnection)==null?void 0:t.targetConnection)!=null?n:(o=this.block.previousConnection)==null?void 0:o.targetConnection,e){let c;this.startChildConn=(c=this.block.nextConnection)==null?void 0:c.targetConnection}this.block.unplug(e),vd(this.block)}fireDragStartEvent(){const e=new(V(O.BLOCK_DRAG))(this.block,!0,this.block.getDescendants(!1));z(e)}fireDragEndEvent(){const e=new(V(O.BLOCK_DRAG))(this.block,!1,this.block.getDescendants(!1));z(e)}fireMoveEvent(){if(!this.block.isDeadOrDying()){var e=new(V(O.BLOCK_MOVE))(this.block);e.setReason(["drag"]),e.oldCoordinate=this.startLoc,e.recordNew(),z(e)}}drag(e){if(this.block.isShadow()){let t;(t=this.block.getParent())==null||t.drag(G.sum(e,this.dragOffset))}else this.block.moveDuringDrag(e),this.updateConnectionPreview(this.block,G.difference(e,this.startLoc))}updateConnectionPreview(e,t){var o=this.connectionCandidate;const n=this.getConnectionCandidate(e,t);if(n){this.connectionCandidate=t=o&&this.currCandidateIsBetter(o,t,n)?o:n;var{local:c,neighbour:h}=t;t=c.type===oe.OUTPUT_VALUE||c.type===oe.PREVIOUS_STATEMENT,o=h.isConnected()&&!h.targetBlock().isInsertionMarker(),t&&o&&!this.orphanCanConnectAtEnd(e,h.targetBlock(),c.type)?this.connectionPreviewer.previewReplacement(c,h,h.targetBlock()):this.connectionPreviewer.previewConnection(c,h)}else this.connectionPreviewer.hidePreview(),this.connectionCandidate=null}orphanCanConnectAtEnd(e,t,o){return!!Be.getConnectionForOrphanedConnection(e,o===oe.OUTPUT_VALUE?t.outputConnection:t.previousConnection)}currCandidateIsBetter(e,t,o){const{local:n,neighbour:c}=e;e=new G(n.x,n.y);const h=new G(c.x,c.y);return t=G.distance(G.sum(e,t),h),o.distance>t-i.config$$module$build$src$core$config.currentConnectionPreference}getConnectionCandidate(e,t){e=this.getLocalConnections(e);let o=this.connectionCandidate?i.config$$module$build$src$core$config.connectingSnapRadius:i.config$$module$build$src$core$config.snapRadius,n=null;for(const c of e){const{connection:h,radius:$}=c.closest(o,t);h&&(n={local:c,neighbour:h,distance:$},o=$)}return n}getLocalConnections(e){const t=e.getConnections_(!1),o=e.lastConnectionInStack(!0);return o&&o!==e.nextConnection&&t.push(o),t}endDrag(e){if(this.block.isShadow()){let t;(t=this.block.getParent())==null||t.endDrag(e)}else{if(this.fireDragEndEvent(),this.fireMoveEvent(),Wo(),ji(),this.connectionPreviewer.hidePreview(),!this.block.isDeadOrDying()&&this.dragging){let t;(t=this.workspace.getLayerManager())==null||t.moveOffDragLayer(this.block,Do),this.block.setDragging(!1)}this.connectionCandidate?(this.applyConnections(this.connectionCandidate),this.disposeStep()):this.block.queueRender().then(()=>this.disposeStep()),this.inGroup||i.setGroup$$module$build$src$core$events$utils(!1)}}disposeStep(){this.block.snapToGrid(),this.connectionPreviewer.dispose(),this.workspace.setResizesEnabled(!0)}applyConnections(e){const{local:t,neighbour:o}=e;t.connect(o);const n=t.isSuperior()?o:t,c=this.block.getRootBlock();ws().then(()=>{Ua(n.getSourceBlock()),setTimeout(()=>{c.bringToFront()},0)})}revertDrag(){if(this.block.isShadow()){let t;(t=this.block.getParent())==null||t.revertDrag()}else{var e;if((e=this.startChildConn)==null||e.connect(this.block.nextConnection),this.startParentConn)switch(this.startParentConn.type){case oe.INPUT_VALUE:this.startParentConn.connect(this.block.outputConnection);break;case oe.NEXT_STATEMENT:this.startParentConn.connect(this.block.previousConnection)}else{this.block.moveTo(this.startLoc,["drag"]);let t;(t=this.workspace.getLayerManager())==null||t.moveOffDragLayer(this.block,Do),zi(this.workspace,this.workspace.getMetricsManager().getScrollMetrics(!0),this.block)}this.startParentConn=this.startChildConn=null,this.connectionPreviewer.hidePreview(),this.connectionCandidate=null,this.block.setDragging(!1),this.dragging=!1}}},Bv=class{constructor(){this.drawer=this.curNode=this.colour=null,this.type="marker"}setDrawer(e){this.drawer=e}getDrawer(){return this.drawer}getCurNode(){return this.curNode}setCurNode(e){const t=this.curNode;this.curNode=e,this.drawer&&this.drawer.draw(t,this.curNode)}draw(){this.drawer&&this.drawer.draw(this.curNode,this.curNode)}hide(){this.drawer&&this.drawer.hide()}dispose(){this.getDrawer()&&this.getDrawer().dispose()}},yp=class extends Bv{constructor(){super(),this.type="cursor"}next(){var e=this.getCurNode();if(!e)return null;for(e=e.next();e&&e.next()&&(e.getType()===P.types.NEXT||e.getType()===P.types.BLOCK);)e=e.next();return e&&this.setCurNode(e),e}in(){var e=this.getCurNode();if(!e)return null;(e.getType()===P.types.PREVIOUS||e.getType()===P.types.OUTPUT)&&(e=e.next());let t,o;return(e=(o=(t=e)==null?void 0:t.in())!=null?o:null)&&this.setCurNode(e),e}prev(){var e=this.getCurNode();if(!e)return null;for(e=e.prev();e&&e.prev()&&(e.getType()===P.types.NEXT||e.getType()===P.types.BLOCK);)e=e.prev();return e&&this.setCurNode(e),e}out(){var e=this.getCurNode();return e?((e=e.out())&&e.getType()===P.types.BLOCK&&(e=e.prev()||e),e&&this.setCurNode(e),e):null}};r(F.CURSOR,js,yp);var Er=class extends yp{constructor(){super()}next(){var e=this.getCurNode();return e?((e=this.getNextNode_(e,this.validNode_))&&this.setCurNode(e),e):null}in(){return this.next()}prev(){var e=this.getCurNode();return e?((e=this.getPreviousNode_(e,this.validNode_))&&this.setCurNode(e),e):null}out(){return this.prev()}getNextNode_(e,t){if(!e)return null;const o=e.in()||e.next();return t(o)?o:o?this.getNextNode_(o,t):(e=this.findSiblingOrParent(e.out()),t(e)?e:e?this.getNextNode_(e,t):null)}getPreviousNode_(e,t){if(!e)return null;let o=e.prev();return o=o?this.getRightMostChild(o):e.out(),t(o)?o:o?this.getPreviousNode_(o,t):null}validNode_(e){let t=!1;return e=e&&e.getType(),(e===P.types.OUTPUT||e===P.types.INPUT||e===P.types.FIELD||e===P.types.NEXT||e===P.types.PREVIOUS||e===P.types.WORKSPACE)&&(t=!0),t}findSiblingOrParent(e){if(!e)return null;const t=e.next();return t||this.findSiblingOrParent(e.out())}getRightMostChild(e){if(!e.in())return e;for(e=e.in();e&&e.next();)e=e.next();return this.getRightMostChild(e)}};Er.registrationName="basicCursor",r(F.CURSOR,Er.registrationName,Er);var jv=class extends Er{validNode_(e){let t=!1;const o=e&&e.getType();return e&&(e=e.getLocation(),o===P.types.FIELD&&e&&e.isTabNavigable()&&e.isClickable()&&(t=!0)),t}},Fv=10,Ut=class extends Be{constructor(e,t){super(e,t),this.highlighted=!1,this.targetConnection=null,this.db=e.workspace.connectionDBList[t],this.dbOpposite=e.workspace.connectionDBList[gi[t]],this.offsetInBlock=new G(0,0),this.trackedState=Ut.TrackedState.WILL_TRACK}dispose(){super.dispose(),this.trackedState===Ut.TrackedState.TRACKED&&this.db.removeConnection(this,this.y);let e,t;(t=(e=this.sourceBlock_.pathObject).removeConnectionHighlight)==null||t.call(e,this)}getSourceBlock(){return super.getSourceBlock()}targetBlock(){return super.targetBlock()}distanceFrom(e){const t=this.x-e.x;return e=this.y-e.y,Math.sqrt(t*t+e*e)}bumpAwayFrom(e,t=!1){if(!this.sourceBlock_.workspace.isDragging()){var o=i.config$$module$build$src$core$config.snapRadius+Math.floor(Math.random()*Fv),n=i.config$$module$build$src$core$config.snapRadius+Math.floor(Math.random()*Fv),c=e.sourceBlock_.getRootBlock(),h=this.sourceBlock_.getRootBlock();if(!c.isInFlyout&&!h.isInFlyout){var $=!0;if(h.isMovable())c.isMovable()&&t&&(n=-n);else if(c.isMovable())$=!1,o=-o,n=-n;else return;t=$?e:this,e=$?this:e,c=$?h:c,(h=I()===c)||c.addSelect(),c.RTL&&(o=-o),c.moveBy(t.x+o-e.x,t.y+n-e.y,["bump"]),h||c.removeSelect()}}}moveTo(e,t){let o=!1;return this.trackedState===Ut.TrackedState.WILL_TRACK?(this.db.addConnection(this,t),this.trackedState=Ut.TrackedState.TRACKED,o=!0):this.trackedState===Ut.TrackedState.TRACKED&&(this.db.removeConnection(this,this.y),this.db.addConnection(this,t),o=!0),this.x=e,this.y=t,o}moveBy(e,t){return this.moveTo(this.x+e,this.y+t)}moveToOffset(e){return this.moveTo(e.x+this.offsetInBlock.x,e.y+this.offsetInBlock.y)}setOffsetInBlock(e,t){this.offsetInBlock.x=e,this.offsetInBlock.y=t}getOffsetInBlock(){return this.offsetInBlock}tightenEfficiently(){var e=this.targetConnection;const t=this.targetBlock();e&&t&&(e=G.difference(this.offsetInBlock,e.offsetInBlock),t.translate(e.x,e.y))}closest(e,t){return this.dbOpposite.searchForClosest(this,e,t)}highlight(){this.highlighted=!0,this.getSourceBlock().queueRender()}unhighlight(){this.highlighted=!1,this.getSourceBlock().queueRender()}isHighlighted(){return this.highlighted}setTracking(e){e&&this.trackedState===Ut.TrackedState.TRACKED||!e&&this.trackedState===Ut.TrackedState.UNTRACKED||this.sourceBlock_.isInFlyout||(e?(this.db.addConnection(this,this.y),this.trackedState=Ut.TrackedState.TRACKED):(this.trackedState===Ut.TrackedState.TRACKED&&this.db.removeConnection(this,this.y),this.trackedState=Ut.TrackedState.UNTRACKED))}stopTrackingAll(){if(this.setTracking(!1),this.targetConnection){const e=this.targetBlock().getDescendants(!1);for(let t=0;tclearTimeout(e)),this.warningTextDb.clear(),this.getIcons().forEach(e=>e.dispose())}checkAndDelete(){this.workspace.isFlyout||(i.setGroup$$module$build$src$core$events$utils(!0),this.workspace.hideChaff(),this.outputConnection?this.dispose(!1,!0):this.dispose(!0,!0),i.setGroup$$module$build$src$core$events$utils(!1))}toCopyData(){return this.isInsertionMarker_?null:{paster:Sr.TYPE,blockState:Qt(this,{addCoordinates:!0,addNextBlocks:!1}),typeCounts:be(this,!0)}}applyColour(){this.pathObject.applyColour(this);const e=this.getIcons();for(let t=0;t{this.isDeadOrDying()||(this.warningTextDb.delete(t),this.setWarningText(e,t))},100));else if(this.isInFlyout&&(e=null),o=this.getIcon(go.TYPE),e){let n=this.getSurroundParent(),c=null;for(;n;)n.isCollapsed()&&(c=n),n=n.getSurroundParent();c&&c.setWarningText(i.Msg$$module$build$src$core$msg.COLLAPSED_WARNINGS_WARNING,gs.COLLAPSED_WARNING_ID),o?o.addMessage(e,t):this.addIcon(new go(this).addMessage(e,t))}else o&&(t?(o.addMessage("",t),o.getText()||this.removeIcon(go.TYPE)):this.removeIcon(go.TYPE))}setMutator(e){this.removeIcon(i.MutatorIcon$$module$build$src$core$icons$mutator_icon.TYPE),e&&this.addIcon(e)}addIcon(e){return super.addIcon(e),e instanceof i.MutatorIcon$$module$build$src$core$icons$mutator_icon&&(this.mutator=e),e.initView(this.createIconPointerDownListener(e)),e.applyColour(),e.updateEditable(),this.queueRender(),e}createIconPointerDownListener(e){return t=>{this.isDeadOrDying()||(t=this.workspace.getGesture(t))&&t.setStartIcon(e)}}removeIcon(e){const t=super.removeIcon(e);return e.equals(i.MutatorIcon$$module$build$src$core$icons$mutator_icon.TYPE)&&(this.mutator=null),this.queueRender(),t}setEnabled(e){y("setEnabled","v11","v12","the setDisabledReason method of BlockSvg");const t=this.isEnabled();super.setEnabled(e),this.isEnabled()===t||this.getInheritedDisabled()||this.updateDisabled()}setDisabledReason(e,t){const o=this.isEnabled();super.setDisabledReason(e,t),this.isEnabled()===o||this.getInheritedDisabled()||this.updateDisabled()}setHighlighted(e){this.pathObject.updateHighlighted(e)}addSelect(){this.pathObject.updateSelected(!0)}removeSelect(){this.pathObject.updateSelected(!1)}setDeleteStyle(e){this.pathObject.updateDraggingDelete(e)}getColour(){return this.style.colourPrimary}setColour(e){super.setColour(e),e=this.workspace.getRenderer().getConstants().getBlockStyleForColour(this.colour_),this.pathObject.setStyle(e.style),this.style=e.style,this.styleName_=e.name,this.applyColour()}setStyle(e){const t=this.workspace.getRenderer().getConstants().getBlockStyle(e);if(this.styleName_=e,t)this.hat=t.hat,this.pathObject.setStyle(t),this.colour_=t.colourPrimary,this.style=t,this.applyColour();else throw Error("Invalid style name: "+e)}getStyle(){return this.style}bringToFront(e=!1){let t=this;if(!t.isDeadOrDying())do{const o=t.getSvgRoot(),n=o.parentNode,c=n.childNodes;if(c[c.length-1]!==o&&n.appendChild(o),e)break;t=t.getParent()}while(t)}setPreviousStatement(e,t){super.setPreviousStatement(e,t),this.queueRender()}setNextStatement(e,t){super.setNextStatement(e,t),this.queueRender()}setOutput(e,t){super.setOutput(e,t),this.queueRender()}setInputsInline(e){super.setInputsInline(e),this.queueRender()}removeInput(e,t){return e=super.removeInput(e,t),this.queueRender(),e}moveNumberedInputBefore(e,t){super.moveNumberedInputBefore(e,t),this.queueRender()}appendInput(e){return super.appendInput(e),this.queueRender(),e}setConnectionTracking(e){if(this.previousConnection&&this.previousConnection.setTracking(e),this.outputConnection&&this.outputConnection.setTracking(e),this.nextConnection){this.nextConnection.setTracking(e);var t=this.nextConnection.targetBlock();t&&t.setConnectionTracking(e)}if(!this.collapsed_)for(t=0;t=this.workspace.options.maxTrashcanContents||(e=new ds({scrollbars:!0,parentWorkspace:this.workspace,rtl:this.workspace.RTL,oneBasedIndex:this.workspace.options.oneBasedIndex,renderer:this.workspace.options.renderer,rendererOverrides:this.workspace.options.rendererOverrides,move:{scrollbars:!0}}),this.workspace.horizontalLayout?(e.toolboxPosition=this.workspace.toolboxPosition===Ee.TOP?Ee.BOTTOM:Ee.TOP,this.flyout=new(_(F.FLYOUTS_HORIZONTAL_TOOLBOX,this.workspace.options,!0))(e)):(e.toolboxPosition=this.workspace.toolboxPosition===Ee.RIGHT?Ee.LEFT:Ee.RIGHT,this.flyout=new(_(F.FLYOUTS_VERTICAL_TOOLBOX,this.workspace.options,!0))(e)),this.workspace.addChangeListener(this.onDelete.bind(this)))}createDom(){this.svgGroup=N(x.G,{class:"blocklyTrash"});let e;const t=String(Math.random()).substring(2);e=N(x.CLIPPATH,{id:"blocklyTrashBodyClipPath"+t},this.svgGroup),N(x.RECT,{width:an,height:Fl,y:ln},e);const o=N(x.IMAGE,{width:jt.width,x:-wp,height:jt.height,y:-Cp,"clip-path":"url(#blocklyTrashBodyClipPath"+t+")"},this.svgGroup);return o.setAttributeNS(es,"xlink:href",this.workspace.options.pathToMedia+jt.url),e=N(x.CLIPPATH,{id:"blocklyTrashLidClipPath"+t},this.svgGroup),N(x.RECT,{width:an,height:ln},e),this.svgLid=N(x.IMAGE,{width:jt.width,x:-wp,height:jt.height,y:-Cp,"clip-path":"url(#blocklyTrashLidClipPath"+t+")"},this.svgGroup),this.svgLid.setAttributeNS(es,"xlink:href",this.workspace.options.pathToMedia+jt.url),ct(this.svgGroup,"pointerdown",this,this.blockMouseDownWhenOpenable),ct(this.svgGroup,"pointerup",this,this.click),ct(o,"pointerover",this,this.mouseOver),ct(o,"pointerout",this,this.mouseOut),this.animateLid(),this.svgGroup}init(){0{let o;(o=this.flyout)==null||o.show(e),t.cursor="";let n;(n=this.workspace.scrollbar)==null||n.setVisible(!1)},10),this.fireUiEvent(!0)}}closeFlyout(){if(this.contentsIsOpen()){var e;(e=this.flyout)==null||e.hide();var t;(t=this.workspace.scrollbar)==null||t.setVisible(!0),this.fireUiEvent(!1),this.workspace.recordDragTargets()}}autoHide(e){!e&&this.flyout&&this.closeFlyout()}emptyContents(){this.hasContents()&&(this.contents.length=0,this.setMinOpenness(0),this.closeFlyout())}position(e,t){if(this.initialized){var o=va(this.workspace,e);e=ba(o,new Le(an,Fl+ln),ok,Hv,e,this.workspace),t=ya(e,Hv,o.vertical===lo.TOP?Io.DOWN:Io.UP,t),this.top=t.top,this.left=t.left;var n;(n=this.svgGroup)==null||n.setAttribute("transform","translate("+this.left+","+this.top+")");var c;(c=this.flyout)==null||c.position()}}getBoundingRectangle(){return new qe(this.top,this.top+Fl+ln,this.left,this.left+an)}getClientRect(){if(!this.svgGroup)return null;var e=this.svgGroup.getBoundingClientRect();const t=e.top+Cp-zl;return e=e.left+wp-zl,new qe(t,t+ln+Fl+2*zl,e,e+an+2*zl)}onDragOver(e){this.setLidOpen(this.wouldDelete_)}onDragExit(e){this.setLidOpen(!1)}onDrop(e){setTimeout(this.setLidOpen.bind(this,!1),100)}setLidOpen(e){this.isLidOpen!==e&&(this.lidTask&&clearTimeout(this.lidTask),this.isLidOpen=e,this.animateLid())}animateLid(){const e=rk;var t=1/(e+1);this.lidOpen+=this.isLidOpen?t:-t,this.lidOpen=Math.min(Math.max(this.lidOpen,this.minOpenness),1),this.setLidAngle(this.lidOpen*Gv),t=Wv+this.lidOpen*(ak-Wv),this.svgGroup&&(this.svgGroup.style.opacity=`${t}`),this.lidOpen>this.minOpenness&&1>this.lidOpen&&(this.lidTask=setTimeout(this.animateLid.bind(this),nk/e))}setLidAngle(e){const t=this.workspace.toolboxPosition===Ee.RIGHT||this.workspace.horizontalLayout&&this.workspace.RTL;let o;(o=this.svgLid)==null||o.setAttribute("transform","rotate("+(t?-e:e)+","+(t?4:an-4)+","+(ln-2)+")")}setMinOpenness(e){this.minOpenness=e,this.isLidOpen||this.setLidAngle(e*Gv)}closeLid(){this.setLidOpen(!1)}click(){this.hasContents()&&!this.workspace.isDragging()&&this.openFlyout()}fireUiEvent(e){e=new(V(O.TRASHCAN_OPEN))(e,this.workspace.id),z(e)}blockMouseDownWhenOpenable(e){!this.contentsIsOpen()&&this.hasContents()&&e.stopPropagation()}mouseOver(){this.hasContents()&&this.setLidOpen(!0)}mouseOut(){this.setLidOpen(!1)}onDelete(e){if(!(0>=this.workspace.options.maxTrashcanContents||!E(e)||e.wasShadow)){if(!e.oldJson)throw Error("Encountered a delete event without proper oldJson");if(e=JSON.stringify(this.cleanBlockJson(e.oldJson)),!this.contents.includes(e)){for(this.contents.unshift(e);this.contents.length>this.workspace.options.maxTrashcanContents;)this.contents.pop();this.setMinOpenness(ik)}}}cleanBlockJson(e){function t(o){if(o){if(delete o.id,delete o.x,delete o.y,delete o.enabled,delete o.disabledReasons,o.icons&&o.icons.comment){var n=o.icons.comment;delete n.height,delete n.width,delete n.pinned}n=o.inputs;for(var c in n){var h=n[c];const $=h.block;h=h.shadow,$&&t($),h&&t(h)}o.next&&(c=o.next,o=c.block,c=c.shadow,o&&t(o),c&&t(c))}}return e=JSON.parse(JSON.stringify(e)),t(e),Object.assign({},{kind:"BLOCK"},e)}},an=47,Fl=44,ln=16,Hv=20,ok=20,zl=10,wp=0,Cp=32,ik=.1,nk=80,rk=4,Wv=.4,ak=.8,Gv=45,He=class{constructor(){this.shortcuts=new Map,this.keyMap=new Map,this.reset()}reset(){this.shortcuts.clear(),this.keyMap.clear()}register(e,t){if(this.shortcuts.get(e.name)&&!t)throw Error(`Shortcut named "${e.name}" already exists.`);if(this.shortcuts.set(e.name,e),t=e.keyCodes,t!=null&&t.length)for(const o of t)this.addKeyMapping(o,e.name,!!e.allowCollision)}unregister(e){return this.shortcuts.get(e)?(this.removeAllKeyMappings(e),this.shortcuts.delete(e),!0):(console.warn(`Keyboard shortcut named "${e}" not found.`),!1)}addKeyMapping(e,t,o){e=`${e}`;const n=this.keyMap.get(e);if(n&&!o)throw Error(`Shortcut named "${t}" collides with shortcuts "${n}"`);n&&o?n.unshift(t):this.keyMap.set(e,[t])}removeKeyMapping(e,t,o){const n=this.keyMap.get(e);if(!n)return o||console.warn(`No keyboard shortcut named "${t}" registered with key code "${e}"`),!1;const c=n.indexOf(t);return-1Vd(t)),e.length?e:null}load(e,t){const o=t.getProcedureMap();for(const n of e)o.add(Kd(this.procedureModelClass,this.parameterModelClass,n,t))}clear(e){e.getProcedureMap().clear()}},Ul={};Ul.ProcedureSerializer=ck,Ul.loadProcedure=Kd,Ul.saveProcedure=Vd;var Vv=class{constructor(){this.priority=zb}save(e){const t=[];for(const o of e.getAllVariables())e={name:o.name,id:o.getId()},o.type&&(e.type=o.type),t.push(e);return t.length?t:null}load(e,t){for(const o of e)t.createVariable(o.name,o.type,o.id)}clear(e){e.getVariableMap().clear()}};jn("variables",new Vv);var Kv={};Kv.VariableSerializer=Vv;var Sp={};Sp.load=Y$,Sp.save=K$;var uk={blocks:gr,exceptions:ii,priorities:jT,procedures:Ul,registry:Ih,variables:Kv,workspaceComments:cl,workspaces:Sp},Ep=class{constructor(e,t,o,n,c){this.workspace=e,this.oldHostMetrics=this.corner_=this.vScroll=this.hScroll=null,t=t===void 0?!0:t,o=o===void 0?!0:o;const h=t&&o;t&&(this.hScroll=new mt(e,!0,h,n,c)),o&&(this.vScroll=new mt(e,!1,h,n,c)),h&&(this.corner_=N(x.RECT,{height:mt.scrollbarThickness,width:mt.scrollbarThickness,class:"blocklyScrollbarBackground"}),Uo(this.corner_,e.getBubbleCanvas()))}dispose(){Ke(this.corner_),this.oldHostMetrics=this.corner_=null,this.hScroll&&(this.hScroll.dispose(),this.hScroll=null),this.vScroll&&(this.vScroll.dispose(),this.vScroll=null)}resize(){const e=this.workspace.getMetrics();if(e){var t=!1,o=!1;if(this.oldHostMetrics&&this.oldHostMetrics.viewWidth===e.viewWidth&&this.oldHostMetrics.viewHeight===e.viewHeight&&this.oldHostMetrics.absoluteTop===e.absoluteTop&&this.oldHostMetrics.absoluteLeft===e.absoluteLeft?(this.oldHostMetrics&&this.oldHostMetrics.scrollWidth===e.scrollWidth&&this.oldHostMetrics.viewLeft===e.viewLeft&&this.oldHostMetrics.scrollLeft===e.scrollLeft||(t=!0),this.oldHostMetrics&&this.oldHostMetrics.scrollHeight===e.scrollHeight&&this.oldHostMetrics.viewTop===e.viewTop&&this.oldHostMetrics.scrollTop===e.scrollTop||(o=!0)):o=t=!0,t||o){try{i.disable$$module$build$src$core$events$utils(),this.hScroll&&t&&this.hScroll.resize(e),this.vScroll&&o&&this.vScroll.resize(e)}finally{i.enable$$module$build$src$core$events$utils()}this.workspace.maybeFireViewportChangeEvent()}if(this.hScroll&&this.vScroll){if(!this.oldHostMetrics||this.oldHostMetrics.viewWidth!==e.viewWidth||this.oldHostMetrics.absoluteLeft!==e.absoluteLeft){let n;(n=this.corner_)==null||n.setAttribute("x",String(this.vScroll.position.x))}if(!this.oldHostMetrics||this.oldHostMetrics.viewHeight!==e.viewHeight||this.oldHostMetrics.absoluteTop!==e.absoluteTop){let n;(n=this.corner_)==null||n.setAttribute("y",String(this.hScroll.position.y))}}this.oldHostMetrics=e}}canScrollHorizontally(){return!!this.hScroll}canScrollVertically(){return!!this.vScroll}setOrigin(e,t){this.hScroll&&this.hScroll.setOrigin(e,t),this.vScroll&&this.vScroll.setOrigin(e,t)}set(e,t,o){this.hScroll&&this.hScroll.set(e,!1),this.vScroll&&this.vScroll.set(t,!1),(o||o===void 0)&&(e={},this.hScroll&&(e.x=this.hScroll.getRatio_()),this.vScroll&&(e.y=this.vScroll.getRatio_()),this.workspace.setMetrics(e))}setX(e){this.hScroll&&this.hScroll.set(e,!0)}setY(e){this.vScroll&&this.vScroll.set(e,!0)}setContainerVisible(e){this.hScroll&&this.hScroll.setContainerVisible(e),this.vScroll&&this.vScroll.setContainerVisible(e)}isVisible(){let e=!1;return this.hScroll&&(e=this.hScroll.isVisible()),this.vScroll&&(e=e||this.vScroll.isVisible()),e}setVisible(e){this.hScroll&&this.hScroll.setVisibleInternal(e),this.vScroll&&this.vScroll.setVisibleInternal(e)}resizeContent(e){this.hScroll&&this.hScroll.resizeContentHorizontal(e),this.vScroll&&this.vScroll.resizeContentVertical(e)}resizeView(e){this.hScroll&&this.hScroll.resizeViewHorizontal(e),this.vScroll&&this.vScroll.resizeViewVertical(e)}},Ip=class{constructor(e){this.workspace_=e}getDimensionsPx_(e){let t=0,o=0;return e&&(t=e.getWidth(),o=e.getHeight()),new Le(t,o)}getFlyoutMetrics(e){return e=this.getDimensionsPx_(this.workspace_.getFlyout(e)),{width:e.width,height:e.height,position:this.workspace_.toolboxPosition}}getToolboxMetrics(){const e=this.getDimensionsPx_(this.workspace_.getToolbox());return{width:e.width,height:e.height,position:this.workspace_.toolboxPosition}}getSvgMetrics(){return this.workspace_.getCachedParentSvgSize()}getAbsoluteMetrics(){let e=0,t=0;const o=this.getToolboxMetrics(),n=this.getFlyoutMetrics(),c=!!this.workspace_.getToolbox();var h;const $=!((h=this.workspace_.getFlyout())!=null&&h.autoClose);h=c?o.position:n.position;const T=h===Ee.TOP;return h===Ee.LEFT&&(c&&(e+=o.width),$&&(e+=n.width)),T&&(c&&(t+=o.height),$&&(t+=n.height)),{top:t,left:e}}getViewMetrics(e){e=e?this.workspace_.scale:1;const t=this.getSvgMetrics(),o=this.getToolboxMetrics(),n=this.getFlyoutMetrics(),c=!!this.workspace_.getToolbox();var h;const $=!((h=this.workspace_.getFlyout())!=null&&h.autoClose);h=c?o.position:n.position;const T=h===Ee.LEFT||h===Ee.RIGHT;return(h===Ee.TOP||h===Ee.BOTTOM)&&(c&&(t.height-=o.height),$&&(t.height-=n.height)),T&&(c&&(t.width-=o.width),$&&(t.width-=n.width)),{height:t.height/e,width:t.width/e,top:-this.workspace_.scrollY/e,left:-this.workspace_.scrollX/e}}getContentMetrics(e){e=e?1:this.workspace_.scale;const t=this.workspace_.getBlocksBoundingBox();return{height:(t.bottom-t.top)*e,width:(t.right-t.left)*e,top:t.top*e,left:t.left*e}}hasFixedEdges(){return!this.workspace_.isMovableHorizontally()||!this.workspace_.isMovableVertically()}getComputedFixedEdges_(e){if(!this.hasFixedEdges())return{};const t=this.workspace_.isMovableHorizontally(),o=this.workspace_.isMovableVertically();e=e||this.getViewMetrics(!1);const n={};return o||(n.top=e.top,n.bottom=e.top+e.height),t||(n.left=e.left,n.right=e.left+e.width),n}getPaddedContent_(e,t){const o=t.top+t.height,n=t.left+t.width,c=e.width;e=e.height;const h=c/2,$=e/2;return{top:Math.min(t.top-$,o-e),bottom:Math.max(o+$,t.top+e),left:Math.min(t.left-h,n-c),right:Math.max(n+h,t.left+c)}}getScrollMetrics(e,t,o){e=e?this.workspace_.scale:1,t=t||this.getViewMetrics(!1);var n=o||this.getContentMetrics();o=this.getComputedFixedEdges_(t),t=this.getPaddedContent_(t,n),n=o.top!==void 0?o.top:t.top;const c=o.left!==void 0?o.left:t.left;return{top:n/e,left:c/e,width:((o.right!==void 0?o.right:t.right)-c)/e,height:((o.bottom!==void 0?o.bottom:t.bottom)-n)/e}}getUiMetrics(){return{viewMetrics:this.getViewMetrics(),absoluteMetrics:this.getAbsoluteMetrics(),toolboxMetrics:this.getToolboxMetrics()}}getMetrics(){const e=this.getToolboxMetrics(),t=this.getFlyoutMetrics(!0),o=this.getSvgMetrics(),n=this.getAbsoluteMetrics(),c=this.getViewMetrics(),h=this.getContentMetrics(),$=this.getScrollMetrics(!1,c,h);return{contentHeight:h.height,contentWidth:h.width,contentTop:h.top,contentLeft:h.left,scrollHeight:$.height,scrollWidth:$.width,scrollTop:$.top,scrollLeft:$.left,viewHeight:c.height,viewWidth:c.width,viewTop:c.top,viewLeft:c.left,absoluteTop:n.top,absoluteLeft:n.left,svgHeight:o.height,svgWidth:o.width,toolboxWidth:e.width,toolboxHeight:e.height,toolboxPosition:e.position,flyoutWidth:t.width,flyoutHeight:t.height}}};r(F.METRICS_MANAGER,js,Ip),"Blockly"in globalThis||(globalThis.Blockly={Msg:Xb});var Yv=class extends Ml{constructor(){super(),this.GRID_UNIT=4,this.CURSOR_COLOUR="#ffa200",this.CURSOR_RADIUS=5,this.JAGGED_TEETH_WIDTH=this.JAGGED_TEETH_HEIGHT=0,this.START_HAT_HEIGHT=22,this.START_HAT_WIDTH=96,this.SHAPES={HEXAGONAL:1,ROUND:2,SQUARE:3,PUZZLE:4,NOTCH:5},this.SHAPE_IN_SHAPE_PADDING={1:{0:5*this.GRID_UNIT,1:2*this.GRID_UNIT,2:5*this.GRID_UNIT,3:5*this.GRID_UNIT},2:{0:3*this.GRID_UNIT,1:3*this.GRID_UNIT,2:1*this.GRID_UNIT,3:2*this.GRID_UNIT},3:{0:2*this.GRID_UNIT,1:2*this.GRID_UNIT,2:2*this.GRID_UNIT,3:2*this.GRID_UNIT}},this.FULL_BLOCK_FIELDS=!0,this.FIELD_TEXT_FONTWEIGHT="bold",this.FIELD_TEXT_FONTFAMILY='"Helvetica Neue", "Segoe UI", Helvetica, sans-serif',this.FIELD_COLOUR_FULL_BLOCK=this.FIELD_TEXTINPUT_BOX_SHADOW=this.FIELD_DROPDOWN_SVG_ARROW=this.FIELD_DROPDOWN_COLOURED_DIV=this.FIELD_DROPDOWN_NO_BORDER_RECT_SHADOW=!0,this.SELECTED_GLOW_COLOUR="#fff200",this.SELECTED_GLOW_SIZE=.5,this.REPLACEMENT_GLOW_COLOUR="#fff200",this.REPLACEMENT_GLOW_SIZE=2,this.selectedGlowFilterId="",this.selectedGlowFilter=null,this.replacementGlowFilterId="",this.SQUARED=this.ROUNDED=this.HEXAGONAL=this.replacementGlowFilter=null,this.SMALL_PADDING=this.GRID_UNIT,this.MEDIUM_PADDING=2*this.GRID_UNIT,this.MEDIUM_LARGE_PADDING=3*this.GRID_UNIT,this.LARGE_PADDING=4*this.GRID_UNIT,this.CORNER_RADIUS=1*this.GRID_UNIT,this.NOTCH_WIDTH=9*this.GRID_UNIT,this.NOTCH_HEIGHT=2*this.GRID_UNIT,this.STATEMENT_INPUT_NOTCH_OFFSET=this.NOTCH_OFFSET_LEFT=3*this.GRID_UNIT,this.MIN_BLOCK_WIDTH=2*this.GRID_UNIT,this.MIN_BLOCK_HEIGHT=12*this.GRID_UNIT,this.EMPTY_STATEMENT_INPUT_HEIGHT=6*this.GRID_UNIT,this.TOP_ROW_MIN_HEIGHT=this.CORNER_RADIUS,this.TOP_ROW_PRECEDES_STATEMENT_MIN_HEIGHT=this.LARGE_PADDING,this.BOTTOM_ROW_MIN_HEIGHT=this.CORNER_RADIUS,this.BOTTOM_ROW_AFTER_STATEMENT_MIN_HEIGHT=6*this.GRID_UNIT,this.STATEMENT_BOTTOM_SPACER=-this.NOTCH_HEIGHT,this.STATEMENT_INPUT_SPACER_MIN_WIDTH=40*this.GRID_UNIT,this.STATEMENT_INPUT_PADDING_LEFT=4*this.GRID_UNIT,this.EMPTY_INLINE_INPUT_PADDING=4*this.GRID_UNIT,this.EMPTY_INLINE_INPUT_HEIGHT=8*this.GRID_UNIT,this.DUMMY_INPUT_MIN_HEIGHT=8*this.GRID_UNIT,this.DUMMY_INPUT_SHADOW_MIN_HEIGHT=6*this.GRID_UNIT,this.CURSOR_WS_WIDTH=20*this.GRID_UNIT,this.FIELD_TEXT_FONTSIZE=3*this.GRID_UNIT,this.FIELD_BORDER_RECT_RADIUS=this.CORNER_RADIUS,this.FIELD_BORDER_RECT_X_PADDING=2*this.GRID_UNIT,this.FIELD_BORDER_RECT_Y_PADDING=1.625*this.GRID_UNIT,this.FIELD_BORDER_RECT_HEIGHT=8*this.GRID_UNIT,this.FIELD_DROPDOWN_BORDER_RECT_HEIGHT=8*this.GRID_UNIT,this.FIELD_DROPDOWN_SVG_ARROW_PADDING=this.FIELD_BORDER_RECT_X_PADDING,this.FIELD_COLOUR_DEFAULT_WIDTH=6*this.GRID_UNIT,this.FIELD_COLOUR_DEFAULT_HEIGHT=8*this.GRID_UNIT,this.FIELD_CHECKBOX_X_OFFSET=1*this.GRID_UNIT,this.MAX_DYNAMIC_CONNECTION_SHAPE_WIDTH=12*this.GRID_UNIT}setFontConstants_(e){super.setFontConstants_(e),this.FIELD_DROPDOWN_BORDER_RECT_HEIGHT=this.FIELD_BORDER_RECT_HEIGHT=this.FIELD_TEXT_HEIGHT+2*this.FIELD_BORDER_RECT_Y_PADDING}init(){super.init(),this.HEXAGONAL=this.makeHexagonal(),this.ROUNDED=this.makeRounded(),this.SQUARED=this.makeSquared(),this.STATEMENT_INPUT_NOTCH_OFFSET=this.NOTCH_OFFSET_LEFT+this.INSIDE_CORNERS.rightWidth}setDynamicProperties_(e){super.setDynamicProperties_(e),this.SELECTED_GLOW_COLOUR=e.getComponentStyle("selectedGlowColour")||this.SELECTED_GLOW_COLOUR;const t=Number(e.getComponentStyle("selectedGlowSize"));this.SELECTED_GLOW_SIZE=t&&!isNaN(t)?t:this.SELECTED_GLOW_SIZE,this.REPLACEMENT_GLOW_COLOUR=e.getComponentStyle("replacementGlowColour")||this.REPLACEMENT_GLOW_COLOUR,this.REPLACEMENT_GLOW_SIZE=(e=Number(e.getComponentStyle("replacementGlowSize")))&&!isNaN(e)?e:this.REPLACEMENT_GLOW_SIZE}dispose(){super.dispose(),this.selectedGlowFilter&&Ke(this.selectedGlowFilter),this.replacementGlowFilter&&Ke(this.replacementGlowFilter)}makeStartHat(){const e=this.START_HAT_HEIGHT,t=this.START_HAT_WIDTH,o=Yt("c",[ue(25,-e),ue(71,-e),ue(t,0)]);return{height:e,width:t,path:o}}makeHexagonal(){function e(o,n,c){var h=o/2;return h=h>t?t:h,c=c?-1:1,o=(n?-1:1)*o/2,Bs(-c*h,o)+Bs(c*h,o)}const t=this.MAX_DYNAMIC_CONNECTION_SHAPE_WIDTH;return{type:this.SHAPES.HEXAGONAL,isDynamic:!0,width(o){return o/=2,o>t?t:o},height(o){return o},connectionOffsetY(o){return o/2},connectionOffsetX(o){return-o},pathDown(o){return e(o,!1,!1)},pathUp(o){return e(o,!0,!1)},pathRightDown(o){return e(o,!1,!0)},pathRightUp(o){return e(o,!1,!0)}}}makeRounded(){function e(n,c,h){const $=n>o?n-o:0;n=(n>o?o:n)/2;const T=h===c?"0":"1";return gt("a","0 0,"+T,n,ue((h?1:-1)*n,(c?-1:1)*n))+ne("v",(c?-1:1)*$)+gt("a","0 0,"+T,n,ue((h?-1:1)*n,(c?-1:1)*n))}const t=this.MAX_DYNAMIC_CONNECTION_SHAPE_WIDTH,o=2*t;return{type:this.SHAPES.ROUND,isDynamic:!0,width(n){return n/=2,n>t?t:n},height(n){return n},connectionOffsetY(n){return n/2},connectionOffsetX(n){return-n},pathDown(n){return e(n,!1,!1)},pathUp(n){return e(n,!0,!1)},pathRightDown(n){return e(n,!1,!0)},pathRightUp(n){return e(n,!1,!0)}}}makeSquared(){function e(o,n,c){o-=2*t;const h=c===n?"0":"1";return gt("a","0 0,"+h,t,ue((c?1:-1)*t,(n?-1:1)*t))+ne("v",(n?-1:1)*o)+gt("a","0 0,"+h,t,ue((c?-1:1)*t,(n?-1:1)*t))}const t=this.CORNER_RADIUS;return{type:this.SHAPES.SQUARE,isDynamic:!0,width(o){return t},height(o){return o},connectionOffsetY(o){return o/2},connectionOffsetX(o){return-o},pathDown(o){return e(o,!1,!1)},pathUp(o){return e(o,!0,!1)},pathRightDown(o){return e(o,!1,!0)},pathRightUp(o){return e(o,!1,!0)}}}shapeFor(e){let t=e.getCheck();switch(!t&&e.targetConnection&&(t=e.targetConnection.getCheck()),e.type){case oe.INPUT_VALUE:case oe.OUTPUT_VALUE:if(e=e.getSourceBlock().getOutputShape(),e!==null)switch(e){case this.SHAPES.HEXAGONAL:return this.HEXAGONAL;case this.SHAPES.ROUND:return this.ROUNDED;case this.SHAPES.SQUARE:return this.SQUARED}return t&&t.includes("Boolean")?this.HEXAGONAL:t&&t.includes("Number")?this.ROUNDED:(t&&t.includes("String"),this.ROUNDED);case oe.PREVIOUS_STATEMENT:case oe.NEXT_STATEMENT:return this.NOTCH;default:throw Error("Unknown type")}}makeNotch(){function e(te){return Yt("c",[ue(te*c/2,0),ue(te*c*3/4,$/2),ue(te*c,$)])+Fi([ue(te*c,h)])+Yt("c",[ue(te*c/4,$/2),ue(te*c/2,$),ue(te*c,$)])+ne("h",te*n)+Yt("c",[ue(te*c/2,0),ue(te*c*3/4,-($/2)),ue(te*c,-$)])+Fi([ue(te*c,-h)])+Yt("c",[ue(te*c/4,-($/2)),ue(te*c/2,-$),ue(te*c,-$)])}const t=this.NOTCH_WIDTH,o=this.NOTCH_HEIGHT,n=t/3,c=n/3,h=o/2,$=h/2,T=e(1),L=e(-1);return{type:this.SHAPES.NOTCH,width:t,height:o,pathLeft:T,pathRight:L}}makeInsideCorners(){const e=this.CORNER_RADIUS,t=gt("a","0 0,0",e,ue(-e,e)),o=gt("a","0 0,1",e,ue(-e,e)),n=gt("a","0 0,0",e,ue(e,e)),c=gt("a","0 0,1",e,ue(e,e));return{width:e,height:e,pathTop:t,pathBottom:n,rightWidth:e,rightHeight:e,pathTopRight:o,pathBottomRight:c}}generateSecondaryColour_(e){return Ko("#000",e,.15)||e}generateTertiaryColour_(e){return Ko("#000",e,.25)||e}createDom(e,t,o){super.createDom(e,t,o),e=N(x.DEFS,{},e),t=N(x.FILTER,{id:"blocklySelectedGlowFilter"+this.randomIdentifier,height:"160%",width:"180%",y:"-30%",x:"-40%"},e),N(x.FEGAUSSIANBLUR,{in:"SourceGraphic",stdDeviation:this.SELECTED_GLOW_SIZE},t),o=N(x.FECOMPONENTTRANSFER,{result:"outBlur"},t),N(x.FEFUNCA,{type:"table",tableValues:"0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"},o),N(x.FEFLOOD,{"flood-color":this.SELECTED_GLOW_COLOUR,"flood-opacity":1,result:"outColor"},t),N(x.FECOMPOSITE,{in:"outColor",in2:"outBlur",operator:"in",result:"outGlow"},t),this.selectedGlowFilterId=t.id,this.selectedGlowFilter=t,e=N(x.FILTER,{id:"blocklyReplacementGlowFilter"+this.randomIdentifier,height:"160%",width:"180%",y:"-30%",x:"-40%"},e),N(x.FEGAUSSIANBLUR,{in:"SourceGraphic",stdDeviation:this.REPLACEMENT_GLOW_SIZE},e),t=N(x.FECOMPONENTTRANSFER,{result:"outBlur"},e),N(x.FEFUNCA,{type:"table",tableValues:"0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"},t),N(x.FEFLOOD,{"flood-color":this.REPLACEMENT_GLOW_COLOUR,"flood-opacity":1,result:"outColor"},e),N(x.FECOMPOSITE,{in:"outColor",in2:"outBlur",operator:"in",result:"outGlow"},e),N(x.FECOMPOSITE,{in:"SourceGraphic",in2:"outGlow",operator:"over"},e),this.replacementGlowFilterId=e.id,this.replacementGlowFilter=e}getCSS_(e){return[`${e} .blocklyText,`,`${e} .blocklyFlyoutLabelText {`,`font: ${this.FIELD_TEXT_FONTWEIGHT} ${this.FIELD_TEXT_FONTSIZE}pt ${this.FIELD_TEXT_FONTFAMILY};`,"}",`${e} .blocklyTextInputBubble textarea {`,"font-weight: normal;","}",`${e} .blocklyText {`,"fill: #fff;","}",`${e} .blocklyNonEditableText>rect:not(.blocklyDropdownRect),`,`${e} .blocklyEditableText>rect:not(.blocklyDropdownRect) {`,`fill: ${this.FIELD_BORDER_RECT_COLOUR};`,"}",`${e} .blocklyNonEditableText>text,`,`${e} .blocklyEditableText>text,`,`${e} .blocklyNonEditableText>g>text,`,`${e} .blocklyEditableText>g>text {`,"fill: #575E75;","}",`${e} .blocklyFlyoutLabelText {`,"fill: #575E75;","}",`${e} .blocklyText.blocklyBubbleText {`,"fill: #575E75;","}",`${e} .blocklyDraggable:not(.blocklyDisabled)`," .blocklyEditableText:not(.editing):hover>rect,",`${e} .blocklyDraggable:not(.blocklyDisabled)`," .blocklyEditableText:not(.editing):hover>.blocklyPath {","stroke: #fff;","stroke-width: 2;","}",`${e} .blocklyHtmlInput {`,`font-family: ${this.FIELD_TEXT_FONTFAMILY};`,`font-weight: ${this.FIELD_TEXT_FONTWEIGHT};`,"color: #575E75;","}",`${e} .blocklyDropdownText {`,"fill: #fff !important;","}",`${e}.blocklyWidgetDiv .blocklyMenuItem,`,`${e}.blocklyDropDownDiv .blocklyMenuItem {`,`font-family: ${this.FIELD_TEXT_FONTFAMILY};`,"}",`${e}.blocklyDropDownDiv .blocklyMenuItemContent {`,"color: #fff;","}",`${e} .blocklyHighlightedConnectionPath {`,`stroke: ${this.SELECTED_GLOW_COLOUR};`,"}",`${e} .blocklyDisabled > .blocklyOutlinePath {`,`fill: url(#blocklyDisabledPattern${this.randomIdentifier})`,"}",`${e} .blocklyInsertionMarker>.blocklyPath {`,`fill-opacity: ${this.INSERTION_MARKER_OPACITY};`,"stroke: none;","}"]}},Jv=class extends Nl{constructor(e,t){super(e,t)}draw(){const e=this.block_.pathObject;e.beginDrawing(),this.drawOutline_(),this.drawInternals_(),this.updateConnectionHighlights(),e.setPath(this.outlinePath_+` -`+this.inlinePath_),this.info_.RTL&&e.flipRTL(),this.recordSizeOnBlock_(),this.info_.outputConnection&&(e.outputShapeType=this.info_.outputConnection.shape.type),e.endDrawing()}drawOutline_(){this.info_.outputConnection&&this.info_.outputConnection.isDynamicShape&&!this.info_.hasStatementInput&&!this.info_.bottomRow.hasNextConnection?(this.drawFlatTop_(),this.drawRightDynamicConnection_(),this.drawFlatBottom_(),this.drawLeftDynamicConnection_()):super.drawOutline_()}drawLeft_(){this.info_.outputConnection&&this.info_.outputConnection.isDynamicShape?this.drawLeftDynamicConnection_():super.drawLeft_()}drawRightSideRow_(e){if(!(0>=e.height)){if(S.isSpacer(e)){const n=e.precedesStatement;var t=e.followsStatement;if(n||t){const c=this.constants_.INSIDE_CORNERS;var o=c.rightHeight;o=e.height-(n?o:0),t=t?c.pathBottomRight:"",e=0=o||0>=t)throw Error("Height and width values of an image field must be greater than 0.");this.size_=new Le(t,o+mi.Y_PADDING),this.imageHeight=o,typeof c=="function"&&(this.clickHandler=c),e!==Qe.SKIP_SETUP&&($?this.configure_($):(this.flipRtl=!!h,this.altText=pt(n)||""),this.setValue(pt(e)))}configure_(e){super.configure_(e),e.flipRtl&&(this.flipRtl=e.flipRtl),e.alt&&(this.altText=pt(e.alt))}initView(){this.imageElement=N(x.IMAGE,{height:this.imageHeight+"px",width:this.size_.width+"px",alt:this.altText},this.fieldGroup_),this.imageElement.setAttributeNS(es,"xlink:href",this.value_),this.clickHandler&&(this.imageElement.style.cursor="pointer")}updateSize_(){}doClassValidation_(e){return typeof e!="string"?null:e}doValueUpdate_(e){this.value_=e,this.imageElement&&this.imageElement.setAttributeNS(es,"xlink:href",this.value_)}getFlipRtl(){return this.flipRtl}setAlt(e){e!==this.altText&&(this.altText=e||"",this.imageElement&&this.imageElement.setAttribute("alt",this.altText))}showEditor_(){this.clickHandler&&this.clickHandler(this)}setOnClickHandler(e){this.clickHandler=e}getText_(){return this.altText}static fromJson(e){if(!e.src||!e.width||!e.height)throw Error("src, width, and height values for an image field arerequired. The width and height must be non-zero.");return new this(e.src,e.width,e.height,void 0,void 0,void 0,e)}};mi.Y_PADDING=1,Ps("field_image",mi),mi.prototype.DEFAULT_VALUE="";var Hl=class extends Qe{constructor(e,t,o){super(Qe.SKIP_SETUP),this.spellcheck_=!0,this.htmlInput_=null,this.isTextValid_=this.isBeingEdited_=!1,this.onKeyInputWrapper=this.onKeyDownWrapper=this.valueWhenEditorWasOpened_=null,this.fullBlockClickTarget_=!1,this.workspace_=null,this.SERIALIZABLE=!0,this.CURSOR="text",e!==Qe.SKIP_SETUP&&(o&&this.configure_(o),this.setValue(e),t&&this.setValidator(t))}configure_(e){super.configure_(e),e.spellcheck!==void 0&&(this.spellcheck_=e.spellcheck)}initView(){if(!this.getSourceBlock())throw new ft;super.initView(),this.isFullBlockField()&&(this.clickTarget_=this.sourceBlock_.getSvgRoot())}isFullBlockField(){const e=this.getSourceBlock();if(!e)throw new ft;let t;return this.fullBlockClickTarget_=!((t=this.getConstants())==null||!t.FULL_BLOCK_FIELDS)&&e.isSimpleReporter()}doValueInvalid_(e,t=!0){this.isBeingEdited_&&(this.isDirty_=!0,this.isTextValid_=!1,e=this.value_,this.value_=this.valueWhenEditorWasOpened_,this.sourceBlock_&&K()&&this.value_!==e&&t&&z(new(V(O.BLOCK_CHANGE))(this.sourceBlock_,"field",this.name||null,e,this.value_)))}doValueUpdate_(e){this.isTextValid_=this.isDirty_=!0,this.value_=e}applyColour(){const e=this.getSourceBlock();if(!e)throw new ft;this.getConstants().FULL_BLOCK_FIELDS&&this.fieldGroup_&&(!this.isFullBlockField()&&this.borderRect_?(this.borderRect_.style.display="block",this.borderRect_.setAttribute("stroke",e.getColourTertiary())):(this.borderRect_.style.display="none",e.pathObject.svgPath.setAttribute("fill",this.getConstants().FIELD_BORDER_RECT_COLOUR)))}getSize(){let e;return(e=this.getConstants())!=null&&e.FULL_BLOCK_FIELDS&&(this.render_(),this.isDirty_=!1),super.getSize()}onLocationChange(){this.isBeingEdited_&&this.resizeEditor_()}render_(){if(super.render_(),this.isBeingEdited_){var e=this.htmlInput_;this.isTextValid_?(ot(e,"blocklyInvalidInput"),It(e,Ct.INVALID,!1)):(ge(e,"blocklyInvalidInput"),It(e,Ct.INVALID,!0))}if(e=this.getSourceBlock(),!e)throw new ft;this.getConstants().FULL_BLOCK_FIELDS&&e.applyColour()}setSpellcheck(e){e!==this.spellcheck_&&(this.spellcheck_=e,this.htmlInput_&&this.htmlInput_.setAttribute("spellcheck",this.spellcheck_))}showEditor_(e,t=!1){this.workspace_=this.sourceBlock_.workspace,!t&&this.workspace_.options.modalInputs&&(Db||yh||nl)?this.showPromptEditor():this.showInlineEditor(t)}showPromptEditor(){Ta(i.Msg$$module$build$src$core$msg.CHANGE_VALUE_TITLE,this.getText(),e=>{e!==null&&this.setValue(this.getValueFromEditorText_(e)),this.onFinishEditing_(this.value_)})}showInlineEditor(e){const t=this.getSourceBlock();if(!t)throw new ft;Pa(this,t.RTL,this.widgetDispose_.bind(this),this.workspace_),this.htmlInput_=this.widgetCreate_(),this.isBeingEdited_=!0,this.valueWhenEditorWasOpened_=this.value_,e||(this.htmlInput_.focus({preventScroll:!0}),this.htmlInput_.select())}widgetCreate_(){var e=this.getSourceBlock();if(!e)throw new ft;i.setGroup$$module$build$src$core$events$utils(!0);const t=Yo();var o=this.getClickTarget_();if(!o)throw Error("A click target has not been set.");ge(o,"editing"),o=document.createElement("input"),o.className="blocklyHtmlInput",o.setAttribute("spellcheck",this.spellcheck_);const n=this.workspace_.getScale();var c=this.getConstants().FIELD_TEXT_FONTSIZE*n+"pt";return t.style.fontSize=c,o.style.fontSize=c,c=Hl.BORDERRADIUS*n+"px",this.isFullBlockField()&&(c=this.getScaledBBox(),c=(c.bottom-c.top)/2+"px",e=e.getParent()?e.getParent().getColourTertiary():this.sourceBlock_.getColourTertiary(),o.style.border=1*n+"px solid "+e,t.style.borderRadius=c,t.style.transition="box-shadow 0.25s ease 0s",this.getConstants().FIELD_TEXTINPUT_BOX_SHADOW&&(t.style.boxShadow="rgba(255, 255, 255, 0.3) 0 0 0 "+4*n+"px")),o.style.borderRadius=c,t.appendChild(o),o.value=o.defaultValue=this.getEditorText_(this.value_),o.setAttribute("data-untyped-default-value",String(this.value_)),this.resizeEditor_(),this.bindInputEvents_(o),o}widgetDispose_(){this.isBeingEdited_=!1,this.isTextValid_=!0,this.forceRerender(),this.onFinishEditing_(this.value_),this.sourceBlock_&&K()&&this.valueWhenEditorWasOpened_!==null&&this.valueWhenEditorWasOpened_!==this.value_&&(z(new(V(O.BLOCK_CHANGE))(this.sourceBlock_,"field",this.name||null,this.valueWhenEditorWasOpened_,this.value_)),this.valueWhenEditorWasOpened_=null),i.setGroup$$module$build$src$core$events$utils(!1),this.unbindInputEvents_();var e=Yo().style;if(e.width="auto",e.height="auto",e.fontSize="",e.transition="",e.boxShadow="",this.htmlInput_=null,e=this.getClickTarget_(),!e)throw Error("A click target has not been set.");ot(e,"editing")}onFinishEditing_(e){}bindInputEvents_(e){this.onKeyDownWrapper=X(e,"keydown",this,this.onHtmlInputKeyDown_),this.onKeyInputWrapper=X(e,"input",this,this.onHtmlInputChange)}unbindInputEvents_(){this.onKeyDownWrapper&&(ze(this.onKeyDownWrapper),this.onKeyDownWrapper=null),this.onKeyInputWrapper&&(ze(this.onKeyInputWrapper),this.onKeyInputWrapper=null)}onHtmlInputKeyDown_(e){e.key==="Enter"?(Jo(this),Ns()):e.key==="Escape"?(this.setValue(this.htmlInput_.getAttribute("data-untyped-default-value"),!1),Jo(this),Ns()):e.key==="Tab"&&(Jo(this),Ns(),this.sourceBlock_.tab(this,!e.shiftKey),e.preventDefault())}onHtmlInputChange(e){e=this.value_,this.setValue(this.getValueFromEditorText_(this.htmlInput_.value),!1),this.sourceBlock_&&K()&&this.value_!==e&&z(new(V(O.BLOCK_FIELD_INTERMEDIATE_CHANGE))(this.sourceBlock_,this.name||null,e,this.value_))}setEditorValue_(e,t=!0){this.isDirty_=!0,this.isBeingEdited_&&(this.htmlInput_.value=this.getEditorText_(e)),this.setValue(e,t)}resizeEditor_(){ws().then(()=>{const e=this.getSourceBlock();if(!e)throw new ft;const t=Yo(),o=this.getScaledBBox();t.style.width=o.right-o.left+"px",t.style.height=o.bottom-o.top+"px";const n=o.top;t.style.left=`${e.RTL?o.right-t.offsetWidth:o.left}px`,t.style.top=`${n}px`})}repositionForWindowResize(){let e;const t=(e=this.getSourceBlock())==null?void 0:e.getRootBlock();return t instanceof gs?(zi(this.workspace_,this.workspace_.getMetricsManager().getViewMetrics(!0),t)||this.resizeEditor_(),!0):!1}isTabNavigable(){return!0}getText_(){return this.isBeingEdited_&&this.htmlInput_?this.htmlInput_.value:null}getEditorText_(e){return`${e}`}getValueFromEditorText_(e){return e}};Hl.BORDERRADIUS=4;var Wl=class extends Hl{constructor(e,t,o){super(e,t,o)}doClassValidation_(e){return e===void 0?null:`${e}`}static fromJson(e){return new this(pt(e.text),void 0,e)}};Ps("field_input",Wl),Wl.prototype.DEFAULT_VALUE="";var qv=class extends ip{constructor(e){super(e)}endsWithElemSpacer(){return!1}hasLeftSquareCorner(e){return!!e.outputConnection}hasRightSquareCorner(e){return!!e.outputConnection&&!e.statementInputCount&&!e.nextConnection}},Gl=class extends wr{constructor(e,t){if(super(e,t),this.connectedBottomNextConnection=!1,this.connectedBlock){for(e=this.connectedBlock;t=e.getNextBlock();)e=t;e.nextConnection||(this.height=this.connectedBlockHeight,this.connectedBottomNextConnection=!0)}}},Xv=class extends zs{constructor(e){super(e),this.width=this.height=0,this.type|=S.getType("RIGHT_CONNECTION")}},Zv=class extends cp{constructor(e){super(e)}endsWithElemSpacer(){return!1}hasLeftSquareCorner(e){const t=(e.hat?e.hat==="cap":this.constants_.ADD_START_HATS)&&!e.outputConnection&&!e.previousConnection;return!!e.outputConnection||t}hasRightSquareCorner(e){return!!e.outputConnection&&!e.statementInputCount&&!e.nextConnection}},Qv=class extends kr{constructor(e,t){super(e,t),this.isInline=!0,this.renderer_=e,this.constants_=this.renderer_.getConstants(),this.topRow=new Zv(this.constants_),this.bottomRow=new qv(this.constants_),this.isMultiRow=!t.getInputsInline()||t.isCollapsed(),this.hasStatementInput=0=this.rows.length-1?!!this.bottomRow.hasNextConnection:!!n.precedesStatement,S.isInputRow(h)&&h.hasStatement){h.measure();let $,T;t=h.width-((T=($=h.getLastInput())==null?void 0:$.width)!=null?T:0)+e}else if(o&&(c===2||n)&&S.isInputRow(h)&&!h.hasStatement){n=h.xPos,o=null;for(let $=0;$o?o:this.height/2,t-o*(1-Math.sin(Math.acos((o-this.constants_.SMALL_PADDING)/o)))):0;if(S.isInlineInput(e)&&e instanceof Ro){const c=e.connectedBlock;return e=c?c.pathObject.outputShapeType:e.shape.type,e==null||c&&c.outputConnection&&(c.statementInputCount||c.nextConnection)||o===n.SHAPES.HEXAGONAL&&o!==e?0:t-this.constants_.SHAPE_IN_SHAPE_PADDING[o][e]}return S.isField(e)&&e instanceof on?o===n.SHAPES.ROUND&&e.field instanceof Wl?t-2.75*n.GRID_UNIT:t-this.constants_.SHAPE_IN_SHAPE_PADDING[o][0]:S.isIcon(e)?this.constants_.SMALL_PADDING:0}finalizeVerticalAlignment_(){if(!this.outputConnection)for(let n=2;n=this.rows.length-1?!!this.bottomRow.hasNextConnection:!!$.precedesStatement;if(e?this.topRow.hasPreviousConnection:c.followsStatement){var o=h.elements[1];if(o=h.elements.length===3&&o instanceof on&&(o.field instanceof hi||o.field instanceof mi),!e&&o)c.height-=this.constants_.SMALL_PADDING,$.height-=this.constants_.SMALL_PADDING,h.height-=this.constants_.MEDIUM_PADDING;else if(!e&&!t)c.height+=this.constants_.SMALL_PADDING;else if(t){for(e=!1,t=0;t{if(!n.isDeadOrDying()){i.disable$$module$build$src$core$events$utils();try{n==null||n.positionNearConnection(c,h,$),n==null||n.getSvgRoot().setAttribute("visibility","visible")}finally{i.enable$$module$build$src$core$events$utils()}}}),c}createInsertionMarker(e){const t=Qt(e,{addCoordinates:!1,addInputBlocks:!1,addNextBlocks:!1,doFullSerialization:!1});if(!t)throw Error(`Failed to serialize source block. ${e.toDevString()}`);e=eo(t,this.workspace);for(const o of e.getDescendants(!1))o.setInsertionMarker(!0);return e.initSvg(),e.getSvgRoot().setAttribute("visibility","hidden"),e}getMatchingConnection(e,t,o){if(e=e.getConnections_(!0),t=t.getConnections_(!0),e.length!==t.length)return null;for(let n=0;n{this.targetWorkspace.isDragging()||t.addSelect()})),this.listeners.push(ct(e,"pointerleave",t,()=>{this.targetWorkspace.isDragging()||t.removeSelect()})),this.listeners.push(ct(o,"pointerenter",t,()=>{this.targetWorkspace.isDragging()||t.addSelect()})),this.listeners.push(ct(o,"pointerleave",t,()=>{this.targetWorkspace.isDragging()||t.removeSelect()}))}blockMouseDown(e){return t=>{const o=this.targetWorkspace.getGesture(t);o&&(o.setStartBlock(e),o.handleFlyoutStart(t,this))}}onMouseDown(e){const t=this.targetWorkspace.getGesture(e);t&&t.handleFlyoutStart(e,this)}isBlockCreatable(e){return e.isEnabled()}createBlock(e){let t=null;i.disable$$module$build$src$core$events$utils();var o=this.targetWorkspace.getAllVariables();this.targetWorkspace.setResizesEnabled(!1);try{t=this.placeNewBlock(e)}finally{i.enable$$module$build$src$core$events$utils()}if(this.targetWorkspace.hideChaff(),e=Hn(this.targetWorkspace,o),K()){for(i.setGroup$$module$build$src$core$events$utils(!0),o=0;o-t||e<-180+t||e>180-t}getClientRect(){if(!this.svgGroup_||this.autoClose||!this.isVisible())return null;const e=this.svgGroup_.getBoundingClientRect(),t=e.left;return this.toolboxPosition_===Ee.LEFT?new qe(-1e9,1e9,-1e9,t+e.width):new qe(-1e9,1e9,t,1e9)}reflowInternal_(){this.workspace_.scale=this.getFlyoutScale();let e=0;var t=this.workspace_.getTopBlocks(!1);for(let n=0,c;c=t[n];n++){var o=c.getHeightWidth().width;c.outputConnection&&(o-=this.tabWidth_),e=Math.max(e,o)}for(let n=0,c;c=this.buttons_[n];n++)e=Math.max(e,c.width);if(e+=1.5*this.MARGIN+this.tabWidth_,e*=this.workspace_.scale,e+=mt.scrollbarThickness,this.width_!==e){for(let n=0,c;c=t[n];n++){if(this.RTL){o=c.getRelativeToSurfaceXY().x;let h=e/this.workspace_.scale-this.MARGIN;c.outputConnection||(h-=this.tabWidth_),c.moveBy(h-o,0)}this.rectMap_.has(c)&&this.moveRectToBlock_(this.rectMap_.get(c),c)}if(this.RTL)for(let n=0,c;c=this.buttons_[n];n++)t=c.getPosition().y,c.moveTo(e/this.workspace_.scale-c.width-this.MARGIN-this.tabWidth_,t);this.targetWorkspace.scrollbar||this.autoClose||this.targetWorkspace.getFlyout()!==this||this.toolboxPosition_!==Ee.LEFT||this.targetWorkspace.translate(this.targetWorkspace.scrollX+e,this.targetWorkspace.scrollY),this.width_=e,this.position(),this.targetWorkspace.resizeContents(),this.targetWorkspace.recordDragTargets()}}};Dp.registryName="verticalFlyout",r(F.FLYOUTS_VERTICAL_TOOLBOX,js,Dp);var ry=class extends Vl{constructor(e){super(e),this.horizontalLayout=!0}setMetrics_(e){if(this.isVisible()){var t=this.workspace_.getMetricsManager(),o=t.getScrollMetrics(),n=t.getViewMetrics();t=t.getAbsoluteMetrics(),typeof e.x=="number"&&(this.workspace_.scrollX=-(o.left+(o.width-n.width)*e.x)),this.workspace_.translate(this.workspace_.scrollX+t.left,this.workspace_.scrollY+t.top)}}getX(){return 0}getY(){if(!this.isVisible())return 0;var e=this.targetWorkspace.getMetricsManager();const t=e.getAbsoluteMetrics(),o=e.getViewMetrics();e=e.getToolboxMetrics();const n=this.toolboxPosition_===Ee.TOP;return this.targetWorkspace.toolboxPosition===this.toolboxPosition_?this.targetWorkspace.getToolbox()?n?e.height:o.height-this.height_:n?0:o.height:n?0:o.height+t.top-this.height_}position(){if(this.isVisible()&&this.targetWorkspace.isVisible()){var e=this.targetWorkspace.getMetricsManager().getViewMetrics();this.width_=e.width,this.setBackgroundPath(e.width-2*this.CORNER_RADIUS,this.height_-this.CORNER_RADIUS),e=this.getX();var t=this.getY();this.positionAt_(this.width_,this.height_,e,t)}}setBackgroundPath(e,t){const o=this.toolboxPosition_===Ee.TOP,n=["M 0,"+(o?0:this.CORNER_RADIUS)];o?(n.push("h",e+2*this.CORNER_RADIUS),n.push("v",t),n.push("a",this.CORNER_RADIUS,this.CORNER_RADIUS,0,0,1,-this.CORNER_RADIUS,this.CORNER_RADIUS),n.push("h",-e),n.push("a",this.CORNER_RADIUS,this.CORNER_RADIUS,0,0,1,-this.CORNER_RADIUS,-this.CORNER_RADIUS)):(n.push("a",this.CORNER_RADIUS,this.CORNER_RADIUS,0,0,1,this.CORNER_RADIUS,-this.CORNER_RADIUS),n.push("h",e),n.push("a",this.CORNER_RADIUS,this.CORNER_RADIUS,0,0,1,this.CORNER_RADIUS,this.CORNER_RADIUS),n.push("v",t),n.push("h",-e-2*this.CORNER_RADIUS)),n.push("z"),this.svgBackground_.setAttribute("d",n.join(" "))}scrollToStart(){let e;(e=this.workspace_.scrollbar)==null||e.setX(this.RTL?1/0:0)}wheel_(e){var t=Zs(e);if(t=t.x||t.y){const o=this.workspace_.getMetricsManager(),n=o.getScrollMetrics();t=o.getViewMetrics().left-n.left+t;let c;(c=this.workspace_.scrollbar)==null||c.setX(t),Yn(this.workspace_),Ns()}e.preventDefault(),e.stopPropagation()}layout_(e,t){this.workspace_.scale=this.targetWorkspace.scale;const o=this.MARGIN;let n=o+this.tabWidth_;this.RTL&&(e=e.reverse());for(let T=0,L;L=e[T];T++)if(L.type==="block"){var c=L.block;if(c==null)continue;var h=c.getDescendants(!1);for(let nt=0,it;it=h[nt];nt++)it.isInFlyout=!0;h=c.getSvgRoot();const te=c.getHeightWidth();var $=c.outputConnection?this.tabWidth_:0;$=this.RTL?n+te.width:n-$,c.moveBy($,o),$=this.createRect_(c,$,o,te,T),n+=te.width+t[T],this.addBlockListeners_(h,c,$)}else L.type==="button"&&(c=L.button,this.initFlyoutButton_(c,n,o),n+=c.width+t[T])}isDragTowardWorkspace(e){e=Math.atan2(e.y,e.x)/Math.PI*180;const t=this.dragAngleRange_;return e<90+t&&e>90-t||e>-90-t&&e<-90+t}getClientRect(){if(!this.svgGroup_||this.autoClose||!this.isVisible())return null;const e=this.svgGroup_.getBoundingClientRect(),t=e.top;return this.toolboxPosition_===Ee.TOP?new qe(-1e9,t+e.height,-1e9,1e9):new qe(t,1e9,-1e9,1e9)}reflowInternal_(){this.workspace_.scale=this.getFlyoutScale();let e=0;const t=this.workspace_.getTopBlocks(!1);for(let n=0,c;c=t[n];n++)e=Math.max(e,c.getHeightWidth().height);const o=this.buttons_;for(let n=0,c;c=o[n];n++)e=Math.max(e,c.height);if(e+=1.5*this.MARGIN,e*=this.workspace_.scale,e+=mt.scrollbarThickness,this.height_!==e){for(let n=0,c;c=t[n];n++)this.rectMap_.has(c)&&this.moveRectToBlock_(this.rectMap_.get(c),c);this.targetWorkspace.scrollbar||this.autoClose||this.targetWorkspace.getFlyout()!==this||this.toolboxPosition_!==Ee.TOP||this.targetWorkspace.translate(this.targetWorkspace.scrollX,this.targetWorkspace.scrollY+e),this.height_=e,this.position(),this.targetWorkspace.resizeContents(),this.targetWorkspace.recordDragTargets()}}};r(F.FLYOUTS_HORIZONTAL_TOOLBOX,js,ry);var xr=class extends qt{constructor(e,t,o,n,c){super(Qe.SKIP_SETUP),this.defaultType="",this.variableTypes=[],this.variable=null,this.SERIALIZABLE=!0,this.menuGenerator_=xr.dropdownCreate,this.defaultVariableName=typeof e=="string"?e:"",this.size_=new Le(0,0),e!==Qe.SKIP_SETUP&&(c?this.configure_(c):this.setTypes(o,n),t&&this.setValidator(t))}configure_(e){super.configure_(e),this.setTypes(e.variableTypes,e.defaultType)}initModel(){var e=this.getSourceBlock();if(!e)throw new ft;this.variable||(e=i.getOrCreateVariablePackage$$module$build$src$core$variables(e.workspace,null,this.defaultVariableName,this.defaultType),this.doValueUpdate_(e.getId()))}shouldAddBorderRect_(){const e=this.getSourceBlock();if(!e)throw new ft;return super.shouldAddBorderRect_()&&(!this.getConstants().FIELD_DROPDOWN_NO_BORDER_RECT_SHADOW||e.type!=="variables_get")}fromXml(e){var t=this.getSourceBlock();if(!t)throw new ft;const o=e.getAttribute("id"),n=e.textContent,c=e.getAttribute("variabletype")||e.getAttribute("variableType")||"";if(t=i.getOrCreateVariablePackage$$module$build$src$core$variables(t.workspace,o,n,c),c!==null&&c!==t.type)throw Error("Serialized variable type with id '"+t.getId()+"' had type "+t.type+", and does not match variable field that references it: "+Ls(e)+".");this.setValue(t.getId())}toXml(e){return this.initModel(),e.id=this.variable.getId(),e.textContent=this.variable.name,this.variable.type&&e.setAttribute("variabletype",this.variable.type),e}saveState(e){var t=this.saveLegacyState(xr);return t!==null||(this.initModel(),t={id:this.variable.getId()},e&&(t.name=this.variable.name,t.type=this.variable.type)),t}loadState(e){const t=this.getSourceBlock();if(!t)throw new ft;this.loadLegacyState(xr,e)||(e=i.getOrCreateVariablePackage$$module$build$src$core$variables(t.workspace,e.id||null,e.name,e.type||""),this.setValue(e.getId()))}setSourceBlock(e){if(e.isShadow())throw Error("Variable fields are not allowed to exist on shadow blocks.");super.setSourceBlock(e)}getValue(){return this.variable?this.variable.getId():null}getText(){return this.variable?this.variable.name:""}getVariable(){return this.variable}getValidator(){return this.variable?this.validator_:null}doClassValidation_(e){if(e===null)return null;var t=this.getSourceBlock();if(!t)throw new ft;return t=i.getVariable$$module$build$src$core$variables(t.workspace,e),t?(t=t.type,this.typeIsAllowed(t)?e:(console.warn("Variable type doesn't match this field! Type was "+t),null)):(console.warn("Variable id doesn't point to a real variable! ID was "+e),null)}doValueUpdate_(e){const t=this.getSourceBlock();if(!t)throw new ft;this.variable=i.getVariable$$module$build$src$core$variables(t.workspace,e),super.doValueUpdate_(e)}typeIsAllowed(e){const t=this.getVariableTypes();if(!t)return!0;for(let o=0;othis.max_&&(e.max=`${this.max_}`,It(e,Ct.VALUEMAX,this.max_)),e}static fromJson(e){return new this(e.value,void 0,void 0,void 0,void 0,e)}};Ps("field_number",Ap),Ap.prototype.DEFAULT_VALUE=0;var ay=class extends hi{constructor(e,t,o){super(String(e??""),t,o),this.EDITABLE=!1,this.SERIALIZABLE=!0}static fromJson(e){return new this(pt(e.text),void 0,e)}};Ps("field_label_serializable",ay);var fi=class extends Qe{constructor(e,t,o){super(Qe.SKIP_SETUP),this.SERIALIZABLE=!0,this.CURSOR="default",this.value_=this.value_,this.checkChar=fi.CHECK_CHAR,e!==Qe.SKIP_SETUP&&(o&&this.configure_(o),this.setValue(e),t&&this.setValidator(t))}configure_(e){super.configure_(e),e.checkCharacter&&(this.checkChar=e.checkCharacter)}saveState(){const e=this.saveLegacyState(fi);return e!==null?e:this.getValueBoolean()}initView(){super.initView();const e=this.getTextElement();ge(e,"blocklyCheckbox"),e.style.display=this.value_?"block":"none"}render_(){this.textContent_&&(this.textContent_.nodeValue=this.getDisplayText_()),this.updateSize_(this.getConstants().FIELD_CHECKBOX_X_OFFSET)}getDisplayText_(){return this.checkChar}setCheckCharacter(e){this.checkChar=e||fi.CHECK_CHAR,this.forceRerender()}showEditor_(){this.setValue(!this.value_)}doClassValidation_(e){return e===!0||e==="TRUE"?"TRUE":e===!1||e==="FALSE"?"FALSE":null}doValueUpdate_(e){this.value_=this.convertValueToBool(e),this.textElement_&&(this.textElement_.style.display=this.value_?"block":"none")}getValue(){return this.value_?"TRUE":"FALSE"}getValueBoolean(){return this.value_}getText(){return String(this.convertValueToBool(this.value_))}convertValueToBool(e){return typeof e=="string"?e==="TRUE":!!e}static fromJson(e){return new this(e.checked,void 0,e)}};fi.CHECK_CHAR="✓",Ps("field_checkbox",fi),fi.prototype.DEFAULT_VALUE=!1;var ly=class{constructor(e,t){this.draggable=e,this.workspace=t,this.dragTarget=null,this.startLoc=e.getRelativeToSurfaceXY()}onDragStart(e){this.draggable.startDrag(e)}onDrag(e,t){this.moveDraggable(e,t),t=this.getRoot(this.draggable),ls(t)&&t.setDeleteStyle(this.wouldDeleteDraggable(e,t)),this.updateDragTarget(e)}updateDragTarget(e){e=this.workspace.getDragTarget(e);const t=this.getRoot(this.draggable);if(this.dragTarget!==e){let o;(o=this.dragTarget)==null||o.onDragExit(t),e==null||e.onDragEnter(t)}e==null||e.onDragOver(t),this.dragTarget=e}moveDraggable(e,t){t=this.pixelsToWorkspaceUnits(t),t=G.sum(this.startLoc,t),this.draggable.drag(t,e)}wouldDeleteDraggable(e,t){return(e=this.workspace.getDragTarget(e))&&this.workspace.getComponentManager().hasCapability(e.id,lt.Capability.DELETE_AREA)?e.wouldDelete(t):!1}onDragEnd(e){const t=i.getGroup$$module$build$src$core$events$utils();var o=this.workspace.getDragTarget(e);const n=this.getRoot(this.draggable);if(o){let c;(c=this.dragTarget)==null||c.onDrop(n)}this.shouldReturnToStart(e,n)&&this.draggable.revertDrag(),(o=ls(n)&&this.wouldDeleteDraggable(e,n))&&this.draggable instanceof gs&&za(this.draggable.getRootBlock()),this.draggable.endDrag(e),o&&ls(n)&&(e=i.getGroup$$module$build$src$core$events$utils(),i.setGroup$$module$build$src$core$events$utils(t),n.dispose(),i.setGroup$$module$build$src$core$events$utils(e))}getRoot(e){return e instanceof gs?e.getRootBlock():e}shouldReturnToStart(e,t){return(e=this.workspace.getDragTarget(e))?e.shouldPreventMove(t):!1}pixelsToWorkspaceUnits(e){return e=new G(e.x/this.workspace.scale,e.y/this.workspace.scale),this.workspace.isMutator&&e.scale(1/this.workspace.options.parentWorkspace.scale),e}};r(F.BLOCK_DRAGGER,js,ly);var Dr={};Dr.BlockDragStrategy=Pv,Dr.BubbleDragStrategy=vv,Dr.CommentDragStrategy=pv,Dr.Dragger=ly;var Rp=class extends Cs{constructor(e,t,o){super(e?e.workspace.id:void 0),this.type=O.BLOCK_DRAG,e&&(this.blockId=e.id,this.isStart=t,this.blocks=o)}toJson(){const e=super.toJson();if(this.isStart===void 0)throw Error("Whether this event is the start of a drag is undefined. Either pass the value to the constructor, or call fromJson");if(this.blockId===void 0)throw Error("The block ID is undefined. Either pass a block to the constructor, or call fromJson");return e.isStart=this.isStart,e.blockId=this.blockId,e.blocks=this.blocks,e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new Rp),t.isStart=e.isStart,t.blockId=e.blockId,t.blocks=e.blocks,t}};r(F.EVENT,O.BLOCK_DRAG,Rp);var Op=class extends ni{constructor(e,t,o,n){super(e),this.type=O.BLOCK_FIELD_INTERMEDIATE_CHANGE,this.recordUndo=!1,e&&(this.name=t,this.oldValue=o,this.newValue=n)}toJson(){const e=super.toJson();if(!this.name)throw Error("The changed field name is undefined. Either pass a name to the constructor, or call fromJson.");return e.name=this.name,e.oldValue=this.oldValue,e.newValue=this.newValue,e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new Op),t.name=e.name,t.oldValue=e.oldValue,t.newValue=e.newValue,t}isNull(){return this.oldValue===this.newValue}run(e){var t=this.getEventWorkspace_();if(!this.blockId)throw Error("The block ID is undefined. Either pass a block to the constructor, or call fromJson");if(t=t.getBlockById(this.blockId),!t)throw Error("The associated block is undefined. Either pass a block to the constructor, or call fromJson");e=e?this.newValue:this.oldValue,(t=t.getField(this.name))?t.setValue(e):console.warn("Can't set non-existent field: "+this.name)}};r(F.EVENT,O.BLOCK_FIELD_INTERMEDIATE_CHANGE,Op);var Mp=class extends ni{constructor(e){super(e),this.type=O.BLOCK_MOVE,e&&(e.isShadow()&&(this.recordUndo=!1),e=this.currentLocation(),this.oldParentId=e.parentId,this.oldInputName=e.inputName,this.oldCoordinate=e.coordinate)}toJson(){const e=super.toJson();return e.oldParentId=this.oldParentId,e.oldInputName=this.oldInputName,this.oldCoordinate&&(e.oldCoordinate=`${Math.round(this.oldCoordinate.x)}, ${Math.round(this.oldCoordinate.y)}`),e.newParentId=this.newParentId,e.newInputName=this.newInputName,this.newCoordinate&&(e.newCoordinate=`${Math.round(this.newCoordinate.x)}, ${Math.round(this.newCoordinate.y)}`),this.reason&&(e.reason=this.reason),this.recordUndo||(e.recordUndo=this.recordUndo),e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new Mp),t.oldParentId=e.oldParentId,t.oldInputName=e.oldInputName,e.oldCoordinate&&(o=e.oldCoordinate.split(","),t.oldCoordinate=new G(Number(o[0]),Number(o[1]))),t.newParentId=e.newParentId,t.newInputName=e.newInputName,e.newCoordinate&&(o=e.newCoordinate.split(","),t.newCoordinate=new G(Number(o[0]),Number(o[1]))),e.reason!==void 0&&(t.reason=e.reason),e.recordUndo!==void 0&&(t.recordUndo=e.recordUndo),t}recordNew(){const e=this.currentLocation();this.newParentId=e.parentId,this.newInputName=e.inputName,this.newCoordinate=e.coordinate}setReason(e){this.reason=e}currentLocation(){var e=this.getEventWorkspace_();if(!this.blockId)throw Error("The block ID is undefined. Either pass a block to the constructor, or call fromJson");var t=e.getBlockById(this.blockId);if(!t)throw Error("The block associated with the block move event could not be found");e={};const o=t.getParent();return o?(e.parentId=o.id,(t=o.getInputWithBlock(t))&&(e.inputName=t.name)):e.coordinate=t.getRelativeToSurfaceXY(),e}isNull(){return this.oldParentId===this.newParentId&&this.oldInputName===this.newInputName&&G.equals(this.oldCoordinate,this.newCoordinate)}run(e){var t=this.getEventWorkspace_();if(!this.blockId)throw Error("The block ID is undefined. Either pass a block to the constructor, or call fromJson");var o=t.getBlockById(this.blockId);if(o){var n=e?this.newParentId:this.oldParentId,c=e?this.newInputName:this.oldInputName;if(e=e?this.newCoordinate:this.oldCoordinate,n){var h=t.getBlockById(n);if(!h){console.warn("Can't connect to non-existent block: "+n);return}}if(o.getParent()&&o.unplug(),e)c=o.getRelativeToSurfaceXY(),o.moveBy(e.x-c.x,e.y-c.y,this.reason);else{t=o.outputConnection,(!t||o.previousConnection&&o.previousConnection.isConnected())&&(t=o.previousConnection);let $,T;o=(T=t)==null?void 0:T.type,c?(o=h.getInput(c))&&($=o.connection):o===oe.PREVIOUS_STATEMENT&&($=h.nextConnection),$&&t?t.connect($):console.warn("Can't connect to non-existent input: "+c)}}else console.warn("Can't move non-existent block: "+this.blockId)}};r(F.EVENT,O.BLOCK_MOVE,Mp);var Np=class extends Cs{constructor(e,t,o){super(e?e.workspace.id:void 0),this.type=O.BUBBLE_OPEN,e&&(this.blockId=e.id,this.isOpen=t,this.bubbleType=o)}toJson(){const e=super.toJson();if(this.isOpen===void 0)throw Error("Whether this event is for opening the bubble is undefined. Either pass the value to the constructor, or call fromJson");if(!this.bubbleType)throw Error("The type of bubble is undefined. Either pass the value to the constructor, or call fromJson");return e.isOpen=this.isOpen,e.bubbleType=this.bubbleType,e.blockId=this.blockId||"",e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new Np),t.isOpen=e.isOpen,t.bubbleType=e.bubbleType,t.blockId=e.blockId,t}},Lp;(function(e){e.MUTATOR="mutator",e.COMMENT="comment",e.WARNING="warning"})(Lp||(Lp={})),r(F.EVENT,O.BUBBLE_OPEN,Np);var Gs=class extends Ui{constructor(e){super(),this.isBlank=!e,e&&(this.commentId=e.id,this.workspaceId=e.workspace.id,this.group=i.getGroup$$module$build$src$core$events$utils(),this.recordUndo=me())}toJson(){const e=super.toJson();if(!this.commentId)throw Error("The comment ID is undefined. Either pass a comment to the constructor, or call fromJson");return e.commentId=this.commentId,e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new Gs),t.commentId=e.commentId,t}static CommentCreateDeleteHelper(e,t){const o=e.getEventWorkspace_();if(t){if(!e.json)throw Error("Encountered a comment event without proper json");Fn(e.json,o)}else{if(!e.commentId)throw Error("The comment ID is undefined. Either pass a comment to the constructor, or call fromJson");(t=o.getCommentById(e.commentId))?t.dispose():console.warn("Can't delete non-existent comment: "+e.commentId)}}},Pp=class extends Gs{constructor(e,t,o){super(e),this.type=O.COMMENT_CHANGE,e&&(this.oldContents_=typeof t>"u"?"":t,this.newContents_=typeof o>"u"?"":o)}toJson(){const e=super.toJson();if(!this.oldContents_)throw Error("The old contents is undefined. Either pass a value to the constructor, or call fromJson");if(!this.newContents_)throw Error("The new contents is undefined. Either pass a value to the constructor, or call fromJson");return e.oldContents=this.oldContents_,e.newContents=this.newContents_,e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new Pp),t.oldContents_=e.oldContents,t.newContents_=e.newContents,t}isNull(){return this.oldContents_===this.newContents_}run(e){var t=this.getEventWorkspace_();if(!this.commentId)throw Error("The comment ID is undefined. Either pass a comment to the constructor, or call fromJson");if(t=t.getCommentById(this.commentId)){var o=e?this.newContents_:this.oldContents_;if(o===void 0)throw Error(e?"The new contents is undefined. Either pass a value to the constructor, or call fromJson":"The old contents is undefined. Either pass a value to the constructor, or call fromJson");t.setText(o)}else console.warn("Can't change non-existent comment: "+this.commentId)}};r(F.EVENT,O.COMMENT_CHANGE,Pp);var Bp=class extends Gs{constructor(e,t){super(e),this.newCollapsed=t,this.type=O.COMMENT_COLLAPSE}toJson(){const e=super.toJson();if(this.newCollapsed===void 0)throw Error("The new collapse value undefined. Either call recordNew, or call fromJson");return e.newCollapsed=this.newCollapsed,e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new Bp),t.newCollapsed=e.newCollapsed,t}run(e){var t=this.getEventWorkspace_();if(!this.commentId)throw Error("The comment ID is undefined. Either pass a comment to the constructor, or call fromJson");(t=t.getCommentById(this.commentId))?t.setCollapsed(e?!!this.newCollapsed:!this.newCollapsed):console.warn("Can't collapse or uncollapse non-existent comment: "+this.commentId)}};r(F.EVENT,O.COMMENT_COLLAPSE,Bp);var jp=class extends Gs{constructor(e){super(e),this.type=O.COMMENT_CREATE,e&&(this.xml=Xn(e),this.json=xi(e,{addCoordinates:!0}))}toJson(){const e=super.toJson();if(!this.xml)throw Error("The comment XML is undefined. Either pass a comment to the constructor, or call fromJson");if(!this.json)throw Error("The comment JSON is undefined. Either pass a block to the constructor, or call fromJson");return e.xml=Ls(this.xml),e.json=this.json,e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new jp),t.xml=i.textToDom$$module$build$src$core$utils$xml(e.xml),t.json=e.json,t}run(e){Gs.CommentCreateDeleteHelper(this,e)}};r(F.EVENT,O.COMMENT_CREATE,jp);var Fp=class extends Gs{constructor(e){super(e),this.type=O.COMMENT_DELETE,e&&(this.xml=Xn(e),this.json=xi(e,{addCoordinates:!0}))}run(e){Gs.CommentCreateDeleteHelper(this,!e)}toJson(){const e=super.toJson();if(!this.xml)throw Error("The comment XML is undefined. Either pass a comment to the constructor, or call fromJson");if(!this.json)throw Error("The comment JSON is undefined. Either pass a block to the constructor, or call fromJson");return e.xml=Ls(this.xml),e.json=this.json,e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new Fp),t.xml=i.textToDom$$module$build$src$core$utils$xml(e.xml),t.json=e.json,t}};r(F.EVENT,O.COMMENT_DELETE,Fp);var zp=class extends Cs{constructor(e,t){super(e?e.workspace.id:void 0),this.type=O.COMMENT_DRAG,e&&(this.commentId=e.id,this.isStart=t)}toJson(){const e=super.toJson();if(this.isStart===void 0)throw Error("Whether this event is the start of a drag is undefined. Either pass the value to the constructor, or call fromJson");if(this.commentId===void 0)throw Error("The comment ID is undefined. Either pass a comment to the constructor, or call fromJson");return e.isStart=this.isStart,e.commentId=this.commentId,e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new zp),t.isStart=e.isStart,t.commentId=e.commentId,t}};r(F.EVENT,O.COMMENT_DRAG,zp);var Up=class extends Gs{constructor(e){super(e),this.type=O.COMMENT_MOVE,e&&(this.comment_=e,this.oldCoordinate_=e.getRelativeToSurfaceXY())}recordNew(){if(this.newCoordinate_)throw Error("Tried to record the new position of a comment on the same event twice.");if(!this.comment_)throw Error("The comment is undefined. Pass a comment to the constructor if you want to use the record functionality");this.newCoordinate_=this.comment_.getRelativeToSurfaceXY()}setReason(e){this.reason=e}setOldCoordinate(e){this.oldCoordinate_=e}toJson(){const e=super.toJson();if(!this.oldCoordinate_)throw Error("The old comment position is undefined. Either pass a comment to the constructor, or call fromJson");if(!this.newCoordinate_)throw Error("The new comment position is undefined. Either call recordNew, or call fromJson");return e.oldCoordinate=`${Math.round(this.oldCoordinate_.x)}, ${Math.round(this.oldCoordinate_.y)}`,e.newCoordinate=Math.round(this.newCoordinate_.x)+","+Math.round(this.newCoordinate_.y),e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new Up),o=e.oldCoordinate.split(","),t.oldCoordinate_=new G(Number(o[0]),Number(o[1])),o=e.newCoordinate.split(","),t.newCoordinate_=new G(Number(o[0]),Number(o[1])),t}isNull(){return G.equals(this.oldCoordinate_,this.newCoordinate_)}run(e){var t=this.getEventWorkspace_();if(!this.commentId)throw Error("The comment ID is undefined. Either pass a comment to the constructor, or call fromJson");if(t=t.getCommentById(this.commentId)){if(e=e?this.newCoordinate_:this.oldCoordinate_,!e)throw Error("Either oldCoordinate_ or newCoordinate_ is undefined. Either pass a comment to the constructor and call recordNew, or call fromJson");t.moveTo(e)}else console.warn("Can't move non-existent comment: "+this.commentId)}};r(F.EVENT,O.COMMENT_MOVE,Up);var Hp=class extends Gs{constructor(e){super(e),this.type=O.COMMENT_RESIZE,e&&(this.oldSize=e.getSize())}recordCurrentSizeAsNewSize(){if(this.newSize)throw Error("Tried to record the new size of a comment on the same event twice.");var e=this.getEventWorkspace_();if(!this.commentId)throw Error("The comment ID is undefined. Either pass a comment to the constructor, or call fromJson");if(e=e.getCommentById(this.commentId),!e)throw Error("The comment associated with the comment resize event could not be found");this.newSize=e.getSize()}toJson(){const e=super.toJson();if(!this.oldSize)throw Error("The old comment size is undefined. Either pass a comment to the constructor, or call fromJson");if(!this.newSize)throw Error("The new comment size is undefined. Either call recordCurrentSizeAsNewSize, or call fromJson");return e.oldWidth=Math.round(this.oldSize.width),e.oldHeight=Math.round(this.oldSize.height),e.newWidth=Math.round(this.newSize.width),e.newHeight=Math.round(this.newSize.height),e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new Hp),t.oldSize=new Le(e.oldWidth,e.oldHeight),t.newSize=new Le(e.newWidth,e.newHeight),t}isNull(){return Le.equals(this.oldSize,this.newSize)}run(e){var t=this.getEventWorkspace_();if(!this.commentId)throw Error("The comment ID is undefined. Either pass a comment to the constructor, or call fromJson");if(t=t.getCommentById(this.commentId)){if(e=e?this.newSize:this.oldSize,!e)throw Error("Either oldSize or newSize is undefined. Either pass a comment to the constructor and call recordCurrentSizeAsNewSize, or call fromJson");t.setSize(e)}else console.warn("Can't resize non-existent comment: "+this.commentId)}};r(F.EVENT,O.COMMENT_RESIZE,Hp);var Wp=class extends Cs{constructor(e,t,o){super(o),this.type=O.TOOLBOX_ITEM_SELECT,this.oldItem=e??void 0,this.newItem=t??void 0}toJson(){const e=super.toJson();return e.oldItem=this.oldItem,e.newItem=this.newItem,e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new Wp),t.oldItem=e.oldItem,t.newItem=e.newItem,t}};r(F.EVENT,O.TOOLBOX_ITEM_SELECT,Wp);var cy=class extends Ui{constructor(e){super(),this.isBlank=!0,this.recordUndo=!1,this.type=O.FINISHED_LOADING,this.isBlank=!!e,e&&(this.workspaceId=e.id)}};r(F.EVENT,O.FINISHED_LOADING,cy);var uy,dy,hy,py,gy,my,fy,$y,by,vy,yy,_y,wy,Cy,Ty,ky,Sy,Ey,Iy,xy,Dy,Ay,Ry,Oy,My,Q;i.BLOCK_CHANGE$$module$build$src$core$events$events=O.BLOCK_CHANGE,i.BLOCK_CREATE$$module$build$src$core$events$events=O.BLOCK_CREATE,i.BLOCK_DELETE$$module$build$src$core$events$events=O.BLOCK_DELETE,uy=O.BLOCK_DRAG,i.BLOCK_MOVE$$module$build$src$core$events$events=O.BLOCK_MOVE,dy=O.BLOCK_FIELD_INTERMEDIATE_CHANGE,hy=O.BUBBLE_OPEN,py=O.BLOCK_CHANGE,gy=O.CLICK,my=O.COMMENT_CHANGE,fy=O.COMMENT_CREATE,$y=O.COMMENT_DELETE,by=O.COMMENT_MOVE,vy=O.COMMENT_RESIZE,yy=O.COMMENT_DRAG,_y=O.BLOCK_CREATE,wy=O.BLOCK_DELETE,Cy=O.FINISHED_LOADING,Ty=O.MARKER_MOVE,ky=O.BLOCK_MOVE,Sy=O.SELECTED,Ey=O.THEME_CHANGE,Iy=O.TOOLBOX_ITEM_SELECT,xy=O.TRASHCAN_OPEN,Dy=O.UI,Ay=O.VAR_CREATE,Ry=O.VAR_DELETE,Oy=O.VAR_RENAME,My=O.VIEWPORT_CHANGE,Q={},Q.Abstract=Ui,Q.BLOCK_CHANGE=i.BLOCK_CHANGE$$module$build$src$core$events$events,Q.BLOCK_CREATE=i.BLOCK_CREATE$$module$build$src$core$events$events,Q.BLOCK_DELETE=i.BLOCK_DELETE$$module$build$src$core$events$events,Q.BLOCK_DRAG=uy,Q.BLOCK_FIELD_INTERMEDIATE_CHANGE=dy,Q.BLOCK_MOVE=i.BLOCK_MOVE$$module$build$src$core$events$events,Q.BUBBLE_OPEN=hy,Q.BUMP_EVENTS=ub,Q.BlockBase=ni,Q.BlockChange=ri,Q.BlockCreate=Xh,Q.BlockDelete=up,Q.BlockDrag=Rp,Q.BlockFieldIntermediateChange=Op,Q.BlockMove=Mp,Q.BubbleOpen=Np,Q.BubbleType=Lp,Q.CHANGE=py,Q.CLICK=gy,Q.COMMENT_CHANGE=my,Q.COMMENT_CREATE=fy,Q.COMMENT_DELETE=$y,Q.COMMENT_DRAG=yy,Q.COMMENT_MOVE=by,Q.COMMENT_RESIZE=vy,Q.CREATE=_y,Q.Click=fh,Q.ClickTarget=$h,Q.CommentBase=Gs,Q.CommentChange=Pp,Q.CommentCollapse=Bp,Q.CommentCreate=jp,Q.CommentDelete=Fp,Q.CommentDrag=zp,Q.CommentMove=Up,Q.CommentResize=Hp,Q.DELETE=wy,Q.FINISHED_LOADING=Cy,Q.FinishedLoading=cy,Q.MARKER_MOVE=Ty,Q.MOVE=ky,Q.MarkerMove=dp,Q.SELECTED=Sy,Q.Selected=vp,Q.THEME_CHANGE=Ey,Q.TOOLBOX_ITEM_SELECT=Iy,Q.TRASHCAN_OPEN=xy,Q.ThemeChange=Zh,Q.ToolboxItemSelect=Wp,Q.TrashcanOpen=_p,Q.UI=Dy,Q.UiBase=Cs,Q.VAR_CREATE=Ay,Q.VAR_DELETE=Ry,Q.VAR_RENAME=Oy,Q.VIEWPORT_CHANGE=My,Q.VarBase=dr,Q.VarCreate=Ph,Q.VarDelete=fp,Q.VarRename=$p,Q.ViewportChange=Qh,Q.clearPendingUndo=ce,Q.disable=i.disable$$module$build$src$core$events$utils,Q.disableOrphans=tt,Q.enable=i.enable$$module$build$src$core$events$utils,Q.filter=ae,Q.fire=z,Q.fromJson=je,Q.get=V,Q.getDescendantIds=he,Q.getGroup=i.getGroup$$module$build$src$core$events$utils,Q.getRecordUndo=me,Q.isEnabled=K,Q.setGroup=i.setGroup$$module$build$src$core$events$utils,Q.setRecordUndo=i.setRecordUndo$$module$build$src$core$events$utils;var xs={};xs.BottomRow=qv,xs.ConstantProvider=Yv,xs.Drawer=Jv,xs.MarkerSvg=ey,xs.PathObject=ty,xs.RenderInfo=Qv,xs.Renderer=xp,xs.RightConnectionShape=Xv,xs.StatementInput=Gl,xs.TopRow=Zv,hh();var Tt={};Tt.registerCleanup=qd,Tt.registerCollapse=Zd,Tt.registerCollapseExpandBlock=nh,Tt.registerComment=oh,Tt.registerCommentCreate=dh,Tt.registerCommentDelete=ch,Tt.registerCommentDuplicate=uh,Tt.registerCommentOptions=ib,Tt.registerDefaultOptions=hh,Tt.registerDelete=ah,Tt.registerDeleteAll=th,Tt.registerDisable=rh,Tt.registerDuplicate=sh,Tt.registerExpand=Qd,Tt.registerHelp=lh,Tt.registerInline=ih,Tt.registerRedo=Jd,Tt.registerUndo=Yd;var Kl={};Kl.CommentView=mv,Kl.RenderedWorkspaceComment=kl,Kl.WorkspaceComment=Tl;var Ar={};Ar.Bubble=Ye,Ar.MiniWorkspaceBubble=uo,Ar.TextBubble=kv,Ar.TextInputBubble=yv;var Ny=class extends Ml{constructor(){super(),this.FIELD_TEXT_BASELINE_CENTER=!1,this.DARK_PATH_OFFSET=1,this.MAX_BOTTOM_WIDTH=30,this.STATEMENT_BOTTOM_SPACER=-this.NOTCH_HEIGHT/2}getCSS_(e){return super.getCSS_(e).concat([`${e} .blocklyInsertionMarker>.blocklyPathLight,`,`${e} .blocklyInsertionMarker>.blocklyPathDark {`,`fill-opacity: ${this.INSERTION_MARKER_OPACITY};`,"stroke: none;","}"])}},Ly=class{constructor(e){this.inlineSteps_=this.steps_="",this.info_=e,this.RTL_=this.info_.RTL,e=e.getRenderer(),this.constants_=e.getConstants(),this.highlightConstants_=e.getHighlightConstants(),this.highlightOffset=this.highlightConstants_.OFFSET,this.outsideCornerPaths_=this.highlightConstants_.OUTSIDE_CORNER,this.insideCornerPaths_=this.highlightConstants_.INSIDE_CORNER,this.puzzleTabPaths_=this.highlightConstants_.PUZZLE_TAB,this.notchPaths_=this.highlightConstants_.NOTCH,this.startPaths_=this.highlightConstants_.START_HAT,this.jaggedTeethPaths_=this.highlightConstants_.JAGGED_TEETH}getPath(){return this.steps_+` -`+this.inlineSteps_}drawTopCorner(e){this.steps_+=at(e.xPos,this.info_.startY);for(let t=0,o;o=e.elements[t];t++)S.isLeftSquareCorner(o)?this.steps_+=this.highlightConstants_.START_POINT:S.isLeftRoundedCorner(o)?this.steps_+=this.outsideCornerPaths_.topLeft(this.RTL_):S.isPreviousConnection(o)?this.steps_+=this.notchPaths_.pathLeft:S.isHat(o)?this.steps_+=this.startPaths_.path(this.RTL_):S.isSpacer(o)&&o.width!==0&&(this.steps_+=ne("H",o.xPos+o.width-this.highlightOffset));this.steps_+=ne("H",e.xPos+e.width-this.highlightOffset)}drawJaggedEdge_(e){this.info_.RTL&&(this.steps_+=this.jaggedTeethPaths_.pathLeft+ne("v",e.height-this.jaggedTeethPaths_.height-this.highlightOffset))}drawValueInput(e){const t=e.getLastInput();if(this.RTL_){const o=e.height-t.connectionHeight;this.steps_+=wt(t.xPos+t.width-this.highlightOffset,e.yPos)+this.puzzleTabPaths_.pathDown(this.RTL_)+ne("v",o)}else this.steps_+=wt(t.xPos+t.width,e.yPos)+this.puzzleTabPaths_.pathDown(this.RTL_)}drawStatementInput(e){const t=e.getLastInput();if(t)if(this.RTL_){const o=e.height-2*this.insideCornerPaths_.height;this.steps_+=wt(t.xPos,e.yPos)+this.insideCornerPaths_.pathTop(this.RTL_)+ne("v",o)+this.insideCornerPaths_.pathBottom(this.RTL_)+Bs(e.width-t.xPos-this.insideCornerPaths_.width,0)}else this.steps_+=wt(t.xPos,e.yPos+e.height)+this.insideCornerPaths_.pathBottom(this.RTL_)+Bs(e.width-t.xPos-this.insideCornerPaths_.width,0)}drawRightSideRow(e){const t=e.xPos+e.width-this.highlightOffset;e instanceof lp&&e.followsStatement&&(this.steps_+=ne("H",t)),this.RTL_&&(this.steps_+=ne("H",t),e.height>this.highlightOffset&&(this.steps_+=ne("V",e.yPos+e.height-this.highlightOffset)))}drawBottomRow(e){if(this.RTL_)this.steps_+=ne("V",e.baseline-this.highlightOffset);else{const t=this.info_.bottomRow.elements[0];S.isLeftSquareCorner(t)?this.steps_+=wt(e.xPos+this.highlightOffset,e.baseline-this.highlightOffset):S.isLeftRoundedCorner(t)&&(this.steps_+=wt(e.xPos,e.baseline),this.steps_+=this.outsideCornerPaths_.bottomLeft())}}drawLeft(){var e=this.info_.outputConnection;e&&(e=e.connectionOffsetY+e.height,this.RTL_?this.steps_+=wt(this.info_.startX,e):(this.steps_+=wt(this.info_.startX+this.highlightOffset,this.info_.bottomRow.baseline-this.highlightOffset),this.steps_+=ne("V",e)),this.steps_+=this.puzzleTabPaths_.pathUp(this.RTL_)),this.RTL_||(e=this.info_.topRow,S.isLeftRoundedCorner(e.elements[0])?this.steps_+=ne("V",this.outsideCornerPaths_.height):this.steps_+=ne("V",e.capline+this.highlightOffset))}drawInlineInput(e){const t=this.highlightOffset,o=e.xPos+e.connectionWidth;var n=e.centerline-e.height/2;const c=e.width-e.connectionWidth,h=n+t;this.RTL_?(n=e.connectionOffsetY-t,e=e.height-(e.connectionOffsetY+e.connectionHeight)+t,this.inlineSteps_+=wt(o-t,h)+ne("v",n)+this.puzzleTabPaths_.pathDown(this.RTL_)+ne("v",e)+ne("h",c)):this.inlineSteps_+=wt(e.xPos+e.width+t,h)+ne("v",e.height)+ne("h",-c)+wt(o,n+e.connectionOffsetY)+this.puzzleTabPaths_.pathDown(this.RTL_)}},Py=class extends Nl{constructor(e,t){super(e,t),this.highlighter_=new Ly(t)}draw(){this.drawOutline_(),this.drawInternals_(),this.updateConnectionHighlights();const e=this.block_.pathObject;e.setPath(this.outlinePath_+` -`+this.inlinePath_),e.setHighlightPath(this.highlighter_.getPath()),this.info_.RTL&&e.flipRTL(),this.recordSizeOnBlock_()}drawTop_(){this.highlighter_.drawTopCorner(this.info_.topRow),this.highlighter_.drawRightSideRow(this.info_.topRow),super.drawTop_()}drawJaggedEdge_(e){this.highlighter_.drawJaggedEdge_(e),super.drawJaggedEdge_(e)}drawValueInput_(e){this.highlighter_.drawValueInput(e),super.drawValueInput_(e)}drawStatementInput_(e){this.highlighter_.drawStatementInput(e),super.drawStatementInput_(e)}drawRightSideRow_(e){this.highlighter_.drawRightSideRow(e),this.outlinePath_+=ne("H",e.xPos+e.width)+ne("V",e.yPos+e.height)}drawBottom_(){this.highlighter_.drawBottomRow(this.info_.bottomRow),super.drawBottom_()}drawLeft_(){this.highlighter_.drawLeft(),super.drawLeft_()}drawInlineInput_(e){this.highlighter_.drawInlineInput(e),super.drawInlineInput_(e)}positionInlineInputConnection_(e){const t=e.centerline-e.height/2;if(e.connectionModel){let o=e.xPos+e.connectionWidth+this.constants_.DARK_PATH_OFFSET;this.info_.RTL&&(o*=-1),e.connectionModel.setOffsetInBlock(o,t+e.connectionOffsetY+this.constants_.DARK_PATH_OFFSET)}}positionStatementInputConnection_(e){const t=e.getLastInput();if(t!=null&&t.connectionModel){let o=e.xPos+e.statementEdge+t.notchOffset;o=this.info_.RTL?-1*o:o+this.constants_.DARK_PATH_OFFSET,t.connectionModel.setOffsetInBlock(o,e.yPos+this.constants_.DARK_PATH_OFFSET)}}positionExternalValueConnection_(e){const t=e.getLastInput();if(t&&t.connectionModel){let o=e.xPos+e.width+this.constants_.DARK_PATH_OFFSET;this.info_.RTL&&(o*=-1),t.connectionModel.setOffsetInBlock(o,e.yPos)}}positionNextConnection_(){const e=this.info_.bottomRow;if(e.connection){const t=e.connection,o=t.xPos;t.connectionModel.setOffsetInBlock((this.info_.RTL?-o:o)+this.constants_.DARK_PATH_OFFSET/2,e.baseline+this.constants_.DARK_PATH_OFFSET)}}},By=class{constructor(e){this.OFFSET=.5,this.constantProvider=e,this.START_POINT=at(this.OFFSET,this.OFFSET)}init(){this.INSIDE_CORNER=this.makeInsideCorner(),this.OUTSIDE_CORNER=this.makeOutsideCorner(),this.PUZZLE_TAB=this.makePuzzleTab(),this.NOTCH=this.makeNotch(),this.JAGGED_TEETH=this.makeJaggedTeeth(),this.START_HAT=this.makeStartHat()}makeInsideCorner(){const e=this.constantProvider.CORNER_RADIUS,t=this.OFFSET,o=(1-Math.SQRT1_2)*(e+t)-t,n=at(o,o)+gt("a","0 0,0",e,ue(-o-t,e-o)),c=gt("a","0 0,0",e+t,ue(e+t,e+t)),h=at(o,-o)+gt("a","0 0,0",e+t,ue(e-o,o+t));return{width:e+t,height:e,pathTop($){return $?n:""},pathBottom($){return $?c:h}}}makeOutsideCorner(){const e=this.constantProvider.CORNER_RADIUS,t=this.OFFSET,o=(1-Math.SQRT1_2)*(e-t)+t,n=at(o,o)+gt("a","0 0,1",e-t,ue(e-o,-o+t)),c=at(t,e)+gt("a","0 0,1",e-t,ue(e,-e+t)),h=-o,$=at(o,h)+gt("a","0 0,1",e-t,ue(-o+t,-h-e));return{height:e,topLeft(T){return T?n:c},bottomLeft(){return $}}}makePuzzleTab(){const e=this.constantProvider.TAB_WIDTH,t=this.constantProvider.TAB_HEIGHT,o=at(-2,-t+3.4)+Bs(-.45*e,-2.1),n=ne("v",2.5)+at(.97*-e,2.5)+Yt("q",[ue(.05*-e,10),ue(.3*e,9.5)])+at(.67*e,-1.9)+ne("v",2.5),c=ne("v",-1.5)+at(-.92*e,-.5)+Yt("q",[ue(-.19*e,-5.5),ue(0,-11)])+at(.92*e,1),h=at(-5,t-.7)+Bs(.46*e,-2.1);return{width:e,height:t,pathUp($){return $?o:c},pathDown($){return $?n:h}}}makeNotch(){return{pathLeft:ne("h",this.OFFSET)+this.constantProvider.NOTCH.pathLeft}}makeJaggedTeeth(){return{pathLeft:Bs(5.1,2.6)+at(-10.2,6.8)+Bs(5.1,2.6),height:12,width:10.2}}makeStartHat(){const e=this.constantProvider.START_HAT.height,t=at(25,-8.7)+Yt("c",[ue(29.7,-6.2),ue(57.2,-.5),ue(75,8.7)]),o=Yt("c",[ue(17.8,-9.2),ue(45.3,-14.9),ue(75,-8.7)])+wt(100.5,e+.5);return{path(n){return n?t:o}}}},jy=class extends rp{constructor(e,t){super(e,t),this.constants_=e,this.connectedBlock&&(this.width+=this.constants_.DARK_PATH_OFFSET,this.height+=this.constants_.DARK_PATH_OFFSET)}},Fy=class extends wr{constructor(e,t){super(e,t),this.constants_=e,this.connectedBlock&&(this.height+=this.constants_.DARK_PATH_OFFSET)}},zy=class extends kr{constructor(e,t){super(e,t),this.renderer_=e}getRenderer(){return this.renderer_}populateBottomRow_(){super.populateBottomRow_(),this.block_.inputList.length&&this.block_.inputList[this.block_.inputList.length-1]instanceof is||(this.bottomRow.minHeight=this.constants_.MEDIUM_PADDING-this.constants_.DARK_PATH_OFFSET)}addInput_(e,t){this.isInline&&e instanceof i.ValueInput$$module$build$src$core$inputs$value_input?(t.elements.push(new jy(this.constants_,e)),t.hasInlineInput=!0):e instanceof is?(t.elements.push(new Fy(this.constants_,e)),t.hasStatement=!0):e instanceof i.ValueInput$$module$build$src$core$inputs$value_input?(t.elements.push(new Ol(this.constants_,e)),t.hasExternalInput=!0):(e instanceof Us||e instanceof fo)&&(t.minHeight=Math.max(t.minHeight,this.constants_.DUMMY_INPUT_MIN_HEIGHT),t.hasDummyInput=!0),this.isInline||t.align!==null||(t.align=e.align)}addElemSpacing_(){let e=!1;for(let o=0,n;n=this.rows[o];o++)n.hasExternalInput&&(e=!0);for(let o=0,n;n=this.rows[o];o++){var t=n.elements;if(n.elements=[],n.startsWithElemSpacer()&&n.elements.push(new os(this.constants_,this.getInRowSpacing_(null,t[0]))),t.length){for(let c=0;c>>/sprites.png); - height: 16px; - vertical-align: middle; - visibility: hidden; - width: 16px; -} - -.blocklyTreeIconClosed { - background-position: -32px -1px; -} - -.blocklyToolboxDiv[dir="RTL"] .blocklyTreeIconClosed { - background-position: 0 -1px; -} - -.blocklyTreeSelected>.blocklyTreeIconClosed { - background-position: -32px -17px; -} - -.blocklyToolboxDiv[dir="RTL"] .blocklyTreeSelected>.blocklyTreeIconClosed { - background-position: 0 -17px; -} - -.blocklyTreeIconOpen { - background-position: -16px -1px; -} - -.blocklyTreeSelected>.blocklyTreeIconOpen { - background-position: -16px -17px; -} - -.blocklyTreeLabel { - cursor: default; - font: 16px sans-serif; - padding: 0 3px; - vertical-align: middle; -} - -.blocklyToolboxDelete .blocklyTreeLabel { - cursor: url("<<>>/handdelete.cur"), auto; -} - -.blocklyTreeSelected .blocklyTreeLabel { - color: #fff; -} -`),r(F.TOOLBOX_ITEM,Ds.registrationName,Ds);var Rr=class extends Vp{constructor(e,t){super(e,t),this.cssConfig_={container:"blocklyTreeSeparator"},this.htmlDiv=null,Object.assign(this.cssConfig_,e.cssconfig||e.cssConfig)}init(){this.createDom_()}createDom_(){const e=document.createElement("div"),t=this.cssConfig_.container;return t&&ge(e,t),this.htmlDiv=e}getDiv(){return this.htmlDiv}dispose(){Ke(this.htmlDiv)}};Rr.registrationName="sep",Et(` -.blocklyTreeSeparator { - border-bottom: solid #e5e5e5 1px; - height: 0; - margin: 5px 0; -} - -.blocklyToolboxDiv[layout="h"] .blocklyTreeSeparator { - border-right: solid #e5e5e5 1px; - border-bottom: none; - height: auto; - margin: 0 5px 0 5px; - padding: 5px 0; - width: 0; -} -`),r(F.TOOLBOX_ITEM,Rr.registrationName,Rr);var dn=class extends Ds{constructor(e,t,o){super(e,t,o),this.subcategoriesDiv_=null,this.expanded_=!1,this.toolboxItems_=[]}makeDefaultCssConfig_(){const e=super.makeDefaultCssConfig_();return e.contents="blocklyToolboxContents",e}parseContents_(e){if("custom"in e)this.flyoutItems_=e.custom;else{const t=e.contents;if(t){this.flyoutItems_=[],e=!0;for(let o=0;o>>/handdelete.cur"), auto; -} - -.blocklyToolboxGrab { - cursor: url("<<>>/handclosed.cur"), auto; - cursor: grabbing; - cursor: -webkit-grabbing; -} - -/* Category tree in Toolbox. */ -.blocklyToolboxDiv { - background-color: #ddd; - overflow-x: visible; - overflow-y: auto; - padding: 4px 0 4px 0; - position: absolute; - z-index: 70; /* so blocks go under toolbox when dragging */ - -webkit-tap-highlight-color: transparent; /* issue #1345 */ -} - -.blocklyToolboxContents { - display: flex; - flex-wrap: wrap; - flex-direction: column; -} - -.blocklyToolboxContents:focus { - outline: none; -} -`),r(F.TOOLBOX,js,Vy);var fk="11.2.2",$k=oe.INPUT_VALUE,bk=oe.OUTPUT_VALUE,vk=oe.NEXT_STATEMENT,yk=oe.PREVIOUS_STATEMENT,_k=Ee.TOP,wk=Ee.BOTTOM,Ck=Ee.LEFT,Tk=Ee.RIGHT;rn.prototype.newBlock=function(e,t){return new Oo(this,e,t)},ns.prototype.newBlock=function(e,t){return new gs(this,e,t)},rn.prototype.newComment=function(e){return new Tl(this,e)},ns.prototype.newComment=function(e){return new kl(this,e)},ns.newTrashcan=function(e){return new Uv(e)},uo.prototype.newWorkspaceSvg=function(e){return new ns(e)},i.Names$$module$build$src$core$names.prototype.populateProcedures=function(e){e=Ka(e),e=e[0].concat(e[1]);for(let t=0;t{this.setState({popper:b.I18n.t("Copied"),anchorEl:i}),setTimeout(()=>this.setState({popper:"",anchorEl:null}),1e3)},50)}render(){const s=new Blob([this.props.text],{type:"application/xml"}),i=`${this.props.scriptId.substring(10)}.xml`;return g.jsxs(Gt,{onClose:()=>!1,maxWidth:"lg",sx:{"& .MuiDialog-paper":Pr.dialog},fullWidth:!0,open:!0,"aria-labelledby":"export-dialog-title",children:[g.jsx(as,{id:"export-dialog-title",children:b.I18n.t("Export selected blocks")}),g.jsx(Vt,{style:Pr.overflowY,children:g.jsx("pre",{id:"export-text",style:{...Pr.textArea,...this.props.themeType==="dark"?void 0:Pr.textAreaLight},children:this.props.text})}),g.jsxs(Kt,{children:[g.jsx(De,{variant:"contained",color:"secondary",startIcon:g.jsx(vc,{}),children:g.jsx("a",{download:i,target:"_blank",rel:"noreferrer",href:URL.createObjectURL(s),style:{textDecoration:"inherit",color:"inherit"},children:b.I18n.t("Download as file")})}),g.jsx(De,{variant:"contained",onClick:r=>this.onCopy(r),color:"secondary",startIcon:g.jsx(rx,{}),children:b.I18n.t("Copy to clipboard")}),g.jsx(De,{variant:"contained",onClick:()=>this.handleCancel(),color:"primary",startIcon:g.jsx(qs,{}),children:b.I18n.t("Close")}),g.jsx(Gk,{id:"popper",style:{zIndex:1e4},open:!!this.state.popper,placement:"top",anchorEl:this.state.anchorEl,transition:!0,children:({TransitionProps:r})=>g.jsx(Vk,{...r,timeout:350,children:g.jsx(Dw,{children:g.jsx("p",{style:Pr.typography,children:this.state.popper})})})}),g.jsx("textarea",{id:"copy_input",readOnly:!0,style:{position:"absolute",left:-9999},tabIndex:-1,"aria-hidden":!0,value:this.props.text})]})]},"export-dialog")}}const Ot={textArea:{width:"calc(100% - 10px)",height:"calc(80% - 20px)",resize:"none",fontFamily:"monospace",fontSize:"1em",backgroundColor:"transparent",borderRadius:4,outline:"none"},dropzone:{marginTop:20,width:"100%",borderWidth:5,borderStyle:"dashed",borderColor:"#d0cccc",textAlign:"center",boxSizing:"border-box",paddingTop:45,borderRadius:10,height:"calc(100% - 10px)"},dropzoneDiv:{width:"100%",height:"20%",position:"relative"},dropzoneRejected:{borderColor:"#970000"},dropzoneAccepted:{borderColor:"#17cd02"},icon:{height:"80%",width:"80%",opacity:.3,color:"#eeeeee",position:"absolute",top:"50%",left:"50%",transform:"translate(-50%,-50%)",zIndex:0},iconError:{color:"#ffc3c6"},iconOk:{color:"#aaeebc"},text:{top:"50%",left:"50%",transform:"translate(-50%,-50%)",color:"#868686",position:"absolute",zIndex:1},dialog:{height:"95%"},fullHeight:{height:"100%",overflow:"hidden"}};class zm extends Y.Component{constructor(s){super(s),this.state={text:"",imageStatus:"",error:""}}componentDidMount(){setTimeout(()=>{var s;try{(s=window.document.getElementById("import-text-area"))==null||s.focus()}catch{}},100)}static readFileDataUrl(s,i){const r=new FileReader;r.onload=()=>{i(null,{data:r.result,name:s.name})},r.onabort=()=>{console.error("file reading was aborted"),i(b.I18n.t("file reading was aborted"))},r.onerror=l=>{console.error("file reading has failed"),i(b.I18n.t("file reading has failed: %s",l))},r.readAsText(s)}handleDropFile(s){if(!(s!=null&&s.length))return;const i=s[s.length-1];i&&zm.readFileDataUrl(i,(r,l)=>{var u;r||!l?this.setState({error:r||"No data"}):this.setState({text:((u=l.data)==null?void 0:u.toString())||""})})}handleCancel(){this.props.onClose()}handleOk(){this.props.onClose(this.state.text)}onChange(s){this.setState({text:s.target.value})}render(){const s={...Ot.dropzone,...this.state.imageStatus==="accepted"?Ot.dropzoneAccepted:this.state.imageStatus==="rejected"?Ot.dropzoneRejected:void 0};return g.jsxs(Gt,{onClose:()=>!1,maxWidth:"lg",sx:{"& .MuiDialog-paper":Ot.dialog},fullWidth:!0,open:!0,"aria-labelledby":"import-dialog-title",children:[g.jsx(as,{id:"import-dialog-title",children:b.I18n.t("Import blocks")}),g.jsxs(Vt,{style:Ot.fullHeight,children:[g.jsx("textarea",{autoFocus:!0,id:"import-text-area",placeholder:b.I18n.t("Paste your blocks here"),style:{...Ot.textArea,color:this.props.themeType==="dark"?"#ffffff":"#000000"},onChange:i=>this.onChange(i),value:this.state.text}),g.jsx(Mw,{maxSize:5e7,onDrop:(i,r)=>{var l,u,d;i.length?this.handleDropFile(i):window.alert(((d=(u=(l=r==null?void 0:r[0])==null?void 0:l.errors)==null?void 0:u[0])==null?void 0:d.message)||b.I18n.t("ra_Cannot upload"))},multiple:!1,accept:{"text/plain":[],"text/xml":[],"application/xml":[]},children:({getRootProps:i,getInputProps:r,isDragActive:l,isDragReject:u})=>u?(this.state.imageStatus!=="rejected"&&this.setState({imageStatus:"rejected"}),g.jsxs("div",{style:{...s,...Ot.dropzoneDiv},...i(),children:[g.jsx("input",{...r()}),g.jsx("span",{style:Ot.text,children:b.I18n.t("Some files will be rejected")},"text"),g.jsx(Wc,{style:{...Ot.icon,...Ot.iconError}},"icon")]})):l?(this.state.imageStatus!=="accepted"&&this.setState({imageStatus:"accepted"}),g.jsxs("div",{style:{...s,...Ot.dropzoneDiv},...i(),children:[g.jsx("input",{...r()}),g.jsx("span",{style:Ot.text,children:b.I18n.t("All files will be accepted")},"text"),g.jsx(Nw,{style:{...Ot.icon,...Ot.iconOk}},"icon")]})):(this.state.imageStatus!=="wait"&&this.setState({imageStatus:"wait"}),g.jsxs("div",{style:{...s,...Ot.dropzoneDiv},...i(),children:[g.jsx("input",{...r()}),g.jsx("span",{style:Ot.text,children:b.I18n.t("Drop some files here or click...")},"text"),g.jsx(Lw,{style:Ot.icon},"icon")]}))})]}),g.jsxs(Kt,{children:[g.jsx(De,{variant:"contained",disabled:!this.state.text,onClick:()=>this.handleOk(),color:"primary",startIcon:g.jsx(zo,{}),children:b.I18n.t("Import")}),g.jsx(De,{color:"grey",variant:"contained",onClick:()=>this.handleCancel(),startIcon:g.jsx(qs,{}),children:b.I18n.t("Close")})]})]})}}const we=window.Blockly;class mg extends Error{constructor(){super("The field has not yet been attached to its input. Call appendField to attach it.")}}class Ic extends we.Field{textGroup=null;borderRect_=null;maxLines_=1/0;isOverflowedY_=!1;constructor(s,i,r){super(s),s!==Symbol("SKIP_SETUP")&&(r&&this.configure_(r),this.SERIALIZABLE=!0,this.setValue((s==null?void 0:s.toString())||""),i&&this.setValidator(i))}configure_(s){super.configure_(s),s.maxLines&&this.setMaxLines(s.maxLines)}toXml(s){return s.textContent=this.getValue().replace(/\n/g," "),s}fromXml(s){this.setValue(s.textContent.replace(/ /g,` -`))}saveState(){const s=this.saveLegacyState(Ic);return s!==null?s:this.getValue()}loadState(s){this.loadLegacyState(we.Field,s)||this.setValue(s)}initView(){this.createBorderRect_(),this.textGroup=we.utils.dom.createSvgElement(we.utils.Svg.G,{class:"blocklyEditableText"},this.fieldGroup_)}onHtmlInputKeyDownSuper_(s){s.key==="Enter"?(we.WidgetDiv.hideIfOwner(this),we.dropDownDiv.hideWithoutAnimation()):s.key==="Escape"?(this.setValue(this.htmlInput_.getAttribute("data-untyped-default-value"),!1),we.WidgetDiv.hideIfOwner(this),we.dropDownDiv.hideWithoutAnimation()):s.key==="Tab"&&(we.WidgetDiv.hideIfOwner(this),we.dropDownDiv.hideWithoutAnimation(),this.sourceBlock_.tab(this,!s.shiftKey),s.preventDefault())}onHtmlInputChange_(s){const i=this.value_;this.setValue(this.getValueFromEditorText_(this.htmlInput_.value),!1),this.sourceBlock_&&we.Events.isEnabled()&&this.value_!==i&&we.Events.fire(new(we.Events.get("block_field_intermediate_change"))(this.sourceBlock_,this.name||null,i,this.value_))}onFinishEditing_(s){}getValueFromEditorText_(s){return s}bindInputEvents_(s){this.onKeyDownWrapper_=we.browserEvents.conditionalBind(s,"keydown",this,this.onHtmlInputKeyDown_),this.onKeyInputWrapper_=we.browserEvents.conditionalBind(s,"input",this,this.onHtmlInputChange_)}getDisplayText_(){const s=this.getSourceBlock();if(!s)throw new Error("The field has not yet been attached to its input. Call appendField to attach it.");let i=this.getText();if(!i)return we.Field.NBSP;const r=i.split(` -`);i="";const l=this.isOverflowedY_?this.maxLines_:r.length;for(let u=0;uthis.maxDisplayLength?d=`${d.substring(0,this.maxDisplayLength-4)}...`:this.isOverflowedY_&&u===l-1&&(d=`${d.substring(0,d.length-3)}...`),d=d.replace(/\s/g,we.Field.NBSP),i+=d,u!==l-1&&(i+=` -`)}return s.RTL&&(i+="‏"),i}doValueUpdate_(s){super.doValueUpdate_(s),this.value_!==null&&(this.isOverflowedY_=this.value_.split(` -`).length>this.maxLines_)}render_(){const s=this.getSourceBlock();if(!s)throw new Error("The field has not yet been attached to its input. Call appendField to attach it.");let i;const r=this.textGroup;for(;i=r.firstChild;)r.removeChild(i);const l=this.getConstants();if(!l)throw Error("Constants not found");const u=this.getDisplayText_().split(` -`);let d=0;for(let p=0;pd&&(d=v),p+=s.FIELD_TEXT_HEIGHT+(m>0?s.FIELD_BORDER_RECT_Y_PADDING:0)}if(this.isBeingEdited_){const m=String(this.value_).split(` -`),f=we.utils.dom.createSvgElement(we.utils.Svg.TEXT,{class:"blocklyText blocklyMultilineText"});for(let y=0;ythis.maxDisplayLength&&(m[y]=m[y].substring(0,this.maxDisplayLength)),f.textContent=m[y];const k=we.utils.dom.getFastTextWidth(f,r,l,u);k>d&&(d=k)}const v=this.htmlInput_,_=v.offsetWidth-v.clientWidth;d+=_}this.borderRect_&&(p+=s.FIELD_BORDER_RECT_Y_PADDING*2,d+=s.FIELD_BORDER_RECT_X_PADDING*2+1,this.borderRect_.setAttribute("width",`${d}`),this.borderRect_.setAttribute("height",`${p}`)),this.size_.width=d,this.size_.height=p,this.positionBorderRect_()}showInlineEditor_(s){const i=this.getSourceBlock();if(!i)throw new mg;we.WidgetDiv.show(this,i.RTL,this.widgetDispose_.bind(this),this.workspace_),this.htmlInput_=this.widgetCreate_(),this.isBeingEdited_=!0,this.valueWhenEditorWasOpened_=this.value_,s||(this.htmlInput_.focus({preventScroll:!0}),this.htmlInput_.select())}getEditorText_(s){return`${s}`}getScaledBBox(){let s,i,r;const l=this.getSourceBlock();if(!l)throw new mg;if(this.isFullBlockField()){const u=this.sourceBlock_.getHeightWidth(),d=l.workspace.scale;r=this.getAbsoluteXY_(),s=(u.width+1)*d,i=(u.height+1)*d,we.utils.userAgent.GECKO?(r.x+=1.5*d,r.y+=1.5*d):(r.x-=.5*d,r.y-=.5*d)}else{const u=this.borderRect_.getBoundingClientRect();r=we.utils.style.getPageOffset(this.borderRect_),s=u.width,i=u.height}return new we.utils.Rect(r.y,r.y+i,r.x,r.x+s)}resizeEditor_(){we.renderManagement.finishQueuedRenders().then(()=>{const s=this.getSourceBlock();if(!s)throw new mg;const i=we.WidgetDiv.getDiv(),r=this.getScaledBBox();i.style.width=`${r.right-r.left}px`,i.style.height=`${r.bottom-r.top}px`;const l=s.RTL?r.right-i.offsetWidth:r.left,u=r.top;i.style.left=`${l}px`,i.style.top=`${u}px`})}unbindInputEvents_(){this.onKeyDownWrapper_&&(we.browserEvents.unbind(this.onKeyDownWrapper_),this.onKeyDownWrapper_=null),this.onKeyInputWrapper_&&(we.browserEvents.unbind(this.onKeyInputWrapper_),this.onKeyInputWrapper_=null)}getClickTarget_(){return this.clickTarget_||this.getSvgRoot()}widgetDispose_(){this.isBeingEdited_=!1,this.isTextValid_=!0,this.forceRerender(),this.onFinishEditing_(this.value_),this.sourceBlock_&&we.Events.isEnabled()&&this.valueWhenEditorWasOpened_!==null&&this.valueWhenEditorWasOpened_!==this.value_&&(we.Events.fire(new(we.Events.get("change"))(this.sourceBlock_,"field",this.name||null,this.valueWhenEditorWasOpened_,this.value_)),this.valueWhenEditorWasOpened_=null),we.Events.setGroup(!1),this.unbindInputEvents_();const s=we.WidgetDiv.getDiv().style;s.width="auto",s.height="auto",s.fontSize="",s.transition="",s.boxShadow="",this.htmlInput_=null;const i=this.getClickTarget_();if(!i)throw new Error("A click target has not been set.");we.utils.dom.removeClass(i,"editing")}showEditor_(s,i){this.workspace_=this.sourceBlock_.workspace,!i&&this.workspace_.options.modalInputs&&(we.utils.userAgent.MOBILE||we.utils.userAgent.ANDROID||we.utils.userAgent.IPAD)?this.showPromptEditor_():this.showInlineEditor_(!!i),this.forceRerender()}widgetCreate_(){const s=we.WidgetDiv.getDiv(),i=this.workspace_.getScale(),r=this.getConstants();if(!r)throw Error("Constants not found");const l=document.createElement("textarea");l.className="blocklyHtmlInput blocklyHtmlTextAreaInput",l.setAttribute("spellcheck",String(this.spellcheck_));const u=`${r.FIELD_TEXT_FONTSIZE*i}pt`;s.style.fontSize=u,l.style.fontSize=u;const d=`${we.FieldTextInput.BORDERRADIUS*i}px`;l.style.borderRadius=d;const p=r.FIELD_BORDER_RECT_X_PADDING*i,m=r.FIELD_BORDER_RECT_Y_PADDING*i/2;l.style.padding=`${m}px ${p}px ${m}px ${p}px`;const f=r.FIELD_TEXT_HEIGHT+r.FIELD_BORDER_RECT_Y_PADDING;return l.style.lineHeight=`${f*i}px`,s.appendChild(l),l.value=l.defaultValue=this.getEditorText_(this.value_),l.setAttribute("data-untyped-default-value",String(this.value_)),l.setAttribute("data-old-value",""),we.utils.userAgent.GECKO?setTimeout(this.resizeEditor_.bind(this),0):this.resizeEditor_(),this.bindInputEvents_(l),l}setMaxLines(s){typeof s=="number"&&s>0&&s!==this.maxLines_&&(this.maxLines_=s,this.forceRerender())}getMaxLines(){return this.maxLines_}onHtmlInputKeyDown_(s){s.key!=="Enter"&&this.onHtmlInputKeyDownSuper_(s)}static fromJson(s){const i=we.utils.parsing.replaceMessageReferences(s.text);return new this(i,void 0,s)}}we.Css.register(` -.blocklyHtmlTextAreaInput { - font-family: monospace; - resize: none; - overflow: hidden; - height: 100%; - text-align: left; -} - -.blocklyHtmlTextAreaInputOverflowedY { - overflow-y: scroll; -} -`);const bT="text_multiline",eR={type:bT,message0:"%1 %2",args0:[{type:"field_image",src:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAARCAYAAADpPU2iAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAdhgAAHYYBXaITgQAAABh0RVh0U29mdHdhcmUAcGFpbnQubmV0IDQuMS42/U4J6AAAAP1JREFUOE+Vks0KQUEYhjmRIja4ABtZ2dm5A3t3Ia6AUm7CylYuQRaUhZSlLZJiQbFAyRnPN33y01HOW08z8873zpwzM4F3GWOCruvGIE4/rLaV+Nq1hVGMBqzhqlxgCys4wJA65xnogMHsQ5lujnYHTejBBCK2mE4abjCgMGhNxHgDFWjDSG07kdfVa2pZMf4ZyMAdWmpZMfYOsLiDMYMjlMB+K613QISRhTnITnsYg5yUd0DETmEoMlkFOeIT/A58iyK5E18BuTBfgYXfwNJv4P9/oEBerLylOnRhygmGdPpTTBZAPkde61lbQe4moWUvYUZYLfUNftIY4zwA5X2Z9AYnQrEAAAAASUVORK5CYII=",width:12,height:17,alt:"¶"},{type:"field_multilinetext",name:"TEXT",text:""}],output:"String",style:"text_blocks",helpUrl:"%{BKY_TEXT_TEXT_HELPURL}",tooltip:"%{BKY_TEXT_TEXT_TOOLTIP}",extensions:["parent_tooltip_when_inline"]};function tR(a,s){const i=s.multiline_quote_(a.getFieldValue("TEXT")),r=i.indexOf("+")!==-1?6.2:0;return[i,r]}const sR=window.Blockly.common.createBlockDefinitionsFromJsonArray([eR]);sR[bT];const Re=window.Blockly;class im extends Re.Field{picker=null;highlightedIndex=null;boundEvents=[];SERIALIZABLE=!0;CURSOR="default";isDirty_=!1;colours=["#ffffff","#cccccc","#c0c0c0","#999999","#666666","#333333","#000000","#ffcccc","#ff6666","#ff0000","#cc0000","#990000","#660000","#330000","#ffcc99","#ff9966","#ff9900","#ff6600","#cc6600","#993300","#663300","#ffff99","#ffff66","#ffcc66","#ffcc33","#cc9933","#996633","#663333","#ffffcc","#ffff33","#ffff00","#ffcc00","#999900","#666600","#333300","#99ff99","#66ff99","#33ff33","#33cc00","#009900","#006600","#003300","#99ffff","#33ffff","#66cccc","#00cccc","#339999","#336666","#003333","#ccffff","#66ffff","#33ccff","#3366ff","#3333ff","#000099","#000066","#ccccff","#9999ff","#6666cc","#6633ff","#6600cc","#333399","#330099","#ffccff","#ff99ff","#cc66cc","#cc33cc","#993399","#663366","#330033"];titles=[];columns=7;constructor(s,i,r){super(s),s!==Symbol("SKIP_SETUP")&&(r&&this.configure_(r),this.setValue(s),i&&this.setValidator(i))}configure_(s){super.configure_(s),s.colourOptions&&(this.colours=s.colourOptions),s.colourTitles&&(this.titles=s.colourTitles),s.columns&&(this.columns=s.columns)}initView(){const s=this.getConstants();if(!s)throw Error("Constants not found");this.size_=new Re.utils.Size(s.FIELD_COLOUR_DEFAULT_WIDTH,s.FIELD_COLOUR_DEFAULT_HEIGHT),this.createBorderRect_(),this.getBorderRect().style.fillOpacity="1",this.getBorderRect().setAttribute("stroke","#fff"),this.isFullBlockField()&&(this.clickTarget_=this.sourceBlock_.getSvgRoot())}isFullBlockField(){if(!this.getSourceBlock())throw new Re.UnattachedFieldError;const i=this.getConstants();return this.blockIsSimpleReporter()&&!!(i!=null&&i.FIELD_COLOUR_FULL_BLOCK)}blockIsSimpleReporter(){const s=this.getSourceBlock();if(!s)throw new Re.UnattachedFieldError;if(!s.outputConnection)return!1;for(const i of s.inputList)if(i.connection||i.fieldRow.length>1)return!1;return!0}applyColour(){const s=this.getSourceBlock();if(!s)throw new Re.UnattachedFieldError;if(!this.fieldGroup_)return;const i=this.borderRect_;if(!i)throw new Error("The border rect has not been initialized");this.isFullBlockField()?(i.style.display="none",s.pathObject.svgPath.setAttribute("fill",this.getValue()),s.pathObject.svgPath.setAttribute("stroke","#fff")):(i.style.display="block",i.style.fill=this.getValue())}getSize(){var s;return(s=this.getConstants())!=null&&s.FIELD_COLOUR_FULL_BLOCK&&(this.render_(),this.isDirty_=!1),super.getSize()}render_(){super.render_();const s=this.getSourceBlock();if(!s)throw new Re.UnattachedFieldError;s.applyColour()}updateSize_(s){const i=this.getConstants();if(!i)return;let r,l;this.isFullBlockField()?(r=(s??0)*2,l=i.FIELD_TEXT_HEIGHT):(r=i.FIELD_COLOUR_DEFAULT_WIDTH,l=i.FIELD_COLOUR_DEFAULT_HEIGHT),this.size_.height=l,this.size_.width=r,this.positionBorderRect_()}doClassValidation_(s){return typeof s!="string"?null:Re.utils.colour.parse(s)}getText(){let s=this.value_;return/^#(.)\1(.)\2(.)\3$/.test(s)&&(s=`#${s[1]}${s[3]}${s[5]}`),s}setColours(s,i){return this.colours=s,i&&(this.titles=i),this}setColumns(s){return this.columns=s,this}showEditor_(){if(this.dropdownCreate(),!this.picker)throw Error("Picker not found");Re.DropDownDiv.getContentDiv().appendChild(this.picker),Re.DropDownDiv.showPositionedByField(this,this.dropdownDispose.bind(this)),this.picker.focus({preventScroll:!0})}onClick(s){const i=s.target,r=i==null?void 0:i.getAttribute("data-colour");r!==null&&(this.setValue(r),Re.DropDownDiv.hideIfOwner(this))}onKeyDown(s){let i=!0,r;switch(s.key){case"ArrowUp":this.moveHighlightBy(0,-1);break;case"ArrowDown":this.moveHighlightBy(0,1);break;case"ArrowLeft":this.moveHighlightBy(-1,0);break;case"ArrowRight":this.moveHighlightBy(1,0);break;case"Enter":if(r=this.getHighlighted(),r){const l=r.getAttribute("data-colour");l!==null&&this.setValue(l)}Re.DropDownDiv.hideWithoutAnimation();break;default:i=!1}i&&s.stopPropagation()}moveHighlightBy(s,i){if(!this.highlightedIndex)return;const r=this.colours,l=this.columns;let u=this.highlightedIndex%l,d=Math.floor(this.highlightedIndex/l);u+=s,d+=i,s<0?u<0&&d>0?(u=l-1,d--):u<0&&(u=0):s>0?u>l-1&&dl-1&&u--:i<0?d<0&&(d=0):i>0&&d>Math.floor(r.length/l)-1&&(d=Math.floor(r.length/l)-1);const p=this.picker.childNodes[d].childNodes[u],m=d*l+u;this.setHighlightedCell(p,m)}onMouseMove(s){const i=s.target,r=i&&Number(i.getAttribute("data-index"));r!==null&&r!==this.highlightedIndex&&this.setHighlightedCell(i,r)}onMouseEnter(){var s;(s=this.picker)==null||s.focus({preventScroll:!0})}onMouseLeave(){var i;(i=this.picker)==null||i.blur();const s=this.getHighlighted();s&&Re.utils.dom.removeClass(s,"blocklyColourHighlighted")}getHighlighted(){var l;if(!this.highlightedIndex)return null;const s=this.highlightedIndex%this.columns,i=Math.floor(this.highlightedIndex/this.columns),r=(l=this.picker)==null?void 0:l.childNodes[i];return r?r.childNodes[s]:null}setHighlightedCell(s,i){const r=this.getHighlighted();r&&Re.utils.dom.removeClass(r,"blocklyColourHighlighted"),Re.utils.dom.addClass(s,"blocklyColourHighlighted"),this.highlightedIndex=i;const l=s.getAttribute("id");l&&this.picker&&Re.utils.aria.setState(this.picker,Re.utils.aria.State.ACTIVEDESCENDANT,l)}dropdownCreate(){const s=this.columns,i=this.colours,r=this.getValue(),l=document.createElement("table");l.className="blocklyColourTable",l.tabIndex=0,l.dir="ltr",Re.utils.aria.setRole(l,Re.utils.aria.Role.GRID),Re.utils.aria.setState(l,Re.utils.aria.State.EXPANDED,!0),Re.utils.aria.setState(l,Re.utils.aria.State.ROWCOUNT,Math.floor(i.length/s)),Re.utils.aria.setState(l,Re.utils.aria.State.COLCOUNT,s);let u=null;for(let d=0;dtr>td { - border: 0.5px solid #888; - box-sizing: border-box; - cursor: pointer; - display: inline-block; - height: 20px; - padding: 0; - width: 20px; -} - -.blocklyColourTable>tr>td.blocklyColourHighlighted { - border-color: #eee; - box-shadow: 2px 2px 7px 2px rgba(0, 0, 0, 0.3); - position: relative; -} - -.blocklyColourSelected, .blocklyColourSelected:hover { - border-color: #eee !important; - outline: 1px solid #333; - position: relative; -} -`);const vT="colour_picker",oR={type:vT,message0:"%1",args0:[{type:"field_colour",name:"COLOUR",colour:"#ff0000"}],output:"Colour",helpUrl:"%{BKY_COLOUR_PICKER_HELPURL}",style:"colour_blocks",tooltip:"%{BKY_COLOUR_PICKER_TOOLTIP}",extensions:["parent_tooltip_when_inline"]};function iR(a,s){return[s.quote_(a.getFieldValue("COLOUR")),0]}const nR=window.Blockly.common.createBlockDefinitionsFromJsonArray([oR]);nR[vT];const yT="colour_random",rR={type:yT,message0:"%{BKY_COLOUR_RANDOM_TITLE}",output:"Colour",helpUrl:"%{BKY_COLOUR_RANDOM_HELPURL}",style:"colour_blocks",tooltip:"%{BKY_COLOUR_RANDOM_TOOLTIP}"};function aR(a,s){return[`${s.provideFunction_("colourRandom",` -function ${s.FUNCTION_NAME_PLACEHOLDER_}() { - var num = Math.floor(Math.random() * 0x1000000); - return '#' + ('00000' + num.toString(16)).substr(-6); -} -`)}()`,2]}const lR=window.Blockly.common.createBlockDefinitionsFromJsonArray([rR]);lR[yT];const _T="colour_rgb",cR={type:_T,message0:"%{BKY_COLOUR_RGB_TITLE} %{BKY_COLOUR_RGB_RED} %1 %{BKY_COLOUR_RGB_GREEN} %2 %{BKY_COLOUR_RGB_BLUE} %3",args0:[{type:"input_value",name:"RED",check:"Number",align:"RIGHT"},{type:"input_value",name:"GREEN",check:"Number",align:"RIGHT"},{type:"input_value",name:"BLUE",check:"Number",align:"RIGHT"}],output:"Colour",helpUrl:"%{BKY_COLOUR_RGB_HELPURL}",style:"colour_blocks",tooltip:"%{BKY_COLOUR_RGB_TOOLTIP}"};function uR(a,s){const i=s.valueToCode(a,"RED",99)||0,r=s.valueToCode(a,"GREEN",99)||0,l=s.valueToCode(a,"BLUE",99)||0;return[`${s.provideFunction_("colourRgb",` -function ${s.FUNCTION_NAME_PLACEHOLDER_}(r, g, b) { - r = Math.max(Math.min(Number(r), 100), 0) * 2.55; - g = Math.max(Math.min(Number(g), 100), 0) * 2.55; - b = Math.max(Math.min(Number(b), 100), 0) * 2.55; - r = ('0' + (Math.round(r) || 0).toString(16)).slice(-2); - g = ('0' + (Math.round(g) || 0).toString(16)).slice(-2); - b = ('0' + (Math.round(b) || 0).toString(16)).slice(-2); - return '#' + r + g + b; -} -`)}(${i}, ${r}, ${l})`,2]}const dR=window.Blockly.common.createBlockDefinitionsFromJsonArray([cR]);dR[_T];const wT="colour_blend",hR={type:wT,message0:"%{BKY_COLOUR_BLEND_TITLE} %{BKY_COLOUR_BLEND_COLOUR1} %1 %{BKY_COLOUR_BLEND_COLOUR2} %2 %{BKY_COLOUR_BLEND_RATIO} %3",args0:[{type:"input_value",name:"COLOUR1",check:"Colour",align:"RIGHT"},{type:"input_value",name:"COLOUR2",check:"Colour",align:"RIGHT"},{type:"input_value",name:"RATIO",check:"Number",align:"RIGHT"}],output:"Colour",helpUrl:"%{BKY_COLOUR_BLEND_HELPURL}",style:"colour_blocks",tooltip:"%{BKY_COLOUR_BLEND_TOOLTIP}"};function pR(a,s){const i=s.valueToCode(a,"COLOUR1",99)||"'#000000'",r=s.valueToCode(a,"COLOUR2",99)||"'#000000'",l=s.valueToCode(a,"RATIO",99)||.5;return[`${s.provideFunction_("colourBlend",` -function ${s.FUNCTION_NAME_PLACEHOLDER_}(c1, c2, ratio) { - ratio = Math.max(Math.min(Number(ratio), 1), 0); - var r1 = parseInt(c1.substring(1, 3), 16); - var g1 = parseInt(c1.substring(3, 5), 16); - var b1 = parseInt(c1.substring(5, 7), 16); - var r2 = parseInt(c2.substring(1, 3), 16); - var g2 = parseInt(c2.substring(3, 5), 16); - var b2 = parseInt(c2.substring(5, 7), 16); - var r = Math.round(r1 * (1 - ratio) + r2 * ratio); - var g = Math.round(g1 * (1 - ratio) + g2 * ratio); - var b = Math.round(b1 * (1 - ratio) + b2 * ratio); - r = ('0' + (r || 0).toString(16)).slice(-2); - g = ('0' + (g || 0).toString(16)).slice(-2); - b = ('0' + (b || 0).toString(16)).slice(-2); - return '#' + r + g + b; -} -`)}(${i}, ${r}, ${l})`,2]}const gR=window.Blockly.common.createBlockDefinitionsFromJsonArray([hR]);gR[wT];function mR(){window.Blockly.FieldMultilineInput||(window.Blockly.fieldRegistry.register("field_multilinetext",Ic),window.Blockly.JavaScript.forBlock.text_multiline=tR,window.Blockly.FieldMultilineInput=Ic,Object.assign(window.Blockly.Blocks,window.Blockly.common.createBlockDefinitionsFromJsonArray([{type:"text_multiline",message0:"%1 %2",args0:[{type:"field_image",src:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAARCAYAAADpPU2iAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAdhgAAHYYBXaITgQAAABh0RVh0U29mdHdhcmUAcGFpbnQubmV0IDQuMS42/U4J6AAAAP1JREFUOE+Vks0KQUEYhjmRIja4ABtZ2dm5A3t3Ia6AUm7CylYuQRaUhZSlLZJiQbFAyRnPN33y01HOW08z8873zpwzM4F3GWOCruvGIE4/rLaV+Nq1hVGMBqzhqlxgCys4wJA65xnogMHsQ5lujnYHTejBBCK2mE4abjCgMGhNxHgDFWjDSG07kdfVa2pZMf4ZyMAdWmpZMfYOsLiDMYMjlMB+K613QISRhTnITnsYg5yUd0DETmEoMlkFOeIT/A58iyK5E18BuTBfgYXfwNJv4P9/oEBerLylOnRhygmGdPpTTBZAPkde61lbQe4moWUvYUZYLfUNftIY4zwA5X2Z9AYnQrEAAAAASUVORK5CYII=",width:12,height:17,alt:"¶"},{type:"field_multilinetext",name:"TEXT",text:""}],output:"String",style:"text_blocks",helpUrl:"%{BKY_TEXT_TEXT_HELPURL}",tooltip:"%{BKY_TEXT_TEXT_TOOLTIP}",extensions:["parent_tooltip_when_inline"]}]))),window.Blockly.FieldColour||(window.Blockly.fieldRegistry.register("field_colour",im),window.Blockly.JavaScript.forBlock.colour_picker=iR,window.Blockly.JavaScript.forBlock.colour_blend=pR,window.Blockly.JavaScript.forBlock.colour_random=aR,window.Blockly.JavaScript.forBlock.colour_rgb=uR,window.Blockly.FieldColour=im,Object.assign(window.Blockly.Blocks,window.Blockly.common.createBlockDefinitionsFromJsonArray([{type:"colour_picker",message0:"%1",args0:[{type:"field_colour",name:"COLOUR",colour:"#ff0000"}],output:"Colour",helpUrl:"%{BKY_COLOUR_PICKER_HELPURL}",style:"colour_blocks",tooltip:"%{BKY_COLOUR_PICKER_TOOLTIP}",extensions:["parent_tooltip_when_inline"]}])),Object.assign(window.Blockly.Blocks,window.Blockly.common.createBlockDefinitionsFromJsonArray([{type:"colour_random",message0:"%{BKY_COLOUR_RANDOM_TITLE}",output:"Colour",helpUrl:"%{BKY_COLOUR_RANDOM_HELPURL}",style:"colour_blocks",tooltip:"%{BKY_COLOUR_RANDOM_TOOLTIP}"}])),Object.assign(window.Blockly.Blocks,window.Blockly.common.createBlockDefinitionsFromJsonArray([{type:"colour_rgb",message0:"%{BKY_COLOUR_RGB_TITLE} %{BKY_COLOUR_RGB_RED} %1 %{BKY_COLOUR_RGB_GREEN} %2 %{BKY_COLOUR_RGB_BLUE} %3",args0:[{type:"input_value",name:"RED",check:"Number",align:"RIGHT"},{type:"input_value",name:"GREEN",check:"Number",align:"RIGHT"},{type:"input_value",name:"BLUE",check:"Number",align:"RIGHT"}],output:"Colour",helpUrl:"%{BKY_COLOUR_RGB_HELPURL}",style:"colour_blocks",tooltip:"%{BKY_COLOUR_RGB_TOOLTIP}"}])),Object.assign(window.Blockly.Blocks,window.Blockly.common.createBlockDefinitionsFromJsonArray([{type:"colour_blend",message0:"%{BKY_COLOUR_BLEND_TITLE} %{BKY_COLOUR_BLEND_COLOUR1} %1 %{BKY_COLOUR_BLEND_COLOUR2} %2 %{BKY_COLOUR_BLEND_RATIO} %3",args0:[{type:"input_value",name:"COLOUR1",check:"Colour",align:"RIGHT"},{type:"input_value",name:"COLOUR2",check:"Colour",align:"RIGHT"},{type:"input_value",name:"RATIO",check:"Number",align:"RIGHT"}],output:"Colour",helpUrl:"%{BKY_COLOUR_BLEND_HELPURL}",style:"colour_blocks",tooltip:"%{BKY_COLOUR_BLEND_TOOLTIP}"}])));const a=window.Blockly.JavaScript;a.forBlock&&Object.keys(a).forEach(s=>{typeof a[s]=="function"&&(a.forBlock[s]||(console.log(`Migrating Blockly.JavaScript.${s} to Blockly.JavaScript.forBlock.${s}`),a.forBlock[s]=a[s],delete a[s]))})}let rc=!1,ac=!1,fg=null,$g=null;const dw=[];function CT(a,s,i,r){var l;if(r=r||[],(a.tagName==="BLOCK"||a.tagName==="block")&&(i=a.id),a.tagName==="FIELD"||a.tagName==="field")for(let u=0;uCT(u,s,i,r)),r}class Fe extends Y.Component{blockly=null;blocklyWorkspace=null;originalCode;someSelected=null;changeTimer=null;someSelectedTime=0;ignoreChanges=!1;blinkBlock;onResizeBind;didUpdate=null;lastCommand="";lastSearch;static Blockly=window.Blockly;constructor(s){super(s),this.state={languageOwnLoaded:ac,languageBlocklyLoaded:rc,changed:!1,message:"",error:"",themeType:this.props.themeType,exportText:"",importText:!1,searchText:this.props.searchText||"",showInputPrompt:null},this.originalCode=s.code||"",this.someSelected=null,this.onResizeBind=this.onResize.bind(this),this.lastSearch=this.props.searchText||"",this.blinkBlock=null,mR(),Fe.Blockly.dialog.setPrompt(this.onShowNameDialog),this.loadLanguages()}onShowNameDialog=(s,i,r)=>{this.setState({showInputPrompt:{promptText:s,defaultText:i,callback:r,value:i}})};static loadJS(s,i,r){const l=document.createElement("script");try{l.src=s,l.onload=i,l.onerror=i,(r||window.document.body).appendChild(l)}catch(u){console.error(`Cannot load ${s}: ${u}`),i&&i()}}static loadScripts(s,i){if(!(s!=null&&s.length)){i&&i();return}const r=s.pop();r&&!dw.includes(r)?(dw.push(r),Fe.loadJS(`../../adapter/${r}/blockly.js`,()=>setTimeout(()=>Fe.loadScripts(s,i),0))):setTimeout(()=>Fe.loadScripts(s,i),0)}static loadCustomBlockly(s,i){var l;const r=[];for(const u in s)!Object.prototype.hasOwnProperty.call(s,u)||!s[u]||!u.match(/^system\.adapter\./)||s[u].type!=="adapter"||(l=s[u].common)!=null&&l.blockly&&(console.log(`Detected custom blockly: ${s[u].common.name}`),r.push(s[u].common.name));Fe.loadScripts(r,i)}static loadXMLDoc(s){let i;return window.DOMParser?i=r=>new window.DOMParser().parseFromString(r,"text/xml"):typeof window.ActiveXObject<"u"&&new window.ActiveXObject("Microsoft.XMLDOM")?i=r=>{const l=new window.ActiveXObject("Microsoft.XMLDOM");return l.async="false",l.loadXML(r),l}:i=()=>null,i(s)}searchBlocks(s){if(this.blocklyWorkspace){const i=Fe.Blockly.Xml.workspaceToDom(this.blocklyWorkspace),r=CT(i,s.toLowerCase());return console.log(`Search "${s}" found blocks: ${r.length?JSON.stringify(r):"none"}`),r}return[]}searchId(){const s=this.lastSearch?this.searchBlocks(this.lastSearch):null;s!=null&&s.length?(this.someSelected=s,this.someSelected.forEach(i=>{var r;return(r=this.blocklyWorkspace)==null?void 0:r.highlightBlock(i,!0)}),this.someSelectedTime=Date.now()):this.someSelected&&(this.someSelected.forEach(i=>{var r;return(r=this.blocklyWorkspace)==null?void 0:r.highlightBlock(i,!1)}),this.someSelected=null)}UNSAFE_componentWillReceiveProps(s){s.command&&this.lastCommand!==s.command&&(this.lastCommand=s.command,setTimeout(()=>this.lastCommand="",300),this.lastCommand==="check"?this.blocklyCheckBlocks((i,r)=>{i?(r&&Fe.blocklyBlinkBlock(r),this.setState({error:{text:b.I18n.t(i),title:b.I18n.t("Error was found")}}),this.blinkBlock=r):this.setState({message:b.I18n.t("Ok")})}):this.lastCommand==="export"?this.exportBlocks():this.lastCommand==="import"&&this.importBlocks()),s.searchText!==this.lastSearch&&(this.lastSearch=s.searchText,this.searchId()),this.state.themeType!==s.themeType&&this.setState({themeType:s.themeType},()=>this.updateBackground()),this.originalCode!==s.code&&(this.originalCode=s.code||"",this.loadCode(),this.searchId())}loadLanguages(){if(!rc){const s=window.document.createElement("script");s.setAttribute("type","text/javascript"),s.setAttribute("src",`google-blockly/msg/js/${b.I18n.getLanguage()}.js`),s.onload=()=>{rc=!0,this.setState({languageBlocklyLoaded:rc})},window.document.getElementsByTagName("head")[0].appendChild(s)}if(!ac){const s=window.document.createElement("script");s.setAttribute("type","text/javascript"),s.setAttribute("src",`google-blockly/own/msg/${b.I18n.getLanguage()}.js`),s.onload=()=>{ac=!0,this.setState({languageOwnLoaded:ac})},window.document.getElementsByTagName("head")[0].appendChild(s)}}onResize(){this.blocklyWorkspace&&Fe.Blockly.svgResize(this.blocklyWorkspace)}static jsCode2Blockly(s){s=s||"";const i=s.split(/[\r\n]+|\r|\n/g);let r="";for(let u=i.length-1;u>=0;u--)if(i[u].substring(0,2)==="//"){r=i[u].substring(2);break}if(r.substring(0,4)==="s.select(),i),setTimeout(()=>s.unselect(),i+150)}blocklyRemoveOrphanedShadows(){if(this.blocklyWorkspace){const s=this.blocklyWorkspace.getAllBlocks();let i;for(let r=0;i=s[r];r++)if(i.isShadow()){const l=i.getConnections_(!0);let u;for(let d=0;u=l[d];d++)if(!u.targetConnection){i.dispose();break}}}}blocklyCheckBlocks(s){let i;if(!this.blocklyWorkspace||this.blocklyWorkspace.getAllBlocks().length===0)return s&&s("no blocks found"),!1;let r=this.blocklyGetUnconnectedBlock();return r?i="not properly connected":(r=this.blocklyGetBlockWithWarning(),r&&(i="warning on this block")),r?(s?s(i,r):Fe.blocklyBlinkBlock(r),!1):(s(),!0)}blocklyGetUnconnectedBlock(){var r;const s=(r=this.blocklyWorkspace)==null?void 0:r.getAllBlocks();let i;if(s)for(let l=0;i=s[l];l++){const u=i.getConnections_(!0);let d;for(let p=0;d=u[p];p++)if(!d.sourceBlock_||(d.type===Fe.Blockly.INPUT_VALUE||d.type===Fe.Blockly.OUTPUT_VALUE)&&!d.targetConnection&&!d._optional)return i}return null}blocklyGetBlockWithWarning(){var r;const s=(r=this.blocklyWorkspace)==null?void 0:r.getAllBlocks();let i;if(s){for(let l=0;i=s[l];l++)if(i.warning)return i}return null}blocklyCode2JSCode(s){if(!this.blocklyWorkspace)return"";let i=Fe.Blockly.JavaScript.workspaceToCode(this.blocklyWorkspace);if(!s){i+=` -`;const r=Fe.Blockly.Xml.workspaceToDom(this.blocklyWorkspace),l=Fe.Blockly.Xml.domToText(r);i+=`//${btoa(encodeURIComponent(l))}`}return i}exportBlocks(){if(!this.blocklyWorkspace)return;let s;const i=Fe.Blockly.getSelected();if(i){const r=Fe.Blockly.Xml.blockToDom(i),l=i.getRelativeToSurfaceXY();r.setAttribute("x",(i.RTL?-l.x:l.x).toString()),r.setAttribute("y",l.y.toString()),s=Fe.Blockly.Xml.domToPrettyText(r)}else{const r=Fe.Blockly.Xml.workspaceToDom(this.blocklyWorkspace);s=Fe.Blockly.Xml.domToPrettyText(r)}this.setState({exportText:s})}importBlocks(){this.setState({importText:!0})}onImportBlocks(s){if(this.blocklyWorkspace&&(s=(s||"").trim(),s))try{s.startsWith("${s}`),s=s.replace(/[\n\r]/g,"").replace(/.*<\/variables>/g,""),window.scripts.loading=!0;const i=Fe.Blockly.utils.xml.textToDom(s);Fe.Blockly.Xml.appendDomToWorkspace(i,this.blocklyWorkspace),window.scripts.loading=!1,this.onBlocklyChanged()}catch(i){this.setState({error:{text:i.toString(),title:b.I18n.t("Import error")}})}}loadCode(){if(this.blocklyWorkspace){this.ignoreChanges=!0,this.blocklyWorkspace.clear();try{const s=Fe.jsCode2Blockly(this.originalCode)||'';window.scripts.loading=!0;const i=Fe.Blockly.utils.xml.textToDom(s);Fe.Blockly.Xml.domToWorkspace(i,this.blocklyWorkspace),window.scripts.loading=!1}catch(s){console.error(s),setTimeout(()=>this.setState({error:b.I18n.t("Cannot extract Blockly code!")}))}setTimeout(()=>this.ignoreChanges=!1,100)}}onBlocklyChanged(){this.blocklyRemoveOrphanedShadows(),this.setState({changed:!0}),this.onChange()}async componentDidUpdate(){if(!this.blockly||(this.didUpdate&&(clearTimeout(this.didUpdate),this.didUpdate=null),this.blocklyWorkspace))return;window.addEventListener("resize",this.onResizeBind,!1),fg=fg||await this.getToolbox(),$g=$g||Fe.Blockly.utils.xml.textToDom(fg),this.blocklyWorkspace=Fe.Blockly.inject(this.blockly,{renderer:"thrasos",theme:this.state.themeType==="dark"?uw:"classic",media:"google-blockly/media/",toolbox:$g,zoom:{controls:!0,wheel:!1,startScale:1,maxScale:3,minScale:.3,scaleSpeed:1.2,pinch:!0},move:{scrollbars:{horizontal:!0,vertical:!0},drag:!0,wheel:!0},trashcan:!0,grid:{spacing:25,length:1,snap:!0},sounds:!1}),window.scripts={blocklyWorkspace:this.blocklyWorkspace},this.blocklyWorkspace.registerToolboxCategoryCallback("PROCEDURE",window.Blockly.Procedures.flyoutCategoryNew),this.blocklyWorkspace.addChangeListener(i=>{var r;if(this.someSelected&&Date.now()-this.someSelectedTime>500){const l=(r=this.blocklyWorkspace)==null?void 0:r.getAllBlocks();this.someSelected=null,l==null||l.forEach(u=>u.removeSelect())}[Fe.Blockly.Events.UI,Fe.Blockly.Events.CREATE,Fe.Blockly.Events.VIEWPORT_CHANGE].includes(i.type)||this.ignoreChanges||(this.changeTimer&&clearTimeout(this.changeTimer),this.changeTimer=setTimeout(()=>{this.changeTimer=null,this.onBlocklyChanged()},200))}),this.loadCode(),this.onResize();const s=document.getElementsByClassName("blocklyToolboxDiv")[0];this.blockly.appendChild(s),this.updateBackground(),setTimeout(()=>this.searchId(),200)}updateBackground(){var s;this.state.themeType==="dark"?(s=this.blocklyWorkspace)==null||s.setTheme(uw):this.blocklyWorkspace&&(this.blocklyWorkspace.getThemeManager(),this.blocklyWorkspace.setTheme(Fe.Blockly.Themes.Classic))}componentWillUnmount(){this.blocklyWorkspace&&(this.blocklyWorkspace.dispose(),this.blocklyWorkspace=null,this.changeTimer&&clearTimeout(this.changeTimer),this.changeTimer=null,window.removeEventListener("resize",this.onResizeBind))}onChange(){this.originalCode=this.blocklyCode2JSCode(),this.props.onChange&&this.props.onChange(this.originalCode)}async getToolbox(s){const i=window.document.getElementById("toolbox");let r=i==null?void 0:i.outerHTML;if(!r)return s?(console.error("Cannot load blocks!"),""):new Promise(l=>{setTimeout(()=>l(this.getToolbox(!0)),500)});if(r=r.replace(/{(\w+)}/g,(l,u)=>window.MSG[u]),window.Blockly.CustomBlocks){let l="";const u=b.I18n.getLanguage();for(let d=0;d`;for(const f in m.blocks)Object.prototype.hasOwnProperty.call(m.blocks,f)&&(l+=m.blocks[f]);l+=""}r=r.replace("%%CUSTOM_BLOCKS%%",l)}return r}renderMessageDialog(){return this.state.message?g.jsx(b.Message,{text:typeof this.state.message=="object"?this.state.message.text:this.state.message,title:typeof this.state.message=="object"?this.state.message.title:"",onClose:()=>this.setState({message:""})},"dialogMessage"):null}renderErrorDialog(){return this.state.error?g.jsx(Zc,{text:typeof this.state.error=="object"?this.state.error.text.toString():this.state.error,title:typeof this.state.error=="object"?this.state.error.title:"",onClose:()=>{this.blinkBlock&&(Fe.blocklyBlinkBlock(this.blinkBlock),this.blinkBlock=null),this.setState({error:""})}},"dialogError"):null}renderExportDialog(){return this.state.exportText?g.jsx(Q0,{themeType:this.state.themeType,onClose:()=>this.setState({exportText:""}),text:this.state.exportText,scriptId:this.props.scriptId},"dialogExport"):null}renderImportDialog(){return this.state.importText?g.jsx(zm,{themeType:this.props.themeType,onClose:s=>{this.setState({importText:!1}),this.onImportBlocks(s)}},"dialogImport"):null}renderDialogPrompt(){return this.state.showInputPrompt?g.jsxs(Gt,{onClose:()=>{var i;const s=(i=this.state.showInputPrompt)==null?void 0:i.callback;s&&s(null),this.setState({showInputPrompt:null})},maxWidth:"sm",fullWidth:!0,open:!0,children:[g.jsx(as,{children:this.state.showInputPrompt.promptText}),g.jsx(Vt,{children:g.jsx(vo,{variant:"standard",fullWidth:!0,autoFocus:!0,value:this.state.showInputPrompt.value,onKeyUp:s=>{var i,r;if(s.key==="Enter"){const l=(i=this.state.showInputPrompt)==null?void 0:i.callback,u=(r=this.state.showInputPrompt)==null?void 0:r.value;l&&l(u===void 0?null:u),this.setState({showInputPrompt:null})}},onChange:s=>{var r,l;const i={...this.state.showInputPrompt};(r=this.state.showInputPrompt)!=null&&r.callback&&(i.callback=(l=this.state.showInputPrompt)==null?void 0:l.callback),i.value=s.target.value,this.setState({showInputPrompt:i})}})}),g.jsxs(Kt,{children:[g.jsx(De,{variant:"contained",disabled:!this.state.showInputPrompt.value,onClick:()=>{var r,l;const s=(r=this.state.showInputPrompt)==null?void 0:r.callback,i=(l=this.state.showInputPrompt)==null?void 0:l.value;s&&s(i===void 0?null:i),this.setState({showInputPrompt:null})},color:"primary",startIcon:g.jsx(zo,{}),children:b.I18n.t("Apply")}),g.jsx(De,{color:"grey",variant:"contained",onClick:()=>{var i;const s=(i=this.state.showInputPrompt)==null?void 0:i.callback;s&&s(null),this.setState({showInputPrompt:null})},startIcon:g.jsx(qs,{}),children:b.I18n.t("Close")})]})]},"inputDialog"):null}render(){return this.state.languageBlocklyLoaded&&this.state.languageOwnLoaded?(this.didUpdate=setTimeout(()=>{this.didUpdate=null,this.componentDidUpdate()},100),[g.jsx("div",{ref:s=>this.blockly=s,style:{width:"100%",height:"100%",position:"relative"}},"blocklyDOM"),this.renderDialogPrompt(),this.renderMessageDialog(),this.renderErrorDialog(),this.renderExportDialog(),this.renderImportDialog()]):null}}const fR=Object.freeze(Object.defineProperty({__proto__:null,default:Fe},Symbol.toStringTag,{value:"Module"})),$R="_nameCard_15el3_28",bR="_iconThemCard_15el3_40",vR="_iconThemCardSelectable_15el3_49",yR="_iconHelp_15el3_53",_R="_blockName_15el3_64",wR="_controlMenuTop_15el3_123",CR="_debugInfo_15el3_132",TR="_tagCard_15el3_142",kR="_displayFlex_15el3_161",SR="_blockMarginTop_15el3_166",ER="_nameBlock_15el3_167",IR="_frontText_15el3_171",xR="_backText_15el3_177",DR="_iconTag_15el3_181",AR="_displayItalic_15el3_191",le={nameCard:$R,iconThemCard:bR,iconThemCardSelectable:vR,iconHelp:yR,blockName:_R,controlMenuTop:wR,debugInfo:CR,tagCard:TR,displayFlex:kR,blockMarginTop:SR,nameBlock:ER,frontText:IR,backText:xR,iconTag:DR,displayItalic:AR},RR="_root_1dr6a_1",OR="_square_1dr6a_11",MR="_icon_1dr6a_16",bg={root:RR,square:OR,icon:MR},Ur=({fullWidth:a,size:s,onClick:i,style:r,className:l,value:u,square:d,icon:p})=>g.jsx(De,{variant:"outlined",color:"primary",onClick:i,fullWidth:a,style:r,className:b.Utils.clsx(bg.root,l,d?bg.square:""),size:s||"medium",children:p?g.jsx(b.Icon,{className:bg.icon,src:p}):u}),NR="_root_1ucda_1",LR={root:NR},PR=({size:a,value:s,title:i,onChange:r,className:l,customValue:u,disabled:d})=>{const[p,m]=vt(!1);return g.jsxs(g.Fragment,{children:[g.jsx(bc,{disabled:d,checked:!!(u?s:p),className:b.Utils.clsx(LR.root,l),onChange:f=>{u&&m(f.target.checked),r&&r(f.target.checked)},size:a||"medium"}),i||null]})},TT=am(PR),BR="_root_19roy_1",hw={root:BR},bi=a=>{const[s,i]=vt(""),{value:r,type:l,error:u,className:d,icon:p,label:m,style:f,onChange:v,fullWidth:_,autoComplete:y,customValue:k,autoFocus:C,rows:w,size:E,variant:R,multiline:D,disabled:A}=Object.assign({value:"",type:"text",error:"",className:null,table:!1,native:{},variant:"standard",size:"medium",component:null,styleComponentBlock:null,fullWidth:!1,autoComplete:"",customValue:!1,autoFocus:!1,rows:1},a);return g.jsx(vo,{error:!!u,autoFocus:C,fullWidth:_,label:m,disabled:A,variant:R,multiline:D,rows:w,value:k?r:s,type:l,helperText:u,style:f,className:b.Utils.clsx(hw.root,d),autoComplete:y,onChange:J=>{!k&&i(J.target.value),v&&v(J.target.value)},slotProps:{input:{endAdornment:p?g.jsx(xw,{position:"end",children:g.jsx(b.Icon,{className:hw.icon,src:p})}):null}},margin:"normal",size:E})},jR={formControl:{m:"10px 0","& .MuiFormControl-marginNormal":{mt:0,mb:0},"& > *":{color:"#2d0440 !important"},"& .MuiSelect-icon":{color:"#81688c"},"& label.Mui-focused":{color:"#81688c"},"& .MuiInput-underline:after":{borderBottomColor:"#510573"},"& .MuiInput-underline:before":{borderBottomColor:"#81688c"},"& .MuiInput-underline:hover:before":{borderBottomColor:"#81688c"}}},FR=({multiple:a,value:s,customValue:i,socket:r,title:l,attr:u,adapter:d,style:p,onChange:m,onInstanceHide:f})=>{const[v,_]=vt(s||"test1"),[y,k]=vt([]);return Mt(()=>{r==null||r.getAdapterInstances(d).then(C=>{const w=C.map(E=>({value:E._id.replace("system.adapter.",""),title:E._id.replace("system.adapter.","")}));w.length===1?f(w[0].value):w.unshift({value:d,title:b.I18n.t("All")}),k(w)})},[r,d,f]),g.jsxs(_i,{sx:jR.formControl,fullWidth:!0,style:p,children:[g.jsx(wi,{variant:"standard",value:(i?s:v)||"_",fullWidth:!0,multiple:a,renderValue:C=>a&&Array.isArray(C)?C.join(", "):C,onChange:C=>{!i&&_(C.target.value),m(C.target.value)},input:u?g.jsx(Dn,{name:u,id:`${u}-helper`}):g.jsx(Dn,{name:u}),children:y.map(C=>g.jsx(Ge,{style:{placeContent:"space-between"},value:C.value||"_",children:b.I18n.t(C.title)},`key-${C.value}`))}),l?g.jsx(Aw,{children:b.I18n.t(l)}):null]})},zR="_modalWrapper_587ci_33",UR="_modalDialog_587ci_40",pw={modalWrapper:zR,modalDialog:UR},nm=({onClose:a,children:s,titleButtonApply:i,titleButtonClose:r,onApply:l,className:u,textInput:d,defaultValue:p,disabled:m})=>{const[f,v]=vt(p||""),[_]=vt(p||"");return g.jsxs(Gt,{open:!0,maxWidth:"md",disableEscapeKeyDown:!1,onClose:a,classes:{paper:pw.modalDialog},className:pw.modalWrapper,children:[g.jsxs(Vt,{children:[d&&g.jsx(bi,{className:u,autoComplete:"off",fullWidth:!0,variant:"outlined",size:"medium",rows:10,multiline:!0,value:f,onChange:v,customValue:!0}),!d&&s]}),g.jsxs(Kt,{children:[g.jsx(De,{disabled:m===void 0?_===f:m,onClick:()=>l(d?f:null),variant:"contained",color:"primary",children:b.I18n.t(i||"Ok")}),g.jsx(De,{color:"grey",onClick:a,variant:"contained",children:b.I18n.t(r||"Cancel")})]})]})},HR="_root_15mo1_1",WR={root:HR},GR=({multiple:a,value:s,customValue:i,title:r,attr:l,options:u,style:d,onChange:p,className:m,doNotTranslate:f,doNotTranslate2:v})=>{const[_,y]=vt(s===void 0?u[0].value:s),k=i?s:_,C=k===""||k===null||k===void 0?"_":k;return g.jsxs(_i,{variant:"standard",className:b.Utils.clsx(WR.root,m),fullWidth:!0,style:d,children:[g.jsxs(wi,{variant:"standard",value:C,fullWidth:!0,multiple:a,renderValue:w=>{if(a&&Array.isArray(w)){w.sort();let R=w.indexOf("0");R!==-1&&(w.splice(R,1),w.push("0")),R=w.indexOf("_"),R!==-1&&(w.splice(R,1),w.unshift("_"));const D=u.find(J=>J.only);return D&&w.includes(D.value)?D.titleShort?f?D.titleShort:b.I18n.t(D.titleShort):f?D.title:b.I18n.t(D.title):w.map(J=>u.find(ie=>ie.value===J||J==="_"&&ie.value==="")||J).map(J=>typeof J=="object"?J.titleShort?f?J.titleShort:b.I18n.t(J.titleShort):f?J.title:b.I18n.t(J.title):f?J:b.I18n.t(J)).join(", ")}const E=u?u.find(R=>R.value===w||w==="_"&&R.value===""):null;return E!=null&&E.title?f?E==null?void 0:E.title:b.I18n.t(E==null?void 0:E.title):w},onChange:w=>{if(i||y(w.target.value),a){const E=w.target.value,R=u.find(D=>D.only);if(R){const D=R.value;if(E.length===u.length-1&&E.includes(D))return p(E.filter(A=>A!==D),l);if(E.includes(D))return p(u.map(A=>A.value),l)}}p(w.target.value,l)},input:l?g.jsx(Dn,{name:l,id:`${l}-helper`}):g.jsx(Dn,{name:l}),children:[!a&&(u==null?void 0:u.map(w=>g.jsxs(Ge,{style:{placeContent:"space-between"},value:w.value===""||w.value===null||w.value===void 0?"_":w.value,children:[f?w.title:b.I18n.t(w.title),w.title2&&g.jsx("div",{children:v?w.title2:b.I18n.t(w.title2)})]},`key-${w.value}`))),a&&(u==null?void 0:u.map(w=>g.jsxs(Ge,{style:{placeContent:"space-between"},value:w.value||"_",children:[f?w.title:b.I18n.t(w.title)," ",g.jsx(TT,{customValue:!0,value:s==null?void 0:s.includes(w.value)})]},`key-${w.value}`)))]}),r?g.jsx(Aw,{children:b.I18n.t(r)}):null]})},VR="_root_1gt4d_1",KR="_mark_1gt4d_27",gw={root:VR,mark:KR},YR=({size:a,value:s,style:i,onChange:r,className:l,customValue:u,min:d,max:p,step:m,unit:f})=>{const[v,_]=vt(0);d=d!==void 0?d:0,p=p!==void 0?p:0,m=m!==void 0?m:(p-d)/100;const y=[{value:d,label:d+(f||"")},{value:p,label:p+(f||"")}];return g.jsx(Kk,{defaultValue:u?s:v,"aria-labelledby":"discrete-slider",valueLabelDisplay:"auto",classes:{mark:gw.mark},marks:y,step:m,min:d,max:p,value:u?s:v,style:i,className:b.Utils.clsx(gw.root,l),onChange:(k,C)=>{Array.isArray(C)?(!u&&_(C[0]),r(C[0])):(!u&&_(C),r(C))},size:a||"medium"})},JR="_root_rzul6_1",qR={root:JR},XR=({label:a,size:s,value:i,style:r,onChange:l,className:u,customValue:d})=>{const[p,m]=vt(!1);return g.jsx(Ag,{className:qR.root,control:g.jsx(Rw,{checked:d?i:p,style:r,className:u,onChange:f=>{d||m(f.target.checked),l(f.target.checked)},size:s||"medium"}),label:a??"all"})},ZR=am(XR),QR="_root_135pm_1",eO={root:QR},tO=({value:a,style:s,onChange:i,className:r})=>g.jsx(vo,{variant:"standard",id:"time",type:"time",onChange:l=>i(l.currentTarget.value),value:a,className:b.Utils.clsx(eO.root,r),fullWidth:!0,style:s,slotProps:{htmlInput:{step:300},inputLabel:{shrink:!0}}}),sO="_root_135pm_1",lc={root:sO},vg=[31,29,31,30,31,30,31,31,30,31,30,31],oO=({value:a,onChange:s,className:i,style:r})=>{const[l,u]=(a||"01.01").toString().split(".");let d=parseInt(u,10)||0,p=parseInt(l,10)||0;p>12?p=12:p<0&&(p=0),d>vg[p]?d=vg[p]:d<0&&(d=0);const m=[];for(let f=0;fs(`${f.target.value.toString().padStart(2,"0")}.${d.toString().padStart(2,"0")}`),value:p,children:[g.jsx(Ge,{style:{placeContent:"space-between"},value:0,children:b.I18n.t("Any month")},0),g.jsx(Ge,{style:{placeContent:"space-between"},value:1,children:b.I18n.t("January")},1),g.jsx(Ge,{style:{placeContent:"space-between"},value:2,children:b.I18n.t("February")},2),g.jsx(Ge,{style:{placeContent:"space-between"},value:3,children:b.I18n.t("March")},3),g.jsx(Ge,{style:{placeContent:"space-between"},value:4,children:b.I18n.t("April")},4),g.jsx(Ge,{style:{placeContent:"space-between"},value:5,children:b.I18n.t("May")},5),g.jsx(Ge,{style:{placeContent:"space-between"},value:6,children:b.I18n.t("June")},6),g.jsx(Ge,{style:{placeContent:"space-between"},value:7,children:b.I18n.t("July")},7),g.jsx(Ge,{style:{placeContent:"space-between"},value:8,children:b.I18n.t("August")},8),g.jsx(Ge,{style:{placeContent:"space-between"},value:9,children:b.I18n.t("September")},9),g.jsx(Ge,{style:{placeContent:"space-between"},value:10,children:b.I18n.t("October")},10),g.jsx(Ge,{style:{placeContent:"space-between"},value:11,children:b.I18n.t("November")},11),g.jsx(Ge,{style:{placeContent:"space-between"},value:12,children:b.I18n.t("December")},12)]})}),g.jsx(_i,{variant:"standard",className:b.Utils.clsx(lc.root,i),style:r,children:g.jsxs(wi,{variant:"standard",className:b.Utils.clsx(lc.root,i),margin:"dense",label:b.I18n.t("Date"),onChange:f=>s(`${p.toString().padStart(2,"0")}.${f.target.value.toString().padStart(2,"0")}`),value:d,children:[g.jsx(Ge,{style:{placeContent:"space-between"},value:0,children:b.I18n.t("Any")},"A"),m.map(f=>g.jsx(Ge,{style:{placeContent:"space-between"},value:f,children:f},f))]})})]})},yg={},iO={Shuffle:mx,Apps:ox,Functions:cx,Language:yS,AddBox:sx,Pause:gc,Subject:$x,PlayForWork:px,Brightness3:ix,HelpOutline:dC,Storage:fx,AccessTime:tx,PlayArrow:Fg,FlashOn:ax};function mw({iconName:a,className:s,adapter:i,socket:r,onClick:l,style:u}){const[d,p]=vt("");if(Mt(()=>{i&&r&&(yg[i]instanceof Promise||(yg[i]=r.getObject(`system.adapter.${i}`)),yg[i].then(f=>{var v;return((v=f==null?void 0:f.common)==null?void 0:v.icon)&&p(`../../adapter/${i}/${f.common.icon}`)}))},[i,r]),i)return g.jsx("img",{onClick:f=>l&&l(f),src:d||"",className:s,style:u,alt:""});const m=a&&iO[a]||_S;return g.jsx(m,{className:s,style:u,onClick:f=>l&&l(f)})}let _g;function nO(a){return _g=_g||b.I18n.getLanguage(),a&&typeof a=="object"?a[_g]||a.en:a||""}function xn(a){return a===null?"null":a===void 0?"undefined":Array.isArray(a)?a.join(", "):typeof a=="object"?JSON.stringify(a):a.toString()}class Xe extends Ew{debugHideTimeout=null;lastObjectIdChange=0;enableSimulationProcessing=!1;lastDebugMessage=0;debugMessageTimeout=null;static getStaticData(){return{acceptedBy:"actions",name:"Not found",id:"ActionEmpty",icon:"Shuffle"}}static compile(s,i){return""}constructor(s,i){super(s),i||={};const r=s.settings||{tagCard:i.tagCardArray?typeof i.tagCardArray[0]!="string"?i.tagCardArray[0].title:i.tagCardArray[0]:""};!r.tagCard&&i.tagCardArray&&(r.tagCard=typeof i.tagCardArray[0]!="string"?i.tagCardArray[0].title:i.tagCardArray[0]),this.state={inputs:i.inputs||s.inputs||[],name:i.name||s.name||"",icon:i.icon||s.icon||"",adapter:i.adapter||s.adapter||"",helpDialog:i.helpDialog||s.helpDialog||"",tagCardArray:i.tagCardArray||[],openTagMenu:!1,openModal:!1,iconTag:!1,error:"",helpText:"",instanceSelectionOptions:[],instanceSelectionDef:"",hideAttributes:[],settings:r,debugMessage:null,enableSimulation:this.props.enableSimulation}}componentWillUnmount(){this.debugMessageTimeout&&(clearTimeout(this.debugMessageTimeout),this.debugMessageTimeout=null),this.debugHideTimeout&&(clearTimeout(this.debugHideTimeout),this.debugHideTimeout=null)}onTagChange(s,i,r,l,u){let d=!1;const p=JSON.parse(JSON.stringify(this.state.settings));this.state.inputs.forEach(m=>{const f=m.attr,v=m.defaultValue;f&&v!==void 0&&p[f]===void 0&&(d=!0,p[f]=v)}),d?(this.setState({settings:p},()=>i==null?void 0:i()),this.props.onChange(p)):i&&i()}onUpdate(){}onValueChanged(s,i){}renderText(s,i,r){const{className:l}=this.props,{attr:u,frontText:d,backText:p,nameBlock:m,name:f,doNotTranslate:v,doNotTranslateBack:_}=s;return g.jsxs(Sg,{children:[g.jsxs("div",{className:b.Utils.clsx(le.displayFlex,le.blockMarginTop),children:[d&&g.jsx("div",{className:le.frontText,children:v?d:b.I18n.t(d)}),g.jsx(bi,{className:l,autoComplete:"off",label:nO(f),variant:"outlined",size:"small",fullWidth:!0,value:i,onChange:r,customValue:!0}),p&&g.jsx("div",{className:le.backText,children:_?p:b.I18n.t(p)})]}),m&&g.jsx("div",{className:le.nameBlock,children:b.I18n.t(m)})]},u)}renderSwitch(s,i,r){const{className:l}=this.props,{attr:u,frontText:d,backText:p,nameBlock:m,doNotTranslate:f,doNotTranslateBack:v}=s;return g.jsxs("div",{children:[g.jsxs("div",{className:b.Utils.clsx(le.displayFlex,le.blockMarginTop),children:[d&&g.jsx("div",{className:le.frontText,children:f?d:b.I18n.t(d)}),g.jsx(ZR,{className:l,label:"",customValue:!0,value:i,onChange:r}),p&&g.jsx("div",{className:le.backText,children:v?p:b.I18n.t(p)})]}),m&&g.jsx("div",{className:le.nameBlock,children:b.I18n.t(m)})]},u)}renderNameText({attr:s,signature:i,doNotTranslate:r,defaultValue:l},u){return g.jsx("div",{className:b.Utils.clsx(i?le.displayItalic:le.displayFlex,le.blockMarginTop),children:u?r?u:b.I18n.t(u):r?l:b.I18n.t(l)},s)}renderNumber(s,i,r){const{className:l}=this.props,{settings:u}=this.state,{attr:d,backText:p,frontText:m,openCheckbox:f,doNotTranslate:v,doNotTranslateBack:_}=s;let y=!0;return f&&(y=typeof u.offset=="boolean"?u.offset:!0),y?g.jsxs("div",{className:b.Utils.clsx(le.displayFlex,le.blockMarginTop),children:[m&&g.jsx("div",{className:le.frontText,children:v?m:b.I18n.t(m)}),g.jsx(bi,{className:b.Utils.clsx(l,s.className),fullWidth:!0,autoComplete:"off",label:s.noHelperText?"":"number",variant:"outlined",size:"small",type:"number",value:i,onChange:r,customValue:!0}),p&&g.jsx("div",{className:le.backText,children:_?p:b.I18n.t(p)})]},d):null}renderColor(s,i,r){const{className:l}=this.props,{attr:u,backText:d,frontText:p,doNotTranslate:m,doNotTranslateBack:f}=s;return g.jsxs("div",{className:b.Utils.clsx(le.displayFlex,le.blockMarginTop),children:[p&&g.jsx("div",{className:le.frontText,children:m?p:b.I18n.t(p)}),g.jsx(bi,{className:l,autoComplete:"off",fullWidth:!0,variant:"outlined",size:"small",type:"color",value:i,onChange:r}),d&&g.jsx("div",{className:le.backText,children:f?d:b.I18n.t(d)})]},u)}renderCheckbox(s,i,r){const{className:l}=this.props,{settings:u}=this.state,{attr:d,backText:p,frontText:m,defaultValue:f,doNotTranslate:v,doNotTranslateBack:_}=s;return g.jsxs("div",{className:le.displayFlex,children:[m&&g.jsx("div",{className:le.frontText,children:v?m:b.I18n.t(m)}),g.jsx(TT,{className:l,size:"small",value:typeof u[d]=="boolean"?!!u[d]:!!f,customValue:!0,onChange:r}),p&&g.jsx("div",{onClick:()=>r(typeof u[d]=="boolean"?!u[d]:!f),className:le.backText,children:_?p:b.I18n.t(p)})]},d)}renderSlider(s,i,r){const{className:l}=this.props,{attr:u,frontText:d,backText:p,nameBlock:m,min:f,max:v,step:_,unit:y,doNotTranslate:k,doNotTranslateBack:C}=s;return g.jsxs("div",{children:[g.jsxs("div",{className:le.displayFlex,style:{marginRight:20},children:[d&&g.jsx("div",{className:le.frontText,children:k?d:b.I18n.t(d)}),g.jsx(YR,{customValue:!0,min:f,max:v,step:_,unit:y,className:l,autoComplete:"off",label:"number",variant:"outlined",size:"small",value:i,onChange:w=>{console.log(w),r(w)}}),p&&g.jsx("div",{style:{marginLeft:20},className:le.backText,children:C?p:b.I18n.t(p)})]}),m&&g.jsx("div",{className:le.nameBlock,children:b.I18n.t(m)})]},u)}renderButton(s,i,r){const{className:l}=this.props,{attr:u,frontText:d,backText:p,doNotTranslate:m,doNotTranslateBack:f}=s;return g.jsxs("div",{className:b.Utils.clsx(le.displayFlex,le.blockMarginTop),children:[d&&g.jsx("div",{className:le.frontText,children:m?d:b.I18n.t(d)}),g.jsx(Ur,{fullWidth:!0,value:i.toString(),className:l,onClick:()=>r(i)}),p&&g.jsx("div",{className:le.backText,children:f?p:b.I18n.t(p)})]},u)}async findIcon(s){var i;if(!s)return null;if((i=s.common)!=null&&i.icon)return b.getSelectIdIcon(s,"../..");if(s.type==="state"||s.type==="channel"){const r=s._id.split(".");r.pop();const l=r.join(".");try{const u=await this.props.socket.getObject(l);return await this.findIcon(u)}catch{return null}}return null}renderObjectID(s,i,r){const{attr:l,openCheckbox:u,checkReadOnly:d}=s,{settings:p}=this.state,m=this.state[`showSelectId${l}`],{className:f,socket:v,style:_}=this.props;let y=!0;u&&(y=typeof p.offset=="boolean"?p.offset:!0);const k=p[l],C=k?this.state[k]:void 0;return k&&!C&&C!==!1&&setTimeout(async w=>{var A;const E=await v.getObject(i),R=await this.findIcon(E),D={[w]:E||!1,[`${w}___icon`]:R,error:d&&this.lastObjectIdChange&&Date.now()-this.lastObjectIdChange<1e3&&((A=E==null?void 0:E.common)==null?void 0:A.write)===!1?b.I18n.t("Read only ID selected: %s",p[w]):""};this.setState(D)},0,k),y?g.jsxs("div",{className:le.blockMarginTop,children:[g.jsxs("div",{className:le.displayFlex,children:[s.title?g.jsx("div",{children:b.I18n.t(s.title)}):null,g.jsx(bi,{className:f,style:_,autoComplete:"off",fullWidth:!0,disabled:!0,variant:"outlined",size:"small",value:i,customValue:!0}),g.jsx(Ur,{icon:this.state[`${k}___icon`],square:!0,style:{..._||void 0,marginLeft:7},value:"...",className:f,onClick:()=>{const w={};w[`showSelectId${l}`]=!0,this.setState(w)}})]}),C?g.jsx("div",{className:b.Utils.clsx(le.nameBlock,le.displayItalic),children:b.Utils.getObjectNameFromObj(C,b.I18n.getLanguage())}):null,m?g.jsx(b.DialogSelectID,{theme:this.props.theme,imagePrefix:"../..",dialogName:"javascript",themeType:b.Utils.getThemeName(),socket:v,selected:i,onClose:()=>{const w={};w[`showSelectId${l}`]=!1,this.setState(w)},onOk:(w,E)=>{const R={};R[`showSelectId${l}`]=!1;const D=Array.isArray(w)?w[0]:w;this.setState(R,async()=>{var J,ie,se,me,z,Oe,Ne,Ze,ae,ce;const A=D?await v.getObject(D):void 0;this.lastObjectIdChange=Date.now(),r({[l]:w,[`${l}Role`]:(J=A==null?void 0:A.common)==null?void 0:J.role,[`${l}Type`]:(ie=A==null?void 0:A.common)==null?void 0:ie.type,[`${l}Unit`]:(se=A==null?void 0:A.common)==null?void 0:se.unit,[`${l}States`]:(me=A==null?void 0:A.common)==null?void 0:me.states,[`${l}Min`]:(z=A==null?void 0:A.common)==null?void 0:z.min,[`${l}Max`]:(Oe=A==null?void 0:A.common)==null?void 0:Oe.max,[`${l}Step`]:(Ne=A==null?void 0:A.common)==null?void 0:Ne.step,[`${l}Def`]:(Ze=A==null?void 0:A.common)==null?void 0:Ze.def,[`${l}Write`]:(ae=A==null?void 0:A.common)==null?void 0:ae.write,[`${l}Read`]:(ce=A==null?void 0:A.common)==null?void 0:ce.read},()=>this.props.setOnUpdate&&this.props.setOnUpdate(!0))})}}):null]},l):null}renderIconTag(){return g.jsx("div",{className:le.iconTag,onClick:s=>{this.state.settings.tagCard&&(this.state.tagCardArray.length<3?this.onChangeTag():this.setState({openTagMenu:s.currentTarget}))},children:this.state.settings.tagCard})}renderTime(s,i,r){const{attr:l,backText:u,frontText:d,doNotTranslate:p,doNotTranslateBack:m}=s;return g.jsxs("div",{className:le.displayFlex,style:{whiteSpace:"nowrap"},children:[d&&g.jsx("div",{className:le.frontText,children:p?d:b.I18n.t(d)}),g.jsx(tO,{value:i,onChange:r}),u&&g.jsx("div",{className:le.backText,children:m?u:b.I18n.t(u)})]},l)}renderSelect(s,i,r){const{className:l,style:u}=this.props,{name:d,options:p,frontText:m,backText:f,attr:v,multiple:_,doNotTranslate:y,doNotTranslate2:k,doNotTranslateBack:C}=s;return g.jsxs("div",{className:b.Utils.clsx(le.displayFlex,le.blockMarginTop),style:{whiteSpace:"nowrap"},children:[m&&g.jsx("div",{className:le.frontText,children:b.I18n.t(m)}),g.jsx(GR,{attr:v,doNotTranslate:y,doNotTranslate2:k,title:d,className:l,style:u,options:p,value:i,onChange:r,multiple:_,customValue:!0}),f&&g.jsx("div",{className:le.backText,children:C?f:b.I18n.t(f)})]},v)}renderInstance(s,i,r){const{socket:l}=this.props,{name:u,frontText:d,backText:p,attr:m,adapter:f,doNotTranslate:v,doNotTranslateBack:_}=s;return this.state.hideAttributes.includes(m)?null:g.jsxs("div",{className:b.Utils.clsx(le.displayFlex,le.blockMarginTop),style:{whiteSpace:"nowrap"},children:[d&&g.jsx("div",{className:le.frontText,children:v?d:b.I18n.t(d)}),g.jsx(FR,{attr:m,socket:l,adapter:f,title:u,value:i,onChange:y=>{r(Array.isArray(y)?y[0]:y)},customValue:!0,onInstanceHide:y=>this.setState({hideAttributes:[...this.state.hideAttributes,m]},()=>r(y))}),p&&g.jsx("div",{className:le.backText,children:_?p:b.I18n.t(p)})]},m)}renderDialog(s){const{onShowDialog:i,frontText:r,backText:l,attr:u,icon:d,doNotTranslate:p,doNotTranslateBack:m}=s;return g.jsxs("div",{className:b.Utils.clsx(le.displayFlex,le.blockMarginTop),style:{whiteSpace:"nowrap"},children:[r&&g.jsx("div",{className:le.frontText,children:p?r:b.I18n.t(r)}),g.jsx(mw,{iconName:d,className:b.Utils.clsx(le.iconDialog),onClick:()=>i&&i()}),l&&g.jsx("div",{className:le.backText,children:m?l:b.I18n.t(l)})]},u)}renderModalInput(s,i,r){const{openModal:l}=this.state,{className:u}=this.props,{attr:d,nameBlock:p,frontText:m,backText:f,noTextEdit:v,doNotTranslate:_,doNotTranslateBack:y}=s;return g.jsxs("div",{children:[g.jsxs("div",{className:b.Utils.clsx(le.displayFlex,le.blockMarginTop),children:[m&&g.jsx("div",{className:le.frontText,children:_?m:b.I18n.t(m)}),g.jsx(bi,{disabled:!!v,className:u,autoComplete:"off",fullWidth:!0,variant:"outlined",size:"small",value:i,onChange:r,customValue:!0}),g.jsx(Ur,{square:!0,style:{marginLeft:5},value:"...",className:u,onClick:()=>this.setState({openModal:!0})}),f&&g.jsx("div",{className:le.backText,children:y?f:b.I18n.t(f)})]}),l?g.jsx(nm,{onApply:k=>this.setState({openModal:!1},()=>k!=null&&r(k)),onClose:()=>this.setState({openModal:!1}),defaultValue:i,textInput:!0}):null,p&&g.jsx("div",{className:le.nameBlock,children:b.I18n.t(p)})]},d)}renderDate(s,i,r){const{attr:l,backText:u,frontText:d,doNotTranslate:p,doNotTranslateBack:m}=s;return g.jsxs("div",{className:le.displayFlex,style:{whiteSpace:"nowrap"},children:[d&&g.jsx("div",{className:le.frontText,children:p?d:b.I18n.t(d)}),g.jsx(oO,{value:i,onChange:r}),u&&g.jsx("div",{className:le.backText,children:m?u:b.I18n.t(u)})]},l)}static getReplacesInText(s){var r;let i="";return(r=s.trigger)!=null&&r.oidType?i=".replace(/%s/g, obj.state.val).replace(/%id/g, obj.id).replace(/%name/g, obj.common && obj.common.name).replace(/%old/g, obj.oldState.val)":s.conditionsStates.length&&(i=`.replace(/%s/g, ${s.conditionsStates[0].name}).replace(/%id/g, "${s.conditionsStates[0].id}")`),i}renderTags(){const{tagCardArray:s,openTagMenu:i}=this.state,{tagCard:r}=this.state.settings;let l=r!=="="&&r!=="<>"&&r!==">="&&r!=="()"&&r!=="."&&r!=="<="&&r!=="<"&&r!==">"&&r?b.I18n.t(r):r;return s.length>=3&&(l=g.jsxs("div",{children:[g.jsx("div",{"aria-controls":"simple-menu","aria-haspopup":"true",onClick:u=>{this.setState({openTagMenu:u.currentTarget},()=>{this.props.isTourOpen&&this.props.tourStep===As.openTagsMenu&&setTimeout(()=>this.props.setTourStep&&this.props.setTourStep(As.selectIntervalTag),300)})},children:l}),g.jsx(cm,{id:"simple-menu",anchorEl:i,keepMounted:!0,open:!!i,onClose:()=>this.setState({openTagMenu:null}),children:s.map((u,d)=>{let p;return typeof u!="string"?p=u.title:p=u,g.jsxs(Ge,{selected:p===r,className:`tag-card-${p}`,style:{placeContent:"space-between"},onClick:m=>{m.stopPropagation(),this.props.isTourOpen&&(this.props.tourStep===As.openTagsMenu||this.props.tourStep===As.selectIntervalTag)&&p==="interval"&&setTimeout(()=>{var v,_;return(_=(v=this.props).setTourStep)==null?void 0:_.call(v,As.selectActions)},500);const f=JSON.parse(JSON.stringify(this.state.settings));f.tagCard=p,this.setState({openTagMenu:null,settings:f},()=>{this.props.onChange(this.state.settings),this.onTagChange(this.state.settings.tagCard)})},children:[p.search(/>|<|<>|<=|>=|=/)!==-1?p:b.I18n.t(p),typeof u!="string"&&u.title2&&g.jsx("div",{style:{marginLeft:4},children:b.I18n.t(u.title2)})]},`${p}_${d}`)})})]})),l}getData(){return{acceptedBy:"triggers",name:"",id:""}}onChangeTag(){const{tagCardArray:s,settings:i,settings:{tagCard:r}}=this.state;let l;if(typeof s[0]!="string"?l=s.map(u=>u.title):l=[...s],r&&l.length<3){const u={...i},d=l[(l.indexOf(r)+1)%l.length];u.tagCard=d,this.setState({settings:u},()=>{this.props.onChange(u),this.onTagChange(d)})}}componentDidMount(){this.onTagChange()}componentDidUpdate(){this.props.acceptedBy!=="triggers"&&this.props.onUpdate&&setTimeout(()=>this.onUpdate(),0)}onChangeInput(s){return(i,r,l)=>{const u=JSON.parse(JSON.stringify(this.state.settings));typeof i=="object"&&(!r||typeof r=="function")?(Object.keys(i).forEach(d=>u[d]=i[d]),typeof r=="function"&&(l=r,r=void 0)):u[r||s]=i,u.id=this.getData().id,u._id=this.props._id,this.setState({settings:u},()=>{this.onValueChanged(i,r||s),this.props.onChange(u),l==null||l()})}}renderSpecific(){return null}renderDebug(s){return""}renderDebugInfo(){return this.state.debugMessage?g.jsx("div",{className:le.debugInfo,style:{opacity:1,height:22,bottom:-22},children:this.renderDebug?this.renderDebug(this.state.debugMessage):b.I18n.t("executed")},this.state.debugMessage.ts):null}renderCron(s,i,r){return null}renderWizard(s,i,r){return null}renderWriteState(){return null}renderInputElement(s,i){const{nameRender:r,defaultValue:l,attr:u}=s,{settings:d}=this.state;let p=u?d[u]:void 0;switch(p===void 0&&(p=l),r){case"renderTime":return u?this.renderTime(s,p,this.onChangeInput(u)):g.jsx("div",{children:b.I18n.t("Invalid renderTime")},`invalid_${i}`);case"renderNameText":return this.renderNameText(s,l);case"renderSelect":return u?this.renderSelect(s,p,this.onChangeInput(u)):g.jsx("div",{children:b.I18n.t("Invalid renderSelect")},`invalid_${i}`);case"renderModalInput":return u?this.renderModalInput(s,p,this.onChangeInput(u)):g.jsx("div",{children:b.I18n.t("Invalid renderModalInput")},`invalid_${i}`);case"renderObjectID":return u?this.renderObjectID(s,p,this.onChangeInput(u)):g.jsx("div",{children:b.I18n.t("Invalid renderObjectID")},`invalid_${i}`);case"renderDialog":return u?this.renderDialog(s):g.jsx("div",{children:b.I18n.t("Invalid renderDialog")},`invalid_${i}`);case"renderInstance":return u?this.renderInstance(s,p,this.onChangeInput(u)):g.jsx("div",{children:b.I18n.t("Invalid renderInstance")},`invalid_${i}`);case"renderText":return u?this.renderText(s,p,this.onChangeInput(u)):g.jsx("div",{children:b.I18n.t("Invalid renderText")},`invalid_${i}`);case"renderSlider":return u?this.renderSlider(s,p,this.onChangeInput(u)):g.jsx("div",{children:b.I18n.t("Invalid renderSlider")},`invalid_${i}`);case"renderCheckbox":return u?this.renderCheckbox(s,p,this.onChangeInput(u)):g.jsx("div",{children:b.I18n.t("Invalid renderCheckbox")},`invalid_${i}`);case"renderButton":return u?this.renderButton(s,p,this.onChangeInput(u)):g.jsx("div",{children:b.I18n.t("Invalid renderButton")},`invalid_${i}`);case"renderColor":return u?this.renderColor(s,p,this.onChangeInput(u)):g.jsx("div",{children:b.I18n.t("Invalid renderColor")},`invalid_${i}`);case"renderSwitch":return u?this.renderSwitch(s,p,this.onChangeInput(u)):g.jsx("div",{children:b.I18n.t("Invalid renderSwitch")},`invalid_${i}`);case"renderDate":return u?this.renderDate(s,p,this.onChangeInput(u)):g.jsx("div",{children:b.I18n.t("Invalid renderDate")},`invalid_${i}`);case"renderCron":return u?this.renderCron(s,p,this.onChangeInput(u)):g.jsx("div",{children:b.I18n.t("Invalid renderCron")},`invalid_${i}`);case"renderWizard":return u?this.renderWizard(s,p,this.onChangeInput(u)):g.jsx("div",{children:b.I18n.t("Invalid renderWizard")},`invalid_${i}`);case"renderWriteState":return this.renderWriteState();case"renderNumber":return u?this.renderNumber(s,p,this.onChangeInput(u)):g.jsx("div",{children:b.I18n.t("Invalid renderNumber")},`invalid_${i}`);default:return this[r]?this[r](s,p,u?this.onChangeInput(u):null):g.jsx("div",{children:b.I18n.t("Invalid input type: %s",r)},`invalid_${i}`)}}render(){var y;const{inputs:s,name:i,icon:r,iconTag:l,settings:u,adapter:d,settings:{tagCard:p},helpDialog:m}=this.state,{socket:f,notFound:v}=this.props;this.state.settings&&!this.state.settings.tagCard&&((y=this.state.tagCardArray)!=null&&y.length)&&setTimeout(()=>{const k=JSON.parse(JSON.stringify(this.state.settings));k.tagCard=typeof this.state.tagCardArray[0]!="string"?this.state.tagCardArray[0].title:this.state.tagCardArray[0],this.setState({settings:k})},50),this.state.enableSimulation!==this.props.enableSimulation&&!this.enableSimulationProcessing&&(this.enableSimulationProcessing=!0,setTimeout(()=>{this.setState({enableSimulation:this.props.enableSimulation},()=>{this.enableSimulationProcessing=!1})},50));let _;if(this.props.onDebugMessage)for(let k=this.props.onDebugMessage.length-1;k>=0;k--){const C=this.props.onDebugMessage[k];if(C.blockId===this.props._id&&C.ts>this.lastDebugMessage&&C.ts>Date.now()-1e3){_=C;break}}return _&&(this.lastDebugMessage=_.ts,this.debugMessageTimeout&&clearTimeout(this.debugMessageTimeout),this.debugHideTimeout&&(clearTimeout(this.debugHideTimeout),this.debugHideTimeout=null),this.debugMessageTimeout=setTimeout(k=>{const C=JSON.parse(k),w=C.hideTimeout||5e3;this.debugMessageTimeout=null,this.setState({debugMessage:C},()=>{this.debugHideTimeout&&clearTimeout(this.debugHideTimeout),this.debugHideTimeout=setTimeout(()=>{this.debugHideTimeout=null,this.setState({debugMessage:null})},w)})},50,JSON.stringify(_))),g.jsxs(Sg,{children:[l?this.renderIconTag():g.jsx(mw,{iconName:r,className:b.Utils.clsx(le.iconThemCard,p&&this.state.tagCardArray.length&&le.iconThemCardSelectable),adapter:d,socket:f,onClick:k=>{p&&(this.state.tagCardArray.length<3?this.onChangeTag():this.setState({openTagMenu:k.currentTarget}))}}),g.jsxs("div",{className:le.blockName,children:[g.jsxs("span",{className:le.nameCard,children:[b.I18n.t(i),v?b.I18n.t("%s not found",u.id):"",m?g.jsx(Me,{className:le.iconHelp,size:"small",onClick:()=>this.setState({helpText:b.I18n.t(m)}),children:g.jsx(dC,{})}):null]}),s.map((k,C)=>this.renderInputElement(k,C))]}),p&&g.jsx("div",{className:le.controlMenuTop,style:{opacity:1,height:22,top:-22},children:g.jsx("div",{onClick:()=>this.onChangeTag(),className:b.Utils.clsx(le.tagCard,"tag-card"),children:this.renderTags()})}),this.renderDebugInfo(),this.state.error?g.jsx(b.DialogError,{title:b.I18n.t("Warning"),text:this.state.error,onClose:()=>this.setState({error:""})}):null,this.state.helpText?g.jsx(b.DialogMessage,{title:b.I18n.t("Instructions"),text:this.state.helpText,onClose:()=>this.setState({helpText:""})}):null,this.renderSpecific()]})}}const fw={en:{name:"Google - English",engine:"google",params:[]},de:{name:"Google - Deutsch",engine:"google",params:[]},ru:{name:"Google - Русский",engine:"google",params:[]},it:{name:"Google - Italiano",engine:"google",params:[]},es:{name:"Google - Espaniol",engine:"google",params:[]},fr:{name:"Google - Français",engine:"google",params:[]},ru_YA:{name:"Yandex - Русский",engine:"yandex",params:["key","voice","emotion","ill","drunk","robot"],voice:["jane","zahar"],emotion:["none","good","neutral","evil","mixed"]},ru_YA_CLOUD:{name:"Yandex Cloud - Русский",engine:"yandexCloud",params:["key","folderID","voice","emotion"],voice:["alyss","oksana","jane","zahar"],emotion:["good","neutral","evil"]},"en-US":{name:"PicoTTS - Englisch US",engine:"PicoTTS",params:[]},"en-GB":{name:"PicoTTS - Englisch GB",engine:"PicoTTS",params:[]},"de-DE":{name:"PicoTTS - Deutsch",engine:"PicoTTS",params:[]},"it-IT":{name:"PicoTTS - Italiano",engine:"PicoTTS",params:[]},"es-ES":{name:"PicoTTS - Espaniol",engine:"PicoTTS",params:[]},"fr-FR":{name:"PicoTTS - Français",engine:"PicoTTS",params:[]},"ru-RU_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"ru-RU",ename:"Tatyana",ssml:!0,name:"Cloud - Русский - Татьяна"},"ru-RU_CLOUD_Male":{gender:"Male",engine:"cloud",params:["cloud"],language:"ru-RU",ename:"Maxim",ssml:!0,name:"Cloud - Русский - Максим"},"de-DE_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"de-DE",ename:"Marlene",ssml:!0,name:"Cloud - Deutsch - Marlene"},"de-DE_CLOUD_Male":{gender:"Male",engine:"cloud",params:["cloud"],language:"de-DE",ename:"Hans",ssml:!0,name:"Cloud - Deutsch - Hans"},"en-US_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"en-US",ename:"Salli",ssml:!0,name:"Cloud - en-US - Female - Salli"},"en-US_CLOUD_Male":{gender:"Male",engine:"cloud",params:["cloud"],language:"en-US",ename:"Joey",ssml:!0,name:"Cloud - en-US - Male - Joey"},"da-DK_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"da-DK",ename:"Naja",ssml:!0,name:"Cloud - da-DK - Female - Naja"},"da-DK_CLOUD_Male":{gender:"Male",engine:"cloud",params:["cloud"],language:"da-DK",ename:"Mads",ssml:!0,name:"Cloud - da-DK - Male - Mads"},"en-AU_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"en-AU",ename:"Nicole",ssml:!0,name:"Cloud - en-AU - Female - Nicole"},"en-AU_CLOUD_Male":{gender:"Male",engine:"cloud",params:["cloud"],language:"en-AU",ename:"Russell",ssml:!0,name:"Cloud - en-AU - Male - Russell"},"en-GB_CLOUD_Female_Amy":{gender:"Female",engine:"cloud",params:["cloud"],language:"en-GB",ename:"Amy",ssml:!0,name:"Cloud - en-GB - Female - Amy"},"en-GB_CLOUD_Male":{gender:"Male",engine:"cloud",params:["cloud"],language:"en-GB",ename:"Brian",ssml:!0,name:"Cloud - en-GB - Male - Brian"},"en-GB_CLOUD_Female_Emma":{gender:"Female",engine:"cloud",params:["cloud"],language:"en-GB",ename:"Emma",ssml:!0,name:"Cloud - en-GB - Female - Emma"},"en-GB-WLS_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"en-GB-WLS",ename:"Gwyneth",ssml:!0,name:"Cloud - en-GB-WLS - Female - Gwyneth"},"en-GB-WLS_CLOUD_Male":{gender:"Male",engine:"cloud",params:["cloud"],language:"en-GB-WLS",ename:"Geraint",ssml:!0,name:"Cloud - en-GB-WLS - Male - Geraint"},"cy-GB_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"cy-GB",ename:"Gwyneth",ssml:!0,name:"Cloud - cy-GB - Female - Gwyneth"},"cy-GB_CLOUD_Male":{gender:"Male",engine:"cloud",params:["cloud"],language:"cy-GB",ename:"Geraint",ssml:!0,name:"Cloud - cy-GB - Male - Geraint"},"en-IN_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"en-IN",ename:"Raveena",ssml:!0,name:"Cloud - en-IN - Female - Raveena"},"en-US_CLOUD_Male_Chipmunk":{gender:"Male",engine:"cloud",params:["cloud"],language:"en-US",ename:"Chipmunk",ssml:!0,name:"Cloud - en-US - Male - Chipmunk"},"en-US_CLOUD_Male_Eric":{gender:"Male",engine:"cloud",params:["cloud"],language:"en-US",ename:"Eric",ssml:!0,name:"Cloud - en-US - Male - Eric"},"en-US_CLOUD_Female_Ivy":{gender:"Female",engine:"cloud",params:["cloud"],language:"en-US",ename:"Ivy",ssml:!0,name:"Cloud - en-US - Female - Ivy"},"en-US_CLOUD_Female_Jennifer":{gender:"Female",engine:"cloud",params:["cloud"],language:"en-US",ename:"Jennifer",ssml:!0,name:"Cloud - en-US - Female - Jennifer"},"en-US_CLOUD_Male_Justin":{gender:"Male",engine:"cloud",params:["cloud"],language:"en-US",ename:"Justin",ssml:!0,name:"Cloud - en-US - Male - Justin"},"en-US_CLOUD_Female_Kendra":{gender:"Female",engine:"cloud",params:["cloud"],language:"en-US",ename:"Kendra",ssml:!0,name:"Cloud - en-US - Female - Kendra"},"en-US_CLOUD_Female_Kimberly":{gender:"Female",engine:"cloud",params:["cloud"],language:"en-US",ename:"Kimberly",ssml:!0,name:"Cloud - en-US - Female - Kimberly"},"es-ES_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"es-ES",ename:"Conchita",ssml:!0,name:"Cloud - es-ES - Female - Conchita"},"es-ES_CLOUD_Male":{gender:"Male",engine:"cloud",params:["cloud"],language:"es-ES",ename:"Enrique",ssml:!0,name:"Cloud - es-ES - Male - Enrique"},"es-US_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"es-US",ename:"Penelope",ssml:!0,name:"Cloud - es-US - Female - Penelope"},"es-US_CLOUD_Male":{gender:"Male",engine:"cloud",params:["cloud"],language:"es-US",ename:"Miguel",ssml:!0,name:"Cloud - es-US - Male - Miguel"},"fr-CA_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"fr-CA",ename:"Chantal",ssml:!0,name:"Cloud - fr-CA - Female - Chantal"},"fr-FR_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"fr-FR",ename:"Celine",ssml:!0,name:"Cloud - fr-FR - Female - Celine"},"fr-FR_CLOUD_Male":{gender:"Male",engine:"cloud",params:["cloud"],language:"fr-FR",ename:"Mathieu",ssml:!0,name:"Cloud - fr-FR - Male - Mathieu"},"is-IS_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"is-IS",ename:"Dora",ssml:!0,name:"Cloud - is-IS - Female - Dora"},"is-IS_CLOUD_Male":{gender:"Male",engine:"cloud",params:["cloud"],language:"is-IS",ename:"Karl",ssml:!0,name:"Cloud - is-IS - Male - Karl"},"it-IT_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"it-IT",ename:"Carla",ssml:!0,name:"Cloud - it-IT - Female - Carla"},"it-IT_CLOUD_Male":{gender:"Male",engine:"cloud",params:["cloud"],language:"it-IT",ename:"Giorgio",ssml:!0,name:"Cloud - it-IT - Male - Giorgio"},"nb-NO_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"nb-NO",ename:"Liv",ssml:!0,name:"Cloud - nb-NO - Female - Liv"},"nl-NL_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"nl-NL",ename:"Lotte",ssml:!0,name:"Cloud - nl-NL - Female - Lotte"},"nl-NL_CLOUD_Male":{gender:"Male",engine:"cloud",params:["cloud"],language:"nl-NL",ename:"Ruben",ssml:!0,name:"Cloud - nl-NL - Male - Ruben"},"pl-PL_CLOUD_Female_Agnieszka":{gender:"Female",engine:"cloud",params:["cloud"],language:"pl-PL",ename:"Agnieszka",ssml:!0,name:"Cloud - pl-PL - Female - Agnieszka"},"pl-PL_CLOUD_Male_Jacek":{gender:"Male",engine:"cloud",params:["cloud"],language:"pl-PL",ename:"Jacek",ssml:!0,name:"Cloud - pl-PL - Male - Jacek"},"pl-PL_CLOUD_Female_Ewa":{gender:"Female",engine:"cloud",params:["cloud"],language:"pl-PL",ename:"Ewa",ssml:!0,name:"Cloud - pl-PL - Female - Ewa"},"pl-PL_CLOUD_Male_Jan":{gender:"Male",engine:"cloud",params:["cloud"],language:"pl-PL",ename:"Jan",ssml:!0,name:"Cloud - pl-PL - Male - Jan"},"pl-PL_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"pl-PL",ename:"Maja",ssml:!0,name:"Cloud - pl-PL - Female - Maja"},"pt-BR_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"pt-BR",ename:"Vitoria",ssml:!0,name:"Cloud - pt-BR - Female - Vitoria"},"pt-BR_CLOUD_Male":{gender:"Male",engine:"cloud",params:["cloud"],language:"pt-BR",ename:"Ricardo",ssml:!0,name:"Cloud - pt-BR - Male - Ricardo"},"pt-PT_CLOUD_Male":{gender:"Male",engine:"cloud",params:["cloud"],language:"pt-PT",ename:"Cristiano",ssml:!0,name:"Cloud - pt-PT - Male - Cristiano"},"pt-PT_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"pt-PT",ename:"Ines",ssml:!0,name:"Cloud - pt-PT - Female - Ines"},"ro-RO_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"ro-RO",ename:"Carmen",ssml:!0,name:"Cloud - ro-RO - Female - Carmen"},"sv-SE_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"sv-SE",ename:"Astrid",ssml:!0,name:"Cloud - sv-SE - Female - Astrid"},"tr-TR_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"tr-TR",ename:"Filiz",ssml:!0,name:"Cloud - tr-TR - Female - Filiz"},"ru-RU_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"ru-RU",ename:"Tatyana",ssml:!0,name:"AWS Polly - Русский - Татьяна"},"ru-RU_AP_Male":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"ru-RU",ename:"Maxim",ssml:!0,name:"AWS Polly - Русский - Максим"},"de-DE_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"de-DE",ename:"Marlene",ssml:!0,name:"AWS Polly - Deutsch - Marlene"},"de-DE_AP_Female_Vicky":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"de-DE",ename:"Vicky",ssml:!0,name:"AWS Polly - Deutsch - Vicky"},"de-DE_AP_Male":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"de-DE",ename:"Hans",ssml:!0,name:"AWS Polly - Deutsch - Hans"},"en-US_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"en-US",ename:"Salli",ssml:!0,name:"AWS Polly - en-US - Female - Salli"},"en-US_AP_Male":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"en-US",ename:"Joey",ssml:!0,name:"AWS Polly - en-US - Male - Joey"},"da-DK_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"da-DK",ename:"Naja",ssml:!0,name:"AWS Polly - da-DK - Female - Naja"},"da-DK_AP_Male":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"da-DK",ename:"Mads",ssml:!0,name:"AWS Polly - da-DK - Male - Mads"},"en-AU_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"en-AU",ename:"Nicole",ssml:!0,name:"AWS Polly - en-AU - Female - Nicole"},"en-AU_AP_Male":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"en-AU",ename:"Russell",ssml:!0,name:"AWS Polly - en-AU - Male - Russell"},"en-GB_AP_Female_Amy":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"en-GB",ename:"Amy",ssml:!0,name:"AWS Polly - en-GB - Female - Amy"},"en-GB_AP_Male":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"en-GB",ename:"Brian",ssml:!0,name:"AWS Polly - en-GB - Male - Brian"},"en-GB_AP_Female_Emma":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"en-GB",ename:"Emma",ssml:!0,name:"AWS Polly - en-GB - Female - Emma"},"en-GB-WLS_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"en-GB-WLS",ename:"Gwyneth",ssml:!0,name:"AWS Polly - en-GB-WLS - Female - Gwyneth"},"en-GB-WLS_AP_Male":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"en-GB-WLS",ename:"Geraint",ssml:!0,name:"AWS Polly - en-GB-WLS - Male - Geraint"},"cy-GB_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"cy-GB",ename:"Gwyneth",ssml:!0,name:"AWS Polly - cy-GB - Female - Gwyneth"},"cy-GB_AP_Male":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"cy-GB",ename:"Geraint",ssml:!0,name:"AWS Polly - cy-GB - Male - Geraint"},"en-IN_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"en-IN",ename:"Raveena",ssml:!0,name:"AWS Polly - en-IN - Female - Raveena"},"en-US_AP_Male_Chipmunk":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"en-US",ename:"Chipmunk",ssml:!0,name:"AWS Polly - en-US - Male - Chipmunk"},"en-US_AP_Male_Eric":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"en-US",ename:"Eric",ssml:!0,name:"AWS Polly - en-US - Male - Eric"},"en-US_AP_Female_Ivy":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"en-US",ename:"Ivy",ssml:!0,name:"AWS Polly - en-US - Female - Ivy"},"en-US_AP_Female_Jennifer":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"en-US",ename:"Jennifer",ssml:!0,name:"AWS Polly - en-US - Female - Jennifer"},"en-US_AP_Male_Justin":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"en-US",ename:"Justin",ssml:!0,name:"AWS Polly - en-US - Male - Justin"},"en-US_AP_Female_Kendra":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"en-US",ename:"Kendra",ssml:!0,name:"AWS Polly - en-US - Female - Kendra"},"en-US_AP_Female_Kimberly":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"en-US",ename:"Kimberly",ssml:!0,name:"AWS Polly - en-US - Female - Kimberly"},"es-ES_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"es-ES",ename:"Conchita",ssml:!0,name:"AWS Polly - es-ES - Female - Conchita"},"es-ES_AP_Male":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"es-ES",ename:"Enrique",ssml:!0,name:"AWS Polly - es-ES - Male - Enrique"},"es-US_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"es-US",ename:"Penelope",ssml:!0,name:"AWS Polly - es-US - Female - Penelope"},"es-US_AP_Male":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"es-US",ename:"Miguel",ssml:!0,name:"AWS Polly - es-US - Male - Miguel"},"fr-CA_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"fr-CA",ename:"Chantal",ssml:!0,name:"AWS Polly - fr-CA - Female - Chantal"},"fr-FR_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"fr-FR",ename:"Celine",ssml:!0,name:"AWS Polly - fr-FR - Female - Celine"},"fr-FR_AP_Male":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"fr-FR",ename:"Mathieu",ssml:!0,name:"AWS Polly - fr-FR - Male - Mathieu"},"is-IS_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"is-IS",ename:"Dora",ssml:!0,name:"AWS Polly - is-IS - Female - Dora"},"is-IS_AP_Male":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"is-IS",ename:"Karl",ssml:!0,name:"AWS Polly - is-IS - Male - Karl"},"it-IT_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"it-IT",ename:"Carla",ssml:!0,name:"AWS Polly - it-IT - Female - Carla"},"it-IT_AP_Male":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"it-IT",ename:"Giorgio",ssml:!0,name:"AWS Polly - it-IT - Male - Giorgio"},"nb-NO_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"nb-NO",ename:"Liv",ssml:!0,name:"AWS Polly - nb-NO - Female - Liv"},"nl-NL_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"nl-NL",ename:"Lotte",ssml:!0,name:"AWS Polly - nl-NL - Female - Lotte"},"nl-NL_AP_Male":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"nl-NL",ename:"Ruben",ssml:!0,name:"AWS Polly - nl-NL - Male - Ruben"},"pl-PL_AP_Female_Agnieszka":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"pl-PL",ename:"Agnieszka",ssml:!0,name:"AWS Polly - pl-PL - Female - Agnieszka"},"pl-PL_AP_Male_Jacek":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"pl-PL",ename:"Jacek",ssml:!0,name:"AWS Polly - pl-PL - Male - Jacek"},"pl-PL_AP_Female_Ewa":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"pl-PL",ename:"Ewa",ssml:!0,name:"AWS Polly - pl-PL - Female - Ewa"},"pl-PL_AP_Male_Jan":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"pl-PL",ename:"Jan",ssml:!0,name:"AWS Polly - pl-PL - Male - Jan"},"pl-PL_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"pl-PL",ename:"Maja",ssml:!0,name:"AWS Polly - pl-PL - Female - Maja"},"pt-BR_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"pt-BR",ename:"Vitoria",ssml:!0,name:"AWS Polly - pt-BR - Female - Vitoria"},"pt-BR_AP_Male":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"pt-BR",ename:"Ricardo",ssml:!0,name:"AWS Polly - pt-BR - Male - Ricardo"},"pt-PT_AP_Male":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"pt-PT",ename:"Cristiano",ssml:!0,name:"AWS Polly - pt-PT - Male - Cristiano"},"pt-PT_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"pt-PT",ename:"Ines",ssml:!0,name:"AWS Polly - pt-PT - Female - Ines"},"ro-RO_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"ro-RO",ename:"Carmen",ssml:!0,name:"AWS Polly - ro-RO - Female - Carmen"},"sv-SE_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"sv-SE",ename:"Astrid",ssml:!0,name:"AWS Polly - sv-SE - Female - Astrid"},"tr-TR_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"tr-TR",ename:"Filiz",ssml:!0,name:"AWS Polly - tr-TR - Female - Filiz"}};class xc extends Xe{constructor(s){super(s,xc.getStaticData())}static compile(s,i){return s.text?`// Sayit ${s.text||""} - const subActionVar${s._id} = "${s.language&&s.language!=="_"?`${s.language};`:""}${s.volume?`${s.volume};`:""}${(s.text||"").replace(/"/g,'\\"')}"${Xe.getReplacesInText(i)}; - _sendToFrontEnd(${s._id}, {text: subActionVar${s._id}}); - await setStateAsync("${s.instance}.tts.text", subActionVar${s._id});`:`// no text defined -_sendToFrontEnd(${s._id}, {text: 'No text defined'});`}renderDebug(s){return`${b.I18n.t("Say:")} ${s.data.text}`}onTagChange(){const s=b.I18n.getLanguage(),r=Object.keys(fw).filter(l=>l.startsWith(s)).map(l=>({title:fw[l].name,value:l}));r.unshift({title:"Default",value:"_"}),this.setState({inputs:[{attr:"instance",nameRender:"renderInstance",adapter:"sayit",defaultValue:"sayit.0",frontText:"Instance:"},{nameRender:"renderSelect",frontText:"Language:",options:r,defaultValue:"_",attr:"language"},{nameRender:"renderNameText",defaultValue:"Volume",attr:"textVol"},{nameRender:"renderSlider",attr:"volume",defaultValue:100,min:0,max:100},{attr:"text",nameRender:"renderModalInput",defaultValue:"Hallo",nameBlock:"",frontText:"Text:"}]},()=>super.onTagChange())}static getStaticData(){return{acceptedBy:"actions",name:"Say It",id:"ActionSayText",adapter:"sayit",title:"Say some text via sayit adapter",helpDialog:"You can use %s in the text to display current trigger value or %id to display the triggered object ID"}}getData(){return xc.getStaticData()}}class Dc extends Xe{constructor(s){super(s,Dc.getStaticData())}static compile(s,i){const r=(s.text||"").replace(/"/g,'\\"');return r?`// Pushover ${s.text||""} - const subActionVar${s._id} = "${r}"${Xe.getReplacesInText(i)}; - _sendToFrontEnd(${s._id}, {text: subActionVar${s._id}}); - sendTo("${s.instance}", "send", { - message: subActionVar${s._id}, - title: "${(s.title||"").replace(/"/g,'\\"')}"${Xe.getReplacesInText(i)}, - sound: "${s.sound}", - priority: ${s.priority} - });`:`// no text defined -_sendToFrontEnd(${s._id}, {text: 'No text defined'});`}renderDebug(s){return`Sent: ${s.data.text}`}onTagChange(){this.setState({inputs:[{nameRender:"renderInstance",adapter:"pushover",frontText:"Instance:",defaultValue:"pushover.0",attr:"instance"},{nameRender:"renderModalInput",attr:"text",defaultValue:"Hello",nameBlock:"",frontText:"Text:"},{nameRender:"renderText",attr:"title",defaultValue:"ioBroker",frontText:"Title:"},{nameRender:"renderSelect",attr:"sound",defaultValue:"magic",frontText:"Sound:",doNotTranslate:!0,options:[{value:"pushover",title:"pushover"},{value:"bike",title:"bike"},{value:"bugle",title:"bugle"},{value:"cashregister",title:"cashregister"},{value:"classical",title:"classical"},{value:"cosmic",title:"cosmic"},{value:"falling",title:"falling"},{value:"gamelan",title:"gamelan"},{value:"incoming",title:"incoming"},{value:"intermission",title:"intermission"},{value:"magic",title:"magic"},{value:"mechanical",title:"mechanical"},{value:"pianobar",title:"pianobar"},{value:"siren",title:"siren"},{value:"spacealarm",title:"spacealarm"},{value:"tugboat",title:"tugboat"},{value:"alien",title:"alien"},{value:"climb",title:"climb"},{value:"persistent",title:"persistent"},{value:"echo",title:"echo"},{value:"updown",title:"updown"},{value:"none",title:"none"}]},{nameRender:"renderSelect",attr:"priority",defaultValue:-1,frontText:"Priority:",options:[{value:-1,title:"quiet"},{value:0,title:"normal"},{value:1,title:"high-priority"},{value:2,title:"acknowledgment"}]}]},()=>super.onTagChange())}static getStaticData(){return{acceptedBy:"actions",name:"Pushover",id:"ActionPushover",adapter:"pushover",title:"Sends message via pushover",helpDialog:"You can use %s in the text to display current trigger value or %id to display the triggered object ID"}}getData(){return Dc.getStaticData()}}class Ac extends Xe{constructor(s){super(s,Ac.getStaticData())}static compile(s,i){const r=(s.text||"").replace(/"/g,'\\"');return r?`// whatsapp ${r||""} - const subActionVar${s._id} = "${(r||"").replace(/"/g,'\\"')}"${Xe.getReplacesInText(i)}; - _sendToFrontEnd(${s._id}, {text: subActionVar${s._id}}); - sendTo("${s.instance}", "send", {text: subActionVar${s._id}${s.phone?`, phone: "${s.phone.replace(/"/g,'\\"')}"`:""}});`:`// no text defined -_sendToFrontEnd(${s._id}, {text: 'No text defined'});`}renderDebug(s){return`${b.I18n.t("Sent:")} ${s.data.text}`}onTagChange(){this.setState({inputs:[{nameRender:"renderInstance",adapter:"whatsapp-cmb",frontText:"Instance:",defaultValue:"whatsapp-cmb.0",attr:"instance"},{nameRender:"renderModalInput",attr:"text",defaultValue:"Hello",nameBlock:"",frontText:"Text:"},{nameRender:"renderText",attr:"phone",defaultValue:"",frontText:"Phone:",backText:"(optional)"}]},()=>super.onTagChange())}static getStaticData(){return{acceptedBy:"actions",name:"Whatsapp-cmb",id:"ActionWhatsappcmb",adapter:"whatsapp-cmb",title:"Sends message via whatsapp-cmb",helpDialog:"You can use %s in the text to display current trigger value or %id to display the triggered object ID"}}getData(){return Ac.getStaticData()}}class Rc extends Xe{constructor(s){super(s,Rc.getStaticData())}static compile(s,i){const r=(s.text||"").replace(/"/g,'\\"');return r?`// Pushsafer ${s.text||""} - const subActionVar${s._id} = "${r}"${Xe.getReplacesInText(i)}; - _sendToFrontEnd(${s._id}, {text: subActionVar${s._id}}); - sendTo("${s.instance}", "send", { - message: subActionVar${s._id}, - title: "${(s.title||"").replace(/"/g,'\\"')}"${Xe.getReplacesInText(i)}, - ${s.sound&&s.sound!=="_"?`sound: "${s.sound}",`:""} - priority: ${s.priority}, - ${s.vibration&&s.vibration!=="_"?`vibration: ${s.vibration},`:""} - });`:`// no text defined -_sendToFrontEnd(${s._id}, {text: 'No text defined'});`}renderDebug(s){return`Sent: ${s.data.text}`}onTagChange(){this.setState({inputs:[{nameRender:"renderInstance",adapter:"pushsafer",frontText:"Instance:",defaultValue:"pushsafer.0",attr:"instance"},{nameRender:"renderModalInput",attr:"text",defaultValue:"Hello",nameBlock:"",frontText:"Text:"},{nameRender:"renderText",attr:"title",defaultValue:"ioBroker",frontText:"Title:"},{nameRender:"renderSelect",attr:"sound",defaultValue:"magic",frontText:"Sound:",doNotTranslate:!0,options:[{value:"_",title:"Device Default"},{value:"0",title:"Silent"},{value:"1",title:"Ahem (IM)"},{value:"2",title:"Applause (Mail)"},{value:"3",title:"Arrow (Reminder)"},{value:"4",title:"Baby (SMS)"},{value:"5",title:"Bell (Alarm)"},{value:"6",title:"Bicycle (Alarm2)"},{value:"7",title:"Boing (Alarm3)"},{value:"8",title:"Buzzer (Alarm4)"},{value:"9",title:"Camera (Alarm5)"},{value:"10",title:"Car Horn (Alarm6)"},{value:"11",title:"Cash Register (Alarm7)"},{value:"12",title:"Chime (Alarm8)"},{value:"13",title:"Creaky Door (Alarm9)"},{value:"14",title:"Cuckoo Clock (Alarm10)"},{value:"15",title:"Disconnect (Call)"},{value:"16",title:"Dog (Call2)"},{value:"17",title:"Doorbell (Call3)"},{value:"18",title:"Fanfare (Call4)"},{value:"19",title:"Gun Shot (Call5)"},{value:"20",title:"Honk (Call6)"},{value:"21",title:"Jaw Harp (Call7)"},{value:"22",title:"Morse (Call8)"},{value:"23",title:"Electricity (Call9)"},{value:"24",title:"Radio Tuner (Call10)"},{value:"25",title:"Sirens"},{value:"26",title:"Military Trumpets"},{value:"27",title:"Ufo"},{value:"28",title:"Whah Whah Whah"},{value:"29",title:"Man Saying Goodbye"},{value:"30",title:"Man Saying Hello"},{value:"31",title:"Man Saying No"},{value:"32",title:"Man Saying Ok"},{value:"33",title:"Man Saying Ooohhhweee"},{value:"34",title:"Man Saying Warning"},{value:"35",title:"Man Saying Welcome"},{value:"36",title:"Man Saying Yeah"},{value:"37",title:"Man Saying Yes"},{value:"38",title:"Beep short"},{value:"39",title:"Weeeee short"},{value:"40",title:"Cut in and out short"},{value:"41",title:"Finger flicking glas short"},{value:"42",title:"Wa Wa Waaaa short"},{value:"43",title:"Laser short"},{value:"44",title:"Wind Chime short"},{value:"45",title:"Echo short"},{value:"46",title:"Zipper short"},{value:"47",title:"HiHat short"},{value:"48",title:"Beep 2 short"},{value:"49",title:"Beep 3 short"},{value:"50",title:"Beep 4 short"},{value:"51",title:"The Alarm is armed"},{value:"52",title:"The Alarm is disarmed"},{value:"53",title:"The Backup is ready"},{value:"54",title:"The Door is closed"},{value:"55",title:"The Door is opend"},{value:"56",title:"The Window is closed"},{value:"57",title:"The Window is open"},{value:"58",title:"The Light is off"},{value:"59",title:"The Light is on"},{value:"60",title:"The Doorbell rings"},{value:"61",title:"Pager short"},{value:"62",title:"Pager long"}]},{nameRender:"renderSelect",attr:"priority",defaultValue:0,frontText:"Priority:",options:[{value:-2,title:"lowest priority"},{value:-1,title:"lower priority"},{value:0,title:"normal priority"},{value:1,title:"high priority"},{value:2,title:"highest priority"}]},{nameRender:"renderSelect",attr:"vibration",defaultValue:0,frontText:"Vibration:",options:[{value:"_",title:"default"},{value:1,title:"1"},{value:2,title:"2"},{value:3,title:"3"}]}]},()=>super.onTagChange())}static getStaticData(){return{acceptedBy:"actions",name:"Pushsafer",id:"ActionPushsafer",adapter:"pushsafer",title:"Sends message via Pushsafer",helpDialog:"You can use %s in the text to display current trigger value or %id to display the triggered object ID"}}getData(){return Rc.getStaticData()}}const kT=`async function (obj) { - "__%%DEBUG_TRIGGER%%__"; - __%%CONDITIONS_VARS%%__ - const _cond = __%%CONDITION%%__; - - "__%%DEBUG_CONDITIONS%%__"; - - if (_cond) { -__%%THEN%%__ - } else { -__%%ELSE%%__ - } -}`,ST=`async function (obj) { - "__%%DEBUG_TRIGGER%%__"; - __%%CONDITIONS_VARS%%__ - const _cond = __%%CONDITION%%__; - - "__%%DEBUG_CONDITIONS%%__"; - - if (__%%STATE%%__ === false && _cond) { - __%%STATE%%__ = true; -__%%THEN%%__ - } else if (__%%STATE%%__ === true && !_cond) { - __%%STATE%%__ = false; -__%%ELSE%%__ - } -}`,rO=`"__%%DEBUG_TRIGGER%%__"; -__%%CONDITIONS_VARS%%__ -const _cond = __%%CONDITION%%__; - -"__%%DEBUG_CONDITIONS%%__"; - -if (_cond) { -__%%THEN%%__ -} else { -__%%ELSE%%__ -}`,wg={triggers:[],conditions:[[]],justCheck:!1,actions:{then:[],else:[]}};function aO(a,s,i){const r=[];let l=a.triggers;l.length||(l=[{id:"TriggerScriptSave"}]);const u=[],d=[],p=a.conditions.find(f=>f.find(v=>v.tagCard==="()"));l.forEach((f,v)=>{var y;const _=Um(f.id,i);if(_){const k={trigger:f,condition:{index:0},justCheck:p?!1:a.justCheck||!a.conditions.length||!a.conditions[0].length,conditionsDebug:[],conditionsVars:[],conditionsStates:[]},C=_.compile(f,k),w=lO(a.conditions,k,i),E=$w(a.actions.then,k,i),R=$w(a.actions.else,k,i);u.push(`cond${v}`),(y=k.prelines)!=null&&y.length&&k.prelines.forEach(D=>d.push(D)),C.includes(" __%%CONDITIONS_VARS%%__")&&(k.conditionsVars=k.conditionsVars.map((D,A)=>A?` ${D}`:D),k.conditionsDebug=k.conditionsDebug.map((D,A)=>A?` ${D}`:D)),r.push(C.replace("__%%CONDITIONS_VARS%%__",k.conditionsVars.join(` -`)).replace('"__%%DEBUG_CONDITIONS%%__";',k.conditionsDebug.join(` -`)).replace("__%%CONDITION%%__",w).replace("__%%THEN%%__",E||"// ignore").replace("__%%ELSE%%__",R||"// ignore").replace(/__%%STATE%%__/g,`cond${v}`))}});let m=r.join(` - -`);return(!a.justCheck||p)&&(m=`${u.map(f=>`let ${f} = false;`).join(` -`)} - -${m}`),d&&(m=`${d.join(` -`)} - -${m}`),m}function Um(a,s){return s.find(i=>i.getStaticData&&i.getStaticData().id===a)}function $w(a,s,i){const r=[];return a==null||a.forEach(l=>{const u=Um(l.id,i);u&&r.push(u.compile(l,s))}),` ${r.join(` - - `)}`}function lO(a,s,i){const r=[];let l=0;return a==null||a.forEach(u=>{const d=[];u!=null&&u.length&&(u.forEach(p=>{const m=Um(p.id,i);m&&(s.condition.index=l++,d.push(m.compile(p,s)))}),r.push(`(${d.join(`) && - (`)})`))}),r.length?r.length===1?r[0]||"true":`(${r.join(") || (")})`:"true"}function cO(a,s){return aO(a,null,s)}function cne(a){if(!a)return wg;const s=a.split(` -`);try{const i=(s.pop()||"").replace(/^\/\//,"");let r=JSON.parse(i);return r.triggers||(r=wg),r}catch{return wg}}function une(a,s){let i="";const r=cO(a,s);return i+=r,i+=` -/* -const demo = ${JSON.stringify(a,null,2).replace(/\*\//g,"* /")}; -*/ -`,`${i} -//${JSON.stringify(a)}`}class Oc extends Xe{constructor(s){super(s,Oc.getStaticData())}static compile(s,i){return rO.replace('"__%%DEBUG_TRIGGER%%__"',`_sendToFrontEnd(${s._id}, {trigger: true})`)}renderDebug(){return b.I18n.t("Triggered")}onTagChange(s){this.setState({inputs:[{nameRender:"renderNameText",defaultValue:"On script save or adapter start",attr:"script"}]},()=>super.onTagChange())}static getStaticData(){return{acceptedBy:"triggers",name:"Start script",id:"TriggerScriptSave",icon:"PlayArrow",title:"Triggers the on script saving or the javascript instance restart"}}getData(){return Oc.getStaticData()}}var ET={exports:{}};(function(a,s){(function(){var i=Math.PI,r=Math.sin,l=Math.cos,u=Math.tan,d=Math.asin,p=Math.atan2,m=Math.acos,f=i/180,v=1e3*60*60*24,_=2440588,y=2451545;function k(q){return q.valueOf()/v-.5+_}function C(q){return new Date((q+.5-_)*v)}function w(q){return k(q)-y}var E=f*23.4397;function R(q,ee){return p(r(q)*l(E)-u(ee)*r(E),l(q))}function D(q,ee){return d(r(ee)*l(E)+l(ee)*r(E)*r(q))}function A(q,ee,B){return p(r(q),l(q)*r(ee)-u(B)*l(ee))}function J(q,ee,B){return d(r(ee)*r(B)+l(ee)*l(B)*l(q))}function ie(q,ee){return f*(280.16+360.9856235*q)-ee}function se(q){return q<0&&(q=0),2967e-7/Math.tan(q+.00312536/(q+.08901179))}function me(q){return f*(357.5291+.98560028*q)}function z(q){var ee=f*(1.9148*r(q)+.02*r(2*q)+3e-4*r(3*q)),B=f*102.9372;return q+ee+B+i}function Oe(q){var ee=me(q),B=z(ee);return{dec:D(B,0),ra:R(B,0)}}var Ne={};Ne.getPosition=function(q,ee,B){var H=f*-B,U=f*ee,re=w(q),I=Oe(re),de=ie(re,H)-I.ra;return{azimuth:A(de,U,I.dec),altitude:J(de,U,I.dec)}};var Ze=Ne.times=[[-.833,"sunrise","sunset"],[-.3,"sunriseEnd","sunsetStart"],[-6,"dawn","dusk"],[-12,"nauticalDawn","nauticalDusk"],[-18,"nightEnd","night"],[6,"goldenHourEnd","goldenHour"]];Ne.addTime=function(q,ee,B){Ze.push([q,ee,B])};var ae=9e-4;function ce(q,ee){return Math.round(q-ae-ee/(2*i))}function K(q,ee,B){return ae+(q+ee)/(2*i)+B}function ye(q,ee,B){return y+q+.0053*r(ee)-.0069*r(2*B)}function he(q,ee,B){return m((r(q)-r(ee)*r(B))/(l(ee)*l(B)))}function je(q,ee,B,H,U,re,I){var de=he(q,B,H),W=K(de,ee,U);return ye(W,re,I)}Ne.getTimes=function(q,ee,B){var H=f*-B,U=f*ee,re=w(q),I=ce(re,H),de=K(0,H,I),W=me(de),Ce=z(W),be=D(Ce,0),Se=ye(de,W,Ce),pe,Ve,Je,_e,ke,$e={solarNoon:C(Se),nadir:C(Se+.5)};for(pe=0,Ve=Ze.length;pe=0&&(bt=Math.sqrt(_e)/(Math.abs(Se)*2),$e=Ve-bt,Pe=Ve+bt,Math.abs($e)<=1&&ke++,Math.abs(Pe)<=1&&ke++,$e<-1&&($e=Pe)),ke===1?I<0?Ce=X+$e:be=X+$e:ke===2&&(Ce=X+(Je<0?Pe:$e),be=X+(Je<0?$e:Pe)),!(Ce&&be));X+=2)I=W;var ct={};return Ce&&(ct.rise=tt(U,Ce)),be&&(ct.set=tt(U,be)),!Ce&&!be&&(ct[Je>0?"alwaysUp":"alwaysDown"]=!0),ct},a.exports=Ne})()})(ET);var uO=ET.exports;const IT=Si(uO),dO='{"time":{"start":"00:00","end":"24:00","mode":"hours","interval":1},"period":{"days":1}}';class vi extends Xe{coordinates=null;constructor(s){super(s,vi.getStaticData())}static compile(s,i){var u;let r="",l=i.justCheck?kT:ST;if(l=l.replace('"__%%DEBUG_TRIGGER%%__"',`_sendToFrontEnd(${s._id}, {trigger: true})`),s.tagCard==="interval")r=`setInterval(${l}, ${s.interval||1} * ${s.unit==="s"?1e3:s.unit==="m"?6e4:36e5});`;else if(s.tagCard==="cron")r=`schedule("${s.cron}", ${l});`;else if(s.tagCard==="at"){const[d,p]=(s.at||"").split(":");let m="*";if((u=s==null?void 0:s.dow)!=null&&u.length&&!s.dow.includes("_")){const f=[...s.dow].map(k=>parseInt(k,10));f.sort();const v=[];let _=f[0],y=1;for(;y1?(_===f[y-1]?v.push(_.toString()):f[y-1]-_===1?v.push(`${_},${f[y-1]}`):v.push(`${_}-${f[y-1]}`),_=f[y]):y===f.length-1&&(_===f[y-1]||f[y]-_===1?v.push(`${_},${f[y]}`):v.push(`${_}-${f[y]}`));m=v.join(",")}r=`schedule("${p||"0"} ${d||"0"} * * ${m}", ${l});`}else s.tagCard==="astro"?r=`schedule({astro: "${s.astro}", shift: ${s.offset?s.offsetValue:0}}, ${l});`:s.tagCard==="wizard"&&(r=`schedule('${s.wizard}', ${l});`);return r}static _time2String(s){return s?`${s.getHours().toString().padStart(2,"0")}:${s.getMinutes().toString().padStart(2,"0")}`:"--:--"}async _setAstro(s,i,r){var m,f;if(s||=this.state.settings.astro||"solarNoon",i??=this.state.settings.offset,r??=this.state.settings.offsetValue,r=parseInt(r,10)||0,!this.coordinates){const v=await this.props.socket.getObject("system.adapter.javascript.0"),_=(m=v==null?void 0:v.native)==null?void 0:m.latitude,y=(f=v==null?void 0:v.native)==null?void 0:f.longitude;if(!_&&!y){const k=await this.props.socket.getObject("system.config");k!=null&&k.common&&(k.common.latitude||k.common.longitude)?this.coordinates={latitude:parseFloat(k.common.latitude),longitude:parseFloat(k.common.longitude)}:this.coordinates=null}else this.coordinates={latitude:parseFloat(_),longitude:parseFloat(y)}}const l=this.coordinates&&IT.getTimes(new Date,this.coordinates.latitude,this.coordinates.longitude),u=l?Object.keys(l).map(v=>({value:v,title:v,title2:`[${vi._time2String(l[v])}]`,order:l?vi._time2String(l[v]):"??:??"})):[];u.sort((v,_)=>v.order>_.order?1:v.order<_.order?-1:0);let d="--:--";if(s&&l&&l[s]){const v=new Date(l[s]);i&&v.setMinutes(v.getMinutes()+parseInt(r,10)),d=b.I18n.t("(at %s)",vi._time2String(v))}let p;i?p=[{frontText:"at",attr:"astro",nameRender:"renderSelect",options:u,defaultValue:"solarNoon",doNotTranslate2:!0},{backText:"with offset",nameRender:"renderCheckbox",attr:"offset"},{backText:r===1?"minute":"minutes",frontText:"offset",nameRender:"renderNumber",defaultValue:0,attr:"offsetValue",noHelperText:!0},{nameRender:"renderNameText",attr:"textTime",defaultValue:d,doNotTranslate:!0}]:p=[{frontText:"at",attr:"astro",nameRender:"renderSelect",options:u,doNotTranslate2:!0,defaultValue:"solarNoon"},{backText:"with offset",nameRender:"renderCheckbox",attr:"offset"},{nameRender:"renderNameText",attr:"textTime1",defaultValue:d,doNotTranslate:!0}],this.setState({inputs:p},()=>super.onTagChange())}_setInterval(s){s=parseInt(s||this.state.settings.interval,10)||30;let i;s===1?i=[{value:"s",title:"second"},{value:"m",title:"minute"},{value:"h",title:"hour"}]:i=[{value:"s",title:"seconds"},{value:"m",title:"minutes"},{value:"h",title:"hours"}],this.setState({inputs:[{nameRender:"renderNumber",attr:"interval",frontText:"every",defaultValue:30,className:"block-input-interval"},{nameRender:"renderSelect",attr:"unit",defaultValue:"s",options:i}]},()=>super.onTagChange())}renderDebug(s){return b.I18n.t("Triggered")}onValueChanged(s,i){this.state.settings.tagCard==="astro"?i==="astro"?this._setAstro(s):i==="offset"?this._setAstro(void 0,s):i==="offsetValue"&&this._setAstro(void 0,void 0,s):this.state.settings.tagCard==="interval"&&i==="interval"&&this._setInterval(s)}renderCron(s,i,r){const{className:l}=this.props;return g.jsxs("div",{children:[g.jsxs("div",{style:{display:"flex",alignItems:"baseline"},children:[g.jsx("div",{style:{width:"100%"},children:this.renderText({nameRender:"renderText",attr:"cron",defaultValue:i},this.state.settings.cron||i,r)}),g.jsx(Ur,{square:!0,style:{marginLeft:7},value:"...",className:l,onClick:()=>this.setState({openDialog:!0,textCron:this.state.settings.cron})})]}),this.state.openDialog?g.jsx(nm,{disabled:this.state.settings.cron===this.state.textCron,onApply:()=>{const u=this.state.textCron;r(u,"cron",()=>{r(b.convertCronToText(u,b.I18n.getLanguage()),"addText"),this.setState({openDialog:!1})})},onClose:()=>this.setState({openDialog:!1,textCron:""}),children:g.jsx(b.ComplexCron,{cronExpression:this.state.settings.cron,onChange:u=>this.setState({textCron:u}),language:b.I18n.getLanguage()})}):null,this.renderNameText({nameRender:"renderNameText",defaultValue:b.I18n.t("every hour at 0 minutes"),attr:"addText",signature:!0,doNotTranslate:!0},this.state.settings.addText||b.I18n.t("every hour at 0 minutes"))]},"cron")}renderWizard(s,i,r){const{className:l}=this.props;return g.jsxs("div",{children:[g.jsxs("div",{style:{display:"flex",alignItems:"center",marginTop:7},children:[g.jsx(bi,{className:l,autoComplete:"off",fullWidth:!0,variant:"outlined",size:"small",multiline:!0,rows:2,value:this.state.settings.wizardText,onChange:u=>r(u),customValue:!0}),g.jsx(Ur,{square:!0,style:{marginLeft:7},value:"...",className:l,onClick:()=>this.setState({openDialog:!0,wizard:this.state.settings.wizard,wizardText:b.Schedule.state2text(this.state.settings.wizard)})})]}),this.state.openDialog?g.jsx(nm,{disabled:this.state.settings.wizard===this.state.wizard,onApply:()=>this.setState({openDialog:!1},()=>{const u=JSON.parse(this.state.wizard);u.valid||={from:b.Schedule.now2string()},u.valid.from||=b.Schedule.now2string(),r({wizardText:this.state.wizardText,wizard:JSON.stringify(u)})}),onClose:()=>this.setState({openDialog:!1}),children:g.jsx(b.Schedule,{theme:this.props.theme,schedule:i,onChange:(u,d)=>this.setState({wizardText:d||"",wizard:u})})}):null]},"wizard")}onTagChange(s){switch(s||=this.state.settings.tagCard,s){case"interval":this._setInterval();break;case"cron":this.setState({inputs:[{nameRender:"renderCron",attr:"cron",defaultValue:"0 * * * *"}]},()=>super.onTagChange());break;case"wizard":{const i=JSON.parse(dO);i.valid||={from:b.Schedule.now2string()},i.valid.from||=b.Schedule.now2string(),this.setState({inputs:[{nameRender:"renderWizard",attr:"wizard",defaultValue:JSON.stringify(i)}]},()=>super.onTagChange(null,()=>{const r=b.Schedule.state2text(this.state.settings.wizard||i);if(this.state.settings.wizard!==r){const l=JSON.parse(JSON.stringify(this.state.settings));l.wizardText=r,this.setState({settings:l}),this.props.onChange(l)}}));break}case"at":this.setState({inputs:[{nameRender:"renderTime",prefix:"at",attr:"at",defaultValue:"07:30"},{nameRender:"renderSelect",attr:"dow",default:"",multiple:!0,defaultValue:["_","1","2","3","4","5","6","0"],options:[{value:"_",title:"Every day",only:!0},{value:"1",title:"Monday",titleShort:"Mo"},{value:"2",title:"Tuesday",titleShort:"Tu"},{value:"3",title:"Wednesday",titleShort:"We"},{value:"4",title:"Thursday",titleShort:"Th"},{value:"5",title:"Friday",titleShort:"Fr"},{value:"6",title:"Saturday",titleShort:"Sa"},{value:"0",title:"Sunday",titleShort:"Su"}]}]},()=>super.onTagChange());break;case"astro":this._setAstro();break}}static getStaticData(){return{acceptedBy:"triggers",name:"Schedule",id:"TriggerScheduleBlock",icon:"AccessTime",tagCardArray:["cron","wizard","interval","at","astro"],title:"Triggers the rule periodically or on some specific time"}}getData(){return vi.getStaticData()}}const yn={valueAck:{color:"#b02323"},valueNotAck:{color:"#12ac15"}},xT=Y.forwardRef((a,s)=>g.jsx(Yk,{direction:"up",ref:s,...a}));xT.displayName="Transition";class Mc extends Xe{inputRef;constructor(s){super(s,Mc.getStaticData()),this.inputRef=Y.createRef()}static compile(s,i){let r=i.justCheck?kT:ST;return r=r.replace('"__%%DEBUG_TRIGGER%%__"',`_sendToFrontEnd(${s._id}, {val: obj.state.val, ack: obj.state.ack, valOld: obj.oldState && obj.oldState.val, ackOld: obj.oldState && obj.oldState.ack})`),`on({id: "${s.oid||""}", change: "${s.tagCard==="on update"?"any":"ne"}"}, ${r});`}renderDebug(s){return s.data.valOld!==void 0?g.jsxs("span",{children:[b.I18n.t("Triggered")," ",g.jsx("span",{style:s.data.ackOld?yn.valueAck:yn.valueNotAck,children:xn(s.data.valOld)})," ","→"," ",g.jsx("span",{style:s.data.ack?yn.valueAck:yn.valueNotAck,children:xn(s.data.val)})]}):g.jsxs("span",{children:[b.I18n.t("Triggered")," ",g.jsx("span",{style:s.data.ack?yn.valueAck:yn.valueNotAck,children:xn(s.data.val)})]})}onWriteValue(){this.setState({openSimulate:!1});let s=this.state.simulateValue;window.localStorage.setItem(`javascript.app.${this.state.settings.oid}_ack`,this.state.simulateAck?"true":"false"),this.state.settings.oidType==="boolean"?(s=s===!0||s==="true"||s==="1",window.localStorage.setItem(`javascript.app.${this.state.settings.oid}`,s?"true":"false")):this.state.settings.oidType==="number"?(s=parseFloat(s)||0,window.localStorage.setItem(`javascript.app.${this.state.settings.oid}`,s.toString())):window.localStorage.setItem(`javascript.app.${this.state.settings.oid}`,(s==null?void 0:s.toString())||""),this.props.socket.setState(this.state.settings.oid,{val:s,ack:!!this.state.simulateAck})}renderWriteState(){return[g.jsx(De,{disabled:!this.state.settings.oid||!this.state.enableSimulation,variant:"contained",color:"primary",onClick:()=>{this.setState({openSimulate:!0,simulateValue:this.state.settings.oidType==="boolean"?window.localStorage.getItem(`javascript.app.${this.state.settings.oid}`)==="true":window.localStorage.getItem(`javascript.app.${this.state.settings.oid}`)||"",simulateAck:window.localStorage.getItem(`javascript.app.${this.state.settings.oid}_ack`)==="true"}),setTimeout(()=>{var s;return(s=this.inputRef.current)==null?void 0:s.focus()},200)},children:b.I18n.t("Simulate")},"buttonWrite"),g.jsxs(Gt,{open:!!this.state.openSimulate,TransitionComponent:xT,keepMounted:!0,onClose:()=>this.setState({openSimulate:!1}),"aria-labelledby":"simulate-dialog-slide-title","aria-describedby":"simulate-dialog-slide-description",children:[g.jsx(as,{id:"simulate-dialog-slide-title",children:b.I18n.t("Trigger with value")}),g.jsxs(Vt,{children:[this.state.settings.oidType==="boolean"?g.jsx(Ag,{control:g.jsx(Rw,{inputRef:this.inputRef,onKeyUp:s=>s.key==="Enter"&&this.onWriteValue(),value:!!this.state.simulateValue,onChange:s=>this.setState({simulateValue:s.target.checked})}),label:b.I18n.t("Value")}):g.jsx(vo,{variant:"standard",inputRef:this.inputRef,label:b.I18n.t("Value"),fullWidth:!0,onKeyUp:s=>s.key==="Enter"&&this.onWriteValue(),value:!this.state.simulateValue&&this.state.simulateValue!==0?"":this.state.simulateValue,onChange:s=>this.setState({simulateValue:s.target.value})}),g.jsx("br",{}),g.jsx(Ag,{control:g.jsx(bc,{checked:!!this.state.simulateAck,onChange:s=>this.setState({simulateAck:s.target.checked}),color:"primary"}),label:b.I18n.t("Ack")})]}),g.jsxs(Kt,{children:[g.jsxs(De,{variant:"contained",onClick:()=>this.onWriteValue(),color:"primary",children:[g.jsx(wS,{}),b.I18n.t("Write")]}),g.jsxs(De,{color:"grey",variant:"contained",onClick:()=>this.setState({openSimulate:!1}),children:[g.jsx(Wc,{}),b.I18n.t("Close")]})]})]},"dialogWrite")]}onTagChange(s){this.setState({inputs:[{nameRender:"renderObjectID",attr:"oid",defaultValue:""},{nameRender:"renderWriteState"}]},()=>{super.onTagChange()})}static getStaticData(){return{acceptedBy:"triggers",name:"State",id:"TriggerState",icon:"FlashOn",tagCardArray:["on change","on update"],title:"Triggers the rule on update or change of some state"}}getData(){return Mc.getStaticData()}}const hO=""+new URL("hysteresis-CLhhemcG.png",import.meta.url).href,bw=`function __hysteresis(val, limit, state, hist, comp) { - let cond1, cond2; - if (comp === '>') { - cond1 = val > limit + hist; - cond2 = val <= limit - hist; - } else if (comp === '<') { - cond1 = val < limit - hist; - cond2 = val >= limit + hist; - } else if (comp === '>=') { - cond1 = val >= limit + hist; - cond2 = val < limit - hist; - } else if (comp === '<=') { - cond1 = val <= limit - hist; - cond2 = val > limit + hist; - } else if (comp === '=') { - cond1 = val <= limit + hist && val > limit - hist; - cond2 = val > limit + hist || val <= limit - hist; - } else if (comp === '<>') { - cond1 = val > limit + hist || val <= limit - hist; - cond2 = val <= limit + hist && val > limit - hist; - } - - if (!state && cond1) { - return true; - } else if (state && cond2) { - return false; - } else { - return state; - } -}`;class Hr extends Xe{constructor(s){super(s,Hr.getStaticData())}isAllTriggersOnState(){var s,i,r,l;return!!((i=(s=this.props.userRules)==null?void 0:s.triggers)!=null&&i.find(u=>u.id==="TriggerState"))&&!((l=(r=this.props.userRules)==null?void 0:r.triggers)!=null&&l.find(u=>u.id!=="TriggerState"))}static compile(s,i){var d,p;let r=s.value;r==null&&(r=!1);let l,u;if(s.tagCard==="()")i.prelines||=[],i.prelines.find(m=>m!==bw)||i.prelines.push(bw),s.useTrigger?(l="obj.state.val",r===""&&(r=0),u=`__hysteresis(subCondVar${s._id}, ${r}, __%%STATE%%__, ${s.hist}, "${s.histComp}")`):(l=`(await getStateAsync("${s.oid}")).val`,r===""&&(r=0),typeof r=="string"&&parseFloat(r.trim()).toString()!==r.trim()&&(r=`"${r}"`),u=`__hysteresis(subCondVar${s._id}, ${r}, __%%STATE%%__, ${s.hist}, "${s.histComp}")`);else if(s.tagCard!=="includes"){const m=s.tagCard==="="?"==":s.tagCard==="<>"?"!=":s.tagCard;s.useTrigger?(l="obj.state.val",((d=i==null?void 0:i.trigger)==null?void 0:d.oidType)==="string"?(r=r.replace(/"/g,'\\"'),u=`subCondVar${s._id} ${m} "${r}"`):(r===""&&(r=0),typeof r=="string"&&parseFloat(r.trim()).toString()!==r.trim()&&(r=`"${r}"`),u=`subCondVar${s._id} ${m} ${r}`)):(l=`(await getStateAsync("${s.oid}")).val`,s.oidType==="string"?(r=r.replace(/"/g,'\\"'),u=`subCondVar${s._id} ${m} "${r}"`):(r===""&&(r=0),typeof r=="string"&&parseFloat(r.trim()).toString()!==r.trim()&&(r=`"${r}"`),u=`subCondVar${s._id} ${m} ${r}`))}else s.useTrigger?(l="obj.state.val",((p=i==null?void 0:i.trigger)==null?void 0:p.oidType)==="string"?(r=r.replace(/"/g,'\\"'),u=`obj.state.val.includes("${r}")`):u="false"):(l=`(await getStateAsync("${s.oid}")).val`,s.oidType==="string"?(r=r.replace(/"/g,'\\"'),u=`subCondVar${s._id}.includes("${r}")`):u="false");return i.conditionsStates.push({name:`subCondVar${s._id}`,id:s.oid}),i.conditionsVars.push(`const subCondVar${s._id} = ${l};`),i.conditionsVars.push(`const subCond${s._id} = ${u};`),i.conditionsDebug.push(`_sendToFrontEnd(${s._id}, {result: subCond${s._id}, value: subCondVar${s._id}, compareWith: "${r}"});`),`subCond${s._id}`}renderDebug(s){const i=this.state.settings.tagCard;return i!=="()"?`${s.data.result.toString().toUpperCase()} [${s.data.value} ${i} ${s.data.compareWith}]`:b.I18n.t("Triggered")}onShowHelp=()=>this.setState({showHysteresisHelp:!0});_setInputs(s,i,r,l,u){var w,E;const d=this.isAllTriggersOnState();i=i||this.state.settings.tagCard,r=r||this.state.settings.oidType,l=l||this.state.settings.oidUnit,u=u||this.state.settings.oidStates,s===void 0&&(s=this.state.settings.useTrigger),d&&s&&((E=(w=this.props.userRules)==null?void 0:w.triggers)==null?void 0:E.length)===1&&(r=this.props.userRules.triggers[0].oidType,l=this.props.userRules.triggers[0].oidUnit,u=this.props.userRules.triggers[0].oidStates);const p=Hr.getStaticData().tagCardArray,m=p.find(R=>R.title===i)||p[0];let f,v=null;r==="number"?(f=[{title:"=",title2:"[equal]",text:"equal to"},{title:">=",title2:"[greater or equal]",text:"greater or equal"},{title:">",title2:"[greater]",text:"greater than"},{title:"<=",title2:"[less or equal]",text:"less or equal"},{title:"<",title2:"[less]",text:"less than"},{title:"<>",title2:"[not equal]",text:"not equal to"},{title:"()",title2:"[hysteresis]",text:"hysteresis"}],u&&(v=Object.keys(u).map(R=>u?{value:R,title:u[R]}:null).filter(R=>R))):r==="boolean"?(f=[{title:"=",title2:"[equal]",text:"equal to"},{title:"<>",title2:"[not equal]",text:"not equal to"}],v=[{title:"false",value:!1},{title:"true",value:!0}]):(f=[{title:"=",title2:"[equal]",text:"equal to"},{title:">=",title2:"[greater or equal]",text:"greater or equal"},{title:">",title2:"[greater]",text:"greater than"},{title:"<=",title2:"[less or equal]",text:"less or equal"},{title:"<",title2:"[less]",text:"less than"},{title:"<>",title2:"[not equal]",text:"not equal to"},{title:".",title2:"[includes]",text:"includes"}],u&&(v=Object.keys(u).map(R=>({value:R,title:u?u[R]:R.toString()}))));let _=null;f.find(R=>R.title===i)||(i=f[0].title,_=_||{...this.state.settings},_.tagCard=i);let y,k={nameRender:"renderText",defaultValue:"",attr:"value",frontText:i==="()"?"Limit":(m==null?void 0:m.text)||"compare with",doNotTranslateBack:!0,backText:l};v&&(k={nameRender:"renderSelect",defaultValue:v[0].value,options:v,attr:"value",frontText:(m==null?void 0:m.text)||"compare with",doNotTranslateBack:!0,backText:l},v.find(R=>R.value===this.state.settings.value)||(_=_||{...this.state.settings},_.value=v[0].value),v.length<=2&&(f=[{title:"=",title2:"[equal]",text:"equal to"},{title:"<>",title2:"[not equal]",text:"not equal to"}])),d&&s?y=[{backText:"use trigger value",nameRender:"renderCheckbox",attr:"useTrigger",defaultValue:!1},k]:d?y=[{backText:"use trigger value",nameRender:"renderCheckbox",attr:"useTrigger"},{nameRender:"renderObjectID",attr:"oid",defaultValue:""},k]:y=[{nameRender:"renderObjectID",attr:"oid",defaultValue:""},k],i==="()"&&(y.splice(1,0,{nameRender:"renderDialog",icon:"HelpOutline",frontText:"Explanation",onShowDialog:this.onShowHelp}),y.splice(2,0,{nameRender:"renderSelect",attr:"histComp",defaultValue:">",frontText:"Condition",doNotTranslate:!0,options:[{title:">",value:">"},{title:">=",value:">="},{title:"<",value:"<"},{title:"<=",value:"<="},{title:"=",value:"="},{title:"<>",value:"<>"}]}),y.push({frontText:"Δ",doNotTranslate:!0,nameRender:"renderNumber",noHelperText:!0,attr:"hist",defaultValue:1,doNotTranslateBack:!0,backText:l}));const C={iconTag:!0,tagCardArray:f,inputs:y};this.setState(C,()=>super.onTagChange(null,()=>{_&&(this.setState({settings:_}),this.props.onChange(_))}))}onValueChanged(s,i){typeof s=="object"?this._setInputs(s.useTrigger,s.tagCard,s.oidType,s.states):i==="useTrigger"?this._setInputs(s):i==="oidType"?this._setInputs(void 0,void 0,s):i==="oidUnit"?this._setInputs(void 0,void 0,void 0,s):i==="oidStates"&&this._setInputs(void 0,void 0,void 0,void 0,s)}onUpdate(){this._setInputs(this.state.settings.useTrigger)}onTagChange(s){this._setInputs(this.state.settings.useTrigger,s)}static getStaticData(){return{acceptedBy:"conditions",name:"State condition",id:"ConditionState",icon:"Shuffle",tagCardArray:[{title:"=",title2:"[equal]",text:"equal to"},{title:">=",title2:"[greater or equal]",text:"greater or equal"},{title:">",title2:"[greater]",text:"greater than"},{title:"<=",title2:"[less or equal]",text:"less or equal"},{title:"<",title2:"[less]",text:"less than"},{title:"<>",title2:"[not equal]",text:"not equal to"},{title:".",title2:"[includes]",text:"includes"},{title:"()",title2:"[hysteresis]",text:"hysteresis"}],title:"Compares the state value with user defined value"}}getData(){return Hr.getStaticData()}renderSpecific(){return this.state.showHysteresisHelp?g.jsxs(Gt,{open:!0,maxWidth:"md",onClose:()=>this.setState({showHysteresisHelp:!1}),"aria-labelledby":"alert-dialog-title","aria-describedby":"alert-dialog-description",children:[g.jsx(Vt,{children:g.jsx(Iw,{id:"alert-dialog-description",children:g.jsx("img",{src:hO,alt:"Hysteresis"})})}),g.jsx(Kt,{children:g.jsx(De,{onClick:()=>this.setState({showHysteresisHelp:!1}),color:"primary",autoFocus:!0,children:b.I18n.t("OK")})})]}):null}}const vw=[31,29,31,30,31,30,31,31,30,31,30,31];class Wr extends Xe{constructor(s){super(s,Wr.getStaticData())}static compile(s,i){const r=s.tagCard==="="?"===":s.tagCard==="<>"?"!==":s.tagCard;let l;if(s.withDate){const[u,d]=(s.date||"01.01").toString().split(".");let p=parseInt(d,10)||0,m=parseInt(u,10)||0;m>12?m=12:m<0&&(m=0),p>vw[m]?p=vw[m]:p<0&&(p=0),p&&m?l=`formatDate(Date.now(), 'MM.DD-hh:mm') ${r} "${s.date}-${s.time}"`:p===0&&m?l=`formatDate(Date.now(), 'MM-hh:mm') ${r} "${m.toString().padStart(2,"0")}-${s.time}"`:m===0&&p?l=`formatDate(Date.now(), 'DD-hh:mm') ${r} "${p.toString().padStart(2,"0")}-${s.time}"`:l=`formatDate(Date.now(), 'hh:mm') ${r} "${s.time}"`}else l=`formatDate(Date.now(), 'hh:mm') ${r} "${s.time}"`;return i.conditionsVars.push(`const subCond${s._id} = ${l};`),i.conditionsDebug.push(`_sendToFrontEnd(${s._id}, {result: subCond${s._id}});`),`subCond${s._id}`}_setInputs(s,i){i=i===void 0?this.state.settings.withDate:i,s=s||this.state.settings.tagCard;const r=Wr.getStaticData().tagCardArray,l=r==null?void 0:r.find(d=>d.title===s),u=[{nameRender:"renderNameText",attr:"interval",defaultValue:"Actual time of day"},{frontText:(l==null?void 0:l.text)||s,nameRender:"renderTime",attr:"time",defaultValue:"12:00"},{frontText:"with date",nameRender:"renderCheckbox",attr:"withDate",defaultValue:!1}];i&&u.push({nameRender:"renderDate",attr:"date",defaultValue:"01.01"}),this.setState({inputs:u,iconTag:!0},()=>super.onTagChange())}onValueChanged(s,i){i==="withDate"&&this._setInputs(void 0,s)}onTagChange(s){this._setInputs(s)}static getStaticData(){return{acceptedBy:"conditions",name:"Time condition",id:"ConditionTime",icon:"Shuffle",tagCardArray:[{title:"=",title2:"[equal]",text:"equal to"},{title:">=",title2:"[greater or equal]",text:"greater or equal"},{title:">",title2:"[greater]",text:"greater than"},{title:"<=",title2:"[less or equal]",text:"less or equal"},{title:"<",title2:"[less]",text:"less than"},{title:"<>",title2:"[not equal]",text:"not equal to"}],title:"Compares current time with the user specific time"}}getData(){return Wr.getStaticData()}}class Po extends Xe{coordinates=null;constructor(s){super(s,Po.getStaticData())}static compile(s,i){const r=s.tagCard==="="?"===":s.tagCard==="<>"?"!==":s.tagCard;let l;s.offset&&(l=parseInt(s.offsetValue,10)||0);const u=`formatDate(Date.now(), 'hh:mm') ${r} formatDate(getAstroDate("${s.astro}"${l?`, undefined, ${l}`:""}), 'hh:mm')`;return i.conditionsVars.push(`const subCond${s._id} = ${u};`),i.conditionsDebug.push(`_sendToFrontEnd(${s._id}, {result: ${u}});`),u}static _time2String(s){return s?`${s.getHours().toString().padStart(2,"0")}:${s.getMinutes().toString().padStart(2,"0")}`:"--:--"}onValueChanged(s,i){i==="astro"?this._setAstro(s):i==="offset"?this._setAstro(void 0,s):i==="offsetValue"&&this._setAstro(void 0,void 0,s)}async _setAstro(s,i,r){if(s=s||this.state.settings.astro||"solarNoon",i=i===void 0?this.state.settings.offset:i,r=r===void 0?this.state.settings.offsetValue:r,r=parseInt(r,10)||0,!this.coordinates){const v=await this.props.socket.getObject("system.adapter.javascript.0");if(!(v!=null&&v.native.latitude)&&!(v!=null&&v.native.longitude)){const _=await this.props.socket.getObject("system.config");_&&(_.common.latitude||_.common.longitude)?this.coordinates={latitude:_.common.latitude,longitude:_.common.longitude}:this.coordinates=null}else this.coordinates={latitude:v==null?void 0:v.native.latitude,longitude:v==null?void 0:v.native.longitude}}const l=this.coordinates?IT.getTimes(new Date,this.coordinates.latitude,this.coordinates.longitude):null,u=l?Object.keys(l).map(v=>({value:v,title:v,title2:`[${Po._time2String(l[v])}]`,order:Po._time2String(l[v])})):[];u.sort((v,_)=>v.order>_.order?1:v.order<_.order?-1:0);const d=Po.getStaticData().tagCardArray,p=d.find(v=>v.title===this.state.settings.tagCard)||d[0];let m="--:--";if(s&&l&&l[s]){const v=new Date(l[s]);i&&v.setMinutes(v.getMinutes()+parseInt(r,10)),m=`(${b.I18n.t(p.text)} ${Po._time2String(v)})`}let f;i?f=[{nameRender:"renderNameText",defaultValue:"Actual time of day",attr:"text"},{frontText:p.text,attr:"astro",nameRender:"renderSelect",options:u,doNotTranslate2:!0,defaultValue:"solarNoon"},{backText:"with offset",nameRender:"renderCheckbox",attr:"offset"},{backText:r===1?"minute":"minutes",frontText:"offset",nameRender:"renderNumber",defaultValue:0,attr:"offsetValue",noHelperText:!0},{nameRender:"renderNameText",attr:"textTime",doNotTranslate:!0,defaultValue:m}]:f=[{nameRender:"renderNameText",defaultValue:"Actual time of day",attr:"text"},{frontText:p.text,attr:"astro",nameRender:"renderSelect",options:u,doNotTranslate2:!0,defaultValue:"solarNoon"},{backText:"with offset",nameRender:"renderCheckbox",attr:"offset"},{nameRender:"renderNameText",attr:"textTime",doNotTranslate:!0,defaultValue:m}],this.setState({inputs:f},()=>super.onTagChange())}onTagChange(){this._setAstro()}static getStaticData(){return{acceptedBy:"conditions",name:"Astronomical",id:"ConditionAstronomical",icon:"Brightness3",tagCardArray:[{title:"=",title2:"[equal]",text:"equal to"},{title:">=",title2:"[greater or equal]",text:"greater or equal to"},{title:">",title2:"[greater]",text:"greater than"},{title:"<=",title2:"[less or equal]",text:"less or equal to"},{title:"<",title2:"[less]",text:"less than"},{title:"<>",title2:"[not equal]",text:"not equal to"}],title:"Compares current time with astronomical event"}}getData(){return Po.getStaticData()}}const yw={valueAck:{color:"#b02323"},valueNotAck:{color:"#12ac15"}};class Nc extends Xe{constructor(s){super(s,Nc.getStaticData())}isAllTriggersOnState(){var s,i,r,l;return!!((i=(s=this.props.userRules)==null?void 0:s.triggers)!=null&&i.find(u=>u.id==="TriggerState"))&&!((l=(r=this.props.userRules)==null?void 0:r.triggers)!=null&&l.find(u=>u.id!=="TriggerState"))}static compile(s,i){let r=s.value;s.useTrigger?r=s.toggle?"!obj.state.val":"obj.state.val":(r==null&&(r=""),typeof s.value=="string"&&parseFloat(s.value).toString()!==s.value&&s.value!=="true"&&s.value!=="false"&&(r=`"${r.replace(/"/g,'\\"')}"${Xe.getReplacesInText(i)}`));let l;return s.toggle&&!s.useTrigger?l=`const subActionVar${s._id} = !(await getStateAsync("${s.oid}")).val`:l=`const subActionVar${s._id} = ${r}`,`// set state ${s.oid} to ${s.toggle&&!s.useTrigger?"toggle":r} - ${l}; - _sendToFrontEnd(${s._id}, {val: subActionVar${s._id}, ack: ${s.tagCard==="update"}}); - await setStateAsync("${s.oid}", subActionVar${s._id}, ${s.tagCard==="update"});`}renderDebug(s){return g.jsxs("span",{children:[b.I18n.t("Set:")," ",g.jsx("span",{style:s.data.ack?yw.valueAck:yw.valueNotAck,children:xn(s.data.val)})]})}_setInputs(s,i){const r=this.isAllTriggersOnState();i=i===void 0?this.state.settings.toggle:i,s=s===void 0?this.state.settings.useTrigger:s;let l="",u;const{oidType:d,oidUnit:p,oidStates:m,oidMax:f,oidMin:v,oidRole:_,oidWrite:y,oidStep:k}=this.state.settings;let C;d&&(d==="number"?(l="number",f!==void 0&&v!==void 0&&(l="slider")):d==="boolean"?(l="boolean",_&&_.includes("button")&&y&&(l="button")):(l="",_&&_.includes("color")&&(l="color")),m&&(u=Object.keys(m).map(E=>({value:E,title:m[E]})),l="select"));let w;if(r&&s)w=[{backText:"use trigger value",nameRender:"renderCheckbox",attr:"useTrigger",defaultValue:!1}],l==="boolean"&&w.push({backText:"toggle value",attr:"toggle",nameRender:"renderCheckbox",defaultValue:!1});else{switch(l){case"number":w=[{backText:p||"",frontText:"with",nameRender:"renderNumber",defaultValue:f===void 0?0:f,attr:"value"}],this.state.settings.value!==void 0&&isNaN(parseFloat(this.state.settings.value))&&(C={value:f===void 0?0:f});break;case"slider":{w=[{nameRender:"renderSlider",defaultValue:f,min:v,max:f,unit:p,step:k,attr:"value"}];const E=parseFloat(this.state.settings.value);this.state.settings.value!==void 0&&(isNaN(E)||Ef)&&(C={value:f});break}case"select":w=[{nameRender:"renderSelect",frontText:"with",options:u,defaultValue:(u==null?void 0:u[0].value)||"",attr:"value"}],this.state.settings.value!==void 0&&!(u!=null&&u.find(E=>E.value===this.state.settings.value))&&(C={value:(u==null?void 0:u[0].value)||""});break;case"boolean":w=[{backText:"toggle value",attr:"toggle",nameRender:"renderCheckbox",defaultValue:!1}],i||w.push({backText:"true",frontText:"false",nameRender:"renderSwitch",defaultValue:!1,attr:"value"}),this.state.settings.value!==void 0&&this.state.settings.value!==!1&&this.state.settings.value!==!0&&(C={value:!1});break;case"button":w=[{nameRender:"renderButton",defaultValue:!0,attr:"value"}],this.state.settings.value!==void 0&&this.state.settings.value!==!0&&(C={value:!0});break;case"color":w=[{nameRender:"renderColor",frontText:"with",defaultValue:"#FFFFFF",attr:"value"}],this.state.settings.value!==void 0&&(typeof this.state.settings.value!="string"||!this.state.settings.value.startsWith("#")&&!this.state.settings.value.startsWith("rgb"))&&(C={value:"#FFFFFF"});break;default:w=[{backText:p||"",frontText:"with",nameRender:"renderText",defaultValue:"",attr:"value"}];break}r&&w.unshift({backText:"use trigger value",nameRender:"renderCheckbox",attr:"useTrigger"})}return{inputs:w,newSettings:C}}onTagChange(s,i,r,l,u){u=u===void 0?this.state.settings.useTrigger:u;const{inputs:d,newSettings:p}=this._setInputs(u,l);d.unshift({nameRender:"renderObjectID",attr:"oid",defaultValue:"",checkReadOnly:!0}),this.setState({inputs:d},()=>super.onTagChange(null,()=>{if(p){const m=JSON.parse(JSON.stringify(this.state.settings));Object.assign(m,p),this.setState(m),this.props.onChange(m)}}))}onValueChanged(s,i){this.onTagChange(void 0,void 0,void 0,i==="toggle"?s:void 0,i==="useTrigger"?s:void 0)}onUpdate(){this.onTagChange()}static getStaticData(){return{acceptedBy:"actions",name:"Set state action",id:"ActionSetState",icon:"PlayForWork",tagCardArray:["control","update"],title:"Control or update some state",helpDialog:"You can use %s in the value to use the current trigger value or %id to display the triggered object ID"}}getData(){return Nc.getStaticData()}}class Lc extends Xe{constructor(s){super(s,Lc.getStaticData())}static compile(s,i){return`// exec "${s.exec}" - const subActionVar${s._id} = "${(s.exec||"").replace(/"/g,'\\"')}"${Xe.getReplacesInText(i)}; - _sendToFrontEnd(${s._id}, {exec: subActionVar${s._id}}); - console.log(subActionVar${s._id});`}renderDebug(s){return`Exec: ${s.data.exec}`}onTagChange(s){this.setState({inputs:[{nameRender:"renderModalInput",attr:"exec",defaultValue:"ls /opt/iobroker",nameBlock:"Shell command"}]},()=>super.onTagChange(s))}static getStaticData(){return{acceptedBy:"actions",name:"Exec",id:"ActionExec",icon:"Apps",title:"Executes some shell command",helpDialog:"You can use %s in the command to use current trigger value or %id to use the triggered object ID"}}getData(){return Lc.getStaticData()}}class Pc extends Xe{constructor(s){super(s,Pc.getStaticData())}static compile(s,i){return`// HTTP request ${s.url} - const subActionVar${s._id} = "${(s.url||"").replace(/"/g,'\\"')}"${Xe.getReplacesInText(i)}; - _sendToFrontEnd(${s._id}, {url: subActionVar${s._id}}); - request(subActionVar${s._id});`}renderDebug(s){return`URL: ${s.data.url}`}onTagChange(s){this.setState({inputs:[{nameRender:"renderModalInput",attr:"url",defaultValue:"http://mydevice.com?...",nameBlock:"URL"}]},()=>super.onTagChange(s))}static getStaticData(){return{acceptedBy:"actions",name:"HTTP Call",id:"ActionHTTPCall",icon:"Language",title:"Make a HTTP get request",helpDialog:"You can use %s in the URL to use current trigger value or %id to use the triggered object ID"}}getData(){return Pc.getStaticData()}}class Bc extends Xe{constructor(s){super(s,Bc.getStaticData())}static compile(s,i){return`// Log ${s.text} - const subActionVar${s._id} = "${(s.text||"").replace(/"/g,'\\"')}"${Xe.getReplacesInText(i)}; - _sendToFrontEnd(${s._id}, {text: subActionVar${s._id}}); - console.log(subActionVar${s._id});`}renderDebug(s){return b.I18n.t("Log: %s",s.data.text)}onTagChange(){this.setState({inputs:[{nameRender:"renderModalInput",attr:"text",defaultValue:"My device triggered",nameBlock:"Log text"}]},()=>super.onTagChange())}static getStaticData(){return{acceptedBy:"actions",name:"Log text",id:"ActionPrintText",icon:"Subject",title:"Print some text in log",helpDialog:"You can use %s in the text to display current trigger value or %id to display the triggered object ID"}}getData(){return Bc.getStaticData()}}class jc extends Xe{constructor(s){super(s,jc.getStaticData())}static compile(s){const i=s.unit==="ms"?1:s.unit==="s"?1e3:s.unit==="m"?6e4:36e5;return`// pause for ${i}ms - _sendToFrontEnd(${s._id}, {paused: true}); - - await wait(${s.pause} * ${i}); - - _sendToFrontEnd(${s._id}, {paused: false});`}renderDebug(s){return b.I18n.t("Paused: %s",s.data.paused)}_getOptions(s){return s=s===void 0?this.state.settings.pause:s,s===1||s==="1"?[{value:"ms",title:"millisecond"},{value:"s",title:"second"},{value:"m",title:"minute"},{value:"h",title:"hour"}]:[{value:"ms",title:"milliseconds"},{value:"s",title:"seconds"},{value:"m",title:"minutes"},{value:"h",title:"hours"}]}_setInputs(s){this.setState({inputs:[{nameRender:"renderNumber",attr:"pause",defaultValue:100,noHelperText:!0},{nameRender:"renderSelect",attr:"unit",defaultValue:"ms",options:this._getOptions(s)}]},()=>super.onTagChange())}onValueChanged(s,i){i==="pause"&&this._setInputs(s)}onTagChange(){this._setInputs()}static getStaticData(){return{acceptedBy:"actions",name:"Pause",id:"ActionPause",icon:"Pause",title:"Make a pause between actions"}}getData(){return jc.getStaticData()}}class Fc extends Xe{constructor(s){super(s,Fc.getStaticData())}static compile(s){const i=(s.func||"").split(` -`).map(r=>` ${r}`);return i.unshift(` _sendToFrontEnd(${s._id}, {func: 'executed'});`),i.unshift("// user function"),i.join(` -`)}renderDebug(){return b.I18n.t("Function: executed")}onTagChange(s){this.setState({inputs:[{nameRender:"renderModalInput",attr:"func",noTextEdit:!0,defaultValue:'console.log("Test")',nameBlock:"Function"}]},()=>super.onTagChange(s))}static getStaticData(){return{acceptedBy:"actions",name:"User function",id:"ActionFunction",icon:"Functions",title:"Write your own code",helpDialog:"This is advances option. You can write your own code here and it will be executed on trigger"}}getData(){return Fc.getStaticData()}}class zc extends Xe{constructor(s){super(s,zc.getStaticData())}isAllTriggersOnState(){var s,i,r,l;return!!((i=(s=this.props.userRules)==null?void 0:s.triggers)!=null&&i.find(u=>u.id==="TriggerState"))&&!((l=(r=this.props.userRules)==null?void 0:r.triggers)!=null&&l.find(u=>u.id!=="TriggerState"))}static compile(s,i){let r=s.value;s.useTrigger?r=s.toggle?"!obj.state.val":"obj.state.val":(r==null&&(r=""),typeof s.value=="string"&&parseFloat(s.value).toString()!==s.value&&s.value!=="true"&&s.value!=="false"&&(r=`"${r.replace(/"/g,'\\"')}"${Xe.getReplacesInText(i)}`));let l;return s.toggle&&!s.useTrigger?l=`const subActionVar${s._id} = !(await getStateAsync("${s.oid}")).val`:l=`const subActionVar${s._id} = ${r}`,`// set delayed state ${s.oid} to ${s.toggle&&!s.useTrigger?"toggle":r} with delay of ${s.delay}ms - ${l}; - _sendToFrontEnd(${s._id}, {val: subActionVar${s._id}, ack: ${s.tagCard==="update"}}); - setStateDelayed("${s.oid}", subActionVar${s._id}, ${s.tagCard==="update"}, ${parseInt(s.delay,10)}, ${s.clearRunning?"true":"false"});`}renderDebug(s){var i,r;return g.jsxs("span",{children:[b.I18n.t("Set:")," ",g.jsx("span",{className:s.data.ack?(i=this.props.classes)==null?void 0:i.valueAck:(r=this.props.classes)==null?void 0:r.valueNotAck,children:xn(s.data.val)})]})}_setInputs(s,i){const r=this.isAllTriggersOnState();i=i===void 0?this.state.settings.toggle:i,s=s===void 0?this.state.settings.useTrigger:s;let l="",u;const{oidType:d,oidUnit:p,oidStates:m,oidMax:f,oidMin:v,oidRole:_,oidWrite:y,oidStep:k}=this.state.settings;let C;d&&(d==="number"?(l="number",f!==void 0&&v!==void 0&&(l="slider")):d==="boolean"?(l="boolean",_&&_.includes("button")&&y&&(l="button")):(l="",_&&_.includes("color")&&(l="color")),m&&(u=Object.keys(m).map(E=>({value:E,title:m[E]})),l="select"));let w;if(r&&s)w=[{backText:"use trigger value",nameRender:"renderCheckbox",attr:"useTrigger",defaultValue:!1}],l==="boolean"&&w.push({backText:"toggle value",attr:"toggle",nameRender:"renderCheckbox",defaultValue:!1});else{switch(l){case"number":w=[{backText:p||"",frontText:"with",nameRender:"renderNumber",defaultValue:f===void 0?0:f,attr:"value"}],this.state.settings.value!==void 0&&isNaN(parseFloat(this.state.settings.value))&&(C={value:f===void 0?0:f});break;case"slider":{w=[{nameRender:"renderSlider",defaultValue:f,min:v,max:f,unit:p,step:k,attr:"value"}];const E=parseFloat(this.state.settings.value);this.state.settings.value!==void 0&&(isNaN(E)||Ef)&&(C={value:f});break}case"select":w=[{nameRender:"renderSelect",frontText:"with",options:u,defaultValue:(u==null?void 0:u[0].value)||"",attr:"value"}],this.state.settings.value!==void 0&&!(u!=null&&u.find(E=>E.value===this.state.settings.value))&&(C={value:(u==null?void 0:u[0].value)||""});break;case"boolean":w=[{backText:"toggle value",attr:"toggle",nameRender:"renderCheckbox",defaultValue:!1}],i||w.push({backText:"true",frontText:"false",nameRender:"renderSwitch",defaultValue:!1,attr:"value"}),this.state.settings.value!==void 0&&this.state.settings.value!==!1&&this.state.settings.value!==!0&&(C={value:!1});break;case"button":w=[{nameRender:"renderButton",defaultValue:!0,attr:"value"}],this.state.settings.value!==void 0&&this.state.settings.value!==!0&&(C={value:!0});break;case"color":w=[{nameRender:"renderColor",frontText:"with",defaultValue:"#FFFFFF",attr:"value"}],this.state.settings.value!==void 0&&(typeof this.state.settings.value!="string"||!this.state.settings.value.startsWith("#")&&!this.state.settings.value.startsWith("rgb"))&&(C={value:"#FFFFFF"});break;default:w=[{backText:p||"",frontText:"with",nameRender:"renderText",defaultValue:"",attr:"value"}];break}r&&w.unshift({backText:"use trigger value",nameRender:"renderCheckbox",attr:"useTrigger"})}return w.push({backText:"ms",frontText:"Delay",nameRender:"renderNumber",defaultValue:1e3,noHelperText:!0,attr:"delay"}),w.push({backText:"clear running",nameRender:"renderCheckbox",defaultValue:!0,attr:"clearRunning"}),{inputs:w,newSettings:C}}onTagChange(s,i,r,l,u){u=u===void 0?this.state.settings.useTrigger:u;const{inputs:d,newSettings:p}=this._setInputs(u,l);d.unshift({nameRender:"renderObjectID",attr:"oid",defaultValue:"",checkReadOnly:!0}),this.setState({inputs:d},()=>super.onTagChange(null,()=>{if(p){const m=JSON.parse(JSON.stringify(this.state.settings));Object.assign(m,p),this.setState(m),this.props.onChange(m)}}))}onValueChanged(s,i){this.onTagChange(void 0,void 0,void 0,i==="toggle"?s:void 0,i==="useTrigger"?s:void 0)}onUpdate(){this.onTagChange()}static getStaticData(){return{acceptedBy:"actions",name:"Set with delay",id:"ActionSetStateDelayed",icon:"PlayForWork",tagCardArray:["control","update"],title:"Control or update some state with delay",helpDialog:"You can use %s in the value to use the current trigger value or %id to display the triggered object ID"}}getData(){return zc.getStaticData()}}class Uc extends Xe{constructor(s){super(s,Uc.getStaticData())}isAllTriggersOnState(){var s,i,r,l;return!!((i=(s=this.props.userRules)==null?void 0:s.triggers)!=null&&i.find(u=>u.id==="TriggerState"))&&!((l=(r=this.props.userRules)==null?void 0:r.triggers)!=null&&l.find(u=>u.id!=="TriggerState"))}static compile(s){const i=`const val2_${s._id} = (await getStateAsync("${s.oid1}")).val;`,r=`const val1_${s._id} = (await getStateAsync("${s.oid2}")).val;`;return`// ${s.oid1} ${s.operation} ${s.oid2} => ${s.oidResult} - ${i} - ${r} - _sendToFrontEnd(${s._id}, {val: val1_${s._id} ${s.operation} val2_${s._id}, ack: ${s.tagCard==="update"}}); - await setStateAsync("${s.oidResult}", val1_${s._id} ${s.operation} val2_${s._id}, ${s.tagCard==="update"});`}renderDebug(s){var i,r;return g.jsxs("span",{children:[b.I18n.t("Set:")," ",g.jsx("span",{className:s.data.ack?(i=this.props.classes)==null?void 0:i.valueAck:(r=this.props.classes)==null?void 0:r.valueNotAck,children:xn(s.data.val)})]})}onTagChange(){const s=[];s.push({nameRender:"renderObjectID",title:"ID1",attr:"oid1",defaultValue:"",checkReadOnly:!1}),s.push({nameRender:"renderSelect",options:[{value:"+",title:"+"},{value:"-",title:"-"},{value:"*",title:"*"},{value:"/",title:"/"}],doNotTranslate:!0,defaultValue:"+",attr:"operation"}),s.push({nameRender:"renderObjectID",title:"ID2",attr:"oid2",defaultValue:"",checkReadOnly:!1}),s.push({nameRender:"renderNameText",defaultValue:"store in",attr:"textEqual"}),s.push({nameRender:"renderObjectID",attr:"oidResult",defaultValue:"",checkReadOnly:!0}),this.setState({inputs:s},()=>super.onTagChange(null,()=>{const i=JSON.parse(JSON.stringify(this.state.settings));this.props.onChange(i)}))}onValueChanged(s,i){this.onTagChange()}onUpdate(){this.onTagChange()}static getStaticData(){return{acceptedBy:"actions",name:"Operate two states",id:"ActionOperateStates",icon:"AddBox",tagCardArray:["control","update"],title:"Operations with two states"}}getData(){return Uc.getStaticData()}}const pO=[vi,Oc,Mc,Hr,Wr,Po,Nc,Lc,Pc,Bc,jc,Fc,zc,Uc],cc={sayit:xc,pushover:Dc,"whatsapp-cmb":Ac,pushsafer:Rc},gO=rm({blocks:null,socket:null,onUpdate:!1,setOnUpdate:a=>{},setOnDebugMessage:a=>{},onDebugMessage:[],enableSimulation:!1,setEnableSimulation:a=>{},changedScripts:{},setChangedScripts:a=>{}}),mO=({children:a,socket:s})=>{const[i,r]=vt(null),[l,u]=vt(!1),[d,p]=vt([]),[m,f]=vt(!1),[v,_]=vt({});return Mt(()=>{l&&u(!1)},[l]),Mt(()=>{(async()=>{const y=await s.getAdapterInstances(),k=Object.keys(cc).filter(D=>y.find(A=>{var J;return((J=A==null?void 0:A.common)==null?void 0:J.name)===D})),C=[],w=y.filter(D=>D.common.javascriptRules),E=[];for(const D of w){if(E.includes(D.common.name)||!D.common.javascriptRules)continue;let A;if(D.common.javascriptRules.url.startsWith("http:")||D.common.javascriptRules.url.startsWith("https:")?A=D.common.javascriptRules.url:D.common.javascriptRules.url.startsWith("./")?A=`${window.location.protocol}//${window.location.host}${D.common.javascriptRules.url.replace(/^\./,"")}`:A=`${window.location.protocol}//${window.location.host}/adapter/${D.common.name}/${D.common.javascriptRules.url}`,D.common.javascriptRules.i18n===!0){const J=A.lastIndexOf("/");let ie;J!==-1?ie=A.substring(0,J):ie=A;const se=b.I18n.getLanguage(),me=`${ie}/i18n/${se}.json`;await fetch(me).then(z=>z.json()).then(z=>b.I18n.extendTranslations(z,se)).catch(z=>{if(se!=="en")return fetch(`${ie}/i18n/en.json`).then(Oe=>Oe.json()).then(Oe=>b.I18n.extendTranslations(Oe,se)).catch(Oe=>console.error(`Cannot load i18n "${me}": ${Oe}`));console.log(`Cannot load i18n "${me}": ${z}`)})}else if(D.common.javascriptRules.i18n&&typeof D.common.javascriptRules.i18n=="object")try{b.I18n.extendTranslations(D.common.javascriptRules.i18n)}catch(J){console.error(`Cannot import i18n for "${D.common.javascriptRules.name}": ${J}`)}try{Xy.registerRemotes([{name:D.common.javascriptRules.name,entry:A,type:D.common.javascriptRules.type}]);const J=(await Xy.loadRemote(`${D.common.javascriptRules.name}/${D.common.javascriptRules.name}`)).default;J&&(C.push(J),E.push(D.common.name),cc[D.common.name]=null)}catch(J){console.error(`Cannot load component "${D.common.javascriptRules.name}": ${J}`)}}const R=k.filter(D=>cc[D]).map(D=>cc[D]);r([...pO,...R,...C])})()},[]),g.jsx(gO.Provider,{value:{blocks:i,socket:s,onUpdate:l,setOnUpdate:u,onDebugMessage:d,setOnDebugMessage:p,enableSimulation:m,setEnableSimulation:f,changedScripts:v,setChangedScripts:_},children:a})},fO="Acknowledged",$O="Actions",bO="Add",vO="All",yO="Any",_O="Apply",wO="April",CO="Ask",TO="Astronomical",kO="August",SO="Cancel",EO="Close",IO="Condition",xO="Conditions",DO="Console",AO="Copied",RO="December",OO="Default",MO="Delay",NO="Delete",LO="Description",PO="Done",BO="Exec shell",jO="Explanation",FO="Export",zO="Februar",UO="February",HO="Filter",WO="Folder",GO="Fr",VO="Friday",KO="ID",YO="ID1",JO="ID2",qO="Import",XO="Instance",ZO="Instances",QO="Instructions",eM="Januar",tM="January",sM="July",oM="June",iM="Limit",nM="March",rM="May",aM="Menu",lM="Message",cM="Mo",uM="Model",dM="Monday",hM="Month",pM="More",gM="Name",mM="November",fM="OK",$M="October",bM="Ok",vM="Pause",yM="Pushover",_M="Pushsafer",wM="Rename",CM="Repeat",TM="Restart",kM="Result",SM="Sa",EM="Saturday",IM="Save",xM="Schedule",DM="Script",AM="September",RM="Simulate",OM="Stack",MM="Start",NM="State",LM="Su",PM="Sunday",BM="Telegram",jM="Th",FM="Thursday",zM="Time",UM="Triggered",HM="Triggers",WM="Tu",GM="Tuesday",VM="URL",KM="Value",YM="Volume",JM="We",qM="Wednesday",XM="Write",ZM="Yes",QM="acknowledgment",eN="all",tN="and",sN="Astro",oN="at",iN="control",nN="copy",rN="CRON",aN="Dawn",lN="This is a special mode in which states and objects will not change. But only information about each planned change will be displayed in the protocol.",cN="Debug",uN="Dusk",dN="easy",hN="every",pN="Function",gN="ID",mN="Name",fN="Role",$N="Room",bN="Golden hour",vN="End of golden hour",yN='The code will be executed only every time when condition is true. E.g. if triggering on the temperature sensor value and the condition is "if temperature is greater than 20°C", the "then" actions will be executed every time when sensor sends the temperature and it is over 20°C. By 21°C, by 22°C and so on.',_N='The code will be executed only if the condition result changes. E.g. if triggering on the temperature sensor value and the condition is "if temperature is greater than 20°C", the "then" actions will be executed once when temperature is over 20. Next time the "then" actions will be executed when the temperature fails under 20 and then rises over 20 again.',wN="hours",CN="includes",TN="interval",kN="magic",SN="milliseconds",EN="minutes",IN="ms",xN="Nadir",DN="Nautical dawn",AN="Nautical dusk",RN="Next Sunrise",ON="Next sunset",MN="Night",NN="Night end",LN="normal",PN="offset",BN="one",jN="or",FN="quiet",zN="search",UN="seconds",HN="Solar noon",WN="sunrise",GN="Sunrise end",VN="Sunset",KN="Sunset start",YN="then",JN="Acknowledge",qN="From",XN="Last changed",ZN="Quality",QN="Timestamp",eL="User",tL="Value",sL="two",oL="update",iL="Adds debug output to the log for many system commands",nL="Verbose log outputs",rL="when",aL="Wizard",lL="Retry",cL={"%s not found":"%s not found","()":"()","(at %s)":"(at %s)","(optional)":"(optional)","-":"-",".":".","AI code generator":"AI code generator","Planning...":"Planning...","Generating code...":"Generating code...","Show plan":"Show plan",Ack:fO,Actions:$O,"Actual time of day":"Actual time of day",Add:bO,"Add new script":"Add new script",All:vO,"All files will be accepted":"All files will be accepted",Any:yO,"Any month":"Any month",Apply:_O,April:wO,"Are you sure?":"Are you sure?",Ask:CO,Astronomical:TO,"Astronomical events today":"Astronomical events today",August:kO,"Blockly description":"Creating rules by graphic blocks","Body:":"Body:",Cancel:SO,"Cannot delete non empty item!":"Cannot delete non empty item!","Change layout":"Change layout",'Change theme (actual "%s")':'Change theme (now - "%s")',"Check blocks":"Check blocks","Check is not active, because javascript adapter is disabled":"Check is not active, because Javascript adapter is disabled","Clear search input":"Clear search input","Click on this icon":"Click on this icon",Close:EO,"Close all but current":"Close all but current","Collapse all":"Collapse all","Compares current time with astronomical event":"Compares current time with astronomical event","Compares current time with the user specific time":"Compares current time with the user specific time","Compares the state value with user defined value":"Compares the state value with user defined value",Condition:IO,Conditions:xO,"Configuration not saved.":"Configuration not saved.",Console:DO,"Control or update some state":"Control or update some state","Control or update some state with delay":"Control or update some state with delay","Convert blockly to javascript for ever.":"Permanently convert Blockly to Javascript.",Copied:AO,"Copy script":"Copy script","Copy to clipboard":"Copy to clipboard","Create new":"Create new","Create new folder":"Create new folder","Create new script":"Create new script","Create or edit CRON or time wizard":"Create or edit CRON or time wizard","Dark Theme":"Dark theme","Dark style":"Dark style",Date:"Date","Debug instance":"Debug instance","Debug options":"Debug options",December:RO,Default:OO,"Define cron...":"Define cron...","Define schedule...":"Define schedule...",Delay:MO,Delete:NO,"Delete %s":"Delete %s...","Delete folder":"Delete folder","Delete script":"Delete script",Description:LO,"Deselect all":"Deselect all","Discard changes for %s":"Discard changes for %s",Done:PO,"Double click to write value":"Double click to write value","Download as file":"Download as file","Drop some files here or click...":"Drop some files here or click...","Duplicate name":"Duplicate name","Edit script or just double click":"Edit script or just double click","Empty name is not allowed":"Empty name is not allowed","End search mode":"End search mode","Enter your question":"Enter your request",Error:"Error","Error formatting code":"Error formatting code","Error was found":"Error was found","Every day":"Every day",Exec:BO,"Executes some shell command":"Executes some shell command","Existing scripts will be overwritten.":"Existing scripts will be overwritten.","Expand all":"Expand all","Expert mode":"Expert mode",Explanation:jO,Export:FO,"Export all scripts":"Export all scripts","Export blocks":"Export blocks","Export selected blocks":"Export selected blocks",Februar:zO,February:UO,Filter:HO,Folder:WO,Fr:GO,Friday:VO,Function:"Function","Function editor":"Function editor","Function: executed":"Function: executed","Go to next line":"Go to next line","HTTP Call":"HTTP Call","Hide logs":"Hide logs",ID:KO,ID1:YO,ID2:JO,Import:qO,"Import blocks":"Import blocks","Import error":"Import error","Import scripts":"Import scripts","Insert object ID":"Insert object ID",Instance:XO,"Instance is disabled":"Instance is disabled","Instance:":"Instance:",Instances:ZO,Instructions:QO,"Invalid CRON":"Invalid CRON","It will not be possible to revert this operation.":"It will not be possible to revert this operation.","JS description":"Creating rules by writing Javascript",Januar:eM,January:tM,July:sM,June:oM,"Just check":"Just check","Language:":"Language:","Learn More":"Learn More","Light style":"Light style",Limit:iM,"Local time":"Local time","Locate file":"Locate file","Log outputs":"Log outputs","Log text":"Log text","Log: %s":"Log: %s","Make a HTTP get request":"Make a HTTP get request","Make a pause between actions":"Make a pause between actions",March:nM,"March ":"March ",May:rM,Menu:aM,Message:lM,Mo:cM,Model:uM,Monday:dM,Month:hM,More:pM,Name:gM,"No API key found":"No API key found","No Chat GPT Key found":"No Chat GPT Key found","No active host found":"No active host found","Nothing found":"Nothing found",November:mM,OK:fM,October:$M,Ok:bM,"On condition change":"On condition result change","On script save or adapter start":"On script save or adapter start","On weekdays":"On weekdays","Open configuration":"Open configuration","Operate two states":"Operate two states","Operations with two states":"Operations with two states","Paste your blocks here":"Paste your blocks here",Pause:vM,"Pause execution":"Pause execution","Pause script":"Pause script","Phone:":"Phone:","Please select object ID...":"Please select object ID...","Press Ctrl+Enter to get the answer":"Press Ctrl+Enter to get the answer","Prettify the script":"Prettify the script","Print some text in log":"Print some text in log","Priority:":"Priority:",Pushover:yM,Pushsafer:_M,"Read only ID selected: %s":"Read only ID selected: %s",Rename:wM,"Reorder scripts in folders":"Reorder scripts in folders",Repeat:CM,Restart:TM,Result:kM,"Resume execution":"Resume execution","Root folder":"Root folder","Rules description":"Create rules with IF, THEN, ELSE blocks","Run script":"Run script",Sa:SM,Saturday:EM,Save:IM,"Save all":"Save all","Say It":"Say It","Say some text via sayit adapter":"Say some text via sayit adapter",Schedule:xM,Script:DM,"Script %s was modified on disk":"Script %s was modified on disk","Script is not running":"Script is not running","Search in scripts":"Search in scripts","Search...":"Search...","Select all":"Select all","Send email":"Send email","Sends an email":"Sends an email","Sends message via Pushsafer":"Sends message via Pushsafer","Sends message via pushover":"Sends message via pushover","Sends message via telegram":"Sends message via telegram","Sends message via whatsapp-cmb":"Sends message via whatsapp-cmb",September:AM,"Server time":"Server time","Set state action":"Set state action","Set with delay":"Set with delay","Shell command":"Shell command","Show astronomical events":"Show astronomical events","Show javascript code":"Show Javascript code","Show logs":"Show logs","Show only paused scripts":"Show only paused scripts","Show only running scripts":"Show only running scripts","Show only scripts with problems":"Show only scripts with problems",Simulate:RM,"Some files will be rejected":"Some files will be rejected","Sound:":"Sound:",Stack:OM,Start:MM,"Start script":"Start script",State:NM,"State condition":"State condition","Step into function":"Step into function","Step out from function":"Step out from function","Stop on exception":"Stop on exception",Su:LM,"Subject:":"Subject:",Sunday:PM,"TS description":"Creating rules by writing Typescript",Telegram:BM,"Text:":"Text:",Th:jM,"The script will be stopped and must be activated manually after debugging. Continue?":"The script will be stopped and must be activated manually after debugging. Continue?","This is advances option. You can write your own code here and it will be executed on trigger":"This is advances option. You can write your own code here and it will be executed on trigger",Thursday:FM,Time:zM,"Time condition":"Time condition","Title:":"Title:","To:":"To:","Trigger with value":"Trigger with value",Triggered:UM,Triggers:HM,"Triggers the on script saving or the javascript instance restart":"Triggers the on script saving or the javascript instance restart","Triggers the rule on update or change of some state":"Triggers the rule on update or change of some state","Triggers the rule periodically or on some specific time":"Triggers the rule periodically or on some specific time",Tu:WM,Tuesday:GM,URL:VM,"Unknown error":"Unknown error","Unknown error!":"Unknown error!","Use generated code":"Use generated code","User function":"User function","User:":"User:",Value:KM,"Vibration:":"Vibration:",Volume:YM,We:JM,Wednesday:qM,"Whatsapp-cmb":"Whatsapp-cmb",Write:XM,"Write your own code":"Write your own code",Yes:ZM,"Yet exists!":"Yet exists!","You can use %s in the URL to use current trigger value or %id to use the triggered object ID":"You can use %s in the URL to use current trigger value, %id to use the triggered object ID, %name to show triggered object ID name or %old to use old trigger value","You can use %s in the command to use current trigger value or %id to use the triggered object ID":"You can use %s in the command to use current trigger value, %id to use the triggered object ID, %name to show triggered object ID name or %old to use old trigger value","You can use %s in the text to display current trigger value or %id to display the triggered object ID":"You can use %s in the text to display current trigger value, %id to use the triggered object ID, %name to show triggered object ID name or %old to use old trigger value","You can use %s in the value to use the current trigger value or %id to display the triggered object ID":"You can use %s in the value to use the current trigger value, %id to use the triggered object ID, %name to show triggered object ID name or %old to use old trigger value","You have to enter OpenAI API key in the configuration of javascript adapter.":"You have to enter OpenAI API key in the configuration of javascript adapter.","You have to enter at least one API key in the configuration of javascript adapter.":"You have to enter at least one API key (OpenAI, Anthropic or Gemini) in the configuration of javascript adapter.","Please select a valid model":"Please select a valid model","[equal]":"[equal]","[greater or equal]":"[greater or equal]","[greater]":"[greater]","[hysteresis]":"[hysteresis]","[includes]":"[includes]","[less or equal]":"[less or equal]","[less]":"[less]","[not equal]":"[not equal]",acknowledgment:QM,all:eN,and:tN,astro:sN,at:oN,"clear running":"clear running",control:iN,copy:nN,cron:rN,dawn:aN,debug_help:lN,debug_label:cN,default:"default",dusk:uN,easy:dN,else:"else","equal to":"equal to",every:hN,"every hour at 0 minutes":"every hour at 0 minutes",false:"false","file reading has failed: %s":"file reading has failed: %s","file reading was aborted":"file reading was aborted",filter_func:pN,filter_id:gN,filter_name:mN,filter_role:fN,filter_room:$N,"for edit or create script":"for edit or create a new script","for professionals":"for professionals","for programmers":"for programmers",goldenHour:bN,goldenHourEnd:vN,"greater or equal":"greater or equal","greater or equal to":"greater or equal to","greater than":"greater than",help_just_check:yN,help_on_change:_N,"high priority":"high priority","high-priority":"high-priority","highest priority":"highest priority",hours:wN,includes:CN,interval:TN,"just check":"just check","less or equal":"less or equal","less or equal to":"less or equal to","less than":"less than","lower priority":"lower priority","lowest priority":"lowest priority",magic:kN,milliseconds:SN,minutes:EN,ms:IN,nadir:xN,nauticalDawn:DN,nauticalDusk:AN,nextSunrise:RN,nextSunset:ON,night:MN,nightEnd:NN,"no blocks found":"No blocks found","no group":"NO GROUP",normal:LN,"normal priority":"normal priority","not equal to":"not equal to","not properly connected":"This block is not properly connected to other blocks.",offset:PN,"on change":"on change","on condition change":"on condition change","on update":"on update",one:BN,or:jN,quiet:FN,"reset search":"reset search",search:zN,seconds:UN,solarNoon:HN,"store in":"store in",sunrise:WN,sunriseEnd:GN,sunset:VN,sunsetStart:KN,then:YN,"toggle value":"toggle value",tooltip_ack:JN,tooltip_from:qN,tooltip_lc:XN,tooltip_quality:ZN,tooltip_ts:QN,tooltip_user:eL,tooltip_value:tL,true:"true",two:sL,undefined:"undefined",update:oL,"use seconds":"use seconds","use trigger value":"use trigger value",verbose_help:iL,verbose_label:nL,when:rL,with:"with","with date":"with date","with offset":"with offset",wizard:aL,"Loading models...":"Loading models...","Could not connect to API at %s":"Could not connect to API at %s","Invalid API key":"Invalid API key","Access denied by API":"Access denied by API","API error: %s":"API error: %s",'Model "%s" not found':'Model "%s" not found',"Request failed: %s":"Request failed: %s",Retry:lL,"No running javascript instance found":"No running javascript instance found"},uL="Bestätigt",dL="Aktionen",hL="Hinzufügen",pL="Alle",gL="Egal",mL="Anwenden",fL="April",$L="Fragen",bL="Astronomisch",vL="August",yL="Abbrechen",_L="Schließen",wL="Bedingung",CL="Bedingungen",TL="Konsole",kL="Kopiert",SL="Dezember",EL="Standard",IL="Verzögerung",xL="Löschen",DL="Beschreibung",AL="Fertig",RL="Exec shell",OL="Erläuterung",ML="Export",NL="Februar",LL="Februar",PL="Filter",BL="Ordner",jL="Fr",FL="Freitag",zL="ID",UL="ID1",HL="ID2",WL="Import",GL="Instanz",VL="Instanzen",KL="Anleitung",YL="Januar",JL="Januar",qL="Juli",XL="Juni",ZL="Grenze",QL="März",e1="Mai",t1="Menü",s1="Nachricht",o1="Mo",i1="Modell",n1="Montag",r1="Monat",a1="Mehr",l1="Name",c1="November",u1="OK",d1="Oktober",h1="Ok",p1="Pause",g1="Pushover",m1="Pushsafer",f1="Umbenennen",$1="Wiederholen",b1="Neustart",v1="Ergebnis",y1="Sa",_1="Samstag",w1="Speichern",C1="Zeitplan",T1="Skript",k1="September",S1="Simulieren",E1="Stack",I1="Start",x1="Zustand",D1="So",A1="Sonntag",R1="Telegram",O1="Do",M1="Donnerstag",N1="Zeit",L1="Ausgelöst",P1="Löst aus",B1="Di",j1="Dienstag",F1="URL",z1="Wert",U1="Volumen",H1="Mi",W1="Mittwoch",G1="Schreiben",V1="Ja",K1="Wissen",Y1="alle",J1="und",q1="Astro",X1="um",Z1="Steuerung",Q1="Kopie",eP="CRON",tP="Morgendämmerung",sP="Dies ist ein spezieller Modus, in dem sich Zustände und Objekte nicht ändern. Im Protokoll werden jedoch nur Informationen zu jeder geplanten Änderung angezeigt.",oP="Debuggen",iP="Abenddämmerung",nP="einfach",rP="jeder",aP="Funktion",lP="ID",cP="Name",uP="Rolle",dP="Raum",hP="Goldene Abendstunde",pP="Vormittag",gP='Der Code wird jedes Mal ausgeführt, wenn die Bedingung erfüllt ist. z.B. wenn der Temperatur wert sich ändert und die Bedingung "Wenn die Temperatur größer als 20°C ist" lautet, werden die "Dann" -Aktionen jedes Mal ausgeführt, wenn der Sensor die Temperatur sendet und diese über 20°C liegt. Bei 21°C, bei 22°C und so weiter.',mP='Der Code wird nur ausgeführt, wenn sich das Ergebnis der Bedingung ändert. z.B. wenn sich der Temperatur wert ändert und die Bedingung "Wenn die Temperatur größer als 20°C ist" lautet, werden die "Dann" -Aktionen einmal ausgeführt, wenn die Temperatur über 20°C liegt. Das nächste Mal werden die "Dann" -Aktionen ausgeführt, wenn die Temperatur unter 20°C gefallen ist und dann wieder über 20°C ansteigt.',fP="Stunden",$P="beinhaltet",bP="Intervall",vP="Magie",yP="Millisekunden",_P="Minuten",wP="ms",CP="Nadir",TP="nautische Morgendämmerung",kP="nautische Abenddämmerung",SP="Nächster Sonnenaufgang",EP="Nächster Sonnenuntergang",IP="Nacht",xP="astronomische Morgendämmerung",DP="Normal",AP="Versatz",RP="einer",OP="oder",MP="ruhig",NP="Suche",LP="Sekunden",PP="(Nach-)Mittag",BP="Sonnenaufgang",jP="Goldene Morgenstunde",FP="Sonnenuntergang",zP="Sonnenuntergang (Anfang)",UP="dann",HP="Bestätigen",WP="Von",GP="Zuletzt geändert",VP="Qualität",KP="Zeitstempel",YP="Benutzer",JP="Wert",qP="zwei",XP="Aktualisieren",ZP="Fügt Debug-Ausgaben für viele Systembefehle zum Protokoll hinzu",QP="Ausführliche Protokollausgaben",eB="falls",tB="Assistent",sB="Erneut versuchen",oB={"%s not found":"%s nicht gefunden","()":"()","(at %s)":"(um %s)","(optional)":"(optional)","-":"-",".":".","AI code generator":"KI-Codegenerator","Planning...":"Plane...","Generating code...":"Generiere Code...","Show plan":"Plan anzeigen",Ack:uL,Actions:dL,"Actual time of day":"Tatsächliche Tageszeit",Add:hL,"Add new script":"Neues Skript hinzufügen",All:pL,"All files will be accepted":"Alle Dateien werden akzeptiert",Any:gL,"Any month":"Jeden Monat",Apply:mL,April:fL,"Are you sure?":"Wirklich sicher?",Ask:$L,Astronomical:bL,"Astronomical events today":"Astronomische Ereignisse heute",August:vL,"Blockly description":"Erstellen von Regeln durch Grafikblöcke","Body:":"Körper:",Cancel:yL,"Cannot delete non empty item!":"Kann nicht gelöscht werden, weil noch einige Elementen darin sind!","Change layout":"Layout ändern",'Change theme (actual "%s")':'Thema ändern (jetzt - "%s")',"Check blocks":"Blöcke prüfen","Check is not active, because javascript adapter is disabled":"Syntax-Check ist nicht aktiv, weil der Javascript Adapter nicht aktiv ist.","Clear search input":"Sucheingabe löschen","Click on this icon":"Auf dieses Symbol klicken",Close:_L,"Close all but current":"Alle anderen außer dem Aktiven schließen","Collapse all":"Alles einklappen","Compares current time with astronomical event":"Vergleicht die aktuelle Zeit mit einem astronomischen Ereignis","Compares current time with the user specific time":"Vergleicht die aktuelle Zeit mit der benutzerspezifischen Zeit","Compares the state value with user defined value":"Vergleicht den Zustandswert mit dem benutzerdefinierten Wert",Condition:wL,Conditions:CL,"Configuration not saved.":"Die Konfiguration ist nicht gespeichert.",Console:TL,"Control or update some state":"Zustand steuern oder aktualisieren","Control or update some state with delay":"Zustand mit Verzögerung steuern oder aktualisieren","Convert blockly to javascript for ever.":"Blockly dauerhaft in Javascript konvertieren.",Copied:kL,"Copy script":"Skript kopieren","Copy to clipboard":"In die Zwischenablage kopieren","Create new":"Neu erstellen","Create new folder":"Neuen Ordner erstellen","Create new script":"Neues Skript erstellen","Create or edit CRON or time wizard":"CRON- oder Zeit-Assistenten erstellen oder bearbeiten","Dark Theme":"Dunkles Thema","Dark style":"Dunkler Stil",Date:"Datum","Debug instance":"Debug-Instanz","Debug options":"Debug-Optionen",December:SL,Default:EL,"Define cron...":"Cron definieren ...","Define schedule...":"Zeitplan definieren ...",Delay:IL,Delete:xL,"Delete %s":"Löschen %s...","Delete folder":"Ordner löschen","Delete script":"Skript löschen",Description:DL,"Deselect all":"Alles abwählen","Discard changes for %s":"Änderungen für %s verwerfen",Done:AL,"Double click to write value":"Doppelklick zum Schreiben des Wertes","Download as file":"Download als Datei","Drop some files here or click...":"Dateien hier ablegen oder klicken ...","Duplicate name":"Doppelter Name","Edit script or just double click":"Skript bearbeiten oder einfach doppelklicken","Empty name is not allowed":"Leerer Name ist nicht zulässig","End search mode":"Suchmodus beenden","Enter your question":"Anfrage eingeben",Error:"Fehler","Error formatting code":"Fehler beim Formatieren des Codes","Error was found":"Fehler wurde gefunden","Every day":"Täglich",Exec:RL,"Executes some shell command":"Führt einen Shell-Befehl aus","Existing scripts will be overwritten.":"Vorhandene Skripte werden überschrieben.","Expand all":"Alle erweitern","Expert mode":"Expertenmodus",Explanation:OL,Export:ML,"Export all scripts":"Alle Skripte exportieren","Export blocks":"Blöcke exportieren","Export selected blocks":"Ausgewählte Blöcke exportieren",Februar:NL,February:LL,Filter:PL,Folder:BL,Fr:jL,Friday:FL,Function:"Funktion","Function editor":"Funktions-Editor","Function: executed":"Funktion: ausgeführt","Go to next line":"Gehe zur nächsten Zeile","HTTP Call":"HTTP-Aufruf","Hide logs":"Protokoll ausblenden",ID:zL,ID1:UL,ID2:HL,Import:WL,"Import blocks":"Blöcke importieren","Import error":"Fehler beim Importieren","Import scripts":"Skripte importieren","Insert object ID":"Objekt-ID einfügen",Instance:GL,"Instance is disabled":"Instanz ist deaktiviert","Instance:":"Instanz:",Instances:VL,Instructions:KL,"Invalid CRON":"Ungültiger CRON","It will not be possible to revert this operation.":"Dieser Vorgang kann nicht rückgängig gemacht werden.","JS description":"Regeln erstellen mit JavaScript",Januar:YL,January:JL,July:qL,June:XL,"Just check":"Einfach überprüfen","Language:":"Sprache:","Learn More":"Mehr erfahren","Light style":"Heller Stil",Limit:ZL,"Local time":"Lokale Zeit","Locate file":"Datei zeigen","Log outputs":"Protokoll","Log text":"Protokolltext","Log: %s":"Log: %s","Make a HTTP get request":"Eine HTTP-Abrufanforderung stellen","Make a pause between actions":"Eine Pause zwischen den Aktionen machen",March:QL,"March ":"März ",May:e1,Menu:t1,Message:s1,Mo:o1,Model:i1,Monday:n1,Month:r1,More:a1,Name:l1,"No API key found":"Kein API-Schlüssel gefunden","No Chat GPT Key found":"Kein Chat-GPT-Schlüssel gefunden","No active host found":"Kein aktiver Host gefunden","Nothing found":"Nichts gefunden",November:c1,OK:u1,October:d1,Ok:h1,"On condition change":"Bei Änderung des Ergebnis der Bedingung","On script save or adapter start":"Beim Speichern des Skripts oder beim Starten des Adapters","On weekdays":"An Wochentagen","Open configuration":"Konfiguration öffnen","Operate two states":"Zwei Zustände operieren","Operations with two states":"Operationen mit zwei Zuständen","Paste your blocks here":"Fügen Sie Ihre Blöcke hier ein",Pause:p1,"Pause execution":"Ausführung pausieren","Pause script":"Skript anhalten","Phone:":"Telefon:","Please select object ID...":"Objekt-ID auswählen ...","Press Ctrl+Enter to get the answer":"Strg+Eingabetaste, um die Antwort zu erhalten","Prettify the script":"Verschönern Sie das Skript","Print some text in log":"Einen Text im Protokoll ausdrucken","Priority:":"Priorität:",Pushover:g1,Pushsafer:m1,"Read only ID selected: %s":"Schreibgeschützte ID ausgewählt: %s",Rename:f1,"Reorder scripts in folders":"Skripte in Ordnern neu ordnen",Repeat:$1,Restart:b1,Result:v1,"Resume execution":"Ausführung fortsetzen","Root folder":"Root-Verzeichnis","Rules description":"Regeln erstellen mit WENN-, DANN- und SONST-Blöcken","Run script":"Skript ausführen",Sa:y1,Saturday:_1,Save:w1,"Save all":"Alle speichern","Say It":"Say It","Say some text via sayit adapter":"Einen Text über den Sayit-Adapter sagen",Schedule:C1,Script:T1,"Script %s was modified on disk":'Skript "%s" wurde auf der Festplatte geändert',"Script is not running":"Skript läuft nicht","Search in scripts":"Suche in Skripten","Search...":"Suche...","Select all":"Alles auswählen","Send email":"E-Mail senden","Sends an email":"Sendet eine E-Mail","Sends message via Pushsafer":"Sendet eine Nachricht über Pushsafer","Sends message via pushover":"Sendet eine Nachricht per Pushover","Sends message via telegram":"Sendet eine Nachricht per telegram","Sends message via whatsapp-cmb":"Sendet eine Nachricht über WhatsApp-Cmb",September:k1,"Server time":"Server-Zeit","Set state action":"Zustand setzten","Set with delay":"Setzen mit Verzögerung","Shell command":"Shell-Befehl","Show astronomical events":"Astronomische Ereignisse anzeigen","Show javascript code":"Javascript-Code zeigen","Show logs":"Protokoll anzeigen","Show only paused scripts":"Nur angehaltene Skripte zeigen","Show only running scripts":"Nur laufende Skripte zeigen","Show only scripts with problems":"Nur Skripte mit Problemen zeigen",Simulate:S1,"Some files will be rejected":"Einige Dateien werden abgelehnt","Sound:":"Klang:",Stack:E1,Start:I1,"Start script":"Skript starten",State:x1,"State condition":"Zustandsbedingung","Step into function":"Schritt in die Funktion","Step out from function":"Raus aus der Funktion","Stop on exception":"Bei Ausnahme anhalten",Su:D1,"Subject:":"Gegenstand:",Sunday:A1,"TS description":"Regeln erstellen mit TypeScript",Telegram:R1,"Text:":"Text:",Th:O1,"The script will be stopped and must be activated manually after debugging. Continue?":"Das Skript wird gestoppt und muss nach dem Debuggen manuell aktiviert werden. Fortsetzen?","This is advances option. You can write your own code here and it will be executed on trigger":"Dies ist eine erweiterte Option. Sie können hier Ihren eigenen Code schreiben, der beim Auslösen ausgeführt wird",Thursday:M1,Time:N1,"Time condition":"Zeitbedingung","Title:":"Titel:","To:":"Zu:","Trigger with value":"Trigger mit Wert",Triggered:L1,Triggers:P1,"Triggers the on script saving or the javascript instance restart":"Löst das Speichern des Skripts oder den Neustart der Javascript-Instanz aus","Triggers the rule on update or change of some state":"Löst die Regel beim Aktualisieren oder Ändern eines Zustands aus","Triggers the rule periodically or on some specific time":"Löst periodisch oder zu einem bestimmten Zeitpunkt aus",Tu:B1,Tuesday:j1,URL:F1,"Unknown error":"Unbekannter Fehler","Unknown error!":"Unbekannter Fehler!","Use generated code":"Code verwenden","User function":"Benutzerfunktion","User:":"Benutzer:",Value:z1,"Vibration:":"Vibration:",Volume:U1,We:H1,Wednesday:W1,"Whatsapp-cmb":"WhatsApp-cmb",Write:G1,"Write your own code":"Eigenen Code schreiben",Yes:V1,"Yet exists!":"Existiert schon!","You can use %s in the URL to use current trigger value or %id to use the triggered object ID":"Sie können %s in der URL verwenden, um den aktuellen Triggerwert zu verwenden, %id, um die ausgelöste Objekt-ID zu verwenden, %name, um den ID-Namen des ausgelösten Objekts anzuzeigen, oder %old, um den alten Triggerwert zu verwenden","You can use %s in the command to use current trigger value or %id to use the triggered object ID":"Sie können %s im Befehl verwenden, um den aktuellen Triggerwert zu verwenden, %id, um die ausgelöste Objekt-ID zu verwenden, %name, um den ID-Namen des ausgelösten Objekts anzuzeigen, oder %old, um den alten Triggerwert zu verwenden","You can use %s in the text to display current trigger value or %id to display the triggered object ID":"Sie können %s im Text verwenden, um den aktuellen Triggerwert anzuzeigen, %id, um die ausgelöste Objekt-ID zu verwenden, %name, um den ID-Namen des ausgelösten Objekts anzuzeigen, oder %old, um den alten Triggerwert zu verwenden","You can use %s in the value to use the current trigger value or %id to display the triggered object ID":"Sie können %s im Wert verwenden, um den aktuellen Triggerwert zu verwenden, %id, um die ID des ausgelösten Objekts zu verwenden, %name, um den ID-Namen des ausgelösten Objekts anzuzeigen, oder %old, um den alten Triggerwert zu verwenden","You have to enter OpenAI API key in the configuration of javascript adapter.":"Sie müssen den OpenAI-API-Schlüssel in der Konfiguration des Javascript-Adapters eingeben.","You have to enter at least one API key in the configuration of javascript adapter.":"Sie müssen mindestens einen API-Schlüssel (OpenAI, Anthropic oder Gemini) in der Konfiguration des Javascript-Adapters eingeben.","Please select a valid model":"Bitte wählen Sie ein gültiges Modell aus","[equal]":"[gleich]","[greater or equal]":"[größer oder gleich]","[greater]":"[größer]","[hysteresis]":"[Hysterese]","[includes]":"[enthält]","[less or equal]":"[kleiner oder gleich]","[less]":"[kleiner]","[not equal]":"[ungleich]",acknowledgment:K1,all:Y1,and:J1,astro:q1,at:X1,"clear running":"laufende abbrechen",control:Z1,copy:Q1,cron:eP,dawn:tP,debug_help:sP,debug_label:oP,default:"Standard",dusk:iP,easy:nP,else:"sonst","equal to":"gleich",every:rP,"every hour at 0 minutes":"jede Stunde bei 0 Minuten",false:"falsch","file reading has failed: %s":"Das Lesen der Datei ist fehlgeschlagen: %s","file reading was aborted":"Das Lesen der Datei wurde abgebrochen",filter_func:aP,filter_id:lP,filter_name:cP,filter_role:uP,filter_room:dP,"for edit or create script":"zum Bearbeiten oder zum Erstellen eines neues Skripts","for professionals":"für Profis","for programmers":"für Programmierer",goldenHour:hP,goldenHourEnd:pP,"greater or equal":"größer oder gleich","greater or equal to":"größer oder gleich","greater than":"größer als",help_just_check:gP,help_on_change:mP,"high priority":"hohe Priorität","high-priority":"hohe Priorität","highest priority":"höchste Priorität",hours:fP,includes:$P,interval:bP,"just check":"einfach prüfen","less or equal":"kleiner oder gleich","less or equal to":"kleiner oder gleich","less than":"kleiner als","lower priority":"geringere Priorität","lowest priority":"niedrigste Priorität",magic:vP,milliseconds:yP,minutes:_P,ms:wP,nadir:CP,nauticalDawn:TP,nauticalDusk:kP,nextSunrise:SP,nextSunset:EP,night:IP,nightEnd:xP,"no blocks found":"Keine Blöcke gefunden","no group":"KEINE GRUPPE",normal:DP,"normal priority":"normale Priorität","not equal to":"ungleich","not properly connected":"Dieser Block ist mit anderen nicht richtig verbunden.",offset:AP,"on change":"bei Änderung","on condition change":"bei Zustandsänderung","on update":"beim Aktualisieren",one:RP,or:OP,quiet:MP,"reset search":"Suche zurücksetzen",search:NP,seconds:LP,solarNoon:PP,"store in":"speichern in",sunrise:BP,sunriseEnd:jP,sunset:FP,sunsetStart:zP,then:UP,"toggle value":"Wert umschalten",tooltip_ack:HP,tooltip_from:WP,tooltip_lc:GP,tooltip_quality:VP,tooltip_ts:KP,tooltip_user:YP,tooltip_value:JP,true:"wahr",two:qP,undefined:"nicht definiert",update:XP,"use seconds":"Sekunden verwenden","use trigger value":"Triggerwert benutzen",verbose_help:ZP,verbose_label:QP,when:eB,with:"mit","with date":"mit Datum","with offset":"mit Versatz",wizard:tB,"Loading models...":"Modelle werden geladen...","Could not connect to API at %s":"Verbindung zur API unter %s nicht möglich","Invalid API key":"Ungültiger API-Schlüssel","Access denied by API":"Zugriff von der API verweigert","API error: %s":"API-Fehler: %s",'Model "%s" not found':'Modell "%s" nicht gefunden',"Request failed: %s":"Anfrage fehlgeschlagen: %s",Retry:sB,"No running javascript instance found":"Keine laufende JavaScript-Instanz gefunden"},iB="Admitido",nB="Comportamiento",rB="Añadir",aB="Todos",lB="Alguna",cB="Apply",uB="abril",dB="Preguntar",hB="Astronómico",pB="agosto",gB="Cancelar",mB="Cerrar",fB="Condición",$B="Condiciones",bB="Consola",vB="Copiado",yB="diciembre",_B="Defecto",wB="Demora",CB="Eliminar",TB="Descripción",kB="Hecho",SB="Ejecutivo shell",EB="Explicación",IB="Exportar",xB="Februar",DB="febrero",AB="Filtrar",RB="Carpeta",OB="P.",MB="viernes",NB="CARNÉ DE IDENTIDAD",LB="ID1",PB="ID2",BB="Importar",jB="Ejemplo",FB="Instancias",zB="Instrucciones",UB="Enero",HB="enero",WB="julio",GB="junio",VB="Límite",KB="marzo",YB="Mayo",JB="Menú",qB="Mensaje",XB="Mes",ZB="Modelo",QB="lunes",ej="Mes",tj="Más",sj="Nombre",oj="noviembre",ij="OK",nj="octubre",rj="Okay",aj="Pausa",lj="Persona fácil de convencer",cj="Pushsafer",uj="Rebautizar",dj="Repetir",hj="Reiniciar",pj="Resultado",gj="Sa",mj="sábado",fj="Salvar",$j="Calendario",bj="Guión",vj="septiembre",yj="Simular",_j="Stack",wj="Comienzo",Cj="Expresar",Tj="Su",kj="domingo",Sj="Telegrama",Ej="4",Ij="jueves",xj="Tiempo",Dj="Motivado",Aj="Disparadores",Rj="Tu",Oj="martes",Mj="URL",Nj="Valor",Lj="Volumen",Pj="3",Bj="miércoles",jj="Escribir",Fj="sí",zj="Reconocimiento",Uj="todos",Hj="y",Wj="astro",Gj="a",Vj="control",Kj="Copiar",Yj="CRON",Jj="Amanecer",qj="Este es un modo especial en el que los estados y los objetos no cambiarán. Pero solo se mostrará información sobre cada cambio planificado en el protocolo.",Xj="Depurar",Zj="Oscuridad",Qj="fácil",eF="cada",tF="Función",sF="CARNÉ DE IDENTIDAD",oF="Nombre",iF="Papel",nF="Habitación",rF="hora dorada",aF="Fin de la hora dorada",lF='El código se ejecutará solo cada vez que la condición sea verdadera. P.ej. si se activa en el valor del sensor de temperatura y la condición es "si la temperatura es superior a 20 ° C", las acciones "entonces" se ejecutarán cada vez que el sensor envíe la temperatura y supere los 20 ° C. Por 21 ° C, por 22 ° C y así sucesivamente.',cF='El código se ejecutará solo si cambia el resultado de la condición. P.ej. si se activa en el valor del sensor de temperatura y la condición es "si la temperatura es superior a 20 ° C", las acciones "entonces" se ejecutarán una vez cuando la temperatura sea superior a 20. La próxima vez, las acciones "entonces" se ejecutarán cuando la temperatura falla por debajo de 20 y luego sube por encima de 20 nuevamente.',uF="horas",dF="incluye",hF="intervalo",pF="magia",gF="milisegundos",mF="minutos",fF="ms",$F="nadir",bF="Amanecer náutico",vF="Atardecer náutico",yF="próximo amanecer",_F="Próxima puesta de sol",wF="Noche",CF="Fin de la noche",TF="normal",kF="compensar",SF="uno",EF="o",IF="tranquilo",xF="buscar",DF="segundos",AF="Mediodía solar",RF="amanecer",OF="Final del amanecer",MF="puesta de sol",NF="Inicio al atardecer",LF="entonces",PF="Reconocer",BF="De",jF="Último cambio",FF="Calidad",zF="Marca de tiempo",UF="Usuario",HF="Valor",WF="dos",GF="actualizar",VF="Agrega salida de depuración al registro para muchos comandos del sistema",KF="Salidas de registro detalladas",YF="cuando",JF="Wizard",qF="Reintentar",XF={"%s not found":"%s no encontrado","()":"()","(at %s)":"(en %s)","(optional)":"(Opcional)","-":"-",".":".","AI code generator":"Generador de código de IA","Planning...":"Planificando...","Generating code...":"Generando código...","Show plan":"Mostrar plan",Ack:iB,Actions:nB,"Actual time of day":"Hora real del día",Add:rB,"Add new script":"Agregar nuevo script",All:aB,"All files will be accepted":"Todos los archivos serán aceptados.",Any:lB,"Any month":"Cualquier mes",Apply:cB,April:uB,"Are you sure?":"¿Estás seguro?",Ask:dB,Astronomical:hB,"Astronomical events today":"Eventos astronómicos hoy",August:pB,"Blockly description":"Crear reglas por bloques gráficos","Body:":"Cuerpo:",Cancel:gB,"Cannot delete non empty item!":"¡No se puede eliminar un elemento no vacío!","Change layout":"Cambia el diseño",'Change theme (actual "%s")':'Cambiar tema (ahora - "%s")',"Check blocks":"Comprobar bloques","Check is not active, because javascript adapter is disabled":"La comprobación no está activa porque el adaptador Javascript está desactivado","Clear search input":"Borrar entrada de búsqueda","Click on this icon":"Haga clic en este ícono",Close:mB,"Close all but current":"Cerrar todo menos el actual","Collapse all":"Desplegar todo","Compares current time with astronomical event":"Compara la hora actual con un evento astronómico","Compares current time with the user specific time":"Compara la hora actual con la hora específica del usuario","Compares the state value with user defined value":"Compara el valor del estado con el valor definido por el usuario",Condition:fB,Conditions:$B,"Configuration not saved.":"Configuración no guardada.",Console:bB,"Control or update some state":"Controlar o actualizar algún estado","Control or update some state with delay":"Controlar o actualizar algún estado con retraso","Convert blockly to javascript for ever.":"Convierta instantáneamente en bloque a Javascript.",Copied:vB,"Copy script":"Copiar guion","Copy to clipboard":"Copiar al portapapeles","Create new":"Crear nuevo","Create new folder":"Crear nueva carpeta","Create new script":"Crear nuevo script","Create or edit CRON or time wizard":"Crear o editar CRON o asistente de tiempo","Dark Theme":"Tema oscuro","Dark style":"Estilo oscuro",Date:"Fecha","Debug instance":"Instancia de depuración","Debug options":"Opciones de depuración",December:yB,Default:_B,"Define cron...":"Definir cron ...","Define schedule...":"Definir horario ...",Delay:wB,Delete:CB,"Delete %s":"Eliminar %s ...","Delete folder":"Eliminar carpeta","Delete script":"Eliminar guión",Description:TB,"Deselect all":"Deseleccionar todo","Discard changes for %s":"Descartar cambios para %s",Done:kB,"Double click to write value":"Doble clic para escribir el valor","Download as file":"Descargar como archivo","Drop some files here or click...":"Suelta algunos archivos aquí o haz clic ...","Duplicate name":"Nombre duplicado","Edit script or just double click":"Editar guión o simplemente hacer doble clic","Empty name is not allowed":"No se permite el nombre vacío","End search mode":"Fin del modo de búsqueda","Enter your question":"Ingrese su solicitud",Error:"Error","Error formatting code":"Código de formato de error","Error was found":"Error encontrado","Every day":"Diario",Exec:SB,"Executes some shell command":"Ejecuta algún comando de shell","Existing scripts will be overwritten.":"Los guiones existentes se sobrescribirán.","Expand all":"Expandir todo","Expert mode":"Modo experto",Explanation:EB,Export:IB,"Export all scripts":"Exportar todos los scripts","Export blocks":"Exportar bloques","Export selected blocks":"Exportar bloques seleccionados",Februar:xB,February:DB,Filter:AB,Folder:RB,Fr:OB,Friday:MB,Function:"Función","Function editor":"Editor de funciones","Function: executed":"Función: ejecutada","Go to next line":"Ir a la siguiente línea","HTTP Call":"Llamada HTTP","Hide logs":"Ocultar registros",ID:NB,ID1:LB,ID2:PB,Import:BB,"Import blocks":"Importar bloques","Import error":"Error de importación","Import scripts":"Importar guiones","Insert object ID":"Insertar ID de objeto",Instance:jB,"Instance is disabled":"La instancia está deshabilitada","Instance:":"Ejemplo:",Instances:FB,Instructions:zB,"Invalid CRON":"CRON inválido","It will not be possible to revert this operation.":"No será posible revertir esta operación.","JS description":"Crear reglas escribiendo Javascript",Januar:UB,January:HB,July:WB,June:GB,"Just check":"Sólo revisa","Language:":"Idioma:","Learn More":"Aprende más","Light style":"Estilo ligero",Limit:VB,"Local time":"Hora local","Locate file":"Localizar el archivo","Log outputs":"Salidas de registro","Log text":"Texto de registro","Log: %s":"Log: %s","Make a HTTP get request":"Realizar una solicitud de obtención HTTP","Make a pause between actions":"Hacer una pausa entre acciones",March:KB,"March ":"marzo",May:YB,Menu:JB,Message:qB,Mo:XB,Model:ZB,Monday:QB,Month:ej,More:tj,Name:sj,"No API key found":"No se encontró ninguna clave API","No Chat GPT Key found":"No se ha encontrado ninguna clave GPT de chat","No active host found":"No se encontró un host activo","Nothing found":"Nada Encontrado",November:oj,OK:ij,October:nj,Ok:rj,"On condition change":"En condición de cambio","On script save or adapter start":"Al guardar el script o al iniciar el adaptador","On weekdays":"De lunes a viernes","Open configuration":"Configuración abierta","Operate two states":"Operar dos estados","Operations with two states":"Operaciones con dos estados","Paste your blocks here":"Pega tus bloques aquí",Pause:aj,"Pause execution":"Pausar ejecución","Pause script":"Pausar guion","Phone:":"Teléfono:","Please select object ID...":"Por favor, seleccione la ID del objeto ...","Press Ctrl+Enter to get the answer":"Presiona Ctrl+Enter para obtener la respuesta","Prettify the script":"Embellecer el guión","Print some text in log":"Imprime texto en el registro","Priority:":"Prioridad:",Pushover:lj,Pushsafer:cj,"Read only ID selected: %s":"ID de solo lectura seleccionado: %s",Rename:uj,"Reorder scripts in folders":"Reordenar guiones en carpetas",Repeat:dj,Restart:hj,Result:pj,"Resume execution":"Reanudar ejecución","Root folder":"Carpeta raíz","Rules description":"Crea reglas con bloques IF, THEN, ELSE","Run script":"Ejecutar guión",Sa:gj,Saturday:mj,Save:fj,"Save all":"Salvar a todos","Say It":"Say It","Say some text via sayit adapter":"Di un mensaje de texto a través del adaptador sayit",Schedule:$j,Script:bj,"Script %s was modified on disk":"El script %s fue modificado en el disco","Script is not running":"El script no se está ejecutando","Search in scripts":"Buscar en guiones","Search...":"Buscar...","Select all":"Seleccionar todo","Send email":"Enviar correo electrónico","Sends an email":"Envía un correo electrónico","Sends message via Pushsafer":"Envía mensaje a través de Pushsafer","Sends message via pushover":"Envía un mensaje a través de un pushover","Sends message via telegram":"Envía mensaje por telegrama","Sends message via whatsapp-cmb":"Envía mensaje vía whatsapp-cmb",September:vj,"Server time":"Tiempo del servidor","Set state action":"Establecer acción estatal","Set with delay":"Establecer con retraso","Shell command":"Comando de Shell","Show astronomical events":"Mostrar eventos astronómicos","Show javascript code":"Mostrar código Javascript","Show logs":"Mostrar registros","Show only paused scripts":"Mostrar solo secuencias de comandos pausadas","Show only running scripts":"Mostrar solo scripts en ejecución","Show only scripts with problems":"Mostrar solo guiones con problemas",Simulate:yj,"Some files will be rejected":"Algunos archivos serán rechazados","Sound:":"Sonido:",Stack:_j,Start:wj,"Start script":"Iniciar guion",State:Cj,"State condition":"Condición del estado","Step into function":"Entra en función","Step out from function":"Sal de la función","Stop on exception":"Deténgase en excepción",Su:Tj,"Subject:":"Sujeto:",Sunday:kj,"TS description":"Crear reglas escribiendo el mecanografiado",Telegram:Sj,"Text:":"Texto:",Th:Ej,"The script will be stopped and must be activated manually after debugging. Continue?":"El script se detendrá y deberá activarse manualmente después de la depuración. ¿Continuar?","This is advances option. You can write your own code here and it will be executed on trigger":"Esta es la opción de avances. Puede escribir su propio código aquí y se ejecutará en el disparador",Thursday:Ij,Time:xj,"Time condition":"Condición de tiempo","Title:":"Título:","To:":"A:","Trigger with value":"Activar con valor",Triggered:Dj,Triggers:Aj,"Triggers the on script saving or the javascript instance restart":"Activa el guardado de la secuencia de comandos o el reinicio de la instancia de JavaScript","Triggers the rule on update or change of some state":"Activa la regla de actualización o cambio de algún estado","Triggers the rule periodically or on some specific time":"Activa la regla periódicamente o en un momento específico",Tu:Rj,Tuesday:Oj,URL:Mj,"Unknown error":"Error desconocido","Unknown error!":"¡Error desconocido!","Use generated code":"Usar código generado","User function":"Función de usuario","User:":"Usuario:",Value:Nj,"Vibration:":"Vibración:",Volume:Lj,We:Pj,Wednesday:Bj,"Whatsapp-cmb":"Whatsapp-cmb",Write:jj,"Write your own code":"Escribe tu propio código",Yes:Fj,"Yet exists!":"¡Sin embargo existe!","You can use %s in the URL to use current trigger value or %id to use the triggered object ID":"Puede usar %s en la URL para usar el valor de activación actual, %id para usar el ID de objeto activado, %name para mostrar el nombre de ID de objeto activado o %old para usar el valor de activación antiguo","You can use %s in the command to use current trigger value or %id to use the triggered object ID":"Puede usar %s en el comando para usar el valor de activación actual, %id para usar el ID de objeto activado, %name para mostrar el nombre de ID de objeto activado o %old para usar el valor de activación anterior","You can use %s in the text to display current trigger value or %id to display the triggered object ID":"Puede usar %s en el texto para mostrar el valor de activación actual, %id para usar el ID de objeto activado, %name para mostrar el nombre de ID de objeto activado o %old para usar el valor de activación antiguo","You can use %s in the value to use the current trigger value or %id to display the triggered object ID":"Puede usar %s en el valor para usar el valor de activación actual, %id para usar el ID de objeto activado, %name para mostrar el nombre de ID de objeto activado o %old para usar el valor de activación antiguo","You have to enter OpenAI API key in the configuration of javascript adapter.":"Debe ingresar la clave API de OpenAI en la configuración del adaptador de JavaScript.","You have to enter at least one API key in the configuration of javascript adapter.":"Debe ingresar al menos una clave API (OpenAI, Anthropic o Gemini) en la configuración del adaptador de JavaScript.","Please select a valid model":"Seleccione un modelo válido","[equal]":"[igual]","[greater or equal]":"[mayor o igual]","[greater]":"[mayor que]","[hysteresis]":"[histéresis]","[includes]":"[incluye]","[less or equal]":"[menor o igual]","[less]":"[menos]","[not equal]":"[no es igual]",acknowledgment:zj,all:Uj,and:Hj,astro:Wj,at:Gj,"clear running":"carrera clara",control:Vj,copy:Kj,cron:Yj,dawn:Jj,debug_help:qj,debug_label:Xj,default:"defecto",dusk:Zj,easy:Qj,else:"demás","equal to":"igual a",every:eF,"every hour at 0 minutes":"cada hora a los 0 minutos",false:"falso","file reading has failed: %s":"la lectura del archivo ha fallado: %s","file reading was aborted":"la lectura del archivo fue abortada",filter_func:tF,filter_id:sF,filter_name:oF,filter_role:iF,filter_room:nF,"for edit or create script":"para editar o crear un nuevo script","for professionals":"para profesionales","for programmers":"para programadores",goldenHour:rF,goldenHourEnd:aF,"greater or equal":"mayor o igual","greater or equal to":"mayor o igual a","greater than":"mas grande que",help_just_check:lF,help_on_change:cF,"high priority":"alta prioridad","high-priority":"alta prioridad","highest priority":"más alta prioridad",hours:uF,includes:dF,interval:hF,"just check":"Sólo revisa","less or equal":"menor o igual","less or equal to":"menor o igual a","less than":"menos que","lower priority":"prioridad más baja","lowest priority":"prioridad más baja",magic:pF,milliseconds:gF,minutes:mF,ms:fF,nadir:$F,nauticalDawn:bF,nauticalDusk:vF,nextSunrise:yF,nextSunset:_F,night:wF,nightEnd:CF,"no blocks found":"No se encontraron bloques","no group":"NO GRUPO",normal:TF,"normal priority":"prioridad normal","not equal to":"no igual a","not properly connected":"Este bloque no está conectado correctamente a otros bloques.",offset:kF,"on change":"en el cambio","on condition change":"con cambio de condición","on update":"en actualización",one:SF,or:EF,quiet:IF,"reset search":"restablecer la búsqueda",search:xF,seconds:DF,solarNoon:AF,"store in":"almacenar en",sunrise:RF,sunriseEnd:OF,sunset:MF,sunsetStart:NF,then:LF,"toggle value":"alternar valor",tooltip_ack:PF,tooltip_from:BF,tooltip_lc:jF,tooltip_quality:FF,tooltip_ts:zF,tooltip_user:UF,tooltip_value:HF,true:"cierto",two:WF,undefined:"indefinido",update:GF,"use seconds":"usar segundos","use trigger value":"usar valor de activación",verbose_help:VF,verbose_label:KF,when:YF,with:"con","with date":"con fecha","with offset":"con desplazamiento",wizard:JF,"Loading models...":"Cargando modelos...","Could not connect to API at %s":"No se pudo conectar a la API en %s","Invalid API key":"Clave API no válida","Access denied by API":"Acceso denegado por la API","API error: %s":"Error de API: %s",'Model "%s" not found':'Modelo "%s" no encontrado',"Request failed: %s":"Solicitud fallida: %s",Retry:qF,"No running javascript instance found":"No se encontró ninguna instancia de JavaScript en ejecución"},ZF="Reconnu",QF="Actions",e2="Ajouter",t2="Tout",s2="Tout",o2="Postuler",i2="avril",n2="Demander",r2="Astronomique",a2="août",l2="Annuler",c2="proche",u2="État",d2="Conditions",h2="Console",p2="Copié",g2="décembre",m2="Défaut",f2="Retard",$2="Effacer",b2="Description",v2="Terminé",y2="Exec shell",_2="Explication",w2="Exportation",C2="Février",T2="février",k2="Filtre",S2="Dossier",E2="Fr",I2="Vendredi",x2="ID",D2="ID1",A2="ID2",R2="Importation",O2="Exemple",M2="Instances",N2="Instructions",L2="Janvier",P2="janvier",B2="juillet",j2="juin",F2="Limite",z2="Mars",U2="Mai",H2="M e n u",W2="Message",G2="Mo",V2="Modèle",K2="Lundi",Y2="Mois",J2="Plus",q2="Nom",X2="novembre",Z2="OK",Q2="octobre",ez="D'accord",tz="Pause",sz="Pushover",oz="Pushsafer",iz="Renommer",nz="Répéter",rz="Redémarrer",az="Résultat",lz="Sa",cz="samedi",uz="sauver",dz="Horaire",hz="Scénario",pz="septembre",gz="Simuler",mz="Stack",fz="Début",$z="État",bz="Su",vz="dimanche",yz="Télégramme",_z="4",wz="Jeudi",Cz="Temps",Tz="Déclenché",kz="Déclencheurs",Sz="Tu",Ez="Mardi",Iz="URL",xz="Valeur",Dz="Le volume",Az="3",Rz="Mercredi",Oz="Écrivez",Mz="Oui",Nz="reconnaissance",Lz="tout",Pz="et",Bz="astro",jz="à",Fz="contrôler",zz="copie",Uz="CRON",Hz="Aube",Wz="Il s'agit d'un mode spécial dans lequel les états et les objets ne changeront pas. Mais seules les informations sur chaque changement prévu seront affichées dans le protocole.",Gz="Déboguer",Vz="Crépuscule",Kz="facile",Yz="chaque",Jz="Une fonction",qz="ID",Xz="Nom",Zz="Rôle",Qz="Pièce",eU="Heure d'or",tU="Fin de l'heure d'or",sU="Le code ne sera exécuté que chaque fois que la condition est vraie. Par exemple. si déclenchement sur la valeur du capteur de température et que la condition est «si la température est supérieure à 20 ° C», les actions «alors» seront exécutées à chaque fois que le capteur envoie la température et qu'elle est supérieure à 20 ° C. À 21 ° C, à 22 ° C et ainsi de suite.",oU="Le code ne sera exécuté que si le résultat de la condition change. Par exemple. si le déclenchement sur la valeur du capteur de température et que la condition est «si la température est supérieure à 20 ° C», les actions «alors» seront exécutées une fois lorsque la température est supérieure à 20. La prochaine fois, les actions «alors» seront exécutées lorsque la température échoue sous 20 puis remonte au-dessus de 20.",iU="les heures",nU="comprend",rU="intervalle",aU="la magie",lU="millisecondes",cU="minutes",uU="ms",dU="nadir",hU="Aube nautique",pU="Crépuscule nautique",gU="Prochain lever de soleil",mU="Prochain coucher de soleil",fU="Nuit",$U="Fin de nuit",bU="Ordinaire",vU="décalage",yU="une",_U="ou",wU="calmer",CU="chercher",TU="secondes",kU="Midi solaire",SU="lever du soleil",EU="Fin du lever du soleil",IU="le coucher du soleil",xU="Début du coucher du soleil",DU="alors",AU="Reconnaître",RU="De",OU="Dernière modification",MU="Qualité",NU="Horodatage",LU="Utilisateur",PU="Valeur",BU="deux",jU="mettre à jour",FU="Ajoute une sortie de débogage au journal pour de nombreuses commandes système",zU="Sorties de journal détaillées",UU="lorsque",HU="Wizard",WU="Réessayer",GU={"%s not found":"%s non trouvé","()":"()","(at %s)":"(à %s)","(optional)":"(optionnel)","-":"-",".":".","AI code generator":"Générateur de code IA","Planning...":"Planification...","Generating code...":"Génération du code...","Show plan":"Afficher le plan",Ack:ZF,Actions:QF,"Actual time of day":"Heure réelle de la journée",Add:e2,"Add new script":"Ajouter un nouveau script",All:t2,"All files will be accepted":"Tous les fichiers seront acceptés",Any:s2,"Any month":"N'importe quel mois",Apply:o2,April:i2,"Are you sure?":"Êtes-vous sûr?",Ask:n2,Astronomical:r2,"Astronomical events today":"Événements astronomiques aujourd'hui",August:a2,"Blockly description":"Création de règles par blocs graphiques","Body:":"Corps:",Cancel:l2,"Cannot delete non empty item!":"Impossible de supprimer un élément non vide!","Change layout":"Changer la disposition",'Change theme (actual "%s")':'Changer de thème (maintenant - "%s")',"Check blocks":"Vérifier les blocs","Check is not active, because javascript adapter is disabled":"La vérification n'est pas active, car l'adaptateur Javascript est désactivé","Clear search input":"Effacer la recherche","Click on this icon":"Cliquez sur cette icône",Close:c2,"Close all but current":"Ferme tout sauf courant","Collapse all":"Réduire tout","Compares current time with astronomical event":"Compare l'heure actuelle avec un événement astronomique","Compares current time with the user specific time":"Compare l'heure actuelle avec l'heure spécifique de l'utilisateur","Compares the state value with user defined value":"Compare la valeur d'état avec la valeur définie par l'utilisateur",Condition:u2,Conditions:d2,"Configuration not saved.":"Configuration non enregistrée.",Console:h2,"Control or update some state":"Contrôler ou mettre à jour un état","Control or update some state with delay":"Contrôler ou mettre à jour un état avec un délai","Convert blockly to javascript for ever.":"Convertissez instantanément en Javascript.",Copied:p2,"Copy script":"Copier le script","Copy to clipboard":"Copier dans le presse-papier","Create new":"Créer un nouveau","Create new folder":"Créer un nouveau dossier","Create new script":"Créer un nouveau script","Create or edit CRON or time wizard":"Créer ou éditer CRON ou un assistant de temps","Dark Theme":"Thème sombre","Dark style":"Style sombre",Date:"Date","Debug instance":"Instance de débogage","Debug options":"Options de débogage",December:g2,Default:m2,"Define cron...":"Définir le cron ...","Define schedule...":"Définir le calendrier ...",Delay:f2,Delete:$2,"Delete %s":"Supprimer %s ...","Delete folder":"Supprimer le dossier","Delete script":"Supprimer le script",Description:b2,"Deselect all":"Tout déselectionner","Discard changes for %s":"Ignorer les modifications pour %s",Done:v2,"Double click to write value":"Double clic pour écrire la valeur","Download as file":"Télécharger le fichier","Drop some files here or click...":"Déposer des fichiers ici ou cliquez sur ...","Duplicate name":"Nom en double","Edit script or just double click":"Modifiez le script ou double-cliquez simplement sur","Empty name is not allowed":"Le nom vide n'est pas autorisé","End search mode":"Fin du mode de recherche","Enter your question":"Entrez votre demande",Error:"Erreur","Error formatting code":"Erreur lors du formatage du code","Error was found":"Une erreur a été trouvée","Every day":"Tous les jours",Exec:y2,"Executes some shell command":"Exécute une commande shell","Existing scripts will be overwritten.":"Les scripts existants seront écrasés.","Expand all":"Développer tout","Expert mode":"Mode expert",Explanation:_2,Export:w2,"Export all scripts":"Exporter tous les scripts","Export blocks":"Blocs d'exportation","Export selected blocks":"Exporter les blocs sélectionnés",Februar:C2,February:T2,Filter:k2,Folder:S2,Fr:E2,Friday:I2,Function:"Fonction","Function editor":"Éditeur de fonction","Function: executed":"Fonction : exécutée","Go to next line":"Aller à la ligne suivante","HTTP Call":"Appel HTTP","Hide logs":"Masquer les journaux",ID:x2,ID1:D2,ID2:A2,Import:R2,"Import blocks":"Blocs d'importation","Import error":"Erreur d'importation","Import scripts":"Importer des scripts","Insert object ID":"Insérer un identifiant d'objet",Instance:O2,"Instance is disabled":"L'instance est désactivée","Instance:":"Exemple:",Instances:M2,Instructions:N2,"Invalid CRON":"CRON invalide","It will not be possible to revert this operation.":"Il ne sera pas possible de revenir sur cette opération.","JS description":"Créer des règles en écrivant du Javascript",Januar:L2,January:P2,July:B2,June:j2,"Just check":"Vérifiez simplement","Language:":"Langue:","Learn More":"Apprendre encore plus","Light style":"Style de lumière",Limit:F2,"Local time":"Heure locale","Locate file":"Localiser le fichier","Log outputs":"Journal des sorties","Log text":"Texte du journal","Log: %s":"Log : %s","Make a HTTP get request":"Faire une requête HTTP Get","Make a pause between actions":"Faites une pause entre les actions",March:z2,"March ":"mars",May:U2,Menu:H2,Message:W2,Mo:G2,Model:V2,Monday:K2,Month:Y2,More:J2,Name:q2,"No API key found":"Aucune clé API trouvée","No Chat GPT Key found":"Aucune clé GPT de chat trouvée","No active host found":"Aucun hôte actif trouvé","Nothing found":"Rien n'a été trouvé",November:X2,OK:Z2,October:Q2,Ok:ez,"On condition change":"En cas de changement de condition","On script save or adapter start":"Lors de l'enregistrement du script ou du démarrage de l'adaptateur","On weekdays":"En semaine","Open configuration":"Configuration ouverte","Operate two states":"Opérer deux états","Operations with two states":"Opérations à deux états","Paste your blocks here":"Collez vos blocs ici",Pause:tz,"Pause execution":"Suspendre l'exécution","Pause script":"Script de pause","Phone:":"Téléphone:","Please select object ID...":"Veuillez sélectionner l'ID d'objet ...","Press Ctrl+Enter to get the answer":"Appuyez sur Ctrl+Entrée pour obtenir la réponse","Prettify the script":"Embellir le scénario","Print some text in log":"Imprimer du texte dans le journal","Priority:":"Priorité:",Pushover:sz,Pushsafer:oz,"Read only ID selected: %s":"ID en lecture seule sélectionné: %s",Rename:iz,"Reorder scripts in folders":"Réorganiser les scripts dans des dossiers",Repeat:nz,Restart:rz,Result:az,"Resume execution":"Reprendre l'exécution","Root folder":"Dossier racine","Rules description":"Créer des règles avec des blocs IF, THEN, ELSE","Run script":"Script de lancement",Sa:lz,Saturday:cz,Save:uz,"Save all":"Sauver tous","Say It":"Say It","Say some text via sayit adapter":"Dites du texte via l'adaptateur sayit",Schedule:dz,Script:hz,"Script %s was modified on disk":"Le script %s a été modifié sur le disque","Script is not running":"Le script n'est pas en cours d'exécution","Search in scripts":"Rechercher dans les scripts","Search...":"Chercher...","Select all":"Tout sélectionner","Send email":"Envoyer un e-mail","Sends an email":"Envoie un e-mail","Sends message via Pushsafer":"Envoie un message via Pushsafer","Sends message via pushover":"Envoie un message via pushover","Sends message via telegram":"Envoie un message par télégramme","Sends message via whatsapp-cmb":"Envoie un message via whatsapp-cmb",September:pz,"Server time":"Heure du serveur","Set state action":"Définir l'action de l'état","Set with delay":"Set avec retard","Shell command":"Commande Shell","Show astronomical events":"Afficher les événements astronomiques","Show javascript code":"Afficher le code Javascript","Show logs":"Afficher les journaux","Show only paused scripts":"Afficher uniquement les scripts en pause","Show only running scripts":"Afficher uniquement les scripts en cours d'exécution","Show only scripts with problems":"Afficher uniquement les scripts avec des problèmes",Simulate:gz,"Some files will be rejected":"Certains fichiers seront rejetés","Sound:":"Sonner:",Stack:mz,Start:fz,"Start script":"Lancer le script",State:$z,"State condition":"État condition","Step into function":"Entrez dans la fonction","Step out from function":"Sortez de la fonction","Stop on exception":"Arrêt sur exception",Su:bz,"Subject:":"Sujet:",Sunday:vz,"TS description":"Créer des règles en écrivant des caractères dactylographiés",Telegram:yz,"Text:":"Texte:",Th:_z,"The script will be stopped and must be activated manually after debugging. Continue?":"Le script sera arrêté et doit être activé manuellement après le débogage. Continuez?","This is advances option. You can write your own code here and it will be executed on trigger":"C'est une option avancée. Vous pouvez écrire votre propre code ici et il sera exécuté au déclenchement",Thursday:wz,Time:Cz,"Time condition":"Condition de temps","Title:":"Titre:","To:":"À:","Trigger with value":"Déclencheur avec valeur",Triggered:Tz,Triggers:kz,"Triggers the on script saving or the javascript instance restart":"Déclenche l'enregistrement du script ou le redémarrage de l'instance javascript","Triggers the rule on update or change of some state":"Déclenche la règle sur la mise à jour ou le changement d'un état","Triggers the rule periodically or on some specific time":"Déclenche la règle périodiquement ou à une heure précise",Tu:Sz,Tuesday:Ez,URL:Iz,"Unknown error":"Erreur inconnue","Unknown error!":"Erreur inconnue!","Use generated code":"Utiliser le code généré","User function":"Fonction utilisateur","User:":"Utilisateur:",Value:xz,"Vibration:":"Vibration:",Volume:Dz,We:Az,Wednesday:Rz,"Whatsapp-cmb":"Whatsapp-cmb",Write:Oz,"Write your own code":"Écrivez votre propre code",Yes:Mz,"Yet exists!":"Pourtant existe!","You can use %s in the URL to use current trigger value or %id to use the triggered object ID":"Vous pouvez utiliser %s dans l'URL pour utiliser la valeur de déclenchement actuelle, %id pour utiliser l'ID de l'objet déclenché, %name pour afficher le nom de l'ID de l'objet déclenché ou %old pour utiliser l'ancienne valeur de déclenchement","You can use %s in the command to use current trigger value or %id to use the triggered object ID":"Vous pouvez utiliser %s dans la commande pour utiliser la valeur de déclenchement actuelle, %id pour utiliser l'ID de l'objet déclenché, %name pour afficher le nom de l'ID de l'objet déclenché ou %old pour utiliser l'ancienne valeur de déclenchement","You can use %s in the text to display current trigger value or %id to display the triggered object ID":"Vous pouvez utiliser %s dans le texte pour afficher la valeur de déclenchement actuelle, %id pour utiliser l'ID de l'objet déclenché, %name pour afficher le nom de l'ID de l'objet déclenché ou %old pour utiliser l'ancienne valeur de déclenchement","You can use %s in the value to use the current trigger value or %id to display the triggered object ID":"Vous pouvez utiliser %s dans la valeur pour utiliser la valeur de déclenchement actuelle, %id pour utiliser l'ID de l'objet déclenché, %name pour afficher le nom de l'ID de l'objet déclenché ou %old pour utiliser l'ancienne valeur de déclenchement","You have to enter OpenAI API key in the configuration of javascript adapter.":"Vous devez entrer la clé API OpenAI dans la configuration de l'adaptateur javascript.","You have to enter at least one API key in the configuration of javascript adapter.":"Vous devez entrer au moins une clé API (OpenAI, Anthropic ou Gemini) dans la configuration de l'adaptateur javascript.","Please select a valid model":"Veuillez sélectionner un modèle valide","[equal]":"[égal]","[greater or equal]":"[supérieur ou égal]","[greater]":"[plus grand]","[hysteresis]":"[hystérèse]","[includes]":"[comprend]","[less or equal]":"[inférieur ou égal]","[less]":"[moins]","[not equal]":"[inégal]",acknowledgment:Nz,all:Lz,and:Pz,astro:Bz,at:jz,"clear running":"course claire",control:Fz,copy:zz,cron:Uz,dawn:Hz,debug_help:Wz,debug_label:Gz,default:"défaut",dusk:Vz,easy:Kz,else:"autre","equal to":"égal à",every:Yz,"every hour at 0 minutes":"toutes les heures à 0 minute",false:"faux","file reading has failed: %s":"La lecture du fichier a échoué: %s","file reading was aborted":"la lecture du fichier a été abandonnée",filter_func:Jz,filter_id:qz,filter_name:Xz,filter_role:Zz,filter_room:Qz,"for edit or create script":"pour éditer ou créer un nouveau script","for professionals":"pour les professionnels","for programmers":"pour les programmeurs",goldenHour:eU,goldenHourEnd:tU,"greater or equal":"supérieur ou égal","greater or equal to":"supérieur ou égal à","greater than":"plus grand que",help_just_check:sU,help_on_change:oU,"high priority":"haute priorité","high-priority":"haute priorité","highest priority":"priorité la plus élevée",hours:iU,includes:nU,interval:rU,"just check":"Vérifiez simplement","less or equal":"inférieur ou égal","less or equal to":"inférieur ou égal à","less than":"moins que","lower priority":"priorité inférieure","lowest priority":"priorité la plus basse",magic:aU,milliseconds:lU,minutes:cU,ms:uU,nadir:dU,nauticalDawn:hU,nauticalDusk:pU,nextSunrise:gU,nextSunset:mU,night:fU,nightEnd:$U,"no blocks found":"Aucun bloc trouvé","no group":"PAS DE GROUPE",normal:bU,"normal priority":"priorité normale","not equal to":"pas égal à","not properly connected":"Ce bloc n'est pas correctement connecté à d'autres blocs.",offset:vU,"on change":"sur le changement","on condition change":"sur changement de condition","on update":"sur mise à jour",one:yU,or:_U,quiet:wU,"reset search":"Réinitialiser la recherche",search:CU,seconds:TU,solarNoon:kU,"store in":"stocker dans",sunrise:SU,sunriseEnd:EU,sunset:IU,sunsetStart:xU,then:DU,"toggle value":"valeur de bascule",tooltip_ack:AU,tooltip_from:RU,tooltip_lc:OU,tooltip_quality:MU,tooltip_ts:NU,tooltip_user:LU,tooltip_value:PU,true:"vrai",two:BU,undefined:"indéfini",update:jU,"use seconds":"utiliser les secondes","use trigger value":"use trigger value",verbose_help:FU,verbose_label:zU,when:UU,with:"avec","with date":"avec date","with offset":"avec offset",wizard:HU,"Loading models...":"Chargement des modèles...","Could not connect to API at %s":"Impossible de se connecter à l'API sur %s","Invalid API key":"Clé API invalide","Access denied by API":"Accès refusé par l'API","API error: %s":"Erreur API : %s",'Model "%s" not found':'Modèle "%s" introuvable',"Request failed: %s":"Requête échouée : %s",Retry:WU,"No running javascript instance found":"Aucune instance JavaScript en cours d'exécution trouvée"},VU="Riconosciuto",KU="Azioni",YU="Inserisci",JU="Tutti",qU="Qualunque",XU="Applica",ZU="aprile",QU="Chiedere",eH="Astronomico",tH="agosto",sH="Annulla",oH="Vicino",iH="Condizione",nH="Condizioni",rH="Console",aH="Copiato",lH="dicembre",cH="Predefinito",uH="Ritardo",dH="Elimina",hH="Descrizione",pH="Fatto",gH="Execshell",mH="Spiegazione",fH="Esportare",$H="Februar",bH="febbraio",vH="Filtro",yH="Cartella",_H="P",wH="Venerdì",CH="ID",TH="ID1",kH="ID2",SH="Importare",EH="Esempio",IH="istanze",xH="Istruzioni",DH="Januar",AH="gennaio",RH="luglio",OH="giugno",MH="Limite",NH="marzo",LH="Maggio",PH="Menu",BH="Messaggio",jH="Mo",FH="Modello",zH="Lunedi",UH="Mese",HH="Di più",WH="Nome",GH="novembre",VH="OK",KH="ottobre",YH="Ok",JH="Pausa",qH="Pushover",XH="Pushsafer",ZH="Rinominare",QH="Ripetere",eW="Ricomincia",tW="Risultato",sW="Sa",oW="Sabato",iW="Salva",nW="Programma",rW="copione",aW="settembre",lW="Simulare",cW="Stack",uW="Cominciare",dW="Stato",hW="Su",pW="Domenica",gW="Telegramma",mW="4",fW="giovedi",$W="Tempo",bW="Innescato",vW="Trigger",yW="Tu",_W="martedì",wW="URL",CW="Valore",TW="Volume",kW="3",SW="mercoledì",EW="Scrivi",IW="sì",xW="riconoscimento",DW="tutti",AW="e",RW="astro",OW="a",MW="controllo",NW="copia",LW="CRON",PW="alba",BW="Questa è una modalità speciale in cui gli stati e gli oggetti non cambieranno. Ma nel protocollo verranno visualizzate solo le informazioni su ogni modifica pianificata.",jW="Debug",FW="crepuscolo",zW="facile",UW="ogni",HW="Funzione",WW="ID",GW="Nome",VW="Ruolo",KW="Camera",YW="Ora d'oro",JW="Fine dell'ora d'oro",qW='Il codice verrà eseguito solo ogni volta che la condizione è vera. Per esempio. se si attiva il valore del sensore di temperatura e la condizione è "se la temperatura è maggiore di 20 ° C", le azioni "allora" verranno eseguite ogni volta che il sensore invia la temperatura e questa è superiore a 20 ° C. Di 21 ° C, di 22 ° C e così via.',XW='Il codice verrà eseguito solo se il risultato della condizione cambia. Per esempio. se si attiva il valore del sensore di temperatura e la condizione è "se la temperatura è maggiore di 20 ° C", le azioni "allora" verranno eseguite una volta quando la temperatura è superiore a 20. La prossima volta le azioni "allora" verranno eseguite quando la temperatura fallisce sotto 20 e poi sale di nuovo oltre 20.',ZW="ore",QW="include",eG="intervallo",tG="Magia",sG="millisecondi",oG="minuti",iG="ms",nG="nadir",rG="Alba nautica",aG="Crepuscolo nautico",lG="Prossima alba",cG="Prossimo tramonto",uG="Notte",dG="Fine della notte",hG="normale",pG="compensare",gG="uno",mG="o",fG="silenzioso",$G="ricerca",bG="secondi",vG="Mezzogiorno solare",yG="Alba",_G="Fine dell'alba",wG="tramonto",CG="Inizio del tramonto",TG="poi",kG="Riconoscere",SG="A partire dal",EG="Ultima modifica",IG="Qualità",xG="timestamp",DG="Utente",AG="Valore",RG="Due",OG="aggiornare",MG="Aggiunge l'output di debug al registro per molti comandi di sistema",NG="Output di log dettagliati",LG="quando",PG="procedura guidata",BG="Riprova",jG={"%s not found":"%s non trovato","()":"()","(at %s)":"(a %s)","(optional)":"(opzionale)","-":"-",".":".","AI code generator":"Generatore di codice AI","Planning...":"Pianificazione...","Generating code...":"Generazione codice...","Show plan":"Mostra piano",Ack:VU,Actions:KU,"Actual time of day":"Ora effettiva della giornata",Add:YU,"Add new script":"Aggiungi nuovo script",All:JU,"All files will be accepted":"Tutti i file saranno accettati",Any:qU,"Any month":"Ogni mese",Apply:XU,April:ZU,"Are you sure?":"Sei sicuro?",Ask:QU,Astronomical:eH,"Astronomical events today":"Eventi astronomici oggi",August:tH,"Blockly description":"Creazione di regole tramite blocchi grafici","Body:":"Corpo:",Cancel:sH,"Cannot delete non empty item!":"Impossibile eliminare l'elemento non vuoto!","Change layout":"Cambia layout",'Change theme (actual "%s")':'Cambia tema (ora - "%s")',"Check blocks":"Controlla i blocchi","Check is not active, because javascript adapter is disabled":"Il controllo non è attivo perché l'adattatore Javascript è disabilitato","Clear search input":"Cancella input di ricerca","Click on this icon":"Clicca su questa icona",Close:oH,"Close all but current":"Chiudi tutto tranne corrente","Collapse all":"Comprimi tutto","Compares current time with astronomical event":"Confronta l'ora corrente con l'evento astronomico","Compares current time with the user specific time":"Confronta l'ora corrente con l'ora specifica dell'utente","Compares the state value with user defined value":"Confronta il valore dello stato con il valore definito dall'utente",Condition:iH,Conditions:nH,"Configuration not saved.":"Configurazione non salvata.",Console:rH,"Control or update some state":"Controlla o aggiorna uno stato","Control or update some state with delay":"Controlla o aggiorna uno stato con ritardo","Convert blockly to javascript for ever.":"Converti istantaneamente a blocchi in Javascript.",Copied:aH,"Copy script":"Copia script","Copy to clipboard":"Copia negli appunti","Create new":"Creare nuovo","Create new folder":"Crea una nuova cartella","Create new script":"Crea nuovo script","Create or edit CRON or time wizard":"Crea o modifica la procedura guidata CRON o time","Dark Theme":"Tema scuro","Dark style":"Stile scuro",Date:"Data","Debug instance":"Istanza di debug","Debug options":"Opzioni di debug",December:lH,Default:cH,"Define cron...":"Definisci cron ...","Define schedule...":"Definisci programma ...",Delay:uH,Delete:dH,"Delete %s":"Elimina %s ...","Delete folder":"Elimina cartella","Delete script":"Elimina script",Description:hH,"Deselect all":"Deselezionare tutto","Discard changes for %s":"Annulla modifiche per %s",Done:pH,"Double click to write value":"Doppio clic per scrivere il valore","Download as file":"Scarica come file","Drop some files here or click...":"Trascina alcuni file qui o fai clic su ...","Duplicate name":"Nome duplicato","Edit script or just double click":"Modifica lo script o fai doppio clic","Empty name is not allowed":"Il nome vuoto non è consentito","End search mode":"Termina la modalità di ricerca","Enter your question":"Inserisci la tua richiesta",Error:"Errore","Error formatting code":"Errore di formattazione del codice","Error was found":"Errore trovato","Every day":"Ogni giorno",Exec:gH,"Executes some shell command":"Esegue alcuni comandi della shell","Existing scripts will be overwritten.":"Gli script esistenti verranno sovrascritti.","Expand all":"Espandi tutto","Expert mode":"Modalità esperto",Explanation:mH,Export:fH,"Export all scripts":"Esporta tutti gli script","Export blocks":"Esporta blocchi","Export selected blocks":"Esporta i blocchi selezionati",Februar:$H,February:bH,Filter:vH,Folder:yH,Fr:_H,Friday:wH,Function:"Funzione","Function editor":"Editor di funzioni","Function: executed":"Funzione: eseguita","Go to next line":"Vai alla riga successiva","HTTP Call":"Chiamata HTTP","Hide logs":"Nascondi i registri",ID:CH,ID1:TH,ID2:kH,Import:SH,"Import blocks":"Importa blocchi","Import error":"Errore di importazione","Import scripts":"Importa script","Insert object ID":"Inserisci l'ID oggetto",Instance:EH,"Instance is disabled":"L'istanza è disabilitata","Instance:":"Esempio:",Instances:IH,Instructions:xH,"Invalid CRON":"CRON non valido","It will not be possible to revert this operation.":"Non sarà possibile ripristinare questa operazione.","JS description":"Creare regole scrivendo Javascript",Januar:DH,January:AH,July:RH,June:OH,"Just check":"Controlla solamente","Language:":"Linguaggio:","Learn More":"Per saperne di più","Light style":"Stile leggero",Limit:MH,"Local time":"Ora locale","Locate file":"Localizza file","Log outputs":"Registra le uscite","Log text":"Testo del registro","Log: %s":"Log: %s","Make a HTTP get request":"Effettua una richiesta get HTTP","Make a pause between actions":"Fai una pausa tra le azioni",March:NH,"March ":"marzo",May:LH,Menu:PH,Message:BH,Mo:jH,Model:FH,Monday:zH,Month:UH,More:HH,Name:WH,"No API key found":"Nessuna chiave API trovata","No Chat GPT Key found":"Nessuna chiave GPT chat trovata","No active host found":"Nessun host attivo trovato","Nothing found":"Non abbiamo trovato nulla",November:GH,OK:VH,October:KH,Ok:YH,"On condition change":"A condizione che cambino","On script save or adapter start":"Al salvataggio dello script o all'avvio dell'adattatore","On weekdays":"Nei giorni della settimana","Open configuration":"Configurazione aperta","Operate two states":"Gestisci due stati","Operations with two states":"Operazioni con due stati","Paste your blocks here":"Incolla qui i tuoi blocchi",Pause:JH,"Pause execution":"Metti in pausa l'esecuzione","Pause script":"Metti in pausa lo script","Phone:":"Telefono:","Please select object ID...":"Seleziona l'ID oggetto ...","Press Ctrl+Enter to get the answer":"Premi Ctrl+Invio per ottenere la risposta","Prettify the script":"Abbellire la sceneggiatura","Print some text in log":"Stampa del testo nel registro","Priority:":"Priorità:",Pushover:qH,Pushsafer:XH,"Read only ID selected: %s":"ID di sola lettura selezionato: %s",Rename:ZH,"Reorder scripts in folders":"Riordina gli script nelle cartelle",Repeat:QH,Restart:eW,Result:tW,"Resume execution":"Riprendi esecuzione","Root folder":"Cartella root","Rules description":"Crea regole con i blocchi IF, THEN, ELSE","Run script":"Esegui script",Sa:sW,Saturday:oW,Save:iW,"Save all":"Salva tutto","Say It":"Say It","Say some text via sayit adapter":"Pronuncia del testo tramite l'adattatore sayit",Schedule:nW,Script:rW,"Script %s was modified on disk":"Lo script %s è stato modificato sul disco","Script is not running":"Lo script non è in esecuzione","Search in scripts":"Cerca negli script","Search...":"Ricerca...","Select all":"Seleziona tutto","Send email":"Invia una email","Sends an email":"Invia un'e-mail","Sends message via Pushsafer":"Invia messaggio tramite Pushsafer","Sends message via pushover":"Invia messaggio tramite pushover","Sends message via telegram":"Invia messaggio tramite telegramma","Sends message via whatsapp-cmb":"Invia messaggio tramite whatsapp-cmb",September:aW,"Server time":"Ora del server","Set state action":"Imposta l'azione dello stato","Set with delay":"Impostato con ritardo","Shell command":"Comando Shell","Show astronomical events":"Mostra eventi astronomici","Show javascript code":"Mostra codice Javascript","Show logs":"Mostra i log","Show only paused scripts":"Mostra solo script in pausa","Show only running scripts":"Mostra solo gli script in esecuzione","Show only scripts with problems":"Mostra solo script con problemi",Simulate:lW,"Some files will be rejected":"Alcuni file verranno rifiutati","Sound:":"Suono:",Stack:cW,Start:uW,"Start script":"Avvia script",State:dW,"State condition":"Condizione dello stato","Step into function":"Entra in funzione","Step out from function":"Esci dalla funzione","Stop on exception":"Ferma in caso di eccezione",Su:hW,"Subject:":"Soggetto:",Sunday:pW,"TS description":"Creare regole scrivendo dattiloscritto",Telegram:gW,"Text:":"Testo:",Th:mW,"The script will be stopped and must be activated manually after debugging. Continue?":"Lo script verrà interrotto e dovrà essere attivato manualmente dopo il debug. Continua?","This is advances option. You can write your own code here and it will be executed on trigger":"Questa è un'opzione anticipata. Puoi scrivere il tuo codice qui e verrà eseguito al trigger",Thursday:fW,Time:$W,"Time condition":"Condizione temporale","Title:":"Titolo:","To:":"Per:","Trigger with value":"Trigger con valore",Triggered:bW,Triggers:vW,"Triggers the on script saving or the javascript instance restart":"Attiva il salvataggio dello script o il riavvio dell'istanza javascript","Triggers the rule on update or change of some state":"Attiva la regola in caso di aggiornamento o modifica di uno stato","Triggers the rule periodically or on some specific time":"Attiva la regola periodicamente o in un momento specifico",Tu:yW,Tuesday:_W,URL:wW,"Unknown error":"Errore sconosciuto","Unknown error!":"Errore sconosciuto!","Use generated code":"Usa il codice generato","User function":"Funzione utente","User:":"Utente:",Value:CW,"Vibration:":"Vibrazione:",Volume:TW,We:kW,Wednesday:SW,"Whatsapp-cmb":"Whatsapp-cmb",Write:EW,"Write your own code":"Scrivi il tuo codice",Yes:IW,"Yet exists!":"Esiste ancora!","You can use %s in the URL to use current trigger value or %id to use the triggered object ID":"È possibile utilizzare %s nell'URL per utilizzare il valore di trigger corrente, %id per utilizzare l'ID dell'oggetto attivato, %name per mostrare il nome dell'ID dell'oggetto attivato o %old per utilizzare il vecchio valore di trigger","You can use %s in the command to use current trigger value or %id to use the triggered object ID":"È possibile utilizzare %s nel comando per utilizzare il valore di trigger corrente, %id per utilizzare l'ID dell'oggetto attivato, %name per mostrare il nome dell'ID dell'oggetto attivato o %old per utilizzare il vecchio valore di trigger","You can use %s in the text to display current trigger value or %id to display the triggered object ID":"È possibile utilizzare %s nel testo per visualizzare il valore di trigger corrente, %id per utilizzare l'ID dell'oggetto attivato, %name per mostrare il nome dell'ID dell'oggetto attivato o %old per utilizzare il vecchio valore di trigger","You can use %s in the value to use the current trigger value or %id to display the triggered object ID":"È possibile utilizzare %s nel valore per utilizzare il valore di trigger corrente, %id per utilizzare l'ID dell'oggetto attivato, %name per mostrare il nome dell'ID dell'oggetto attivato o %old per utilizzare il vecchio valore di trigger","You have to enter OpenAI API key in the configuration of javascript adapter.":"Devi inserire la chiave API OpenAI nella configurazione dell'adattatore javascript.","You have to enter at least one API key in the configuration of javascript adapter.":"Devi inserire almeno una chiave API (OpenAI, Anthropic o Gemini) nella configurazione dell'adattatore javascript.","Please select a valid model":"Seleziona un modello valido","[equal]":"[pari]","[greater or equal]":"[maggiore o uguale]","[greater]":"[maggiore]","[hysteresis]":"[isteresi]","[includes]":"[include]","[less or equal]":"[minore o uguale]","[less]":"[Di meno]","[not equal]":"[non uguale]",acknowledgment:xW,all:DW,and:AW,astro:RW,at:OW,"clear running":"chiara esecuzione",control:MW,copy:NW,cron:LW,dawn:PW,debug_help:BW,debug_label:jW,default:"predefinito",dusk:FW,easy:zW,else:"altro","equal to":"uguale a",every:UW,"every hour at 0 minutes":"ogni ora a 0 minuti",false:"falso","file reading has failed: %s":"lettura file non riuscita: %s","file reading was aborted":"la lettura del file è stata interrotta",filter_func:HW,filter_id:WW,filter_name:GW,filter_role:VW,filter_room:KW,"for edit or create script":"per modificare o creare un nuovo script","for professionals":"per i professionisti","for programmers":"per i programmatori",goldenHour:YW,goldenHourEnd:JW,"greater or equal":"maggiore o uguale","greater or equal to":"maggiore o uguale a","greater than":"più grande di",help_just_check:qW,help_on_change:XW,"high priority":"priorità alta","high-priority":"priorità alta","highest priority":"massima priorità",hours:ZW,includes:QW,interval:eG,"just check":"controlla solamente","less or equal":"inferiore o uguale","less or equal to":"minore o uguale a","less than":"meno di","lower priority":"priorità inferiore","lowest priority":"priorità più bassa",magic:tG,milliseconds:sG,minutes:oG,ms:iG,nadir:nG,nauticalDawn:rG,nauticalDusk:aG,nextSunrise:lG,nextSunset:cG,night:uG,nightEnd:dG,"no blocks found":"Nessun blocco trovato","no group":"NESSUN GRUPPO",normal:hG,"normal priority":"priorità normale","not equal to":"non uguale a","not properly connected":"Questo blocco non è correttamente collegato ad altri blocchi.",offset:pG,"on change":"sul cambiamento","on condition change":"a cambio di condizione","on update":"in aggiornamento",one:gG,or:mG,quiet:fG,"reset search":"resetta la ricerca",search:$G,seconds:bG,solarNoon:vG,"store in":"conservare in",sunrise:yG,sunriseEnd:_G,sunset:wG,sunsetStart:CG,then:TG,"toggle value":"alterna valore",tooltip_ack:kG,tooltip_from:SG,tooltip_lc:EG,tooltip_quality:IG,tooltip_ts:xG,tooltip_user:DG,tooltip_value:AG,true:"vero",two:RG,undefined:"non definito",update:OG,"use seconds":"usa i secondi","use trigger value":"usa il trigger",verbose_help:MG,verbose_label:NG,when:LG,with:"con","with date":"con data","with offset":"con offset",wizard:PG,"Loading models...":"Caricamento modelli...","Could not connect to API at %s":"Impossibile connettersi all'API su %s","Invalid API key":"Chiave API non valida","Access denied by API":"Accesso negato dall'API","API error: %s":"Errore API: %s",'Model "%s" not found':'Modello "%s" non trovato',"Request failed: %s":"Richiesta fallita: %s",Retry:BG,"No running javascript instance found":"Nessuna istanza JavaScript in esecuzione trovata"},FG="Erkend",zG="Acties",UG="Toevoegen",HG="Alle",WG="Ieder",GG="Solliciteer",VG="april",KG="Vragen",YG="Astronomisch",JG="augustus",qG="annuleren",XG="Dichtbij",ZG="Staat",QG="Voorwaarden",eV="Troosten",tV="Gekopieerd",sV="december",oV="Standaard",iV="Vertraging",nV="Verwijder",rV="Beschrijving",aV="Gedaan",lV="Exec shell",cV="Uitleg",uV="Exporteren",dV="Februari",hV="februari",pV="Filter",gV="Map",mV="Vr",fV="vrijdag",$V="ID kaart",bV="ID1",vV="ID2",yV="Importeren",_V="Voorbeeld",wV="Instanties",CV="Instructies",TV="Januar",kV="januari",SV="juli",EV="juni",IV="Begrenzing",xV="maart",DV="mei",AV="Menu",RV="Bericht",OV="Ma",MV="Model",NV="maandag",LV="Maand",PV="Meer",BV="Naam",jV="november",FV="OK",zV="oktober",UV="OK",HV="Pauze",WV="Pushover",GV="Duwijzer",VV="andere naam geven",KV="Herhaling",YV="Herstarten",JV="Resultaat",qV="Za",XV="zaterdag",ZV="Opslaan",QV="Schema",e5="Script",t5="september",s5="Simuleren",o5="Stack",i5="Begin",n5="Staat",r5="Zo",a5="zondag",l5="Telegram",c5="4",u5="donderdag",d5="Tijd",h5="Veroorzaakt",p5="Triggers",g5="Di",m5="dinsdag",f5="URL",$5="Waarde",b5="Volume",v5="3",y5="woensdag",_5="Schrijven",w5="Ja",C5="erkenning",T5="alle",k5="en",S5="astro",E5="Bij",I5="controle",x5="kopiëren",D5="cron",A5="dageraad",R5="Dit is een speciale modus waarin toestanden en objecten niet veranderen. Maar alleen informatie over elke geplande wijziging wordt in het protocol weergegeven.",O5="Debuggen",M5="schemer",N5="eenvoudig",L5="elke",P5="Functie",B5="ID kaart",j5="Naam",F5="Rol",z5="Kamer",U5="gouden uur",H5="Einde van gouden uur",W5='De code wordt alleen uitgevoerd als de voorwaarde waar is. Bijv. als het triggeren op de temperatuursensorwaarde en de conditie is "als de temperatuur hoger is dan 20 ° C", zullen de "dan" acties worden uitgevoerd elke keer dat de sensor de temperatuur verzendt en deze hoger is dan 20 ° C. Bij 21 ° C, bij 22 ° C enzovoort.',G5='De code wordt alleen uitgevoerd als het conditieresultaat verandert. Bijv. als de temperatuursensor wordt geactiveerd en de conditie is "als de temperatuur hoger is dan 20 ° C", worden de "dan" -acties eenmaal uitgevoerd wanneer de temperatuur hoger is dan 20. De volgende keer worden de "dan" -acties uitgevoerd wanneer de temperatuur faalt onder de 20 en stijgt dan weer boven de 20.',V5="uren",K5="omvat",Y5="interval",J5="magie",q5="milliseconden",X5="minuten",Z5="ms",Q5="nadir",e3="Nautische dageraad",t3="Nautische schemering",s3="Volgende zonsopgang",o3="Volgende zonsondergang",i3="nacht",n3="Einde van de nacht",r3="normaal",a3="compensatie",l3="een",c3="of",u3="stil",d3="zoeken",h3="seconden",p3="Zonne-middag",g3="zonsopkomst",m3="Einde zonsopgang",f3="zonsondergang",$3="Begin van de zonsondergang",b3="vervolgens",v3="Erkennen",y3="Van",_3="Laatst gewijzigd",w3="Kwaliteit",C3="tijdstempel",T3="Gebruiker",k3="Waarde",S3="twee",E3="bijwerken",I3="Voegt foutopsporingsuitvoer toe aan het logboek voor veel systeemopdrachten",x3="Uitgebreide log-uitgangen",D3="wanneer",A3="tovenaar",R3="Opnieuw proberen",O3={"%s not found":"%s niet gevonden","()":"()","(at %s)":"(op %s)","(optional)":"(optioneel)","-":"-",".":".","AI code generator":"AI-codegenerator","Planning...":"Planning...","Generating code...":"Code genereren...","Show plan":"Plan weergeven",Ack:FG,Actions:zG,"Actual time of day":"Werkelijke tijd van de dag",Add:UG,"Add new script":"Nieuw script toevoegen",All:HG,"All files will be accepted":"Alle bestanden worden geaccepteerd",Any:WG,"Any month":"Elke maand",Apply:GG,April:VG,"Are you sure?":"Weet je zeker dat?",Ask:KG,Astronomical:YG,"Astronomical events today":"Astronomische gebeurtenissen vandaag",August:JG,"Blockly description":"Regels maken door grafische blokken","Body:":"Lichaam:",Cancel:qG,"Cannot delete non empty item!":"Kan niet leeg item niet verwijderen!","Change layout":"Opmaak veranderen",'Change theme (actual "%s")':'Thema wijzigen (nu - "%s")',"Check blocks":"Controleer blokken","Check is not active, because javascript adapter is disabled":"Controle is niet actief, omdat Javascript-adapter is uitgeschakeld","Clear search input":"Zoekopdracht wissen","Click on this icon":"Klik op dit pictogram",Close:XG,"Close all but current":"Alles sluiten behalve huidig","Collapse all":"Alles inklappen","Compares current time with astronomical event":"Vergelijkt huidige tijd met astronomische gebeurtenis","Compares current time with the user specific time":"Vergelijkt de huidige tijd met de gebruikerspecifieke tijd","Compares the state value with user defined value":"Vergelijkt de statuswaarde met de door de gebruiker gedefinieerde waarde",Condition:ZG,Conditions:QG,"Configuration not saved.":"Configuratie niet opgeslagen.",Console:eV,"Control or update some state":"Beheer of update een bepaalde staat","Control or update some state with delay":"Beheer of update een bepaalde staat met vertraging","Convert blockly to javascript for ever.":"Converteer direct blockly naar Javascript.",Copied:tV,"Copy script":"Kopieer script","Copy to clipboard":"Kopieer naar klembord","Create new":"Maak nieuw","Create new folder":"Maak een nieuwe map","Create new script":"Maak een nieuw script","Create or edit CRON or time wizard":"Creëer of bewerk CRON of tijdwizard","Dark Theme":"Donker thema","Dark style":"Donkere stijl",Date:"Datum","Debug instance":"Debug-instantie","Debug options":"Foutopsporingsopties",December:sV,Default:oV,"Define cron...":"Definieer cron ...","Define schedule...":"Definieer schema ...",Delay:iV,Delete:nV,"Delete %s":"%s verwijderen ...","Delete folder":"Verwijder map","Delete script":"Script verwijderen",Description:rV,"Deselect all":"Deselecteer alles","Discard changes for %s":"Wijzigingen voor %s annuleren",Done:aV,"Double click to write value":"Dubbelklikken om waarde te schrijven","Download as file":"Download","Drop some files here or click...":"Zet hier enkele bestanden neer of klik op ...","Duplicate name":"Dubbele naam","Edit script or just double click":"Bewerk het script of dubbelklik erop","Empty name is not allowed":"Lege naam is niet toegestaan","End search mode":"Zoekmodus beëindigen","Enter your question":"Voer uw verzoek in",Error:"Fout","Error formatting code":"Fout bij het opmaken van de code","Error was found":"Er is een fout gevonden","Every day":"Elke dag",Exec:lV,"Executes some shell command":"Voert een shell-commando uit","Existing scripts will be overwritten.":"Bestaande scripts worden overschreven.","Expand all":"Alles uitvouwen","Expert mode":"Expert modus",Explanation:cV,Export:uV,"Export all scripts":"Exporteer alle scripts","Export blocks":"Blokken exporteren","Export selected blocks":"Exporteer geselecteerde blokken",Februar:dV,February:hV,Filter:pV,Folder:gV,Fr:mV,Friday:fV,Function:"Functie","Function editor":"Functie-editor","Function: executed":"Functie: uitgevoerd","Go to next line":"Ga naar de volgende regel","HTTP Call":"HTTP-oproep","Hide logs":"Verberg logboeken",ID:$V,ID1:bV,ID2:vV,Import:yV,"Import blocks":"Blokken importeren","Import error":"Importfout","Import scripts":"Scripts importeren","Insert object ID":"Object-ID invoegen",Instance:_V,"Instance is disabled":"Exemplaar is uitgeschakeld","Instance:":"Voorbeeld:",Instances:wV,Instructions:CV,"Invalid CRON":"Ongeldige CRON","It will not be possible to revert this operation.":"Het is niet mogelijk om deze bewerking terug te zetten.","JS description":"Regels maken door Javascript te schrijven",Januar:TV,January:kV,July:SV,June:EV,"Just check":"Kijk maar","Language:":"Taal:","Learn More":"Leer meer","Light style":"Lichte stijl",Limit:IV,"Local time":"Lokale tijd","Locate file":"Vind het bestand","Log outputs":"Log uitgangen","Log text":"Log tekst","Log: %s":"Logboek: %s","Make a HTTP get request":"Maak een HTTP-ophaalverzoek","Make a pause between actions":"Pauzeer tussen acties",March:xV,"March ":"maart",May:DV,Menu:AV,Message:RV,Mo:OV,Model:MV,Monday:NV,Month:LV,More:PV,Name:BV,"No API key found":"Geen API-sleutel gevonden","No Chat GPT Key found":"Geen Chat GPT-sleutel gevonden","No active host found":"Geen actieve host gevonden","Nothing found":"Niets gevonden",November:jV,OK:FV,October:zV,Ok:UV,"On condition change":"Op voorwaarde verandering","On script save or adapter start":"Bij het opslaan van het script of het starten van de adapter","On weekdays":"Op weekdagen","Open configuration":"Configuratie openen","Operate two states":"Bedien twee toestanden:","Operations with two states":"Bewerkingen met twee toestanden","Paste your blocks here":"Plak hier je blokken",Pause:HV,"Pause execution":"Uitvoering pauzeren","Pause script":"Pauzeer script","Phone:":"Telefoon:","Please select object ID...":"Selecteer object-ID ...","Press Ctrl+Enter to get the answer":"Druk op Ctrl+Enter om het antwoord te krijgen","Prettify the script":"Maak het script mooier","Print some text in log":"Druk wat tekst af in het logboek","Priority:":"Prioriteit:",Pushover:WV,Pushsafer:GV,"Read only ID selected: %s":"Alleen-lezen ID geselecteerd: %s",Rename:VV,"Reorder scripts in folders":"Sorteer scripts in mappen opnieuw",Repeat:KV,Restart:YV,Result:JV,"Resume execution":"Uitvoering hervatten","Root folder":"Hoofdmap","Rules description":"Maak regels met IF, THEN, ELSE blokken","Run script":"Voer script uit",Sa:qV,Saturday:XV,Save:ZV,"Save all":"Sla alles op","Say It":"Say It","Say some text via sayit adapter":"Zeg wat tekst via de sayit-adapter",Schedule:QV,Script:e5,"Script %s was modified on disk":"Script %s is gewijzigd op schijf","Script is not running":"Script is niet actief","Search in scripts":"Zoeken in scripts","Search...":"Zoeken...","Select all":"Selecteer alles","Send email":"E-mail verzenden","Sends an email":"Stuurt een e-mail","Sends message via Pushsafer":"Stuurt bericht via Pushsafer","Sends message via pushover":"Stuurt bericht via pushover","Sends message via telegram":"Verzendt bericht via telegram","Sends message via whatsapp-cmb":"Stuurt bericht via whatsapp-cmb",September:t5,"Server time":"Servertijd","Set state action":"Stel statusactie in","Set with delay":"Met vertraging ingesteld","Shell command":"Shell-opdracht","Show astronomical events":"Laat astronomische gebeurtenissen zien","Show javascript code":"Javascript-code weergeven","Show logs":"Toon logboeken","Show only paused scripts":"Toon alleen onderbroken scripts","Show only running scripts":"Toon alleen actieve scripts","Show only scripts with problems":"Toon alleen scripts met problemen",Simulate:s5,"Some files will be rejected":"Sommige bestanden worden geweigerd","Sound:":"Geluid:",Stack:o5,Start:i5,"Start script":"Start het script",State:n5,"State condition":"Staat staat","Step into function":"Stap in functie","Step out from function":"Stap uit de functie","Stop on exception":"Stop bij uitzondering",Su:r5,"Subject:":"Onderwerpen:",Sunday:a5,"TS description":"Regels maken door Typescript te schrijven",Telegram:l5,"Text:":"Tekst:",Th:c5,"The script will be stopped and must be activated manually after debugging. Continue?":"Het script wordt gestopt en moet na het debuggen handmatig worden geactiveerd. Doorgaan met?","This is advances option. You can write your own code here and it will be executed on trigger":"Dit is een voorschotoptie. U kunt hier uw eigen code schrijven en deze wordt bij een trigger uitgevoerd",Thursday:u5,Time:d5,"Time condition":"Tijdsvoorwaarde","Title:":"Titel:","To:":"Naar:","Trigger with value":"Trigger met waarde",Triggered:h5,Triggers:p5,"Triggers the on script saving or the javascript instance restart":"Activeert het opslaan van het script of het opnieuw opstarten van de JavaScript-instantie","Triggers the rule on update or change of some state":"Activeert de regel voor het bijwerken of wijzigen van een bepaalde staat","Triggers the rule periodically or on some specific time":"Activeert de regel periodiek of op een specifieke tijd",Tu:g5,Tuesday:m5,URL:f5,"Unknown error":"Onbekende fout","Unknown error!":"Onbekende fout!","Use generated code":"Gebruik gegenereerde code","User function":"Gebruikersfunctie","User:":"Gebruiker:",Value:$5,"Vibration:":"Trilling:",Volume:b5,We:v5,Wednesday:y5,"Whatsapp-cmb":"Whatsapp-cmb",Write:_5,"Write your own code":"Schrijf je eigen code",Yes:w5,"Yet exists!":"Toch bestaat!","You can use %s in the URL to use current trigger value or %id to use the triggered object ID":"U kunt %s in de URL gebruiken om de huidige triggerwaarde te gebruiken, %id om de geactiveerde object-ID te gebruiken, %name om de geactiveerde object-ID-naam te tonen of %old om de oude triggerwaarde te gebruiken","You can use %s in the command to use current trigger value or %id to use the triggered object ID":"U kunt %s in de opdracht gebruiken om de huidige triggerwaarde te gebruiken, %id om de getriggerde object-ID te gebruiken, %name om de getriggerde object-ID-naam te tonen of %old om de oude triggerwaarde te gebruiken","You can use %s in the text to display current trigger value or %id to display the triggered object ID":"U kunt %s in de tekst gebruiken om de huidige triggerwaarde weer te geven, %id om de geactiveerde object-ID te gebruiken, %name om de geactiveerde object-ID-naam weer te geven of %old om de oude triggerwaarde te gebruiken","You can use %s in the value to use the current trigger value or %id to display the triggered object ID":"U kunt %s in de waarde gebruiken om de huidige triggerwaarde te gebruiken, %id om de geactiveerde object-ID te gebruiken, %name om de geactiveerde object-ID-naam te tonen of %old om de oude triggerwaarde te gebruiken","You have to enter OpenAI API key in the configuration of javascript adapter.":"U moet de OpenAI API-sleutel invoeren in de configuratie van de javascript-adapter.","You have to enter at least one API key in the configuration of javascript adapter.":"U moet ten minste één API-sleutel (OpenAI, Anthropic of Gemini) invoeren in de configuratie van de javascript-adapter.","Please select a valid model":"Selecteer een geldig model","[equal]":"[Gelijk]","[greater or equal]":"[groter of gelijk]","[greater]":"[groter]","[hysteresis]":"[hysterese]","[includes]":"[inclusief]","[less or equal]":"[minder of gelijk]","[less]":"[minder]","[not equal]":"[niet gelijk]",acknowledgment:C5,all:T5,and:k5,astro:S5,at:E5,"clear running":"duidelijk rennen",control:I5,copy:x5,cron:D5,dawn:A5,debug_help:R5,debug_label:O5,default:"standaard",dusk:M5,easy:N5,else:"anders","equal to":"gelijk aan",every:L5,"every hour at 0 minutes":"elk uur op 0 minuten",false:"false","file reading has failed: %s":"bestands lezen is mislukt: %s","file reading was aborted":"bestands lezen is afgebroken",filter_func:P5,filter_id:B5,filter_name:j5,filter_role:F5,filter_room:z5,"for edit or create script":"voor bewerken of een nieuw script maken","for professionals":"voor professionals","for programmers":"voor programmeurs",goldenHour:U5,goldenHourEnd:H5,"greater or equal":"groter of gelijk","greater or equal to":"groter of gelijk aan","greater than":"groter dan",help_just_check:W5,help_on_change:G5,"high priority":"hoge prioriteit","high-priority":"hoge prioriteit","highest priority":"hoogste prioriteit",hours:V5,includes:K5,interval:Y5,"just check":"kijk maar","less or equal":"minder of gelijk","less or equal to":"minder of gelijk aan","less than":"minder dan","lower priority":"lagere prioriteit","lowest priority":"laagste prioriteit",magic:J5,milliseconds:q5,minutes:X5,ms:Z5,nadir:Q5,nauticalDawn:e3,nauticalDusk:t3,nextSunrise:s3,nextSunset:o3,night:i3,nightEnd:n3,"no blocks found":"Geen blokken gevonden","no group":"GEEN GROEP",normal:r3,"normal priority":"normale prioriteit","not equal to":"niet gelijk aan","not properly connected":"Dit blok is niet correct verbonden met andere blokken.",offset:a3,"on change":"bij verandering","on condition change":"op voorwaarde verandering","on update":"bij update",one:l3,or:c3,quiet:u3,"reset search":"reset zoeken",search:d3,seconds:h3,solarNoon:p3,"store in":"opslaan in",sunrise:g3,sunriseEnd:m3,sunset:f3,sunsetStart:$3,then:b3,"toggle value":"schakelwaarde",tooltip_ack:v3,tooltip_from:y3,tooltip_lc:_3,tooltip_quality:w3,tooltip_ts:C3,tooltip_user:T3,tooltip_value:k3,true:"waar",two:S3,undefined:"ongedefinieerd",update:E3,"use seconds":"gebruik seconden","use trigger value":"triggerwaarde gebruiken",verbose_help:I3,verbose_label:x3,when:D3,with:"met","with date":"met datum","with offset":"met offset",wizard:A3,"Loading models...":"Modellen laden...","Could not connect to API at %s":"Kan geen verbinding maken met API op %s","Invalid API key":"Ongeldige API-sleutel","Access denied by API":"Toegang geweigerd door API","API error: %s":"API-fout: %s",'Model "%s" not found':'Model "%s" niet gevonden',"Request failed: %s":"Verzoek mislukt: %s",Retry:R3,"No running javascript instance found":"Geen draaiende JavaScript-instantie gevonden"},M3="Potwierdzony",N3="Działania",L3="Dodaj",P3="Wszystko",B3="Każdy",j3="Zastosuj",F3="Kwiecień",z3="Zapytać",U3="Astronomiczny",H3="Sierpień",W3="Odwołaj",G3="Zamknij",V3="Stan",K3="Warunki",Y3="Konsola",J3="Skopiowano",q3="Grudzień",X3="Domyślna",Z3="Opóźnienie",Q3="Usuń",e4="Opis",t4="Gotowe",s4="Uruchom shell",o4="Wyjaśnienie",i4="Eksport",n4="Luty",r4="Luty",a4="Filtr",l4="Folder",c4="Pt",u4="Piątek",d4="ID",h4="ID1",p4="ID2",g4="Import",m4="Instancja",f4="Instancje",$4="Instrukcje",b4="Styczeń",v4="Styczeń",y4="Lipiec",_4="Czerwiec",w4="Limit",C4="Marzec",T4="Maj",k4="Menu",S4="Wiadomość",E4="Po",I4="Model",x4="Poniedziałek",D4="Miesiąc",A4="Więcej",R4="Nazwa",O4="Listopad",M4="OK",N4="Październik",L4="Ok",P4="Pauza",B4="Pushover",j4="Pushsafer",F4="Przemianuj",z4="Powtórz",U4="Uruchom ponownie",H4="Wynik",W4="So",G4="Sobota",V4="Zapisz",K4="Harmonogram",Y4="Skrypt",J4="Wrzesień",q4="Symulacja",X4="Stos",Z4="Początek",Q4="Stan",e8="Nd",t8="Niedziela",s8="Telegram",o8="Cz",i8="Czwartek",n8="Czas",r8="Wyzwolony",a8="Wyzwalacze",l8="Wt",c8="Wtorek",u8="URL",d8="Wartość",h8="Wolumen",p8="Śr",g8="Środa",m8="Pisać",f8="Tak",$8="potwierdzenie",b8="wszystko",v8="i",y8="Astro",_8="w",w8="kontrola",C8="Kopiuj",T8="CRON",k8="Świt",S8="Jest to specjalny tryb, w którym stany i obiekty się nie zmieniają. Jednak w protokole będą wyświetlane tylko informacje o każdej planowanej zmianie.",E8="Odpluskwić",I8="Zmierzch",x8="łatwy",D8="każdy",A8="Funkcja",R8="ID",O8="Nazwa",M8="Rola",N8="Pokój",L8="Złota godzina",P8="Koniec złotej godziny",B8="Kod zostanie wykonany tylko za każdym razem, gdy warunek będzie spełniony. Na przykład. jeśli wyzwalanie na wartość czujnika temperatury i warunek to „jeśli temperatura jest wyższa niż 20 ° C”, to działania „następnie” będą wykonywane za każdym razem, gdy czujnik wyśle temperaturę i jest powyżej 20 ° C. O 21 ° C, o 22 ° C i tak dalej.",j8="Kod zostanie wykonany tylko wtedy, gdy wynik warunku ulegnie zmianie. Na przykład. jeśli wyzwalanie na wartość czujnika temperatury i warunek „jeśli temperatura jest wyższa niż 20 ° C”, to akcje „następnie” zostaną wykonane raz, gdy temperatura przekroczy 20. Następnym razem działania „następnie” zostaną wykonane, gdy temperatura nie udaje się poniżej 20, a następnie ponownie wzrasta powyżej 20.",F8="godziny",z8="zawiera",U8="interwał",H8="magia",W8="milisekund",G8="minuty",V8="ms",K8="Północ słoneczna",Y8="Żeglarski świt",J8="Żeglarski zmierzch",q8="Następny wschód słońca",X8="Następny zachód słońca",Z8="Noc",Q8="Koniec nocy",e6="normalny",t6="przesunięcie",s6="jeden",o6="lub",i6="cisza",n6="Szukaj",r6="sekundy",a6="Południe słoneczne",l6="Wschód słońca",c6="Koniec wschodu słońca",u6="Zachód słońca",d6="Początek zachodu słońca",h6="następnie",p6="Akceptuj",g6="Od",m6="Ostatnia zmiana",f6="Jakość",$6="Znacznik czasu",b6="Użytkownik",v6="Wartość",y6="dwa",_6="aktualizacja",w6="Dodaje wyniki debugowania do dziennika dla wielu poleceń systemowych",C6="Pełne dane wyjściowe dziennika",T6="gdy",k6="Wizard",S6="Ponów próbę",E6={"%s not found":"%s nie znaleziono","()":"()","(at %s)":"(w %s)","(optional)":"(opcjonalny)","-":"-",".":".","AI code generator":"Generator kodu AI","Planning...":"Planowanie...","Generating code...":"Generowanie kodu...","Show plan":"Pokaż plan",Ack:M3,Actions:N3,"Actual time of day":"Aktualna pora dnia",Add:L3,"Add new script":"Dodaj nowy skrypt",All:P3,"All files will be accepted":"Wszystkie pliki zostaną zaakceptowane",Any:B3,"Any month":"Dowolny miesiąc",Apply:j3,April:F3,"Are you sure?":"Jesteś pewny?",Ask:z3,Astronomical:U3,"Astronomical events today":"Wydarzenia astronomiczne dzisiaj",August:H3,"Blockly description":"Tworzenie reguł za pomocą bloków graficznych","Body:":"Treść:",Cancel:W3,"Cannot delete non empty item!":"Nie można usunąć niepustego elementu!","Change layout":"Zmiana układu",'Change theme (actual "%s")':"Zmień motyw (obecnie - „%s”)","Check blocks":"Sprawdź bloki","Check is not active, because javascript adapter is disabled":"Sprawdzanie nie jest aktywne, ponieważ adapter Javascript jest wyłączony","Clear search input":"Wyczyść dane wyszukiwania","Click on this icon":"Kliknij tę ikonę",Close:G3,"Close all but current":"Zamknij wszystkie oprócz bieżących","Collapse all":"Zwinąć wszystkie","Compares current time with astronomical event":"Porównuje aktualny czas z wydarzeniem astronomicznym","Compares current time with the user specific time":"Porównuje aktualny czas z czasem określonym przez użytkownika","Compares the state value with user defined value":"Porównuje wartość stanu z wartością zdefiniowaną przez użytkownika",Condition:V3,Conditions:K3,"Configuration not saved.":"Konfiguracja nie została zapisana.",Console:Y3,"Control or update some state":"Kontroluj lub aktualizuj stan","Control or update some state with delay":"Kontroluj lub aktualizuj jakiś stan z opóźnieniem","Convert blockly to javascript for ever.":"Bezpowrotna konwersja Blockly na Javascript.",Copied:J3,"Copy script":"Skopiuj skrypt","Copy to clipboard":"Skopiuj do schowka","Create new":"Utwórz nowy","Create new folder":"Utwórz nowy folder","Create new script":"Utwórz nowy skrypt","Create or edit CRON or time wizard":"Utwórz lub edytuj CRON lub kreator czasu","Dark Theme":"Ciemny schemat","Dark style":"Ciemny styl",Date:"Data","Debug instance":"Debuguj instancję","Debug options":"Opcje debugowania",December:q3,Default:X3,"Define cron...":"Zdefiniuj CRON ...","Define schedule...":"Zdefiniuj harmonogram ...",Delay:Z3,Delete:Q3,"Delete %s":"Usuń %s ...","Delete folder":"Usuń folder","Delete script":"Usuń skrypt",Description:e4,"Deselect all":"Odznacz wszystkie","Discard changes for %s":"Odrzuć zmiany dla %s",Done:t4,"Double click to write value":"Kliknij dwukrotnie, aby zapisać wartość","Download as file":"Download jako plik plik","Drop some files here or click...":"Upuść niektóre pliki tutaj lub kliknij ...","Duplicate name":"Duplikat nazwy","Edit script or just double click":"Edytuj skrypt lub po prostu kliknij dwukrotnie","Empty name is not allowed":"Pusta nazwa jest niedozwolona","End search mode":"Zakończ tryb wyszukiwania","Enter your question":"Wpisz swoją prośbę",Error:"Błąd","Error formatting code":"Błąd formatowania kodu","Error was found":"Błąd został znaleziony","Every day":"Codziennie",Exec:s4,"Executes some shell command":"Wykonuje polecenie powłoki","Existing scripts will be overwritten.":"Istniejące skrypty zostaną zastąpione.","Expand all":"Rozwiń wszystkie","Expert mode":"Tryb ekspercki",Explanation:o4,Export:i4,"Export all scripts":"Wyeksportuj wszystkie skrypty","Export blocks":"Eksportuj bloki","Export selected blocks":"Eksportuj wybrane bloki",Februar:n4,February:r4,Filter:a4,Folder:l4,Fr:c4,Friday:u4,Function:"Funkcja","Function editor":"Edytor funkcji","Function: executed":"Funkcja: wykonywana","Go to next line":"Przejdź do następnej linii","HTTP Call":"Połączenie HTTP","Hide logs":"Ukryj dzienniki",ID:d4,ID1:h4,ID2:p4,Import:g4,"Import blocks":"Importuj bloki","Import error":"Błąd importowania","Import scripts":"Importuj skrypty","Insert object ID":"Wstaw identyfikator obiektu",Instance:m4,"Instance is disabled":"Instancja jest wyłączona","Instance:":"Instancja:",Instances:f4,Instructions:$4,"Invalid CRON":"Nieprawidłowy CRON","It will not be possible to revert this operation.":"Cofnięcie tej operacji nie będzie możliwe.","JS description":"Tworzenie reguł w Javascript",Januar:b4,January:v4,July:y4,June:_4,"Just check":"Po prostu sprawdź","Language:":"Język:","Learn More":"Ucz się więcej","Light style":"Lekki styl",Limit:w4,"Local time":"Czas lokalny","Locate file":"Znajdź plik","Log outputs":"Log dziennika","Log text":"Tekst dziennika","Log: %s":"Dziennik: %s","Make a HTTP get request":"Złóż żądanie HTTP get","Make a pause between actions":"Zrób przerwę między czynnościami",March:C4,"March ":"Marzec ",May:T4,Menu:k4,Message:S4,Mo:E4,Model:I4,Monday:x4,Month:D4,More:A4,Name:R4,"No API key found":"Nie znaleziono klucza API","No Chat GPT Key found":"Nie znaleziono klucza GPT czatu","No active host found":"Nie znaleziono aktywnego hosta","Nothing found":"Nic nie znaleziono",November:O4,OK:M4,October:N4,Ok:L4,"On condition change":"W przypadku zmiany warunków","On script save or adapter start":"Podczas zapisywania skryptu lub uruchamiania adaptera","On weekdays":"W dni powszednie","Open configuration":"Otwarta konfiguracja","Operate two states":"Obsługuj dwa stany","Operations with two states":"Operacje z dwoma stanami","Paste your blocks here":"Wklej tutaj swoje bloki",Pause:P4,"Pause execution":"Wstrzymaj wykonanie","Pause script":"Wstrzymaj skrypt","Phone:":"Telefon:","Please select object ID...":"Wybierz identyfikator obiektu ...","Press Ctrl+Enter to get the answer":"Naciśnij klawisze Ctrl+Enter, aby uzyskać odpowiedź","Prettify the script":"Upiększ skrypt","Print some text in log":"Wydrukuj tekst w dzienniku","Priority:":"Priorytet:",Pushover:B4,Pushsafer:j4,"Read only ID selected: %s":"Wybrano identyfikator tylko do odczytu: %s",Rename:F4,"Reorder scripts in folders":"Zmień kolejność skryptów w folderach",Repeat:z4,Restart:U4,Result:H4,"Resume execution":"Wznów wykonanie","Root folder":"Folder główny","Rules description":"Twórz reguły z blokami IF, THEN, ELSE","Run script":"Uruchom skrypt",Sa:W4,Saturday:G4,Save:V4,"Save all":"Zapisz wszystko","Say It":"Wypowiedz","Say some text via sayit adapter":"Powiedz tekst przez adapter sayit",Schedule:K4,Script:Y4,"Script %s was modified on disk":"Skrypt %s został zmodyfikowany na dysku","Script is not running":"Skrypt nie działa","Search in scripts":"Szukaj w skryptach","Search...":"Szukaj...","Select all":"Zaznacz wszystko","Send email":"Wysłać email","Sends an email":"Wysyła e-mail","Sends message via Pushsafer":"Wysyła wiadomość przez Pushsafer","Sends message via pushover":"Wysyła wiadomość przez pushover","Sends message via telegram":"Wysyła wiadomość telegramem","Sends message via whatsapp-cmb":"Wysyła wiadomość przez WhatsApp-cmb",September:J4,"Server time":"Czas serwera","Set state action":"Ustaw stan działania","Set with delay":"Ustaw z opóźnieniem","Shell command":"Polecenie powłoki","Show astronomical events":"Pokaż wydarzenia astronomiczne","Show javascript code":"Pokaż kod JavaScript","Show logs":"Pokaż dzienniki","Show only paused scripts":"Pokaż tylko wstrzymane skrypty","Show only running scripts":"Pokaż tylko działające skrypty","Show only scripts with problems":"Pokaż tylko skrypty z problemami",Simulate:q4,"Some files will be rejected":"Niektóre pliki zostaną odrzucone","Sound:":"Dźwięk:",Stack:X4,Start:Z4,"Start script":"Uruchom skrypt",State:Q4,"State condition":"Warunek stanu","Step into function":"Wejdź do funkcji","Step out from function":"Wyjdź z funkcji","Stop on exception":"Zatrzymaj się na wyjątku",Su:e8,"Subject:":"Temat:",Sunday:t8,"TS description":"Tworzenie reguł w Typescript",Telegram:s8,"Text:":"Tekst:",Th:o8,"The script will be stopped and must be activated manually after debugging. Continue?":"Skrypt zostanie zatrzymany i należy go aktywować ręcznie po debugowaniu. Kontyntynuj?","This is advances option. You can write your own code here and it will be executed on trigger":"To jest opcja zaawansowana. Możesz tutaj napisać własny kod, który zostanie wykonany po wyzwoleniu",Thursday:i8,Time:n8,"Time condition":"Warunek czasowy","Title:":"Tytuł:","To:":"Do:","Trigger with value":"Wyzwalacz z wartością",Triggered:r8,Triggers:a8,"Triggers the on script saving or the javascript instance restart":"Uruchamia zapisywanie skryptu lub restart instancji javascript","Triggers the rule on update or change of some state":"Uruchamia regułę przy aktualizacji lub zmianie jakiegoś stanu","Triggers the rule periodically or on some specific time":"Uruchamia regułę okresowo lub w określonym czasie",Tu:l8,Tuesday:c8,URL:u8,"Unknown error":"Nieznany błąd","Unknown error!":"Nieznany błąd!","Use generated code":"Użyj wygenerowanego kodu","User function":"Funkcja użytkownika","User:":"Użytkownik:",Value:d8,"Vibration:":"Wibracja:",Volume:h8,We:p8,Wednesday:g8,"Whatsapp-cmb":"Whatsapp-cmb",Write:m8,"Write your own code":"Napisz swój własny kod",Yes:f8,"Yet exists!":"A jednak istnieje!","You can use %s in the URL to use current trigger value or %id to use the triggered object ID":"Możesz użyć %s w adresie URL, aby użyć bieżącej wartości wyzwalacza, %id, aby użyć wyzwalanego identyfikatora obiektu, %name, aby wyświetlić nazwę identyfikatora wyzwalanego obiektu, lub %old, aby użyć starej wartości wyzwalacza","You can use %s in the command to use current trigger value or %id to use the triggered object ID":"Możesz użyć %s w poleceniu, aby użyć bieżącej wartości wyzwalającej, %id, aby użyć identyfikatora wyzwalanego obiektu, %name, aby wyświetlić nazwę identyfikatora wyzwalanego obiektu, lub %old, aby użyć starej wartości wyzwalającej","You can use %s in the text to display current trigger value or %id to display the triggered object ID":"Możesz użyć %s w tekście, aby wyświetlić aktualną wartość wyzwalającą, %id, aby użyć identyfikatora wyzwolonego obiektu, %name, aby wyświetlić nazwę identyfikatora wyzwolonego obiektu lub %old, aby użyć starej wartości wyzwalającej","You can use %s in the value to use the current trigger value or %id to display the triggered object ID":"Możesz użyć %s w wartości, aby użyć bieżącej wartości wyzwalacza, %id, aby użyć identyfikatora wyzwalanego obiektu, %name, aby wyświetlić nazwę identyfikatora wyzwalanego obiektu, lub %old, aby użyć starej wartości wyzwalacza","You have to enter OpenAI API key in the configuration of javascript adapter.":"Należy wprowadzić klucz OpenAI API w konfiguracji adaptera javascript.","You have to enter at least one API key in the configuration of javascript adapter.":"Musisz wprowadzić co najmniej jeden klucz API (OpenAI, Anthropic lub Gemini) w konfiguracji adaptera javascript.","Please select a valid model":"Wybierz prawidłowy model","[equal]":"[równy]","[greater or equal]":"[większe lub równe]","[greater]":"[większe]","[hysteresis]":"[histereza]","[includes]":"[obejmuje]","[less or equal]":"[mniejsze lub równe]","[less]":"[mniejsze]","[not equal]":"[nie równe]",acknowledgment:$8,all:b8,and:v8,astro:y8,at:_8,"clear running":"czyste uruchomienie",control:w8,copy:C8,cron:T8,dawn:k8,debug_help:S8,debug_label:E8,default:"domyślna",dusk:I8,easy:x8,else:"inaczej","equal to":"równy",every:D8,"every hour at 0 minutes":"co godzinę po 0 minutach",false:"fałsz","file reading has failed: %s":"odczyt pliku nie powiódł się: %s","file reading was aborted":"odczyt pliku został przerwany",filter_func:A8,filter_id:R8,filter_name:O8,filter_role:M8,filter_room:N8,"for edit or create script":"do edycji lub utwórz nowy skrypt","for professionals":"dla profesjonalistów","for programmers":"dla programistów",goldenHour:L8,goldenHourEnd:P8,"greater or equal":"większe lub równe","greater or equal to":"więcej lub równo","greater than":"więcej niż",help_just_check:B8,help_on_change:j8,"high priority":"wysoki priorytet","high-priority":"wysoki priorytet","highest priority":"najwyższy priorytet",hours:F8,includes:z8,interval:U8,"just check":"po prostu sprawdź","less or equal":"mniejsze lub równe","less or equal to":"mniej lub równo","less than":"mniej niż","lower priority":"niższy priorytet","lowest priority":"najniższy priorytet",magic:H8,milliseconds:W8,minutes:G8,ms:V8,nadir:K8,nauticalDawn:Y8,nauticalDusk:J8,nextSunrise:q8,nextSunset:X8,night:Z8,nightEnd:Q8,"no blocks found":"Nie znaleziono bloków","no group":"BRAK GRUPY",normal:e6,"normal priority":"normalny priorytet","not equal to":"nie równa się","not properly connected":"Ten blok nie jest poprawnie podłączony do innych bloków.",offset:t6,"on change":"na zmianę","on condition change":"pod warunkiem zmiany warunków","on update":"po aktualizacji",one:s6,or:o6,quiet:i6,"reset search":"zresetuj wyszukiwanie",search:n6,seconds:r6,solarNoon:a6,"store in":"przechowaj w",sunrise:l6,sunriseEnd:c6,sunset:u6,sunsetStart:d6,then:h6,"toggle value":"wartość przełączania",tooltip_ack:p6,tooltip_from:g6,tooltip_lc:m6,tooltip_quality:f6,tooltip_ts:$6,tooltip_user:b6,tooltip_value:v6,true:"prawda",two:y6,undefined:"nieokreślony",update:_6,"use seconds":"użyj sekund","use trigger value":"użyj wartości wyzwalającej",verbose_help:w6,verbose_label:C6,when:T6,with:"z","with date":"z datą","with offset":"z przesunięciem",wizard:k6,"Loading models...":"Ładowanie modeli...","Could not connect to API at %s":"Nie można połączyć się z API pod adresem %s","Invalid API key":"Nieprawidłowy klucz API","Access denied by API":"Odmowa dostępu przez API","API error: %s":"Błąd API: %s",'Model "%s" not found':'Model "%s" nie znaleziony',"Request failed: %s":"Żądanie nie powiodło się: %s",Retry:S6,"No running javascript instance found":"Nie znaleziono uruchomionej instancji JavaScript"},I6="Reconhecido",x6="Ações",D6="Adicionar",A6="Todos",R6="Nenhum",O6="Aplique",M6="abril",N6="Perguntar",L6="Astronômico",P6="agosto",B6="Cancelar",j6="Fechar",F6="Doença",z6="Condições",U6="Console",H6="Copiado",W6="dezembro",G6="Predefinição",V6="Atraso",K6="Deletar",Y6="Descrição",J6="Pronto",q6="Exec shell",X6="Explicação",Z6="Exportação",Q6="Februar",e9="fevereiro",t9="Filtro",s9="Pasta",o9="Fr",i9="Sexta-feira",n9="ID",r9="ID1",a9="ID2",l9="Importar",c9="Instância",u9="Instâncias",d9="Instruções",h9="Januar",p9="janeiro",g9="julho",m9="junho",f9="Limite",$9="março",b9="maio",v9="Menu",y9="mensagem",_9="Mo",w9="Modelo",C9="Segunda-feira",T9="Mês",k9="Mais",S9="Nome",E9="novembro",I9="OK",x9="outubro",D9="Ok",A9="Pausa",R9="Pushover",O9="Pushsafer",M9="Renomear",N9="Repetir",L9="Reiniciar",P9="Resultado",B9="Sá",j9="Sábado",F9="Salve",z9="Cronograma",U9="Script",H9="setembro",W9="Simular",G9="Pilha",V9="Começar",K9="Estado",Y9="Su",J9="Domingo",q9="Telegrama",X9="4",Z9="Quinta-feira",Q9="Tempo",eK="Provocado",tK="Gatilhos",sK="Tu",oK="terça",iK="URL",nK="Valor",rK="Volume",aK="3",lK="quarta",cK="Escrever",uK="sim",dK="reconhecimento",hK="todos",pK="e",gK="astro",mK="no",fK="ao controle",$K="copiar",bK="CRON",vK="alvorecer",yK="Este é um modo especial no qual estados e objetos não serão alterados. Mas apenas as informações sobre cada mudança planejada serão exibidas no protocolo.",_K="Depurar",wK="Crepúsculo",CK="fácil",TK="cada",kK="Função",SK="ID",EK="Nome",IK="Tipo",xK="Quarto",DK="Hora dourada",AK="Fim da hora de ouro",RK='O código será executado apenas sempre que a condição for verdadeira. Por exemplo. se disparar no valor do sensor de temperatura e a condição for "se a temperatura for maior que 20 ° C", as ações "então" serão executadas toda vez que o sensor enviar a temperatura e ela estiver acima de 20 ° C. Por 21 ° C, por 22 ° C e assim por diante.',OK='O código será executado apenas se o resultado da condição mudar. Por exemplo. se disparar no valor do sensor de temperatura e a condição for "se a temperatura for maior que 20 ° C", as ações "então" serão executadas uma vez quando a temperatura estiver acima de 20. Na próxima vez, as ações "então" serão executadas quando a temperatura falha abaixo de 20 e sobe acima de 20 novamente.',MK="horas",NK="inclui",LK="intervalo",PK="Magia",BK="milissegundos",jK="minutos",FK="ms",zK="nadir",UK="Madrugada náutica",HK="Crepúsculo náutico",WK="próximo nascer do sol",GK="Próximo pôr do sol",VK="Noite",KK="Fim de noite",YK="normal",JK="Deslocamento",qK="1",XK="ou",ZK="quieto",QK="procurar",eY="segundos",tY="Meio-dia solar",sY="nascer do sol",oY="Fim do nascer do sol",iY="pôr do sol",nY="Começo do pôr do sol",rY="então",aY="reconhecer",lY="de",cY="Última alteração",uY="Qualidade",dY="timestamp",hY="usuário",pY="valor",gY="dois",mY="atualizar",fY="Adiciona saída de depuração ao log para muitos comandos do sistema",$Y="Saídas de log detalhadas",bY="quando",vY="Wizard",yY="Tentar novamente",_Y={"%s not found":"%s não encontrado","()":"()","(at %s)":"(em %s)","(optional)":"(opcional)","-":"-",".":".","AI code generator":"Gerador de código de IA","Planning...":"Planejando...","Generating code...":"Gerando código...","Show plan":"Mostrar plano",Ack:I6,Actions:x6,"Actual time of day":"Hora real do dia",Add:D6,"Add new script":"Adicionar novo script",All:A6,"All files will be accepted":"Todos os arquivos serão aceitos",Any:R6,"Any month":"Qualquer mês",Apply:O6,April:M6,"Are you sure?":"Você tem certeza?",Ask:N6,Astronomical:L6,"Astronomical events today":"Eventos astronômicos hoje",August:P6,"Blockly description":"Criando regras por blocos gráficos","Body:":"Corpo:",Cancel:B6,"Cannot delete non empty item!":"Não pode ser deletar, porque não está vazio!","Change layout":"Alterar layout",'Change theme (actual "%s")':'Alterar tema (agora - "%s")',"Check blocks":"Verificar blocos","Check is not active, because javascript adapter is disabled":"A verificação de sintaxe não está ativa porque o adaptador javascript não está rodando.","Clear search input":"Limpar entrada de pesquisa","Click on this icon":"Clique neste ícone",Close:j6,"Close all but current":"Fechar tudo, menos atual","Collapse all":"Recolher todos","Compares current time with astronomical event":"Compara o tempo atual com o evento astronômico","Compares current time with the user specific time":"Compara a hora atual com a hora específica do usuário","Compares the state value with user defined value":"Compara o valor do estado com o valor definido pelo usuário",Condition:F6,Conditions:z6,"Configuration not saved.":"Configuração não esta salva.",Console:U6,"Control or update some state":"Controlar ou atualizar algum estado","Control or update some state with delay":"Controlar ou atualizar algum estado com atraso","Convert blockly to javascript for ever.":"Converter Blockly em Javascript permanentemente.",Copied:H6,"Copy script":"Copiar script","Copy to clipboard":"Copiar para área de transferência","Create new":"Crie um novo","Create new folder":"Criar nova pasta","Create new script":"Criar novo script","Create or edit CRON or time wizard":"Criar ou editar o assistente cron ou o assistente de horário","Dark Theme":"Layout escuro","Dark style":"Estilo escuro",Date:"Encontro","Debug instance":"Instância de depuração","Debug options":"Opções de depuração",December:W6,Default:G6,"Define cron...":"Definir cron...","Define schedule...":"Definir agendamento ...",Delay:V6,Delete:K6,"Delete %s":"Deletar %s...","Delete folder":"Deletar pasta","Delete script":"Deletar script",Description:Y6,"Deselect all":"Desmarcar todos","Discard changes for %s":"Descartar alterações para %s",Done:J6,"Double click to write value":"Clique duas vezes para escrever o valor","Download as file":"Baixar como arquivo","Drop some files here or click...":"Solte alguns arquivos aqui ou clique em...","Duplicate name":"Nome duplicado","Edit script or just double click":"Edite o script ou clique duas vezes","Empty name is not allowed":"Nome vazio não é permitido","End search mode":"Finalizar modo de pesquisa","Enter your question":"Digite sua solicitação",Error:"Erro","Error formatting code":"Erro de formatação de código","Error was found":"Erro foi encontrado","Every day":"Todos os dias",Exec:q6,"Executes some shell command":"Executa algum comando shell","Existing scripts will be overwritten.":"Os scripts existentes serão substituídos.","Expand all":"Expandir todos","Expert mode":"Modo de especialista",Explanation:X6,Export:Z6,"Export all scripts":"Exportar todos os scripts","Export blocks":"Exportar blocos","Export selected blocks":"Exportar blocos selecionados",Februar:Q6,February:e9,Filter:t9,Folder:s9,Fr:o9,Friday:i9,Function:"Função","Function editor":"Editor de funções","Function: executed":"Função: executado","Go to next line":"Vá para a próxima linha","HTTP Call":"Chamada HTTP","Hide logs":"Ocultar logs",ID:n9,ID1:r9,ID2:a9,Import:l9,"Import blocks":"Importar blocos","Import error":"Erro de importação","Import scripts":"Importar script","Insert object ID":"Inserir ID do objeto",Instance:c9,"Instance is disabled":"Instância está desativada","Instance:":"Instância:",Instances:u9,Instructions:d9,"Invalid CRON":"CRON inválido","It will not be possible to revert this operation.":"Não será possível reverter esta operação.","JS description":"Criando regras escrevendo Javascript",Januar:h9,January:p9,July:g9,June:m9,"Just check":"Apenas verifique","Language:":"Língua:","Learn More":"Aprender mais","Light style":"Estilo claro",Limit:f9,"Local time":"Hora local","Locate file":"Localize o arquivo","Log outputs":"Saídas de log","Log text":"Texto de registro","Log: %s":"Log: %s","Make a HTTP get request":"Faça uma solicitação HTTP get","Make a pause between actions":"Faça uma pausa entre as ações",March:$9,"March ":"Março",May:b9,Menu:v9,Message:y9,Mo:_9,Model:w9,Monday:C9,Month:T9,More:k9,Name:S9,"No API key found":"Nenhuma chave API encontrada","No Chat GPT Key found":"Nenhuma chave GPT de bate-papo encontrada","No active host found":"Nenhum host ativo encontrado","Nothing found":"Nada encontrado",November:E9,OK:I9,October:x9,Ok:D9,"On condition change":"Na mudança de condição","On script save or adapter start":"Ao salvar o script ou iniciar o adaptador","On weekdays":"Nos dias úteis","Open configuration":"Configuração aberta","Operate two states":"Operar dois estados","Operations with two states":"Operações com dois estados","Paste your blocks here":"Cole seus blocos aqui",Pause:A9,"Pause execution":"Pausar a execução","Pause script":"Pausar script","Phone:":"Telefone:","Please select object ID...":"Selecione o ID do objeto...","Press Ctrl+Enter to get the answer":"Pressione Ctrl+Enter para obter a resposta","Prettify the script":"Embeleze o roteiro","Print some text in log":"Imprimir algum texto no log","Priority:":"Prioridade:",Pushover:R9,Pushsafer:O9,"Read only ID selected: %s":"ID somente leitura selecionada: %s",Rename:M9,"Reorder scripts in folders":"Reordenar scripts em pastas",Repeat:N9,Restart:L9,Result:P9,"Resume execution":"Retomar execução","Root folder":"Pasta principal","Rules description":"Crie regras com blocos IF, THEN, ELSE","Run script":"Executar script",Sa:B9,Saturday:j9,Save:F9,"Save all":"Salvar tudo","Say It":"Say It","Say some text via sayit adapter":"Diga algum texto através do adaptador sayit",Schedule:z9,Script:U9,"Script %s was modified on disk":'O script "%s" foi modificado no disco rígido',"Script is not running":"Script não está sendo executado","Search in scripts":"Pesquisa em scripts","Search...":"Procurar...","Select all":"Selecionar tudo","Send email":"Enviar email","Sends an email":"Envia um email","Sends message via Pushsafer":"Envia mensagem via Pushsafer","Sends message via pushover":"Envia mensagem via pushover","Sends message via telegram":"Envia mensagem via telegrama","Sends message via whatsapp-cmb":"Envia mensagem via whatsapp-cmb",September:H9,"Server time":"Tempo de servidor","Set state action":"Definir ação de estado","Set with delay":"Definido com atraso","Shell command":"Comando shell","Show astronomical events":"Mostrar eventos astronômicos","Show javascript code":"Mostrar código Javascript","Show logs":"Mostrar logs","Show only paused scripts":"Mostrar apenas scripts pausados","Show only running scripts":"Mostrar apenas scripts em execução","Show only scripts with problems":"Mostrar apenas scripts com problemas",Simulate:W9,"Some files will be rejected":"Alguns arquivos serão rejeitados","Sound:":"Som:",Stack:G9,Start:V9,"Start script":"Iniciar script",State:K9,"State condition":"Condição de estado","Step into function":"Entre na função","Step out from function":"Saia da função","Stop on exception":"Pare na exceção",Su:Y9,"Subject:":"Sujeito:",Sunday:J9,"TS description":"Criando regras escrevendo Typecript",Telegram:q9,"Text:":"Texto:",Th:X9,"The script will be stopped and must be activated manually after debugging. Continue?":"O script será interrompido e deve ser ativado manualmente após a depuração. Continuar?","This is advances option. You can write your own code here and it will be executed on trigger":"Esta é a opção de avanços. Você pode escrever seu próprio código aqui e ele será executado no gatilho",Thursday:Z9,Time:Q9,"Time condition":"Condição de tempo","Title:":"Título:","To:":"Para:","Trigger with value":"Trigger com valor",Triggered:eK,Triggers:tK,"Triggers the on script saving or the javascript instance restart":"Aciona o salvamento do script ou a reinicialização da instância javascript","Triggers the rule on update or change of some state":"Aciona a regra na atualização ou mudança de algum estado","Triggers the rule periodically or on some specific time":"Aciona a regra periodicamente ou em algum momento específico",Tu:sK,Tuesday:oK,URL:iK,"Unknown error":"Erro desconhecido","Unknown error!":"Erro desconhecido!","Use generated code":"Usar código gerado","User function":"Função do usuário","User:":"Do utilizador:",Value:nK,"Vibration:":"Vibração:",Volume:rK,We:aK,Wednesday:lK,"Whatsapp-cmb":"Whatsapp-cmb",Write:cK,"Write your own code":"Escreva seu próprio código",Yes:uK,"Yet exists!":"Ainda existe!","You can use %s in the URL to use current trigger value or %id to use the triggered object ID":"Você pode usar %s na URL para usar o valor do gatilho atual, %id para usar o ID do objeto acionado, %name para mostrar o nome do ID do objeto acionado ou %old para usar o valor do gatilho antigo","You can use %s in the command to use current trigger value or %id to use the triggered object ID":"Você pode usar %s no comando para usar o valor do acionador atual, %id para usar o ID do objeto acionado, %name para mostrar o nome do ID do objeto acionado ou %old para usar o valor do acionador antigo","You can use %s in the text to display current trigger value or %id to display the triggered object ID":"Você pode usar %s no texto para exibir o valor do acionador atual, %id para usar o ID do objeto acionado, %name para mostrar o nome do ID do objeto acionado ou %old para usar o valor do acionador antigo","You can use %s in the value to use the current trigger value or %id to display the triggered object ID":"Você pode usar %s no valor para usar o valor do acionador atual, %id para usar o ID do objeto acionado, %name para mostrar o nome do ID do objeto acionado ou %old para usar o valor do acionador antigo","You have to enter OpenAI API key in the configuration of javascript adapter.":"Você deve inserir a chave da API OpenAI na configuração do adaptador javascript.","You have to enter at least one API key in the configuration of javascript adapter.":"Você deve inserir pelo menos uma chave API (OpenAI, Anthropic ou Gemini) na configuração do adaptador javascript.","Please select a valid model":"Selecione um modelo válido","[equal]":"[igual]","[greater or equal]":"[maior ou igual]","[greater]":"[maior]","[hysteresis]":"[histerese]","[includes]":"[inclui]","[less or equal]":"[menor ou igual]","[less]":"[menos]","[not equal]":"[não igual]",acknowledgment:dK,all:hK,and:pK,astro:gK,at:mK,"clear running":"corrida limpa",control:fK,copy:$K,cron:bK,dawn:vK,debug_help:yK,debug_label:_K,default:"predefinição",dusk:wK,easy:CK,else:"outro","equal to":"igual a",every:TK,"every hour at 0 minutes":"a cada hora em 0 minutos",false:"falso","file reading has failed: %s":"a leitura do arquivo falhou: %s","file reading was aborted":"a leitura do arquivo foi abortada",filter_func:kK,filter_id:SK,filter_name:EK,filter_role:IK,filter_room:xK,"for edit or create script":"para editar ou criar um novo script","for professionals":"para profissionais","for programmers":"para programadores",goldenHour:DK,goldenHourEnd:AK,"greater or equal":"maior ou igual","greater or equal to":"maior ou igual a","greater than":"Maior que",help_just_check:RK,help_on_change:OK,"high priority":"prioridade máxima","high-priority":"prioridade máxima","highest priority":"Prioridade máxima",hours:MK,includes:NK,interval:LK,"just check":"Apenas verifique","less or equal":"menor ou igual","less or equal to":"menor ou igual a","less than":"Menor que","lower priority":"prioridade mais baixa","lowest priority":"prioridade mais baixa",magic:PK,milliseconds:BK,minutes:jK,ms:FK,nadir:zK,nauticalDawn:UK,nauticalDusk:HK,nextSunrise:WK,nextSunset:GK,night:VK,nightEnd:KK,"no blocks found":"Nenhum bloco encontrado","no group":"SEM GRUPO",normal:YK,"normal priority":"prioridade normal","not equal to":"não é igual a","not properly connected":"Este bloco não está conectado corretamente com outros blocos.",offset:JK,"on change":"em mudança","on condition change":"na mudança de condição","on update":"em atualização",one:qK,or:XK,quiet:ZK,"reset search":"redefinir pesquisa",search:QK,seconds:eY,solarNoon:tY,"store in":"armazenar em",sunrise:sY,sunriseEnd:oY,sunset:iY,sunsetStart:nY,then:rY,"toggle value":"valor de alternância",tooltip_ack:aY,tooltip_from:lY,tooltip_lc:cY,tooltip_quality:uY,tooltip_ts:dY,tooltip_user:hY,tooltip_value:pY,true:"verdade",two:gY,undefined:"Indefinido",update:mY,"use seconds":"use segundos","use trigger value":"use o gatilho",verbose_help:fY,verbose_label:$Y,when:bY,with:"com","with date":"com data","with offset":"com deslocamento",wizard:vY,"Loading models...":"Carregando modelos...","Could not connect to API at %s":"Não foi possível conectar à API em %s","Invalid API key":"Chave API inválida","Access denied by API":"Acesso negado pela API","API error: %s":"Erro de API: %s",'Model "%s" not found':'Modelo "%s" não encontrado',"Request failed: %s":"Solicitação falhou: %s",Retry:yY,"No running javascript instance found":"Nenhuma instância JavaScript em execução encontrada"},wY="Подтверждение",CY="Действия",TY="Добавить",kY="Все",SY="Любая",EY="Применить",IY="Апрель",xY="Спросить",DY="Aстрономический",AY="Август",RY="Отмена",OY="Закрыть",MY="Условие",NY="Условия",LY="Приставка",PY="Скопировано",BY="Декабрь",jY="Дефолт",FY="Задержка",zY="Удалить",UY="Описание",HY="Готово",WY="Исполнить shell",GY="Объяснение",VY="Экспорт",KY="Февраль",YY="Февраль",JY="Фильтр",qY="Папка",XY="Пт",ZY="пятница",QY="ID",eJ="ID1",tJ="ID2",sJ="Импорт",oJ="Экземпляр",iJ="Экземпляры",nJ="Инструкции",rJ="Январь",aJ="Январь",lJ="Июль",cJ="Июнь",uJ="Предел",dJ="Март",hJ="Май",pJ="Меню",gJ="Сообщение",mJ="Пн",fJ="Модель",$J="понедельник",bJ="Месяц",vJ="Более",yJ="Имя",_J="Ноябрь",wJ="Ок",CJ="Октябрь",TJ="Ok",kJ="Пауза",SJ="Pushover",EJ="Pushsafer",IJ="Переименовать",xJ="Повторение",DJ="Перезапустить",AJ="Результат",RJ="Сб",OJ="суббота",MJ="Сохранить",NJ="Расписание",LJ="скрипт",PJ="Сентябрь",BJ="Симулировать",jJ="Stack",FJ="Начинать",zJ="Состояние",UJ="Вс",HJ="Воскресенье",WJ="Telegram",GJ="Чт",VJ="Четверг",KJ="Время",YJ="Срабатывает",JJ="Триггеры",qJ="Вт",XJ="вторник",ZJ="URL",QJ="Значение",e7="Громкость",t7="Ср",s7="среда",o7="Напишите",i7="Да",n7="подтверждение",r7="все",a7="и",l7="Астро",c7="в",u7="контроль",d7="копия",h7="CRON",p7="Рассвет",g7="Это особый режим, в котором состояния и объекты не будут меняться. Но в протоколе будет отображаться только информация о каждом планируемом изменении.",m7="Отлаживать",f7="Сумерки",$7="легкий",b7="каждые(ый)",v7="Функция",y7="ID",_7="Название",w7="Роль",C7="Комната",T7="Золотой час",k7="Конец золотого часа",S7="Код будет выполняться только каждый раз, когда условие истинно. Например. при срабатывании по значению датчика температуры и условию «если температура выше 20°C», действия «затем» будут выполняться каждый раз, когда датчик отправляет значение температуры, и оно превышает 20°C. На 21°С, на 22°С и так далее.",E7="Код будет выполнен только в случае изменения результата условия. Например, при срабатывании по значению датчика температуры и условию «если температура больше 20°C», действия «затем» будут выполнены один раз, когда температура превысит 20°C. В следующий раз действия «затем» будут выполнены, когда температура опустится ниже 20°C, а затем снова поднимается выше 20°C.",I7="час(ов)",x7="содержит",D7="интервал",A7="магия",R7="миллисекунды",O7="минут(у)",M7="мс",N7="Надир",L7="Морской рассвет",P7="Морские сумерки",B7="Следующий восход",j7="Следующий закат",F7="Ночь",z7="Конец ночи",U7="нормальный",H7="сдвиг",W7="один",G7="или",V7="тихий",K7="поиск",Y7="секунд",J7="Солнечный полдень",q7="Восход солнца",X7="Конец восхода",Z7="Закат солнца",Q7="Начало заката",eq="тогда",tq="Подтверждено",sq="От",oq="Последнее изменение",iq="Качественный",nq="Время",rq="Пользователь",aq="Значение",lq="два",cq="обновить",uq="Добавляет вывод отладки в журнал для многих системных команд.",dq="Подробный протокол",hq="если",pq="Мастер",gq="Повторить",mq={"%s not found":"%s не найден","()":"()","(at %s)":"(в %s)","(optional)":"(необязательный)","-":"-",".":".","AI code generator":"ИИ Генератор кода","Planning...":"Планирование...","Generating code...":"Генерация кода...","Show plan":"Показать план",Ack:wY,Actions:CY,"Actual time of day":"Фактическое время суток",Add:TY,"Add new script":"Добавить новый скрипт",All:kY,"All files will be accepted":"Все файлы будут приняты",Any:SY,"Any month":"В любой месяц",Apply:EY,April:IY,"Are you sure?":"Вы уверены?",Ask:xY,Astronomical:DY,"Astronomical events today":"Астрономические события сегодня",August:AY,"Blockly description":"Создание правил графическими блоками","Body:":"Тело:",Cancel:RY,"Cannot delete non empty item!":"Не удается удалить непустой элемент!","Change layout":"Изменить макет",'Change theme (actual "%s")':'Сменить тему (сейчас - "%s")',"Check blocks":"Проверить блоки","Check is not active, because javascript adapter is disabled":"Проверка неактивна, потому что адаптер Javascript отключен","Clear search input":"Очистить ввод","Click on this icon":"Нажмите на этот значок",Close:OY,"Close all but current":"Закрыть все кроме текущего","Collapse all":"Свернуть все","Compares current time with astronomical event":"Сравнивает текущее время с астрономическим событием","Compares current time with the user specific time":"Сравнивает текущее время с конкретным временем пользователя","Compares the state value with user defined value":"Сравнивает значение состояния с пользовательским значением",Condition:MY,Conditions:NY,"Configuration not saved.":"Конфигурация не сохранена.",Console:LY,"Control or update some state":"Контролировать или обновлять какое-то состояние","Control or update some state with delay":"Контролировать или обновлять какое-либо состояние с задержкой","Convert blockly to javascript for ever.":"Преобразовать blockly в Javascript навсегда.",Copied:PY,"Copy script":"Скопировать скрипт","Copy to clipboard":"Скопировать в буфер обмена","Create new":"Создать новый","Create new folder":"Создать новую папку","Create new script":"Создать новый скрипт","Create or edit CRON or time wizard":"Создание или редактирование CRON или мастера времени","Dark Theme":"Тёмная тема","Dark style":"Темный стиль",Date:"Дата","Debug instance":"Экземпляр отладки","Debug options":"Варианты отладки",December:BY,Default:jY,"Define cron...":"Задать правило ...","Define schedule...":"Задать расписание...",Delay:FY,Delete:zY,"Delete %s":"Удалить %s...","Delete folder":"Удалить папку","Delete script":"Удалить скрипт",Description:UY,"Deselect all":"Снять выбор со всех","Discard changes for %s":"Отменить изменения для %s",Done:HY,"Double click to write value":"Двойной щелчок для записи значения","Download as file":"Скачать как файл","Drop some files here or click...":"Перетыщите сюда файлы или нажмите ...","Duplicate name":"Повторяющееся имя","Edit script or just double click":"Редактировать скрипт или просто дважды щелкнуть","Empty name is not allowed":"Пустое имя не допускается","End search mode":"Закончить поиск","Enter your question":"Введи свою просьбу",Error:"Ошибка","Error formatting code":"Ошибка форматирования кода","Error was found":"Ошибка была найдена","Every day":"Каждый день",Exec:WY,"Executes some shell command":"Выполняет некоторую команду оболочки","Existing scripts will be overwritten.":"Существующие скрипты будут перезаписаны.","Expand all":"Открыть все","Expert mode":"Экспертный режим",Explanation:GY,Export:VY,"Export all scripts":"Экспорт всех скриптов","Export blocks":"Экспортировать блоки","Export selected blocks":"Экспортировать выбранные блоки",Februar:KY,February:YY,Filter:JY,Folder:qY,Fr:XY,Friday:ZY,Function:"Функция","Function editor":"Редактор функции","Function: executed":"Функция: выполнено","Go to next line":"Перейти к следующей строке","HTTP Call":"HTTP-вызов","Hide logs":"Скрыть журналы",ID:QY,ID1:eJ,ID2:tJ,Import:sJ,"Import blocks":"Импортировать блоки","Import error":"Ошибка импорта","Import scripts":"Импорт скриптов","Insert object ID":"Вставить ID объекта",Instance:oJ,"Instance is disabled":"Экземпляр отключен","Instance:":"Пример:",Instances:iJ,Instructions:nJ,"Invalid CRON":"Неправильный CRON","It will not be possible to revert this operation.":"Невозможно вернуть эту операцию.","JS description":"Создание правил путём написания Javascript",Januar:rJ,January:aJ,July:lJ,June:cJ,"Just check":"Просто проверить","Language:":"Язык:","Learn More":"Узнать больше","Light style":"Светлый стиль",Limit:uJ,"Local time":"Местное время","Locate file":"Показать файл в дереве","Log outputs":"Журнал","Log text":"Текст журнала","Log: %s":"Журнал: %s","Make a HTTP get request":"Сделайте HTTP-запрос на получение","Make a pause between actions":"Сделайте паузу между действиями",March:dJ,"March ":"Март ",May:hJ,Menu:pJ,Message:gJ,Mo:mJ,Model:fJ,Monday:$J,Month:bJ,More:vJ,Name:yJ,"No API key found":"API-ключ не найден","No Chat GPT Key found":"Ключ GPT для чата не найден","No active host found":"Активный host не найден","Nothing found":"Ничего не найдено",November:_J,OK:wJ,October:CJ,Ok:TJ,"On condition change":"При изменении реузльтата условий","On script save or adapter start":"При сохранении скрипта или запуске адаптера","On weekdays":"По дням недели","Open configuration":"Открыть настройки","Operate two states":"Операции над двумя состояниями","Operations with two states":"Операции с двумя состояниями","Paste your blocks here":"Вставьте свои блоки сюда",Pause:kJ,"Pause execution":"Приостановить выполнение","Pause script":"Остановить скрипт","Phone:":"Телефон:","Please select object ID...":"Пожалуйста, выберите ID объекта ...","Press Ctrl+Enter to get the answer":"Нажмите Ctrl+Enter, чтобы получить ответ","Prettify the script":"Украсьте сценарий","Print some text in log":"Напечатать текст в журнале","Priority:":"Приоритет:",Pushover:SJ,Pushsafer:EJ,"Read only ID selected: %s":"Выбран идентификатор только для чтения: %s",Rename:IJ,"Reorder scripts in folders":"Сортировать скрипты в папках",Repeat:xJ,Restart:DJ,Result:AJ,"Resume execution":"Возобновить выполнение","Root folder":"Корневая папка","Rules description":"Создавайте правила с блоками ЕСЛИ, ТО, ИНАЧЕ","Run script":"Запустить скрипт",Sa:RJ,Saturday:OJ,Save:MJ,"Save all":"Сохранить все","Say It":"Say It","Say some text via sayit adapter":"Произнесите текст через адаптер Sayit",Schedule:NJ,Script:LJ,"Script %s was modified on disk":'Скрипт "%s" был изменен на диске',"Script is not running":"Сценарий не запущен","Search in scripts":"Поиск в скриптах","Search...":"Поиск...","Select all":"Выбрать все","Send email":"Отправить email","Sends an email":"Отправляет электронное письмо","Sends message via Pushsafer":"Отправляет сообщение через Pushsafer","Sends message via pushover":"Отправляет сообщение через пустышку","Sends message via telegram":"Отправляет сообщение в телеграмме","Sends message via whatsapp-cmb":"Отправляет сообщение через whatsapp-cmb",September:PJ,"Server time":"Время сервера","Set state action":"Установить состояние","Set with delay":"Установить с задержкой","Shell command":"Команда оболочки","Show astronomical events":"Показать астрономические события","Show javascript code":"Показать код Javascript","Show logs":"Показать журналы","Show only paused scripts":"Показывать только приостановленные сценарии","Show only running scripts":"Показывать только запущенные скрипты","Show only scripts with problems":"Показывать только скрипты с проблемами",Simulate:BJ,"Some files will be rejected":"Некоторые файлы будут отклонены","Sound:":"Звук:",Stack:jJ,Start:FJ,"Start script":"Старт скрипта",State:zJ,"State condition":"Сравнение состояния","Step into function":"Шаг в функционирование","Step out from function":"Выйти из функции","Stop on exception":"Остановить при исключении",Su:UJ,"Subject:":"Предмет:",Sunday:HJ,"TS description":"Создание правил путём написания Typescript",Telegram:WJ,"Text:":"Текст:",Th:GJ,"The script will be stopped and must be activated manually after debugging. Continue?":"Cкрипт будет остановлен и должен быть активирован вручную после отладки. Продолжать?","This is advances option. You can write your own code here and it will be executed on trigger":"Это расширеный вариант. Вы можете написать здесь свой код и он будет выполняться по триггеру",Thursday:VJ,Time:KJ,"Time condition":"Условие времени","Title:":"Заголовок:","To:":"К:","Trigger with value":"Триггер со значением",Triggered:YJ,Triggers:JJ,"Triggers the on script saving or the javascript instance restart":"Запускает при сохранении скрипта или перезапуске экземпляра javascript","Triggers the rule on update or change of some state":"Запускает правило при обновлении или изменении какого-либо состояния","Triggers the rule periodically or on some specific time":"Срабатывает правило периодически или в определенное время",Tu:qJ,Tuesday:XJ,URL:ZJ,"Unknown error":"Неизвестная ошибка","Unknown error!":"Неизвестная ошибка!","Use generated code":"Использовать сгенерированный код","User function":"Функция пользователя","User:":"Пользователь:",Value:QJ,"Vibration:":"Вибрация:",Volume:e7,We:t7,Wednesday:s7,"Whatsapp-cmb":"Whatsapp-cmb",Write:o7,"Write your own code":"Напишите свой код",Yes:i7,"Yet exists!":"Имя уже существует!","You can use %s in the URL to use current trigger value or %id to use the triggered object ID":"Вы можете использовать %s в URL-адресе, чтобы использовать текущее значение триггера, %id, чтобы использовать идентификатор инициированного объекта, %name, чтобы показать имя идентификатора инициированного объекта, или %old, чтобы использовать старое значение триггера.","You can use %s in the command to use current trigger value or %id to use the triggered object ID":"Вы можете использовать %s в команде, чтобы использовать текущее значение триггера, %id, чтобы использовать идентификатор сработавшего объекта, %name, чтобы показать имя сработавшего идентификатора объекта, или %old, чтобы использовать старое значение триггера.","You can use %s in the text to display current trigger value or %id to display the triggered object ID":"Вы можете использовать %s в тексте для отображения текущего значения триггера, %id для использования идентификатора сработавшего объекта, %name для отображения имени сработавшего идентификатора объекта или %old для использования старого значения триггера.","You can use %s in the value to use the current trigger value or %id to display the triggered object ID":"Вы можете использовать %s в значении, чтобы использовать текущее значение триггера, %id, чтобы использовать идентификатор инициированного объекта, %name, чтобы показать имя идентификатора инициированного объекта, или %old, чтобы использовать старое значение триггера.","You have to enter OpenAI API key in the configuration of javascript adapter.":"Вы должны ввести ключ OpenAI API в конфигурации адаптера javascript.","You have to enter at least one API key in the configuration of javascript adapter.":"Необходимо ввести хотя бы один API-ключ (OpenAI, Anthropic или Gemini) в конфигурации адаптера javascript.","Please select a valid model":"Пожалуйста, выберите допустимую модель","[equal]":"[равно]","[greater or equal]":"[больше или равно]","[greater]":"[больше]","[hysteresis]":"[гистерезис]","[includes]":"[содержит]","[less or equal]":"[меньше или равно]","[less]":"[меньше]","[not equal]":"[не равно]",acknowledgment:n7,all:r7,and:a7,astro:l7,at:c7,"clear running":"остановить уже бегущие",control:u7,copy:d7,cron:h7,dawn:p7,debug_help:g7,debug_label:m7,default:"дефолт",dusk:f7,easy:$7,else:"иначе","equal to":"равно",every:b7,"every hour at 0 minutes":"каждый час через 0 минут",false:"false","file reading has failed: %s":"Ошибка чтения файла: %s","file reading was aborted":"Чтение файла было прервано",filter_func:v7,filter_id:y7,filter_name:_7,filter_role:w7,filter_room:C7,"for edit or create script":"для редактирования или создайте новый скрипт","for professionals":"для профессионалов","for programmers":"для программистов",goldenHour:T7,goldenHourEnd:k7,"greater or equal":"больше или равно","greater or equal to":"больше или равно","greater than":"больше чем",help_just_check:S7,help_on_change:E7,"high priority":"высокий приоритет","high-priority":"высокий-приоритет","highest priority":"высший приоритет",hours:I7,includes:x7,interval:D7,"just check":"просто проверить","less or equal":"меньше или равно","less or equal to":"меньше или равно","less than":"меньше, чем","lower priority":"более низкий приоритет","lowest priority":"самый низкий приоритет",magic:A7,milliseconds:R7,minutes:O7,ms:M7,nadir:N7,nauticalDawn:L7,nauticalDusk:P7,nextSunrise:B7,nextSunset:j7,night:F7,nightEnd:z7,"no blocks found":"Блоков нет","no group":"Нет группы",normal:U7,"normal priority":"нормальный приоритет","not equal to":"не равно","not properly connected":"Этот блок неправильно соединён или не соединён с другими блоками.",offset:H7,"on change":"по изменению","on condition change":"при изменении результата условия","on update":"при обновлении",one:W7,or:G7,quiet:V7,"reset search":"Cбросить поиск",search:K7,seconds:Y7,solarNoon:J7,"store in":"сохранить в",sunrise:q7,sunriseEnd:X7,sunset:Z7,sunsetStart:Q7,then:eq,"toggle value":"инвертировать текщее значение",tooltip_ack:tq,tooltip_from:sq,tooltip_lc:oq,tooltip_quality:iq,tooltip_ts:nq,tooltip_user:rq,tooltip_value:aq,true:"true",two:lq,undefined:"неопределенный",update:cq,"use seconds":"использовать секунды","use trigger value":"использовать значение триггера",verbose_help:uq,verbose_label:dq,when:hq,with:"с","with date":"с датой","with offset":"со сдвигом",wizard:pq,"Loading models...":"Загрузка моделей...","Could not connect to API at %s":"Не удалось подключиться к API по адресу %s","Invalid API key":"Недействительный ключ API","Access denied by API":"Доступ запрещён API","API error: %s":"Ошибка API: %s",'Model "%s" not found':'Модель "%s" не найдена',"Request failed: %s":"Запрос не удался: %s",Retry:gq,"No running javascript instance found":"Не найден работающий экземпляр JavaScript"},fq="Визнано",$q="Дії",bq="додати",vq="все",yq="Будь-який",_q="Застосувати",wq="квітень",Cq="Запитуйте",Tq="Астрономічний",kq="серпень",Sq="Скасувати",Eq="Закрити",Iq="Хвороба",xq="Умови",Dq="Консоль",Aq="Скопійовано",Rq="Грудень",Oq="За замовчуванням",Mq="Затримка",Nq="Видалити",Lq="опис",Pq="Готово",Bq="Виконавча оболонка",jq="Пояснення",Fq="Експорт",zq="Лютий",Uq="Лютий",Hq="фільтр",Wq="Папка",Gq="О",Vq="П'ятниця",Kq="ID",Yq="ID1",Jq="ID2",qq="Імпорт",Xq="Екземпляр",Zq="Примірники",Qq="Інструкції",eX="січень",tX="січня",sX="липень",oX="червень",iX="Ліміт",nX="березень",rX="Може",aX="Меню",lX="повідомлення",cX="пн",uX="Модель",dX="понеділок",hX="місяць",pX="Більше",gX="Ім'я",mX="Листопад",fX="в порядку",$X="жовтень",bX="В порядку",vX="Пауза",yX="Pushover",_X="Pushsafer",wX="Перейменувати",CX="Повторіть",TX="Перезапустіть",kX="Результат",SX="Sa",EX="Субота",IX="зберегти",xX="розклад",DX="Сценарій",AX="Вересень",RX="Симулювати",OX="Стек",MX="старт",NX="Держава",LX="Нд",PX="неділя",BX="Телеграма",jX="чт",FX="четвер",zX="час",UX="Спрацьовує",HX="Тригери",WX="вт",GX="вівторок",VX="URL",KX="Значення",YX="Обсяг",JX="ми",qX="Середа",XX="Напишіть",ZX="Так",QX="підтвердження",eZ="все",tZ="і",sZ="Астро",oZ="в",iZ="КОНТРОЛЬ",nZ="копія",rZ="CRON",aZ="Світанок",lZ="Це особливий режим, в якому стану та об'єкти не змінюватимуться. Але в протоколі відображатиметься лише інформація про кожну заплановану зміну.",cZ="Відлагоджувати",uZ="Сутінки",dZ="легко",hZ="кожен",pZ="функція",gZ="ID",mZ="Ім'я",fZ="Роль",$Z="Кімната",bZ="Золота година",vZ="Кінець золотої години",yZ="Код буде виконуватися лише щоразу, коли умова виконується. наприклад якщо спрацьовує значення датчика температури та умова «якщо температура перевищує 20°C», дії «тоді» виконуватимуться щоразу, коли датчик надсилає температуру, і вона перевищує 20°C. На 21°C, на 22°C і так далі.",_Z="Код буде виконано лише у разі зміни результату умови. наприклад якщо спрацьовує значення датчика температури та умова «якщо температура перевищує 20°C», дії «тоді» будуть виконані один раз, коли температура буде вище 20. Наступного разу дії «тоді» буде виконано, коли температура падає нижче 20, а потім знову піднімається вище 20.",wZ="години",CZ="включає в себе",TZ="інтервал",kZ="магія",SZ="мілісекунд",EZ="хвилин",IZ="РС",xZ="Надір",DZ="Морський світанок",AZ="Морські сутінки",RZ="Наступний схід сонця",OZ="Наступний захід сонця",MZ="ніч",NZ="Кінець ночі",LZ="нормально",PZ="зсув",BZ="один",jZ="або",FZ="тихо",zZ="пошук",UZ="секунд",HZ="Сонячний полудень",WZ="схід сонця",GZ="Кінець сходу сонця",VZ="Захід сонця",KZ="Початок заходу сонця",YZ="потім",JZ="Визнати",qZ="Від",XZ="Востаннє змінено",ZZ="якість",QZ="Мітка часу",eQ="Користувач",tQ="Значення",sQ="два",oQ="оновлення",iQ="Додає вихідні дані налагодження до журналу для багатьох системних команд",nQ="Докладні результати журналу",rQ="коли",aQ="майстер",lQ="Повторити",cQ={"%s not found":"%s не знайдено","()":"()","(at %s)":"(у %s)","(optional)":"(необов'язково)","-":"-",".":".","AI code generator":"Генератор коду ШІ","Planning...":"Планування...","Generating code...":"Генерування коду...","Show plan":"Показати план",Ack:fq,Actions:$q,"Actual time of day":"Фактичний час доби",Add:bq,"Add new script":"Додати новий сценарій",All:vq,"All files will be accepted":"Усі файли будуть прийняті",Any:yq,"Any month":"Будь-який місяць",Apply:_q,April:wq,"Are you sure?":"Ти впевнений?",Ask:Cq,Astronomical:Tq,"Astronomical events today":"Астрономічні події сьогодні",August:kq,"Blockly description":"Створення правил за графічними блоками","Body:":"Тіло:",Cancel:Sq,"Cannot delete non empty item!":"Неможливо видалити непорожній елемент!","Change layout":"Змінити макет",'Change theme (actual "%s")':'Змінити тему (тепер - "%s")',"Check blocks":"Перевірте блоки","Check is not active, because javascript adapter is disabled":"Перевірка не активна, оскільки адаптер Javascript вимкнено","Clear search input":"Очистити пошуковий запит","Click on this icon":"Натисніть на цей значок",Close:Eq,"Close all but current":"Закрити всі, крім поточних","Collapse all":"Закрити всі","Compares current time with astronomical event":"Порівнює поточний час з астрономічною подією","Compares current time with the user specific time":"Порівнює поточний час із конкретним часом користувача","Compares the state value with user defined value":"Порівнює значення стану з визначеним користувачем значенням",Condition:Iq,Conditions:xq,"Configuration not saved.":"Конфігурація не збережена.",Console:Dq,"Control or update some state":"Контролюйте або оновлюйте певний стан","Control or update some state with delay":"Контролюйте або оновлюйте деякий стан із затримкою","Convert blockly to javascript for ever.":"Назавжди конвертуйте Blockly у Javascript.",Copied:Aq,"Copy script":"Копіювати сценарій","Copy to clipboard":"Копіювати в буфер обміну","Create new":"Створити новий","Create new folder":"Створити нову папку","Create new script":"Створіть новий сценарій","Create or edit CRON or time wizard":"Створення або редагування CRON або майстра часу","Dark Theme":"Темна тема","Dark style":"Темний стиль",Date:"Дата","Debug instance":"Екземпляр налагодження","Debug options":"Параметри налагодження",December:Rq,Default:Oq,"Define cron...":"Визначити cron...","Define schedule...":"Визначити розклад...",Delay:Mq,Delete:Nq,"Delete %s":"Видалити %s...","Delete folder":"Видалити папку","Delete script":"Видалити сценарій",Description:Lq,"Deselect all":"Зняти вибір із усіх","Discard changes for %s":"Скасувати зміни для %s",Done:Pq,"Double click to write value":"Двічі клацніть, щоб записати значення","Download as file":"Завантажити файл","Drop some files here or click...":"Перетягніть кілька файлів сюди або натисніть...","Duplicate name":"Повторюване ім'я","Edit script or just double click":"Відредагуйте сценарій або просто двічі клацніть","Empty name is not allowed":"Порожнє ім'я не допускається","End search mode":"Завершити режим пошуку","Enter your question":"Введи своє прохання",Error:"Помилка","Error formatting code":"Помилка форматування коду","Error was found":"Виявлено помилку","Every day":"Кожен день",Exec:Bq,"Executes some shell command":"Виконує певну команду оболонки","Existing scripts will be overwritten.":"Існуючі сценарії буде перезаписано.","Expand all":"Розгорнути все","Expert mode":"Експертний режим",Explanation:jq,Export:Fq,"Export all scripts":"Експортувати всі сценарії","Export blocks":"Експорт блоків","Export selected blocks":"Експортувати вибрані блоки",Februar:zq,February:Uq,Filter:Hq,Folder:Wq,Fr:Gq,Friday:Vq,Function:"функція","Function editor":"Редактор функцій","Function: executed":"Функція: виконано","Go to next line":"Перейти до наступного рядка","HTTP Call":"Виклик HTTP","Hide logs":"Приховати журнали",ID:Kq,ID1:Yq,ID2:Jq,Import:qq,"Import blocks":"Імпорт блоків","Import error":"Помилка імпорту","Import scripts":"Імпорт скриптів","Insert object ID":"Вставте ID об'єкта",Instance:Xq,"Instance is disabled":"Примірник вимкнено","Instance:":"екземпляр:",Instances:Zq,Instructions:Qq,"Invalid CRON":"Недійсний CRON","It will not be possible to revert this operation.":"Скасувати цю операцію буде неможливо.","JS description":"Створення правил шляхом написання Javascript",Januar:eX,January:tX,July:sX,June:oX,"Just check":"Просто перевірте","Language:":"Мову:","Learn More":"Вивчайте більше","Light style":"Легкий стиль",Limit:iX,"Local time":"Місцевий час","Locate file":"Знайти файл","Log outputs":"Виходи журналу","Log text":"Текст журналу","Log: %s":"Журнал: %s","Make a HTTP get request":"Зробіть HTTP-запит на отримання","Make a pause between actions":"Між діями робіть паузу",March:nX,"March ":"березень",May:rX,Menu:aX,Message:lX,Mo:cX,Model:uX,Monday:dX,Month:hX,More:pX,Name:gX,"No API key found":"API-ключ не знайдено","No Chat GPT Key found":"Ключ GPT для чату не знайдено","No active host found":"Активний хост не знайдено","Nothing found":"Нічого не знайдено",November:mX,OK:fX,October:$X,Ok:bX,"On condition change":"За умови зміни результату","On script save or adapter start":"Під час збереження сценарію або запуску адаптера","On weekdays":"В будні дні","Open configuration":"Відкрита конфігурація","Operate two states":"Керуйте двома станами","Operations with two states":"Операції з двома станами","Paste your blocks here":"Вставте сюди свої блоки",Pause:vX,"Pause execution":"Призупинити виконання","Pause script":"Призупинити сценарій","Phone:":"телефон:","Please select object ID...":"Виберіть ідентифікатор об'єкта...","Press Ctrl+Enter to get the answer":"Натисніть Ctrl+Enter, щоб отримати відповідь","Prettify the script":"Прикрасьте сценарій","Print some text in log":"Надрукувати текст у журналі","Priority:":"Пріоритет:",Pushover:yX,Pushsafer:_X,"Read only ID selected: %s":"Вибрано ідентифікатор лише для читання: %s",Rename:wX,"Reorder scripts in folders":"Зміна порядку сценаріїв у папках",Repeat:CX,Restart:TX,Result:kX,"Resume execution":"Відновити виконання","Root folder":"Коренева папка","Rules description":"Створюйте правила з блоками IF, THEN, ELSE","Run script":"Запустіть сценарій",Sa:SX,Saturday:EX,Save:IX,"Save all":"Зберегти все","Say It":"Скажи це","Say some text via sayit adapter":"Скажіть текст через адаптер sayit",Schedule:xX,Script:DX,"Script %s was modified on disk":"Сценарій %s змінено на диску","Script is not running":"Сценарій не працює","Search in scripts":"Пошук у скриптах","Search...":"пошук...","Select all":"Вибрати все","Send email":"Відправити лист","Sends an email":"Надсилає електронний лист","Sends message via Pushsafer":"Надсилає повідомлення через Pushsafer","Sends message via pushover":"Надсилає повідомлення через pushover","Sends message via telegram":"Надсилає повідомлення через телеграм","Sends message via whatsapp-cmb":"Надсилає повідомлення через whatsapp-cmb",September:AX,"Server time":"Час сервера","Set state action":"Встановити дію стану","Set with delay":"Встановити із затримкою","Shell command":"Команда оболонки","Show astronomical events":"Показати астрономічні події","Show javascript code":"Показати код Javascript","Show logs":"Показати журнали","Show only paused scripts":"Показувати лише призупинені сценарії","Show only running scripts":"Показувати лише запущені сценарії","Show only scripts with problems":"Показувати лише сценарії з проблемами",Simulate:RX,"Some files will be rejected":"Деякі файли буде відхилено","Sound:":"звук:",Stack:OX,Start:MX,"Start script":"Запустити сценарій",State:NX,"State condition":"Стан стану","Step into function":"Крок у функції","Step out from function":"Вийти з функції","Stop on exception":"Зупинка на винятках",Su:LX,"Subject:":"Тема:",Sunday:PX,"TS description":"Створення правил шляхом написання Typescript",Telegram:BX,"Text:":"Текст:",Th:jX,"The script will be stopped and must be activated manually after debugging. Continue?":"Сценарій буде зупинено, і його необхідно активувати вручну після налагодження. Продовжити?","This is advances option. You can write your own code here and it will be executed on trigger":"Це авансовий варіант. Ви можете написати тут свій власний код, і він буде виконано на тригері",Thursday:FX,Time:zX,"Time condition":"Умова часу","Title:":"Назва:","To:":"до:","Trigger with value":"Тригер зі значенням",Triggered:UX,Triggers:HX,"Triggers the on script saving or the javascript instance restart":"Ініціює збереження сценарію або перезапуск екземпляра JavaScript","Triggers the rule on update or change of some state":"Запускає правило при оновленні або зміні якогось стану","Triggers the rule periodically or on some specific time":"Спрацьовує правило періодично або в певний час",Tu:WX,Tuesday:GX,URL:VX,"Unknown error":"Невідома помилка","Unknown error!":"Невідома помилка!","Use generated code":"Використовуйте згенерований код","User function":"Функція користувача","User:":"Користувач:",Value:KX,"Vibration:":"Вібрація:",Volume:YX,We:JX,Wednesday:qX,"Whatsapp-cmb":"Whatsapp-cmb",Write:XX,"Write your own code":"Напишіть власний код",Yes:ZX,"Yet exists!":"Все ж існує!","You can use %s in the URL to use current trigger value or %id to use the triggered object ID":"Ви можете використовувати %s в URL-адресі, щоб використовувати поточне значення тригера, %id, щоб використовувати ідентифікатор активованого об’єкта, %name, щоб показати назву ідентифікатора активованого об’єкта, або %old, щоб використовувати старе значення тригера","You can use %s in the command to use current trigger value or %id to use the triggered object ID":"Ви можете використовувати %s у команді, щоб використовувати поточне значення тригера, %id, щоб використовувати ідентифікатор активованого об’єкта, %name, щоб показати назву ідентифікатора активованого об’єкта, або %old, щоб використовувати старе значення тригера","You can use %s in the text to display current trigger value or %id to display the triggered object ID":"Ви можете використовувати %s у тексті для відображення поточного значення тригера, %id для використання ідентифікатора активованого об’єкта, %name для відображення імені ідентифікатора активованого об’єкта або %old для використання старого значення тригера","You can use %s in the value to use the current trigger value or %id to display the triggered object ID":"Ви можете використовувати %s у значенні, щоб використовувати поточне значення тригера, %id, щоб використовувати ідентифікатор активованого об’єкта, %name, щоб показати назву ідентифікатора активованого об’єкта, або %old, щоб використовувати старе значення тригера","You have to enter OpenAI API key in the configuration of javascript adapter.":"Ви повинні ввести ключ OpenAI API у конфігурації адаптера JavaScript.","You have to enter at least one API key in the configuration of javascript adapter.":"Необхідно ввести хоча б один API-ключ (OpenAI, Anthropic або Gemini) у конфігурації адаптера JavaScript.","Please select a valid model":"Будь ласка, виберіть дійсну модель","[equal]":"[рівний]","[greater or equal]":"[більше або дорівнює]","[greater]":"[більший]","[hysteresis]":"[гістерезис]","[includes]":"[включає]","[less or equal]":"[менше або рівно]","[less]":"[менше]","[not equal]":"[не дорівнює]",acknowledgment:QX,all:eZ,and:tZ,astro:sZ,at:oZ,"clear running":"чіткий біг",control:iZ,copy:nZ,cron:rZ,dawn:aZ,debug_help:lZ,debug_label:cZ,default:"за замовчуванням",dusk:uZ,easy:dZ,else:"інше","equal to":"дорівнює",every:hZ,"every hour at 0 minutes":"щогодини о 0 хвилин",false:"помилковий","file reading has failed: %s":"не вдалося прочитати файл: %s","file reading was aborted":"читання файлу було перервано",filter_func:pZ,filter_id:gZ,filter_name:mZ,filter_role:fZ,filter_room:$Z,"for edit or create script":"для редагування або створення нового сценарію","for professionals":"для професіоналів","for programmers":"для програмістів",goldenHour:bZ,goldenHourEnd:vZ,"greater or equal":"більший або рівний","greater or equal to":"більше або дорівнює","greater than":"більше, ніж, величніше ніж, крутіший за",help_just_check:yZ,help_on_change:_Z,"high priority":"високий пріоритет","high-priority":"високий пріоритет","highest priority":"найвищий пріоритет",hours:wZ,includes:CZ,interval:TZ,"just check":"просто перевірте","less or equal":"менше або дорівнює","less or equal to":"менше або дорівнює","less than":"менше ніж","lower priority":"нижчий пріоритет","lowest priority":"найнижчий пріоритет",magic:kZ,milliseconds:SZ,minutes:EZ,ms:IZ,nadir:xZ,nauticalDawn:DZ,nauticalDusk:AZ,nextSunrise:RZ,nextSunset:OZ,night:MZ,nightEnd:NZ,"no blocks found":"Блоків не знайдено","no group":"НЕМАЄ ГРУПИ",normal:LZ,"normal priority":"нормальний пріоритет","not equal to":"не дорівнює","not properly connected":"Цей блок неправильно з’єднаний з іншими блоками.",offset:PZ,"on change":"на зміну","on condition change":"про зміну умов","on update":"на оновлення",one:BZ,or:jZ,quiet:FZ,"reset search":"скинути пошук",search:zZ,seconds:UZ,solarNoon:HZ,"store in":"зберігати в",sunrise:WZ,sunriseEnd:GZ,sunset:VZ,sunsetStart:KZ,then:YZ,"toggle value":"значення перемикання",tooltip_ack:JZ,tooltip_from:qZ,tooltip_lc:XZ,tooltip_quality:ZZ,tooltip_ts:QZ,tooltip_user:eQ,tooltip_value:tQ,true:"правда",two:sQ,undefined:"невизначений",update:oQ,"use seconds":"використовуйте секунди","use trigger value":"використовувати значення тригера",verbose_help:iQ,verbose_label:nQ,when:rQ,with:"з","with date":"з датою","with offset":"зі зміщенням",wizard:aQ,"Loading models...":"Завантаження моделей...","Could not connect to API at %s":"Не вдалося підключитися до API за адресою %s","Invalid API key":"Недійсний ключ API","Access denied by API":"Доступ заборонено API","API error: %s":"Помилка API: %s",'Model "%s" not found':'Модель "%s" не знайдено',"Request failed: %s":"Запит не вдався: %s",Retry:lQ,"No running javascript instance found":"Не знайдено запущеного екземпляра JavaScript"},uQ="确认",dQ="动作",hQ="添加",pQ="所有",gQ="任何",mQ="申请",fQ="四月",$Q="问",bQ="天文",vQ="八月",yQ="取消",_Q="关闭",wQ="健康)状况",CQ="情况",TQ="安慰",kQ="复制的",SQ="十二月",EQ="默认",IQ="延迟",xQ="删除",DQ="描述",AQ="完成",RQ="执行力",OQ="解释",MQ="导出",NQ="二月",LQ="二月",PQ="筛选",BQ="文件夹",jQ="r",FQ="星期五",zQ="ID",UQ="ID1",HQ="ID2",WQ="导入",GQ="实例",VQ="实例",KQ="指示",YQ="亚努尔",JQ="一月",qQ="七月",XQ="六月",ZQ="限制",QQ="三月",eee="五月",tee="菜单",see="信息",oee="莫",iee="模型",nee="星期一",ree="月",aee="更多的",lee="名称",cee="十一月",uee="好的",dee="十月",hee="确定",pee="暂停",gee="俯卧撑",mee="推安全",fee="重命名",$ee="重复",bee="重启",vee="结果",yee="萨",_ee="星期六",wee="保存",Cee="日程",Tee="脚本",kee="九月",See="模拟",Eee="堆",Iee="开始",xee="状态",Dee="苏",Aee="星期日",Ree="电报",Oee="4",Mee="星期四",Nee="时间",Lee="触发",Pee="扳机",Bee="涂",jee="星期二",Fee="网址",zee="价值",Uee="体积",Hee="3",Wee="星期三",Gee="写",Vee="是的",Kee="致谢",Yee="全部",Jee="和",qee="天文",Xee="在",Zee="控制",Qee="复制",ete="克朗",tte="黎明",ste="这是一种特殊模式,其中状态和对象不会改变。但只有有关每个计划更改的信息才会显示在协议中。",ote="调试",ite="黄昏",nte="简单的",rte="每一个",ate="功能",lte="ID",cte="名字",ute="角色",dte="房间",hte="黄金时段",pte="黄金时段结束",gte="仅在条件为真时才执行代码。例如。如果触发温度传感器值并且条件为“如果温度大于20°C”,则每次传感器发送温度且温度超过20°C时,将执行“然后”动作。 21°C,22°C等。",mte="仅当条件结果更改时,代码才会执行。例如。如果触发温度传感器值且条件为“如果温度大于20°C”,则温度超过20时将执行一次“则”动作,下一次,当温度超过20时将执行“则”动作低于20失败,然后再次超过20。",fte="小时",$te="包括",bte="间隔",vte="魔法",yte="毫秒",_te="分钟",wte="毫秒",Cte="最低点",Tte="航海黎明",kte="航海黄昏",Ste="下一个日出",Ete="下一个日落",Ite="夜晚",xte="夜晚结束",Dte="普通的",Ate="抵消",Rte="一",Ote="或",Mte="安静的",Nte="搜索",Lte="秒",Pte="星期日正午",Bte="日出",jte="日出结束",Fte="日落",zte="日落开始",Ute="然后",Hte="确认",Wte="从",Gte="上一次改变",Vte="质量",Kte="时间戳",Yte="用户",Jte="值",qte="二",Xte="更新",Zte="将调试输出添加到许多系统命令的日志中",Qte="详细日志输出",ese="什么时候",tse="巫师",sse="重试",ose={"%s not found":"%s 未找到","()":"()","(at %s)":"(在 %s)","(optional)":"(选修的)","-":"-",".":".","AI code generator":"AI代码生成器","Planning...":"规划中...","Generating code...":"生成代码中...","Show plan":"显示计划",Ack:uQ,Actions:dQ,"Actual time of day":"一天中的实际时间",Add:hQ,"Add new script":"添加新脚本",All:pQ,"All files will be accepted":"所有文件都将被接受",Any:gQ,"Any month":"任何月份",Apply:mQ,April:fQ,"Are you sure?":"你确定吗?",Ask:$Q,Astronomical:bQ,"Astronomical events today":"今天的天文事件",August:vQ,"Blockly description":"按图形块创建规则","Body:":"身体:",Cancel:yQ,"Cannot delete non empty item!":"无法删除非空项目!","Change layout":"变更版面",'Change theme (actual "%s")':"更改主题(现在为“%s”)","Check blocks":"检查块","Check is not active, because javascript adapter is disabled":"检查未激活,因为禁用了Javascript适配器","Clear search input":"清除搜索输入","Click on this icon":"单击此图标",Close:_Q,"Close all but current":"关闭所有(当前除外)","Collapse all":"全部收缩","Compares current time with astronomical event":"将当前时间与天文事件进行比较","Compares current time with the user specific time":"将当前时间与用户特定时间进行比较","Compares the state value with user defined value":"比较状态值和用户定义的值",Condition:wQ,Conditions:CQ,"Configuration not saved.":"配置未保存。",Console:TQ,"Control or update some state":"控制或更新某些状态","Control or update some state with delay":"延迟控制或更新某些状态","Convert blockly to javascript for ever.":"立即将blockly转换为Javascript。",Copied:kQ,"Copy script":"复制脚本","Copy to clipboard":"复制到剪贴板","Create new":"创建新的","Create new folder":"创建新文件夹","Create new script":"创建新脚本","Create or edit CRON or time wizard":"创建或编辑周期任务或时间向导","Dark Theme":"深色调主题","Dark style":"深色调风格",Date:"日期","Debug instance":"调试实例","Debug options":"调试选项",December:SQ,Default:EQ,"Define cron...":"定义周期任务...","Define schedule...":"定义调度器......",Delay:IQ,Delete:xQ,"Delete %s":"删除%s...","Delete folder":"删除文件夹","Delete script":"删除脚本",Description:DQ,"Deselect all":"取消全选","Discard changes for %s":"放弃%s的更改",Done:AQ,"Double click to write value":"Double click to write value","Download as file":"档案","Drop some files here or click...":"将文件拖拽到这里或单击......","Duplicate name":"重名","Edit script or just double click":"双击编辑脚本","Empty name is not allowed":"不允许使用空名称","End search mode":"结束搜索模式","Enter your question":"输入您的要求",Error:"错误","Error formatting code":"代码格式错误","Error was found":"发现错误","Every day":"每天",Exec:RQ,"Executes some shell command":"执行一些shell命令","Existing scripts will be overwritten.":"现有脚本将被覆盖。","Expand all":"展开全部","Expert mode":"专家模式",Explanation:OQ,Export:MQ,"Export all scripts":"导出所有脚本","Export blocks":"导出块","Export selected blocks":"导出选定的块",Februar:NQ,February:LQ,Filter:PQ,Folder:BQ,Fr:jQ,Friday:FQ,Function:"功能","Function editor":"功能编辑器","Function: executed":"功能:执行","Go to next line":"转到下一行","HTTP Call":"HTTP呼叫","Hide logs":"隐藏日志",ID:zQ,ID1:UQ,ID2:HQ,Import:WQ,"Import blocks":"导入块","Import error":"导入错误","Import scripts":"导入脚本","Insert object ID":"插入对象ID",Instance:GQ,"Instance is disabled":"实例已禁用","Instance:":"实例:",Instances:VQ,Instructions:KQ,"Invalid CRON":"无效的周期任务","It will not be possible to revert this operation.":"无法恢复此操作。","JS description":"通过编写Javascript来创建规则",Januar:YQ,January:JQ,July:qQ,June:XQ,"Just check":"只是检查","Language:":"语言:","Learn More":"了解更多","Light style":"浅色调风格",Limit:ZQ,"Local time":"当地时间","Locate file":"定位文件","Log outputs":"记录输出","Log text":"记录文字","Log: %s":"日志:%s","Make a HTTP get request":"发出HTTP获取请求","Make a pause between actions":"在动作之间暂停",March:QQ,"March ":"行进",May:eee,Menu:tee,Message:see,Mo:oee,Model:iee,Monday:nee,Month:ree,More:aee,Name:lee,"No API key found":"未找到 API 密钥","No Chat GPT Key found":"找不到聊天 GPT 密钥","No active host found":"找不到活动主机","Nothing found":"没有发现",November:cee,OK:uee,October:dee,Ok:hee,"On condition change":"条件变化时","On script save or adapter start":"在脚本保存或适配器启动时","On weekdays":"在工作日","Open configuration":"开放配置","Operate two states":"操作两种状态","Operations with two states":"具有两种状态的操作","Paste your blocks here":"在此处粘贴您的区块",Pause:pee,"Pause execution":"暂停执行","Pause script":"暂停脚本","Phone:":"电话:","Please select object ID...":"请选择对象ID...","Press Ctrl+Enter to get the answer":"按 Ctrl+Enter 即可得到答案","Prettify the script":"美化脚本","Print some text in log":"在日志中打印一些文本","Priority:":"优先:",Pushover:gee,Pushsafer:mee,"Read only ID selected: %s":"选择的只读ID:%s",Rename:fee,"Reorder scripts in folders":"重新排序文件夹中的脚本",Repeat:$ee,Restart:bee,Result:vee,"Resume execution":"恢复执行","Root folder":"根文件夹","Rules description":"使用IF,THEN,ELSE块创建规则","Run script":"运行脚本",Sa:yee,Saturday:_ee,Save:wee,"Save all":"保存全部","Say It":"Say It","Say some text via sayit adapter":"通过sayit适配器说一些文字",Schedule:Cee,Script:Tee,"Script %s was modified on disk":"脚本%s已在磁盘上修改","Script is not running":"脚本没有运行","Search in scripts":"在脚本中搜索","Search...":"搜索...","Select all":"全选","Send email":"发送电子邮件","Sends an email":"发送邮件","Sends message via Pushsafer":"通过Pushsafer发送消息","Sends message via pushover":"通过推播发送消息","Sends message via telegram":"通过电报发送消息","Sends message via whatsapp-cmb":"通过whatsapp-cmb发送消息",September:kee,"Server time":"服务器时间","Set state action":"设定状态动作","Set with delay":"延迟设置","Shell command":"Shell命令","Show astronomical events":"显示天文事件","Show javascript code":"显示Javascript代码","Show logs":"显示记录","Show only paused scripts":"仅显示暂停的脚本","Show only running scripts":"仅显示正在运行的脚本","Show only scripts with problems":"仅显示有问题的脚本",Simulate:See,"Some files will be rejected":"有些文件将被拒绝","Sound:":"声音:",Stack:Eee,Start:Iee,"Start script":"启动脚本",State:xee,"State condition":"状态条件","Step into function":"进入功能","Step out from function":"退出函数","Stop on exception":"异常停止",Su:Dee,"Subject:":"学科:",Sunday:Aee,"TS description":"通过编写Typescript来创建规则",Telegram:Ree,"Text:":"文本:",Th:Oee,"The script will be stopped and must be activated manually after debugging. Continue?":"该脚本将停止,并且必须在调试后手动激活。继续?","This is advances option. You can write your own code here and it will be executed on trigger":"这是高级选项。您可以在此处编写自己的代码,它将在触发器上执行",Thursday:Mee,Time:Nee,"Time condition":"时间条件","Title:":"标题:","To:":"到:","Trigger with value":"用值触发",Triggered:Lee,Triggers:Pee,"Triggers the on script saving or the javascript instance restart":"触发脚本保存或javascript实例重启","Triggers the rule on update or change of some state":"在某些状态的更新或更改时触发规则","Triggers the rule periodically or on some specific time":"定期或在特定时间触发规则",Tu:Bee,Tuesday:jee,URL:Fee,"Unknown error":"未知错误","Unknown error!":"未知错误!","Use generated code":"使用生成的代码","User function":"用户功能","User:":"用户:",Value:zee,"Vibration:":"振动:",Volume:Uee,We:Hee,Wednesday:Wee,"Whatsapp-cmb":"Whatsapp的cmb",Write:Gee,"Write your own code":"编写自己的代码",Yes:Vee,"Yet exists!":"不存在!","You can use %s in the URL to use current trigger value or %id to use the triggered object ID":"您可以在 URL 中使用 %s 以使用当前触发值,%id 以使用触发对象 ID,%name 以显示触发对象 ID 名称或 %old 以使用旧触发值","You can use %s in the command to use current trigger value or %id to use the triggered object ID":"您可以在命令中使用 %s 以使用当前触发值,%id 使用触发对象 ID,%name 显示触发对象 ID 名称或 %old 使用旧触发值","You can use %s in the text to display current trigger value or %id to display the triggered object ID":"您可以在文本中使用 %s 显示当前触发值,%id 使用触发对象 ID,%name 显示触发对象 ID 名称或 %old 使用旧触发值","You can use %s in the value to use the current trigger value or %id to display the triggered object ID":"您可以在值中使用 %s 以使用当前触发器值,%id 使用触发对象 ID,%name 显示触发对象 ID 名称或 %old 使用旧触发器值","You have to enter OpenAI API key in the configuration of javascript adapter.":"您必须在 javascript 适配器的配置中输入 OpenAI API 密钥。","You have to enter at least one API key in the configuration of javascript adapter.":"您必须在 javascript 适配器的配置中输入至少一个 API 密钥(OpenAI、Anthropic 或 Gemini)。","Please select a valid model":"请选择一个有效的模型","[equal]":"[平等的]","[greater or equal]":"[大于等于]","[greater]":"[更大]","[hysteresis]":"[磁滞]","[includes]":"[包括]","[less or equal]":"[小于或等于]","[less]":"[较少的]","[not equal]":"[不相等]",acknowledgment:Kee,all:Yee,and:Jee,astro:qee,at:Xee,"clear running":"畅通无阻",control:Zee,copy:Qee,cron:ete,dawn:tte,debug_help:ste,debug_label:ote,default:"默认",dusk:ite,easy:nte,else:"别的","equal to":"等于",every:rte,"every hour at 0 minutes":"每小时0分钟",false:"错误的","file reading has failed: %s":"文件读取失败:%s","file reading was aborted":"文件读取中止",filter_func:ate,filter_id:lte,filter_name:cte,filter_role:ute,filter_room:dte,"for edit or create script":"用于编辑或创建脚本","for professionals":"对于专业人士","for programmers":"对于程序员",goldenHour:hte,goldenHourEnd:pte,"greater or equal":"大于或等于","greater or equal to":"大于或等于","greater than":"比...更棒",help_just_check:gte,help_on_change:mte,"high priority":"高优先级","high-priority":"高优先级","highest priority":"最高优先级",hours:fte,includes:$te,interval:bte,"just check":"只是检查","less or equal":"小于或等于","less or equal to":"小于或等于","less than":"少于","lower priority":"低优先级","lowest priority":"最低优先级",magic:vte,milliseconds:yte,minutes:_te,ms:wte,nadir:Cte,nauticalDawn:Tte,nauticalDusk:kte,nextSunrise:Ste,nextSunset:Ete,night:Ite,nightEnd:xte,"no blocks found":"找不到块","no group":"没有组",normal:Dte,"normal priority":"正常优先","not equal to":"不等于","not properly connected":"此块未正确连接到其他块。",offset:Ate,"on change":"在变化","on condition change":"在条件变化时","on update":"更新时",one:Rte,or:Ote,quiet:Mte,"reset search":"重置搜索",search:Nte,seconds:Lte,solarNoon:Pte,"store in":"存放在",sunrise:Bte,sunriseEnd:jte,sunset:Fte,sunsetStart:zte,then:Ute,"toggle value":"切换值",tooltip_ack:Hte,tooltip_from:Wte,tooltip_lc:Gte,tooltip_quality:Vte,tooltip_ts:Kte,tooltip_user:Yte,tooltip_value:Jte,true:"真的",two:qte,undefined:"不明确的",update:Xte,"use seconds":"精确到秒","use trigger value":"使用触发值",verbose_help:Zte,verbose_label:Qte,when:ese,with:"和","with date":"有日期","with offset":"带偏移",wizard:tse,"Loading models...":"加载模型...","Could not connect to API at %s":"无法连接到 %s 的 API","Invalid API key":"无效的 API 密钥","Access denied by API":"API 拒绝访问","API error: %s":"API 错误:%s",'Model "%s" not found':'未找到模型 "%s"',"Request failed: %s":"请求失败:%s",Retry:sse,"No running javascript instance found":"未找到正在运行的 JavaScript 实例"};function ise(a){const[s,i]=Y.useState(""),[r,l]=Y.useState("");return Mt(()=>{a.socket.decrypt(a.systemConfig.native.javascriptPassword).then(u=>l(u))},[a.systemConfig,a.socket]),g.jsxs(Gt,{open:!0,onClose:()=>a.onEntered(null),fullWidth:!0,maxWidth:"sm",children:[g.jsx(as,{children:b.I18n.t("Please enter a password for expert mode")}),g.jsx(Vt,{children:g.jsx(vo,{autoFocus:!0,margin:"dense",variant:"standard",label:b.I18n.t("Password"),type:"password",fullWidth:!0,value:s,onKeyDown:u=>{u.key==="Enter"&&s&&(u.preventDefault(),u.stopPropagation(),r===s?a.onEntered(s):a.onEntered(""))},onChange:u=>i(u.target.value)})}),g.jsxs(Kt,{children:[g.jsx(De,{variant:"contained",disabled:!s,onClick:()=>{r===s?a.onEntered(s):a.onEntered("")},startIcon:g.jsx(zo,{}),children:b.I18n.t("Ok")}),g.jsx(De,{color:"grey",variant:"contained",onClick:()=>a.onEntered(null),startIcon:g.jsx(qs,{}),children:b.I18n.t("Cancel")})]})]})}const Br={root:{flexGrow:1,display:"flex",width:"100%",height:"100%"},mainDiv:{width:"100%",height:"100%",overflow:"hidden"},content:a=>({width:"100%",height:"100%",backgroundColor:a.palette.background&&a.palette.background.default,position:"relative"}),menuOpenCloseButton:a=>({position:"absolute",left:0,borderRadius:"0 5px 5px 0",top:6,pt:1,cursor:"pointer",zIndex:1,height:25,width:20,background:a.palette.secondary.main,color:a.palette.primary.main,pl:"3px","&:hover":{color:"white"}}),showLogButton:a=>({position:"absolute",right:3,borderRadius:"5px 5px 0 0",bottom:0,pt:"3px",cursor:"pointer",zIndex:10,height:20,width:25,background:a.palette.secondary.main,color:a.palette.primary.main,pl:1,"&:hover":{color:"white"}})};class nse extends b.GenericApp{hosts=[];importFile=null;scripts={};confirmCallback=null;changedScripts={};javascriptPassword="";constructor(s){super(s,{Connection:b.AdminConnection,translations:{en:cL,de:oB,es:XF,fr:GU,it:jG,nl:O3,pl:E6,pt:_Y,ru:mq,uk:cQ,"zh-cn":ose},bottomButtons:!1,socket:{autoSubscribeLog:!0},sentryDSN:window.sentryDSN});const i=window.localStorage.getItem("JS.logSizes");let r=[80,20];if(i)try{r=JSON.parse(i)}catch{}const l=window.localStorage.getItem("JS.splitSizes");let u=[20,80];if(l)try{u=JSON.parse(l)}catch{}this.state={...this.state,splitSizes:u,logSizes:r},window.alert=d=>{console.error(d),this.showJsError(d.toString())}}onScriptsChanged=(s,i)=>{if(!s)return;let r=!1;const l={};s.startsWith("script.js.")&&(i?JSON.stringify(this.scripts[s])!==JSON.stringify(i)&&(this.scripts[s]=i,r=!0,l.scriptsHash=this.state.scriptsHash+1):this.scripts[s]&&(delete this.scripts[s],r=!0,l.scriptsHash=this.state.scriptsHash+1)),r&&this.setState(l)};onInstanceChanged=(s,i)=>{var u;if(!s)return;let r=!1;const l={};if(s.match(/^system\.adapter\.[-_\w\d]+\$/)){if(s.startsWith(`system.adapter.${this.adapterName}.`)){const d=parseInt(s.split(".").pop()||"0",10)||0;if((i==null?void 0:i.type)==="instance")this.state.instances.includes(d)||(l.instances=[...this.state.instances],l.instances.push(d),l.instances.sort(),r=!0,this.socket.subscribeState(`${i._id}.alive`,this.onInstanceAliveChange));else if(!i&&this.state.instances.includes(d)){this.socket.unsubscribeState(`${s}.alive`,this.onInstanceAliveChange),l.instances=[...this.state.instances];const p=l.instances.indexOf(d);l.instances.splice(p,1),r=!0}}(u=i==null?void 0:i.common)!=null&&u.blockly&&(this.confirmCallback=d=>d&&window.location.reload(),l.confirm=b.I18n.t("Some blocks were updated. Reload admin?"),r=!0)}r&&this.setState(l)};onHostChanged=(s,i)=>{if(s&&s.startsWith("system.host.")){if((i==null?void 0:i.type)==="host")this.hosts.includes(s)||(this.hosts.push(s),this.hosts.sort());else if(!i&&this.hosts.includes(s)){const r=this.hosts.indexOf(s);this.hosts.splice(r,1)}}};onConnectionReady(){window.systemLang=this.socket.systemLang,this.setState({ready:!1,scriptsHash:0,instances:[],updating:!1,resizing:!1,selected:null,logMessage:{},editing:[],menuOpened:window.localStorage.getItem("App.menuOpened")!=="false",menuSelectId:"",expertMode:window.localStorage.getItem("App.expertMode")==="true",logHorzLayout:window.localStorage.getItem("App.logHorzLayout")==="true",runningInstances:{},confirm:"",importFile:!1,message:"",searchText:"",hideLog:window.localStorage.getItem("App.hideLog")==="true",debugMode:!1,debugInstance:null,splitSizes:[20,80],password:""},async()=>{var d;const s={},i=await this.subscribeOnInstances();s.instances=i.instances,s.runningInstances=i.runningInstances,this.javascriptPassword=((d=this.socket.systemConfig)==null?void 0:d.native.javascriptPassword)||"",await this.readAdaptersWithBlockly();const r=await this.socket.getHosts();this.hosts=r.map(p=>p._id);const l=await this.readAllScripts();window.localStorage.getItem("App.expertMode")!=="true"&&window.localStorage.getItem("App.expertMode")!=="false"&&!this.javascriptPassword?Object.keys(l).find(p=>p.startsWith("script.js.global.")&&l[p].type==="script")&&(s.expertMode=!0):this.javascriptPassword&&(s.expertMode=!1),this.scripts=l;let u=this.state.scriptsHash;this.compareScripts(l)&&u++,s.scriptsHash=u,s.ready=!0,this.setState(s),await this.socket.subscribeObject("script.*",this.onScriptsChanged),await this.socket.subscribeObject("system.adapter.*",this.onInstanceChanged),await this.socket.subscribeObject("system.host.*",this.onHostChanged)})}async subscribeOnInstances(){const i=(await this.socket.getAdapterInstances(this.adapterName)).map(l=>parseInt(l._id.split(".").pop()||"0")).sort(),r={};i.forEach(l=>r[`system.adapter.${this.adapterName}.${l}`]=!1);for(let l=0;ls[r]=i[r]),s}async readAdaptersWithBlockly(){const s=await this.socket.getObjectViewSystem("adapter","system.adapter.","system.adapter.香");return new Promise(i=>Fe.loadCustomBlockly(s,()=>i()))}onInstanceAliveChange=(s,i)=>{if(s&&(s=s?s.substring(0,s.length-6):"",this.state.runningInstances[s]!==(i?i.val:!1))){const r=JSON.parse(JSON.stringify(this.state.runningInstances));r[s]=i?!!i.val:!1,this.setState({runningInstances:r})}};compareScripts(s){const i=Object.keys(this.scripts),r=Object.keys(s);if(i.length!==r.length)return this.scripts=s,!0;if(JSON.stringify(i)!==JSON.stringify(r))return this.scripts=s,!0;for(let l=0;l ${i}`),this.setState({updating:!0});try{if(((u=this.scripts[s])==null?void 0:u.type)==="script"){const d=JSON.parse(JSON.stringify(this.scripts[s].common));d.name=r||d.name,l!==void 0&&(d.engine=`system.adapter.javascript.${l}`);const p=i.split(".");p.pop();const m=p.join(".");this.scripts[m]&&this.scripts[m].type==="script"&&(p.pop(),i=`${p.join(".")}.${i.split(".").pop()}`),await this.updateScript(s,i,d)}else await this.renameGroup(s,i,r)}catch(d){d.toString().includes("canceled")||this.showJsError(d)}this.setState({updating:!1})}async renameGroup(s,i,r,l){if(l){if(l.length){let u=l.pop();if(u){const d=await this.socket.getObject(u);if(d){try{await this.socket.delObject(u)}catch{}u=i+u.substring(s.length),d._id=u,d.common=d.common||{},d.common.expert=!0,await this.socket.setObject(u,d),await this.renameGroup(s,i,r,l)}}}}else{l=[],l=Object.keys(this.scripts).filter(d=>d.startsWith(`${s}.`));let u=await this.socket.getObject(s);u=u||{common:{},type:"channel"},u.common.name=r||u.common.name||s.split(".").pop()||"",u._id=i;try{await this.socket.delObject(s)}catch{}try{await this.socket.setObject(i,u),await this.renameGroup(s,i,r,l)}catch(d){console.log(d);const p={_id:i,type:"channel",common:{name:r||s.split(".").pop()||"",expert:!0},native:{}};await this.socket.setObject(i,p),await this.renameGroup(s,i,r,l)}}}async onUpdateScript(s,i){var r;if(((r=this.scripts[s])==null?void 0:r.type)==="script")try{await this.updateScript(s,s,i)}catch(l){l.toString().includes("canceled")||this.showJsError(l)}}onSelect(s){this.scripts[s]&&this.scripts[s].common&&this.scripts[s].type==="script"&&this.setState({selected:s,menuSelectId:s},()=>setTimeout(()=>this.setState({menuSelectId:""}),300))}renderPasswordDialog(){return this.state.showPasswordDialog?g.jsx(ise,{socket:this.socket,systemConfig:this.socket.systemConfig,onEntered:s=>{s===null?this.setState({showPasswordDialog:!1,expertMode:!1,password:""}):s?this.setState({expertMode:!0,showPasswordDialog:!1,password:s}):this.setState({showPasswordDialog:!1,expertMode:!1,message:b.I18n.t("Wrong password"),password:""})}},"passwordDialog"):null}onExpertModeChange(s){var i;if(this.state.expertMode!==s)if(s&&this.javascriptPassword)this.setState({showPasswordDialog:!0});else{let r=this.state.selected;r&&!s&&((i=this.scripts[r].native)!=null&&i.protected)&&(r=this.state.editing.find(l=>{var u;return this.scripts[l]&&!((u=this.scripts[l].native)!=null&&u.protected)})||null),window.localStorage.setItem("App.expertMode",s?"true":"false"),this.setState({expertMode:s,password:"",selected:r})}}showJsError(s){this.setState({errorText:s?s.toString():""})}showMessage(s){this.setState({message:s?s.toString():""})}onDelete(s){this.socket.delObject(s).catch(i=>this.showJsError(i))}onEdit(s){this.state.selected!==s&&this.setState({selected:s})}onAddNew(s,i,r,l,u,d){const p=new RegExp(`^${s}\\.`);if(Object.keys(this.scripts).find(m=>s===m||p.test(s)))return this.showJsError(b.I18n.t("Yet exists!"));r?this.socket.setObject(s,{_id:s,type:"channel",common:{name:i,expert:!0},native:{}}).then(()=>setTimeout(()=>this.setState({menuSelectId:s},()=>setTimeout(()=>this.setState({menuSelectId:""}),300)),1e3)).catch(m=>this.showJsError(m)):(u==="Blockly"&&!d&&(d=` -//${btoa(encodeURIComponent(''))}`),this.socket.setObject(s,{_id:s,type:"script",common:{name:i,expert:!0,engineType:u||"Javascript/js",enabled:!1,engine:`system.adapter.javascript.${l||0}`,source:d||"",debug:!1,verbose:!1},native:{}}).then(()=>setTimeout(()=>this.onSelect(s),1e3)).catch(m=>this.showJsError(m)))}async updateScript(s,i,r){let l=await this.socket.getObject(s);const u={common:{}};if(r.engine!==void 0&&(u.common.engine=r.engine),r.enabled!==void 0&&(u.common.enabled=r.enabled),r.source!==void 0&&(u.common.source=r.source),r.debug!==void 0&&(u.common.debug=r.debug),r.verbose!==void 0&&(u.common.verbose=r.verbose),u.from="system.adapter.admin.0",s===i&&(l!=null&&l.common)&&r.name===l.common.name){(!r.engineType||r.engineType!==l.common.engineType)&&r.engineType!==void 0&&(u.common.engineType=r.engineType||"Javascript/js"),u.type="script",await this.socket.extendObject(s,u);return}if(l!=null&&l.common){l.common.engineType=r.engineType||l.common.engineType||"Javascript/js",await this.socket.delObject(s),u.common.engine!==void 0&&(l.common.engine=u.common.engine),u.common.enabled!==void 0&&(l.common.enabled=u.common.enabled),u.common.source!==void 0&&(l.common.source=u.common.source),u.common.name!==void 0&&(l.common.name=u.common.name),u.common.debug!==void 0&&(l.common.debug=u.common.debug),u.common.verbose!==void 0&&(l.common.verbose=u.common.verbose),l._rev!==void 0&&delete l._rev,l.common.name=r.name,l.common.expert=!0,l.type="script",l._id=i,await this.socket.setObject(i,l);return}l=u,l.common.name=r.name,l.common.expert=!0,l.type="script",l._id=i,await this.socket.setObject(i,l)}onEnableDisable(s,i){var r;if(((r=this.scripts[s])==null?void 0:r.type)==="script"){const l=this.scripts[s].common;l.enabled=i,l.expert=!0,this.updateScript(s,s,l).catch(u=>u!=="canceled"&&this.showJsError(u))}}async getLiveHost(){for(let s=0;s{if(typeof u=="string"){const d=document.createElement("a");d.href=`../../files/${u}`,document.body.appendChild(d),d.click(),d.remove()}else if(u.error&&this.showJsError(u.error),u.data){const d=document.createElement("a");d.href=`data: application/zip;base64,${u.data}`,d.download=`${r}scripts.zip`,document.body.appendChild(d),d.click(),d.remove()}})}onImport(s){this.importFile=s||null,s?(this.confirmCallback=this.onImportConfirmed.bind(this),this.setState({importFile:!1,confirm:b.I18n.t("Existing scripts will be overwritten.")})):this.setState({importFile:!1})}async onImportConfirmed(s){let i=this.importFile;if(this.importFile=null,s&&i){i=i.split(",")[1];const r=await this.getLiveHost();if(!r){this.showJsError(b.I18n.t("No active host found"));return}this.socket.getRawSocket().emit("sendToHost",r,"writeObjectsAsZip",{data:i,adapter:"javascript",id:"script.js"},l=>{l==="permissionError"?this.showJsError(b.I18n.t(l)):!l||l.error?this.showJsError(l?b.I18n.t(l.error||""):b.I18n.t("Unknown error")):this.showMessage(b.I18n.t("Done"))})}}toggleLogLayout(){window.localStorage.setItem("App.logHorzLayout",this.state.logHorzLayout?"false":"true"),this.setState({logHorzLayout:!this.state.logHorzLayout})}renderEditor(){var i;const s=Object.keys(this.scripts).reduce((r,l)=>r+(this.scripts[l].common.engineType==="Rules"?1:0),0);return g.jsx(kn,{scriptsHash:this.state.scriptsHash,debugMode:this.state.debugMode,onDebugModeChange:r=>{r?this.setState({debugMode:!0}):this.setState({debugMode:!1,debugInstance:null})},visible:!this.state.resizing,socket:this.socket,adapterName:this.adapterName,onLocate:r=>this.setState({menuSelectId:r}),password:this.state.password,runningInstances:this.state.runningInstances,menuOpened:this.state.menuOpened,searchText:this.state.searchText,themeType:this.state.themeType,themeName:this.state.themeName,theme:this.state.theme,expertMode:this.state.expertMode,onChange:(r,l)=>this.onUpdateScript(r,l),isAnyRulesExists:s,debugInstance:this.state.debugInstance,onSelectedChange:(r,l)=>{const u={};let d=!1;r!==this.state.selected&&(d=!0,u.selected=r),JSON.stringify(l)!==JSON.stringify(this.state.editing)&&(d=!0,u.editing=[...l]),d&&this.setState(u)},onRestart:r=>this.socket.extendObject(r,{common:{enabled:!0}}),selected:this.state.selected&&((i=this.scripts[this.state.selected])==null?void 0:i.type)==="script"?this.state.selected:"",objects:this.scripts,resizing:this.state.resizing,onChangedChanged:r=>this.changedScripts=r},"editor")}showLogButton(){return g.jsx($t,{title:b.I18n.t("Show logs"),sx:Br.showLogButton,onClick:()=>{window.localStorage.setItem("App.hideLog","false"),this.setState({hideLog:!1,resizing:!0}),setTimeout(()=>this.setState({resizing:!1}),300)},children:g.jsx(CS,{})},"showLog")}renderErrorDialog(){return this.state.errorText?g.jsx(Zc,{onClose:()=>this.setState({errorText:""}),text:this.state.errorText},"dialogError"):null}renderMain(){let s;return this.state.debugMode||this.state.hideLog?s=g.jsxs(g.Fragment,{children:[!this.state.debugMode&&this.state.hideLog?this.showLogButton():void 0,this.renderEditor()]}):s=g.jsxs(l_,{direction:this.state.logHorzLayout?dt.Horizontal:dt.Vertical,initialSizes:this.state.logSizes,minWidths:[500,100],minHeights:[150,50],onResizeStarted:()=>this.setState({resizing:!0}),onResizeFinished:(i,r)=>{this.setState({logSizes:r,resizing:!1}),window.localStorage.setItem("JS.logSizes",JSON.stringify(r))},gutterClassName:this.state.themeType==="dark"?"Dark visGutter":"Light visGutter",children:[this.renderEditor(),g.jsx(bm,{verticalLayout:!this.state.logHorzLayout,onLayoutChange:()=>this.toggleLogLayout(),editing:this.state.editing,socket:this.socket,selected:this.state.selected,onHideLog:()=>{window.localStorage.setItem("App.hideLog","true"),this.setState({hideLog:!0,resizing:!0}),setTimeout(()=>this.setState({resizing:!1}),300)}},"log")]}),g.jsxs($t,{sx:Br.content,className:"iobVerticalSplitter",children:[g.jsx($t,{sx:Br.menuOpenCloseButton,onClick:()=>{window.localStorage.setItem("App.menuOpened",this.state.menuOpened?"false":"true"),this.setState({menuOpened:!this.state.menuOpened,resizing:!0}),setTimeout(()=>this.setState({resizing:!1}),300)},children:this.state.menuOpened?g.jsx(TS,{}):g.jsx(kS,{})},"closeMenu"),this.state.message?g.jsx(b.Message,{onClose:()=>this.setState({message:""}),text:this.state.message},"dialogMessage"):null,this.renderErrorDialog(),this.state.importFile?g.jsx(jm,{onClose:i=>this.onImport(i)},"dialogImportFile"):null,this.state.confirm?g.jsx(b.Confirm,{onClose:i=>{this.state.confirm&&this.setState({confirm:""}),this.confirmCallback&&this.confirmCallback(i),this.confirmCallback=null},text:this.state.confirm},"dialogConfirm"):null,this.renderPasswordDialog(),s]},"main")}render(){if(!this.state.ready)return g.jsx(i_,{injectFirst:!0,children:g.jsx(n_,{theme:this.state.theme,children:g.jsx(b.Loader,{themeType:this.state.themeType})})});let s;return this.state.menuOpened?s=g.jsxs(l_,{direction:dt.Horizontal,initialSizes:this.state.splitSizes,minWidths:[270,400],onResizeFinished:(i,r)=>{this.setState({splitSizes:r}),window.localStorage.setItem("JS.splitSizes",JSON.stringify(r))},gutterClassName:this.state.themeType==="dark"?"Dark visGutter":"Light visGutter",children:[g.jsx("div",{style:Br.mainDiv,children:g.jsx(bo,{password:this.state.password,debugMode:this.state.debugMode,onDebugInstance:i=>this.setState({debugInstance:i,debugMode:!!i}),scripts:this.scripts,scriptsHash:this.state.scriptsHash,instances:this.state.instances,onRename:this.onRename.bind(this),socket:this.socket,selectId:this.state.menuSelectId,onEdit:this.onEdit.bind(this),expertMode:this.state.expertMode,themeName:this.state.themeName,onThemeChange:i=>{b.Utils.setThemeName(i);const r=b.Utils.getThemeType(i);this.setState({themeName:i,themeType:r},()=>this.toggleTheme(i))},runningInstances:this.state.runningInstances,onExpertModeChange:i=>this.onExpertModeChange(i),onDelete:this.onDelete.bind(this),onAddNew:this.onAddNew.bind(this),onEnableDisable:this.onEnableDisable.bind(this),onExport:this.onExport.bind(this),width:500,onImport:()=>this.setState({importFile:!0}),onSearch:i=>this.setState({searchText:i}),version:this.props.version,changedScripts:this.changedScripts},"sidemenu")},"menu"),this.renderMain()]}):s=this.renderMain(),g.jsx(i_,{injectFirst:!0,children:g.jsx(n_,{theme:this.state.theme,children:g.jsx("div",{style:Br.root,children:g.jsx(mO,{socket:this.socket,children:s})})})})}}window.location.hostname==="localhost"||window.location.hostname==="[::1]"||window.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/);function rse(){"serviceWorker"in navigator&&navigator.serviceWorker.ready.then(a=>{a.unregister()})}const ase="9.1.1",DT={version:ase};var Fo;(function(a){a.mouse="mouse",a.touch="touch",a.keyboard="keyboard"})(Fo||(Fo={}));class lse{get delay(){var s;return(s=this.args.delay)!==null&&s!==void 0?s:0}get scrollAngleRanges(){return this.args.scrollAngleRanges}get getDropTargetElementsAtPoint(){return this.args.getDropTargetElementsAtPoint}get ignoreContextMenu(){var s;return(s=this.args.ignoreContextMenu)!==null&&s!==void 0?s:!1}get enableHoverOutsideTarget(){var s;return(s=this.args.enableHoverOutsideTarget)!==null&&s!==void 0?s:!1}get enableKeyboardEvents(){var s;return(s=this.args.enableKeyboardEvents)!==null&&s!==void 0?s:!1}get enableMouseEvents(){var s;return(s=this.args.enableMouseEvents)!==null&&s!==void 0?s:!1}get enableTouchEvents(){var s;return(s=this.args.enableTouchEvents)!==null&&s!==void 0?s:!0}get touchSlop(){return this.args.touchSlop||0}get delayTouchStart(){var s,i,r,l;return(l=(r=(s=this.args)===null||s===void 0?void 0:s.delayTouchStart)!==null&&r!==void 0?r:(i=this.args)===null||i===void 0?void 0:i.delay)!==null&&l!==void 0?l:0}get delayMouseStart(){var s,i,r,l;return(l=(r=(s=this.args)===null||s===void 0?void 0:s.delayMouseStart)!==null&&r!==void 0?r:(i=this.args)===null||i===void 0?void 0:i.delay)!==null&&l!==void 0?l:0}get window(){if(this.context&&this.context.window)return this.context.window;if(typeof window<"u")return window}get document(){var s;if(!((s=this.context)===null||s===void 0)&&s.document)return this.context.document;if(this.window)return this.window.document}get rootElement(){var s;return((s=this.args)===null||s===void 0?void 0:s.rootElement)||this.document}constructor(s,i){this.args=s,this.context=i}}function cse(a,s,i,r){return Math.sqrt(Math.pow(Math.abs(i-a),2)+Math.pow(Math.abs(r-s),2))}function use(a,s,i,r,l){if(!l)return!1;const u=Math.atan2(r-s,i-a)*180/Math.PI+180;for(let d=0;d=p.start)&&(p.end==null||u<=p.end))return!0}return!1}const dse={Left:1},hse={Left:0};function Cg(a){return a.button===void 0||a.button===hse.Left}function pse(a){return a.buttons===void 0||(a.buttons&dse.Left)===0}function AT(a){return!!a.targetTouches}const gse=1;function mse(a){const s=a.nodeType===gse?a:a.parentElement;if(!s)return;const{top:i,left:r}=s.getBoundingClientRect();return{x:r,y:i}}function fse(a,s){if(a.targetTouches.length===1)return Hc(a.targetTouches[0]);if(s&&a.touches.length===1&&a.touches[0].target===s.target)return Hc(a.touches[0])}function Hc(a,s){return AT(a)?fse(a,s):{x:a.clientX,y:a.clientY}}const _w=(()=>{let a=!1;try{addEventListener("test",()=>{},Object.defineProperty({},"passive",{get(){return a=!0,!0}}))}catch{}return a})(),jr={[Fo.mouse]:{start:"mousedown",move:"mousemove",end:"mouseup",contextmenu:"contextmenu"},[Fo.touch]:{start:"touchstart",move:"touchmove",end:"touchend"},[Fo.keyboard]:{keydown:"keydown"}};class Gr{profile(){var s;return{sourceNodes:this.sourceNodes.size,sourcePreviewNodes:this.sourcePreviewNodes.size,sourcePreviewNodeOptions:this.sourcePreviewNodeOptions.size,targetNodes:this.targetNodes.size,dragOverTargetIds:((s=this.dragOverTargetIds)===null||s===void 0?void 0:s.length)||0}}get document(){return this.options.document}setup(){const s=this.options.rootElement;s&&(Ie(!Gr.isSetUp,"Cannot have two Touch backends at the same time."),Gr.isSetUp=!0,this.addEventListener(s,"start",this.getTopMoveStartHandler()),this.addEventListener(s,"start",this.handleTopMoveStartCapture,!0),this.addEventListener(s,"move",this.handleTopMove),this.addEventListener(s,"move",this.handleTopMoveCapture,!0),this.addEventListener(s,"end",this.handleTopMoveEndCapture,!0),this.options.enableMouseEvents&&!this.options.ignoreContextMenu&&this.addEventListener(s,"contextmenu",this.handleTopMoveEndCapture),this.options.enableKeyboardEvents&&this.addEventListener(s,"keydown",this.handleCancelOnEscape,!0))}teardown(){const s=this.options.rootElement;s&&(Gr.isSetUp=!1,this._mouseClientOffset={},this.removeEventListener(s,"start",this.handleTopMoveStartCapture,!0),this.removeEventListener(s,"start",this.handleTopMoveStart),this.removeEventListener(s,"move",this.handleTopMoveCapture,!0),this.removeEventListener(s,"move",this.handleTopMove),this.removeEventListener(s,"end",this.handleTopMoveEndCapture,!0),this.options.enableMouseEvents&&!this.options.ignoreContextMenu&&this.removeEventListener(s,"contextmenu",this.handleTopMoveEndCapture),this.options.enableKeyboardEvents&&this.removeEventListener(s,"keydown",this.handleCancelOnEscape,!0),this.uninstallSourceNodeRemovalObserver())}addEventListener(s,i,r,l=!1){const u=_w?{capture:l,passive:!1}:l;this.listenerTypes.forEach(function(d){const p=jr[d][i];p&&s.addEventListener(p,r,u)})}removeEventListener(s,i,r,l=!1){const u=_w?{capture:l,passive:!1}:l;this.listenerTypes.forEach(function(d){const p=jr[d][i];p&&s.removeEventListener(p,r,u)})}connectDragSource(s,i){const r=this.handleMoveStart.bind(this,s);return this.sourceNodes.set(s,i),this.addEventListener(i,"start",r),()=>{this.sourceNodes.delete(s),this.removeEventListener(i,"start",r)}}connectDragPreview(s,i,r){return this.sourcePreviewNodeOptions.set(s,r),this.sourcePreviewNodes.set(s,i),()=>{this.sourcePreviewNodes.delete(s),this.sourcePreviewNodeOptions.delete(s)}}connectDropTarget(s,i){const r=this.options.rootElement;if(!this.document||!r)return()=>{};const l=u=>{if(!this.document||!r||!this.monitor.isDragging())return;let d;switch(u.type){case jr.mouse.move:d={x:u.clientX,y:u.clientY};break;case jr.touch.move:var p,m;d={x:((p=u.touches[0])===null||p===void 0?void 0:p.clientX)||0,y:((m=u.touches[0])===null||m===void 0?void 0:m.clientY)||0};break}const f=d!=null?this.document.elementFromPoint(d.x,d.y):void 0,v=f&&i.contains(f);if(f===i||v)return this.handleMove(u,s)};return this.addEventListener(this.document.body,"move",l),this.targetNodes.set(s,i),()=>{this.document&&(this.targetNodes.delete(s),this.removeEventListener(this.document.body,"move",l))}}getTopMoveStartHandler(){return!this.options.delayTouchStart&&!this.options.delayMouseStart?this.handleTopMoveStart:this.handleTopMoveStartDelay}installSourceNodeRemovalObserver(s){this.uninstallSourceNodeRemovalObserver(),this.draggedSourceNode=s,this.draggedSourceNodeRemovalObserver=new MutationObserver(()=>{s&&!s.parentElement&&(this.resurrectSourceNode(),this.uninstallSourceNodeRemovalObserver())}),!(!s||!s.parentElement)&&this.draggedSourceNodeRemovalObserver.observe(s.parentElement,{childList:!0})}resurrectSourceNode(){this.document&&this.draggedSourceNode&&(this.draggedSourceNode.style.display="none",this.draggedSourceNode.removeAttribute("data-reactid"),this.document.body.appendChild(this.draggedSourceNode))}uninstallSourceNodeRemovalObserver(){this.draggedSourceNodeRemovalObserver&&this.draggedSourceNodeRemovalObserver.disconnect(),this.draggedSourceNodeRemovalObserver=void 0,this.draggedSourceNode=void 0}constructor(s,i,r){this.getSourceClientOffset=l=>{const u=this.sourceNodes.get(l);return u&&mse(u)},this.handleTopMoveStartCapture=l=>{Cg(l)&&(this.moveStartSourceIds=[])},this.handleMoveStart=l=>{Array.isArray(this.moveStartSourceIds)&&this.moveStartSourceIds.unshift(l)},this.handleTopMoveStart=l=>{if(!Cg(l))return;const u=Hc(l);u&&(AT(l)&&(this.lastTargetTouchFallback=l.targetTouches[0]),this._mouseClientOffset=u),this.waitingForDelay=!1},this.handleTopMoveStartDelay=l=>{if(!Cg(l))return;const u=l.type===jr.touch.start?this.options.delayTouchStart:this.options.delayMouseStart;this.timeout=setTimeout(this.handleTopMoveStart.bind(this,l),u),this.waitingForDelay=!0},this.handleTopMoveCapture=()=>{this.dragOverTargetIds=[]},this.handleMove=(l,u)=>{this.dragOverTargetIds&&this.dragOverTargetIds.unshift(u)},this.handleTopMove=l=>{if(this.timeout&&clearTimeout(this.timeout),!this.document||this.waitingForDelay)return;const{moveStartSourceIds:u,dragOverTargetIds:d}=this,p=this.options.enableHoverOutsideTarget,m=Hc(l,this.lastTargetTouchFallback);if(!m)return;if(this._isScrolling||!this.monitor.isDragging()&&use(this._mouseClientOffset.x||0,this._mouseClientOffset.y||0,m.x,m.y,this.options.scrollAngleRanges)){this._isScrolling=!0;return}if(!this.monitor.isDragging()&&this._mouseClientOffset.hasOwnProperty("x")&&u&&cse(this._mouseClientOffset.x||0,this._mouseClientOffset.y||0,m.x,m.y)>(this.options.touchSlop?this.options.touchSlop:0)&&(this.moveStartSourceIds=void 0,this.actions.beginDrag(u,{clientOffset:this._mouseClientOffset,getSourceClientOffset:this.getSourceClientOffset,publishSource:!1})),!this.monitor.isDragging())return;const f=this.sourceNodes.get(this.monitor.getSourceId());this.installSourceNodeRemovalObserver(f),this.actions.publishDragSource(),l.cancelable&&l.preventDefault();const v=(d||[]).map(C=>this.targetNodes.get(C)).filter(C=>!!C),_=this.options.getDropTargetElementsAtPoint?this.options.getDropTargetElementsAtPoint(m.x,m.y,v):this.document.elementsFromPoint(m.x,m.y),y=[];for(const C in _){if(!_.hasOwnProperty(C))continue;let w=_[C];for(w!=null&&y.push(w);w;)w=w.parentElement,w&&y.indexOf(w)===-1&&y.push(w)}const k=y.filter(C=>v.indexOf(C)>-1).map(C=>this._getDropTargetId(C)).filter(C=>!!C).filter((C,w,E)=>E.indexOf(C)===w);if(p)for(const C in this.targetNodes){const w=this.targetNodes.get(C);if(f&&w&&w.contains(f)&&k.indexOf(C)===-1){k.unshift(C);break}}k.reverse(),this.actions.hover(k,{clientOffset:m})},this._getDropTargetId=l=>{const u=this.targetNodes.keys();let d=u.next();for(;d.done===!1;){const p=d.value;if(l===this.targetNodes.get(p))return p;d=u.next()}},this.handleTopMoveEndCapture=l=>{if(this._isScrolling=!1,this.lastTargetTouchFallback=void 0,!!pse(l)){if(!this.monitor.isDragging()||this.monitor.didDrop()){this.moveStartSourceIds=void 0;return}l.cancelable&&l.preventDefault(),this._mouseClientOffset={},this.uninstallSourceNodeRemovalObserver(),this.actions.drop(),this.actions.endDrag()}},this.handleCancelOnEscape=l=>{l.key==="Escape"&&this.monitor.isDragging()&&(this._mouseClientOffset={},this.uninstallSourceNodeRemovalObserver(),this.actions.endDrag())},this.options=new lse(r,i),this.actions=s.getActions(),this.monitor=s.getMonitor(),this.sourceNodes=new Map,this.sourcePreviewNodes=new Map,this.sourcePreviewNodeOptions=new Map,this.targetNodes=new Map,this.listenerTypes=[],this._mouseClientOffset={},this._isScrolling=!1,this.options.enableMouseEvents&&this.listenerTypes.push(Fo.mouse),this.options.enableTouchEvents&&this.listenerTypes.push(Fo.touch),this.options.enableKeyboardEvents&&this.listenerTypes.push(Fo.keyboard)}}const $se=function(s,i={},r={}){return new Gr(s,i,r)};window.GenericBlock=Xe;window.adapterName="javascript";window.sentryDSN="https://504499a725eb4898930d3b9e9da95740@sentry.iobroker.net/56";console.log(`iobroker.${window.adapterName}@${DT.version}`);const bse=window.innerWidth<600,ww=document.getElementById("root");ww&&Pw(ww).render(g.jsx(Zw,{backend:bse?$se:uC,children:g.jsx(nse,{version:DT.version})}));rse();const uc=window.loadDynamicScript;uc&&uc(window.location.port==="3000"?`${window.location.protocol}//${window.location.hostname}:8081/lib/js/socket.io.js`:"./../../lib/js/socket.io.js",()=>uc("vs/loader.js",()=>uc("vs/configure.js",()=>typeof window.socketLoadedHandler=="function"&&window.socketLoadedHandler())));export{gO as C,Q0 as D,Xe as G,dC as I,mw as M,As as S,gI as a,OI as b,zI as c,bi as d,cne as e,zm as f,Zc as g,rx as h,une as j,l_ as m,Mn as u,dt as z}; diff --git a/admin/assets/index-Cd8FZ0ou.js b/admin/assets/index-Cd8FZ0ou.js deleted file mode 100644 index 2eba55322..000000000 --- a/admin/assets/index-Cd8FZ0ou.js +++ /dev/null @@ -1 +0,0 @@ -import{j as n}from"./createSvgIcon-DPvF8xqu.js";import{c as E,h as yt,j as M,m as nt,k as lt,l as Dt,b as ut,o as xt}from"./iobroker_javascript__loadShare__react__loadShare__.mjs-CTZOFJS2.js";import{_ as u}from"./iobroker_javascript__loadShare___mf_0_iobroker_mf_1_adapter_mf_2_react_mf_2_v5__loadShare__.mjs-DkBjPSMw.js";import{u as kt,a as St,M as Y,C as et,G as Nt,b as $t,c as bt,I as qt,S as J,d as Bt,e as ft,j as Mt,D as Ht,f as Wt}from"./index-CEbKg781.js";import{_ as wt,b as Ct,h as vt,i as jt,p as Tt,f as Et,g as mt,o as Pt,Y as Ut,Z as Ft,C as Jt,D as st}from"./iobroker_javascript__loadShare___mf_0_mui_mf_1_material__loadShare__.mjs-QWG5Arqe.js";import{I as Lt}from"./index-C49cpVll.js";import"./iobroker_javascript__loadShare__react__loadShare__.mjs_commonjs-proxy-CE9lvhW8.js";import"./iobroker_javascript__loadShare__prop_mf_2_types__loadShare__.mjs-BCtSFofY.js";import"./virtual_mf-REMOTE_ENTRY_ID_iobroker_javascript__remoteEntry_js-s4ROfmWJ.js";import"./preload-helper-BDBacUwf.js";import"./iobroker_javascript__loadShare__react_mf_2_dom__loadShare__.mjs_commonjs-proxy-RQRRZMX5.js";import"./iobroker_javascript__loadShare__react_mf_2_dom__loadShare__.mjs-DeVAS-oa.js";import"./inheritsLoose-B0Ba5G9z.js";function zt(e){const s=kt().getMonitor(),[i,a]=St(s,e);return E(()=>s.subscribeToOffsetChange(a)),E(()=>s.subscribeToStateChange(a)),i}let V;function Gt(){return V||(V=new Image,V.src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="),V}const Kt="_wrapperRules_nnott_1",Qt="_rootWrapper_nnott_9",Yt="_addClass_nnott_14",ot={wrapperRules:Kt,rootWrapper:Qt,addClass:Yt},Zt="_switchesItem_10ls3_1",Xt="_switchesItemActive_10ls3_28",Vt="_iconTheme_10ls3_36",it={switchesItem:Zt,switchesItemActive:Xt,iconTheme:Vt},It=({name:e,id:t,active:s,icon:i,adapter:a,socket:o,onDoubleClick:c,title:l,onTouchMove:d,style:j})=>n.jsxs("div",{onDoubleClick:c,onTouchMove:d,title:l?u.I18n.t(l):void 0,className:u.Utils.clsx(it.switchesItem,s&&it.switchesItemActive,`block-${t}`),children:[n.jsx(Y,{iconName:i,className:it.iconTheme,adapter:a,socket:o,style:j}),n.jsx("span",{children:e?u.I18n.t(e):""})]},t),Rt="_cardStyle_8rq8v_1",tn="_cardStyleActive_8rq8v_17",nn="_controlMenu_8rq8v_22",en="_closeBtn_8rq8v_31",sn="_isDelete_8rq8v_73",on="_drag_mobile_8rq8v_90",G={cardStyle:Rt,cardStyleActive:tn,controlMenu:nn,closeBtn:en,isDelete:sn,drag_mobile:on};function K(e,t,s){let i;switch(e){case"actions":if(s==="else")return i={...t,actions:{...t[e],else:[...t[e].else]}},i;if(s==="then")return i={...t,actions:{...t[e],then:[...t[e].then]}},i;throw console.error(`Unknown additionalParameter: ${s}`),new Error(`Unknown additionalParameter: ${s}`);case"triggers":return i={...t,triggers:[...t.triggers]},i;case"conditions":return i={...t,conditions:[...t.conditions]},i;default:throw new Error(`Unknown name: ${e}`)}}function z(e,t,s,i){var a;switch(e){case"actions":return t.actions[s]=t.actions[s].filter(o=>o._id!==i),t;case"conditions":return t.conditions[s]=(a=t.conditions[s])==null?void 0:a.filter(o=>o._id!==i),t;default:return t.triggers=t.triggers.filter(o=>o._id!==i),t}}function cn(e,t,s){const{_id:i,acceptedBy:a}=e;let o;if(!a||!t[a])return console.warn(`Cannot find ${a}`),t;switch(a){case"actions":if(o=t.actions[s].find(c=>c._id===i),!o)console.warn(`Cannot find ${i}`);else{const c=t.actions[s].indexOf(o);t.actions[s][c]=e}return t;case"conditions":if(o=t.conditions[s].find(c=>c._id===i),!o)console.warn(`Cannot find ${i}`);else{const c=t.conditions[s].indexOf(o);t.conditions[s][c]=e}return t;default:if(o=t.triggers.find(c=>c._id===i),!o)console.warn(`Cannot find ${i}`);else{const c=t.triggers.indexOf(o);t.triggers[c]=e}return t}}const Ot=yt(e=>{var N;const{setUserRules:t,userRules:s,_id:i,id:a,blockValue:o,active:c,acceptedBy:l,isTourOpen:d,setTourStep:j,tourStep:O}=e,[I,_]=M(null),{blocks:r,socket:k,onUpdate:H,setOnUpdate:w,onDebugMessage:f,enableSimulation:x}=nt(et),p=lt(h=>r==null?void 0:r.find(b=>b.getStaticData().id===h),[r]),g=lt(h=>{const b=cn(h,s,o);b&&t(b)},[s]),C=h=>{h.currentTarget!==I&&_(h.currentTarget)},q=()=>_(null),T=Dt(()=>{const h=p(a)||Nt;return n.jsx(h,{...e,notFound:!p(a),isTourOpen:d,setTourStep:j,tourStep:O,onUpdate:H,setOnUpdate:w,enableSimulation:x,onDebugMessage:f,onChange:g,className:void 0,socket:k})},[s,H,f,x]),[S,B]=M(!1);return n.jsxs("div",{onMouseMove:C,onMouseEnter:C,onMouseLeave:q,onMouseDown:h=>{if(h.ctrlKey){let b;const v=K(l,s,o);l==="conditions"?(b=v.conditions[o].find(m=>m._id===i),b&&v.conditions[o].splice(v.conditions[o].indexOf(b),0,{...b,_id:Date.now()})):l==="actions"?(b=v.actions[o].find(m=>m._id===i),b&&v.actions[o].splice(v.actions[o].indexOf(b),0,{...b,_id:Date.now()})):(b=v.triggers.find(m=>m._id===i),b&&v.triggers.splice(v[l].indexOf(b),0,{...b,_id:Date.now()})),t(v)}},id:"height",style:c?{width:(((N=document.getElementById("width"))==null?void 0:N.clientWidth)||0)-70}:void 0,className:`${G.cardStyle} ${c?G.cardStyleActive:null} ${S?G.isDelete:null}`,children:[n.jsx("div",{className:G.drag_mobile}),T,t&&n.jsx("div",{className:G.controlMenu,style:I?{opacity:1}:{opacity:0},children:n.jsx("div",{onClick:()=>{let h=K(l,s,o);h=z(l,h,o,i),B(!0),setTimeout(()=>{l==="triggers"&&w(!0),t(h)},300)},className:G.closeBtn})})]})}),rn={position:"fixed",pointerEvents:"none",zIndex:100,left:0,top:0,width:"100%",height:"100%"},an=(e,t,s)=>{if(!e||!t)return{display:"none"};let{x:i,y:a}=t;const o=`translate(${i}px, ${a}px)`;return{transform:o,WebkitTransform:o}},ln=e=>{const{itemType:t,isDragging:s,item:i,initialOffset:a,currentOffset:o,targetIds:c}=zt(d=>({item:d.getItem(),itemType:d.getItemType(),initialOffset:d.getInitialSourceClientOffset(),currentOffset:d.getSourceClientOffset(),isDragging:d.isDragging(),targetIds:d.getTargetIds()})),l=()=>t==="box"?c.length?n.jsx(Ot,{active:!0,...i,allBlocks:e.allBlocks}):n.jsx(It,{active:!0,...i,socket:e.socket}):null;return s?n.jsx("div",{style:rn,children:n.jsx("div",{style:an(a,o),children:l()})}):null},dn="_border_wrpm3_1",fn="_emptyBlockStyle_wrpm3_6",mn="_emptyBlock_wrpm3_6",gn="_selectOnChange_wrpm3_22",hn="_selectOnChangeHelp_wrpm3_28",_n="_selectOnChangeHelpIcon_wrpm3_34",pn="_emptyBlockNone_wrpm3_49",un="_mainBlockItemRules_wrpm3_55",xn="_nameBlockItems_wrpm3_63",bn="_contentBlockItem_wrpm3_73",wn="_wrapperMargin_wrpm3_81",Cn="_contentHeightOn_wrpm3_87",vn="_contentHeightOff_wrpm3_99",jn="_cardAdd_wrpm3_105",In="_blockCardAdd_wrpm3_125",On="_addClassOverflow_wrpm3_136",An="_addClassHeight_wrpm3_140",D={border:dn,emptyBlockStyle:fn,emptyBlock:mn,selectOnChange:gn,selectOnChangeHelp:hn,selectOnChangeHelpIcon:_n,emptyBlockNone:pn,mainBlockItemRules:un,nameBlockItems:xn,contentBlockItem:bn,wrapperMargin:wn,contentHeightOn:Cn,contentHeightOff:vn,cardAdd:jn,blockCardAdd:In,addClassOverflow:On,addClassHeight:An};function dt(e,t){const[s,i]=M(window.localStorage.getItem(t)?JSON.parse(window.localStorage.getItem(t)||""):e);return[s,o=>{window.localStorage.setItem(t,JSON.stringify(o)),i(o)},!!window.localStorage.getItem(t)]}function yn(e,t){let s=0,i=null,a;return function(...o){const c=Date.now();a=o,c-s>=t?(s=c,e.apply(this,o)):i||(i=setTimeout(()=>{s=Date.now(),i=null,e.apply(this,a)},t-(c-s)))}}function tt(e){if(Array.isArray(e))return e.map(t=>tt(t));if(typeof e=="function")return e.bind(null);if(e&&typeof e=="object"){const t={};return Object.keys(e).forEach(s=>{t[s]=tt(e[s])}),t}return e}const ct=yn((e,t)=>e(t),0);function R(e,t){const s=t.find(i=>i._id===e);return{card:s,index:s?t.indexOf(s):-1}}function rt(e,t,s,i,a,o,c,l,d){const{card:j,index:O}=R(e,s);if(!(Ot&&l>d)&&j&&O!==t){const I=tt(s);I.splice(O,1),I.splice(t,0,j);const _=tt(a);switch(o){case"actions":_.actions[c]=I,ct(i,_);return;case"conditions":_.conditions[c]=I,ct(i,_);return;default:_.triggers=I,ct(i,_);return}}}const Dn="_drag_7xfhc_1",kn="_root_7xfhc_11",gt={drag:Dn,root:kn},At=({typeBlock:e,allProperties:t,id:s,isActive:i,setUserRules:a,userRules:o,children:c,_id:l,blockValue:d})=>{const{setOnUpdate:j}=nt(et),[{opacity:O},I,_]=$t({type:"box",item:()=>({...t,id:s,isActive:i,_id:l}),end:(w,f)=>{const{acceptedBy:x}=w,p=f.getDropResult();let g;if(!p)return typeof l=="number"&&!f.getTargetIds().length&&(g=K(x,o,d),g=z(x,g,d,l),a(g)),null;if(p.blockValue!==d){const C=typeof l=="number"?l:Date.now();g=K(x,o,p.blockValue);const q={id:w.id,acceptedBy:w.acceptedBy};switch(x){case"actions":return d&&(g=z("actions",g,d,C)),g=z("actions",g,p.blockValue,C),g.actions[p.blockValue].push({...q,_id:C}),a(g);case"conditions":return typeof d=="number"&&(g=z("conditions",g,d,C)),g=z("conditions",g,p.blockValue,C),g.conditions[p.blockValue].push({...q,_id:C}),a(g);default:return j(!0),g=z("triggers",g,p.blockValue,C),g.triggers.push({...q,_id:C}),a(g)}}},collect:w=>({opacity:w.isDragging()?.4:1,isDragging:w.isDragging()})}),r=ut(null),[,k]=bt({accept:"box",canDrop:()=>!1,hover({_id:w,acceptedBy:f},x){var T;if(!r.current||e!==f)return;const p=(T=r.current)==null?void 0:T.getBoundingClientRect(),g=(p.bottom-p.top)/2,C=x.getClientOffset(),q=((C==null?void 0:C.y)||0)-p.top;if(l&&w!==l)switch(f){case"actions":if(d==="then"||d==="else"){const{index:S}=R(l,o.actions[d]);S!==w&&rt(w,S,o[f][d],a,o,f,d,q,g)}return;case"conditions":if(typeof d=="number"){const{index:S}=R(l,o[f][d]);S!==w&&rt(w,S,o[f][d],a,o,f,d,q,g)}return;default:{const{index:S}=R(l,o[f]);S!==w&&rt(w,S,o[f],a,o,f,void 0,q,g);return}}}});E(()=>{_(Gt(),{captureDraggingState:!0})},[]),I(k(r));const H=window.innerWidth<600;return n.jsxs("div",{ref:H&&l?null:r,className:gt.root,style:{opacity:O},children:[n.jsx("div",{className:l?gt.drag:null,ref:l&&H?r:null}),c]})},Sn=({onClose:e,open:t})=>n.jsxs(wt,{open:t,onClose:e,"aria-labelledby":"alert-dialog-title","aria-describedby":"alert-dialog-description",children:[n.jsx(Ct,{children:n.jsxs("div",{style:{fontSize:"1rem",fontFamily:'"Roboto", "Helvetica", "Arial", sans-serif',fontWeight:400,lineHeight:1.5,letterSpacing:"0.00938em"},children:[n.jsx("h3",{children:u.I18n.t("On condition change")}),n.jsx("div",{children:u.I18n.t("help_on_change")}),n.jsx("h3",{children:u.I18n.t("Just check")}),n.jsx("div",{children:u.I18n.t("help_just_check")})]})}),n.jsx(vt,{children:n.jsx(jt,{onClick:e,color:"primary",autoFocus:!0,startIcon:n.jsx(Lt,{}),children:u.I18n.t("OK")})})]}),Nn=({onClose:e,open:t})=>n.jsxs(wt,{open:t,onClose:e,"aria-labelledby":"alert-dialog-title","aria-describedby":"alert-dialog-description",children:[n.jsx(Ct,{children:n.jsxs(Tt,{id:"alert-dialog-description",children:[n.jsx("h3",{children:u.I18n.t("On condition change")}),n.jsx("div",{children:u.I18n.t("help_on_change")}),n.jsx("h3",{children:u.I18n.t("Just check")}),n.jsx("div",{children:u.I18n.t("help_just_check")})]})}),n.jsx(vt,{children:n.jsx(jt,{onClick:e,color:"primary",autoFocus:!0,children:u.I18n.t("OK")})})]}),ht=({size:e,blockValue:t,boolean:s,typeBlock:i,userRules:a,setUserRules:o,animation:c,setTourStep:l,tourStep:d,isTourOpen:j,theme:O,themeType:I,themeName:_})=>{var W;const[r,k]=M(!1),[H,w]=M(!1),[f,x]=M(!1),[p,g]=M("");s===void 0&&(s=!0);const C=bt({accept:"box",drop:()=>({blockValue:t}),hover:({acceptedBy:A,_id:L},Z)=>{k(A===i),x(!!L),g(Z.getHandlerId()||"")},canDrop:({acceptedBy:A})=>(w(A===i),A===i),collect:A=>{var L;return{isOver:A.isOver(),canDrop:((L=A.getItem())==null?void 0:L.acceptedBy)===i,offset:A.getClientOffset(),targetId:A.getHandlerId()}}}),q=C[0],{canDrop:T,isOver:S,offset:B,targetId:N}=q,h=C[1];E(()=>{g("")},[B]);const b=T&&S;let v="";b?v=r?"#00fb003d":"#fb00002e":T?v=H?"#00fb003d":"#fb00002e":B&&(v=N===p?"#fb00002e":"");let m;return i==="actions"?m=a.actions[t]:i==="conditions"?m=a.conditions[t]:m=a.triggers,n.jsx("div",{ref:h,style:{backgroundColor:v},className:`${u.Utils.clsx(D.contentBlockItem,e&&D.addClassHeight)} ${s?c?D.contentHeightOn:null:D.contentHeightOff}`,children:n.jsxs("div",{className:D.wrapperMargin,children:[m.map(A=>n.jsx(At,{typeBlock:i,...A,blockValue:t,allProperties:A,userRules:a,setUserRules:o,children:n.jsx(Ot,{...A,isTourOpen:j,setTourStep:l,tourStep:d,settings:A,blockValue:t,userRules:a,setUserRules:o,theme:O,themeType:I,themeName:_})},A._id)),n.jsx("div",{style:b&&r&&!f?{height:((W=document.getElementById("height"))==null?void 0:W.clientHeight)||200}:void 0,className:`${D.emptyBlockStyle} ${b&&r&&!f?D.emptyBlock:D.emptyBlockNone}`})]})})},at=({size:e,typeBlock:t,name:s,nameAdditionally:i,additionally:a,border:o,userRules:c,setUserRules:l,iconName:d,adapter:j,socket:O,setTourStep:I,tourStep:_,isTourOpen:r,theme:k,themeType:H,themeName:w})=>{const[f,x,p]=dt(t==="actions"?!1:[],`additionallyClickItems_${t}`),[g,C]=M(!1),[q,T]=M(!1);E(()=>{if(t==="conditions"&&(f==null?void 0:f.length)!==c.conditions.length-1){const N=[];c.conditions.forEach((h,b)=>{b>0&&N.push({_id:Date.now(),open:!0})}),x([...f,...N])}t==="actions"&&!p&&c.actions.else.length&&x(!0)},[]);const[S,B]=M(!1);return n.jsxs("div",{className:`${u.Utils.clsx(D.mainBlockItemRules,e&&D.addClassOverflow)} ${o&&!e?D.border:null}`,children:[n.jsxs("span",{id:"width",className:D.nameBlockItems,children:[n.jsx(Y,{iconName:d,className:D.iconThemCard,adapter:j,socket:O}),s]}),t==="conditions"?n.jsxs("div",{style:{width:"100%"},children:[n.jsxs(Et,{variant:"standard",className:D.selectOnChange,value:c.justCheck||!1,onChange:N=>{const h=K("conditions",c);h.justCheck=N.target.value==="true",l(h)},children:[n.jsx(mt,{value:"false",children:u.I18n.t("on condition change")}),n.jsx(mt,{value:"true",children:u.I18n.t("just check")})]}),n.jsx(Pt,{size:"small",title:u.I18n.t("Explanation"),className:D.selectOnChangeHelp,onClick:()=>C(!0),children:n.jsx(qt,{className:D.selectOnChangeHelpIcon})})]}):null,n.jsx(ht,{setTourStep:I,tourStep:_,isTourOpen:r,blockValue:t==="actions"?"then":t==="conditions"?0:t,typeBlock:t,setUserRules:l,userRules:c,theme:k,themeName:w,themeType:H,size:e}),a&&[...Array(t==="actions"?1:c.conditions.length-1)].map((N,h)=>{const b=(v=h)=>t==="actions"?!!f:!!f.find((m,W)=>W===v&&m.open);return n.jsxs(xt,{children:[n.jsxs("div",{onClick:()=>{if(t==="actions")return x(!f),null;let v=JSON.parse(JSON.stringify(f));if(c.conditions[h+1].length)return v[h].open=!v[h].open,x(v),null;v=v.filter((m,W)=>W!==h),x(v),B(h),setTimeout(()=>{B(!1),l({...c,conditions:[...c.conditions.filter((m,W)=>W!==h+1)]})},250)},className:D.blockCardAdd,children:[b()?"-":"+",n.jsx("div",{className:D.cardAdd,children:i})]},h),n.jsx(ht,{blockValue:t==="actions"?"else":t==="conditions"?h+1:t,typeBlock:t,setUserRules:l,userRules:c,boolean:b(),animation:S===h,size:e,theme:k,themeName:w,themeType:H})]},`${h}_block_${t}`)}),a&&t==="conditions"&&n.jsxs("div",{onClick:()=>{x([...f,{_id:Date.now(),open:!0}]),l({...c,conditions:[...c.conditions,[]]}),B(c.conditions.length-1),setTimeout(()=>B(!1),1e3)},className:D.blockCardAdd,children:["+",n.jsx("div",{className:D.cardAdd,children:i})]}),n.jsx(Sn,{open:g,onClose:()=>C(!1)}),n.jsx(Nn,{open:q,onClose:()=>T(!1)})]})},$n="_menuRules_1qqcb_1",qn="_switchesRenderWrapper_1qqcb_13",Bn="_menuOff_1qqcb_22",Mn="_menuTitle_1qqcb_28",Hn="_marginAuto_1qqcb_42",Wn="_inputWidth_1qqcb_47",Tn="_menuWrapper_1qqcb_52",En="_hamburgerWrapper_1qqcb_57",Pn="_hamburgerOff_1qqcb_74",Un="_nothingFound_1qqcb_82",Fn="_resetSearch_1qqcb_89",Jn="_controlPanel_1qqcb_101",Ln="_controlPanelAppBar_1qqcb_112",zn="_addClassMenu_1qqcb_126",Gn="_addClassBackground_1qqcb_132",Kn="_addClassPosition_1qqcb_136",$={menuRules:$n,switchesRenderWrapper:qn,menuOff:Bn,menuTitle:Mn,marginAuto:Hn,inputWidth:Wn,menuWrapper:Tn,hamburgerWrapper:En,hamburgerOff:Pn,nothingFound:Un,resetSearch:Fn,controlPanel:Jn,controlPanelAppBar:Ln,addClassMenu:zn,addClassBackground:Gn,addClassPosition:Kn},Qn=e=>{const{allProperties:t,allProperties:{acceptedBy:s,id:i},setUserRules:a,userRules:o,setTourStep:c,tourStep:l,isTourOpen:d,onTouchMove:j,isActive:O}=e;return n.jsx(At,{allProperties:t,id:t.id,isActive:O,setUserRules:a,userRules:o,children:n.jsx(It,{onDoubleClick:()=>{d&&l===J.addScheduleByDoubleClick&&i==="TriggerScheduleBlock"&&c(J.openTagsMenu),d&&l===J.addActionPrintText&&i==="ActionPrintText"&&c(J.showJavascript);const I=Date.now();let _;switch(s){case"actions":_="then";break;case"conditions":_=o[s].length-1;break}const r=K(s,o,_),k={id:i,_id:I,acceptedBy:s};_!==void 0?s==="actions"?r.actions[_].push({...k}):s==="conditions"&&r.conditions[_].push({...k}):r.triggers.push({...k}),a(r)},...e,...t,onTouchMove:j})})},Yn="_hamburgerMenu_hqnsm_8",Zn="_animate_hqnsm_21",_t={hamburgerMenu:Yn,animate:Zn};function Xn({bool:e}){return n.jsx("div",{className:`${_t.hamburgerMenu} ${e?_t.animate:""}`})}const Vn=({addClass:e,setAllBlocks:t,allBlocks:s,userRules:i,onChangeBlocks:a,setTourStep:o,tourStep:c,isTourOpen:l})=>{const{blocks:d,socket:j}=nt(et),[O,I]=dt(!1,"hamburgerOnOff"),[_,r]=dt({text:"",type:"triggers",index:0},"filterControlPanel"),k=(f=_.text,x=_.type)=>{if(!d)return;let p=[...d];p=p.filter(g=>{if(!f)return!0;const{name:C}=g.getStaticData();return C&&u.I18n.t(C).toLowerCase().includes(f.toLowerCase())}),p=p.filter(g=>x===g.getStaticData().acceptedBy),t(p)},H=(f,x)=>{l&&x===0&&c===J.selectTriggers&&o(J.addScheduleByDoubleClick),l&&x===2&&c===J.selectActions&&o(J.addActionPrintText),r({..._,index:x,type:["triggers","conditions","actions"][x]}),k(_.text,["triggers","conditions","actions"][x])},w=f=>({id:`scrollable-force-tab-${f}`,"aria-controls":`scrollable-force-tabpanel-${f}`});return E(()=>{k()},[d]),n.jsx(Ut,{mouseEvent:!1,touchEvent:"onTouchStart",onClickAway:()=>I(!0),children:n.jsxs("div",{className:u.Utils.clsx($.menuWrapper,e[1035]&&$.addClassMenu),children:[n.jsx("div",{className:`${$.hamburgerWrapper} ${O?$.hamburgerOff:null}`,onClick:()=>I(!O),children:n.jsx(Xn,{bool:!O})}),n.jsxs("div",{className:`${u.Utils.clsx($.menuRules,e[1035]&&$.addClassBackground,e[835]&&$.addClassPosition)} ${O?$.menuOff:null}`,children:[n.jsx("div",{className:$.controlPanel,children:n.jsx(Ft,{className:$.controlPanelAppBar,position:"static",children:n.jsxs(Jt,{value:_.index,onChange:H,children:[n.jsx(st,{className:"blocks-triggers",title:u.I18n.t("Triggers"),icon:n.jsx(Y,{iconName:"FlashOn"}),...w(0)}),n.jsx(st,{title:u.I18n.t("Conditions"),className:"blocks-conditions",icon:n.jsx(Y,{iconName:"Help"}),...w(1)}),n.jsx(st,{title:u.I18n.t("Actions"),className:"blocks-actions",icon:n.jsx(Y,{iconName:"PlayForWork"}),...w(2)})]})})}),n.jsx("div",{className:$.switchesRenderWrapper,children:n.jsxs("span",{children:[s.map(f=>{const{name:x,id:p,icon:g,adapter:C}=f.getStaticData();return n.jsx(xt,{children:n.jsx(Qn,{adapter:C,allProperties:f.getStaticData(),icon:g,id:p,isActive:!1,isTourOpen:l,name:x,onTouchMove:()=>I(!0),setTourStep:o,setUserRules:a,socket:j,tourStep:c,userRules:i})},p)}),!s.length&&n.jsxs("div",{className:$.nothingFound,children:[u.I18n.t("Nothing found"),"...",n.jsx("div",{className:$.resetSearch,onClick:()=>{r({..._,text:""}),k("")},children:u.I18n.t("reset search")})]})]})}),n.jsx("div",{className:u.Utils.clsx($.menuTitle,$.marginAuto)}),n.jsx(Bt,{className:$.inputWidth,fullWidth:!0,customValue:!0,value:_.text,size:"small",autoComplete:"off",label:u.I18n.t("search"),variant:"outlined",onChange:f=>{r({..._,text:f}),k(f)}})]})]})})};let pt=[];const me=({code:e,onChange:t,themeName:s,themeType:i,theme:a,setTourStep:o,tourStep:c,isTourOpen:l,command:d,scriptId:j,changed:O,running:I})=>{var v;const{blocks:_,socket:r,setOnUpdate:k,setOnDebugMessage:H,setEnableSimulation:w}=nt(et),[f,x]=M([]),[p,g]=M(ft(e)),[C,q]=M(""),[T,S]=M(!1);E(()=>{let m,W;const A=(P,y)=>{P===`${m}.alive`&&W!==(y==null?void 0:y.val)&&(W=!!(y!=null&&y.val),W&&m&&(r==null||r.sendTo(m.replace(/^system\.adapter\./,""),"rulesOn",j)))},L=(P,y)=>{var U,Q;r&&m!==((U=y==null?void 0:y.common)==null?void 0:U.engine)&&(m&&(r.unsubscribeState(`${m}.alive`,A),W&&r.sendTo(m.replace(/^system\.adapter\./,""),"rulesOn",j)),m=(Q=y==null?void 0:y.common)==null?void 0:Q.engine,m&&m&&r.subscribeState(`${m}.alive`,A))},Z=(P,y)=>{if(y)try{const U=JSON.parse(y.val),Q=Date.now();if(U.ruleId===j&&Q-U.ts<1e3){const F=[...pt,{blockId:U.blockId,data:U.data,ts:U.ts}];F.length>200&&F.splice(0,200-F.length);for(let X=F.length-1;X>=0;X--)if(F[X].ts{var y;m=(y=P==null?void 0:P.common)==null?void 0:y.engine,r.subscribeObject(j,L),m&&(r.subscribeState(`${m}.alive`,A),r.subscribeState(`${m.replace(/^system\.adapter\./,"")}.debug.rules`,Z))}),function(){r==null||r.unsubscribeObject(j,L),m&&(r==null||r.unsubscribeState(`${m}.alive`,A),W&&(r==null||r.sendTo(m.replace(/^system\.adapter\./,""),"rulesOff",j)),r==null||r.unsubscribeState(`${m.replace(/^system\.adapter\./,"")}.debug.rules`,Z))}},[]),E(()=>{w(!O&&I)},[O,I,w]),E(()=>{d&&(q(d),T||S(!0))},[d]),E(()=>{const m=ft(e);JSON.stringify(m)!==JSON.stringify(p)&&(g(m),k(!0))},[e]),E(()=>{document.getElementsByTagName("HTML")[0].className=s||"blue"},[s]);const B=lt(m=>{g(m),_&&t(Mt(m,_))},[_,t]),N=ut(null),[h,b]=M({835:!1,1035:!1});return E(()=>{N.current&&(N.current.clientWidth<=1035&&b({835:!1,1035:!0}),N.current.clientWidth<=835&&b({1035:!0,835:!0}),N.current.clientWidth>1035&&b({835:!1,1035:!1}))},[((v=N.current)==null?void 0:v.clientWidth)||0]),!_||!r?null:n.jsxs("div",{className:ot.wrapperRules,ref:N,children:[n.jsx(ln,{allBlocks:f,socket:r}),T?C==="export"?n.jsx(Ht,{scriptId:j,themeType:i,onClose:()=>S(!1),text:JSON.stringify(p,null,2)}):n.jsx(Wt,{themeType:i,onClose:m=>{S(!1),m&&B(JSON.parse(m))}}):null,n.jsxs("div",{className:u.Utils.clsx(ot.rootWrapper,h[835]&&ot.addClass),children:[n.jsx(Vn,{setAllBlocks:x,allBlocks:f,userRules:p,onChangeBlocks:B,setTourStep:o,tourStep:c,addClass:h,isTourOpen:l}),n.jsx(at,{socket:r,setUserRules:B,userRules:p,isTourOpen:l,setTourStep:o,tourStep:c,name:`${u.I18n.t("when")}...`,typeBlock:"triggers",iconName:"FlashOn",size:h[835],themeType:i,themeName:s,theme:a}),n.jsx(at,{socket:r,setUserRules:B,isTourOpen:l,setTourStep:o,tourStep:c,userRules:p,name:`...${u.I18n.t("and")}...`,typeBlock:"conditions",iconName:"Help",nameAdditionally:u.I18n.t("or"),additionally:!0,border:!0,size:h[835],themeType:i,themeName:s,theme:a}),n.jsx(at,{socket:r,setUserRules:B,isTourOpen:l,setTourStep:o,tourStep:c,userRules:p,name:`...${u.I18n.t("then")}`,typeBlock:"actions",iconName:"PlayForWork",nameAdditionally:u.I18n.t("else"),additionally:!0,size:h[835],themeType:i,themeName:s,theme:a})]})]},"rulesEditor")};export{me as default}; diff --git a/admin/assets/index-CZzmETwg.js b/admin/assets/index-Dl-EtX3d.js similarity index 99% rename from admin/assets/index-CZzmETwg.js rename to admin/assets/index-Dl-EtX3d.js index c50447056..36d4e8c24 100644 --- a/admin/assets/index-CZzmETwg.js +++ b/admin/assets/index-Dl-EtX3d.js @@ -1,4 +1,4 @@ -import{j as M}from"./createSvgIcon-DPvF8xqu.js";import{a as ft}from"./iobroker_javascript__loadShare__react__loadShare__.mjs-CTZOFJS2.js";import{m as Rt,z as Bt,g as Ut}from"./index-CEbKg781.js";import{z as Ze,o as Te,v as Nt,w as Mt,s as Lt,u as Vt,r as zt,_ as Ht,a as Gt,C as Pt,D as _t,F as Yt,G as wt,H as Qt}from"./iobroker_javascript__loadShare___mf_0_mui_mf_1_material__loadShare__.mjs-QWG5Arqe.js";import{M as Zt,k as Xt,l as ea,O as Tt,S as ta,J as aa,n as ra,t as na,v as sa,u as oa,T as ia,U as la,V as ca,W as ua}from"./index-C49cpVll.js";import{_ as we}from"./iobroker_javascript__loadShare___mf_0_iobroker_mf_1_adapter_mf_2_react_mf_2_v5__loadShare__.mjs-DkBjPSMw.js";import pa from"./ScriptEditorVanillaMonaco-DSYvOslZ.js";import{r as fa}from"./iobroker_javascript__loadShare__react__loadShare__.mjs_commonjs-proxy-CE9lvhW8.js";function da(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}import"./iobroker_javascript__loadShare__prop_mf_2_types__loadShare__.mjs-BCtSFofY.js";import"./virtual_mf-REMOTE_ENTRY_ID_iobroker_javascript__remoteEntry_js-s4ROfmWJ.js";import"./preload-helper-BDBacUwf.js";import"./iobroker_javascript__loadShare__react_mf_2_dom__loadShare__.mjs_commonjs-proxy-RQRRZMX5.js";import"./iobroker_javascript__loadShare__react_mf_2_dom__loadShare__.mjs-DeVAS-oa.js";import"./inheritsLoose-B0Ba5G9z.js";const ba={editorDiv:{height:"100%",width:"100%",overflow:"hidden",position:"relative"}};class ha extends ft.Component{constructor(v){super(v),this.state={lines:(this.props.script||"").split(/\r\n|\n/)}}render(){return M.jsx("div",{style:ba.editorDiv,children:M.jsx(pa,{triggerPrettier:1,name:this.props.scriptName,adapterName:this.props.adapterName,readOnly:!0,code:this.props.script||"",isDark:this.props.themeType==="dark",socket:this.props.socket,runningInstances:this.props.runningInstances,language:"javascript",breakpoints:this.props.breakpoints,location:this.props.paused?this.props.location:null,onToggleBreakpoint:v=>this.props.onToggleBreakpoint(v)},"scriptEditor2")},"scriptEditorDiv2")}}const Dt=34,Ke={logBox:{width:"100%",height:"100%",position:"relative",overflow:"hidden"},logBoxInner:Z=>({display:"inline-block",color:Z.palette.mode==="dark"?"white":"black",width:`calc(100% - ${Dt}px)`,height:"100%",overflow:"auto",position:"relative",verticalAlign:"top"}),info:Z=>({background:Z.palette.mode==="dark"?"darkgrey":"lightgrey",color:(Z.palette.mode==="dark","black")}),error:Z=>({background:"#FF0000",color:Z.palette.mode==="dark"?"black":"white"}),warn:Z=>({background:"#FF8000",color:Z.palette.mode==="dark"?"black":"white"}),debug:Z=>({background:"gray",opacity:.8,color:Z.palette.mode==="dark"?"black":"white"}),silly:Z=>({background:"gray",opacity:.6,color:Z.palette.mode==="dark"?"black":"white"}),table:{fontFamily:"monospace",width:"100%"},toolbox:{width:Dt,height:"100%",boxShadow:"2px 0px 4px -1px rgba(0, 0, 0, 0.2), 4px 0px 5px 0px rgba(0, 0, 0, 0.14), 1px 0px 10px 0px rgba(0, 0, 0, 0.12)",display:"inline-block",verticalAlign:"top",overflow:"hidden"},trTime:{width:90},trSeverity:{width:40,fontWeight:"bold"},iconButtons:{width:32,height:32,padding:4}};function ma(Z){let v,g=Z.getHours();return g<10&&(g=`0${g.toString()}`),v=`${g}:`,g=Z.getMinutes(),g<10&&(g=`0${g.toString()}`),v+=`${g}:`,g=Z.getSeconds(),g<10&&(g=`0${g.toString()}`),v+=`${g}.`,g=Z.getMilliseconds(),g<10?g=`00${g.toString()}`:g<100&&(g=`0${g.toString()}`),v+=g,v}class Ct extends ft.Component{messagesEnd;constructor(v){super(v),this.state={goBottom:!0},this.messagesEnd=ft.createRef()}static generateLine(v){return M.jsxs(Ze,{component:"tr",sx:Ke[v.severity],children:[M.jsx("td",{style:Ke.trTime,children:ma(new Date(v.ts))}),M.jsx("td",{style:Ke.trSeverity,children:v.severity}),M.jsx("td",{children:v.text})]},`tr_${v.ts}_${v.text.substring(v.text.length-10,v.text.length)}`)}renderLogList(v){return v!=null&&v.length?M.jsxs(Ze,{sx:Ke.logBoxInner,children:[M.jsx("table",{style:Ke.table,children:M.jsx("tbody",{children:v.map(g=>Ct.generateLine(g))})},"logTable"),M.jsx("div",{ref:this.messagesEnd,style:{float:"left",clear:"both"}},"logScrollPoint")]},"logList"):M.jsx(Ze,{sx:Ke.logBoxInner,style:{paddingLeft:10},children:we.I18n.t("Log outputs")},"logList")}onCopy(){we.Utils.copyToClipboard(this.props.console.join(` +import{j as M}from"./createSvgIcon-DPvF8xqu.js";import{a as ft}from"./iobroker_javascript__loadShare__react__loadShare__.mjs-CTZOFJS2.js";import{m as Rt,z as Bt,g as Ut}from"./index-DvPtUWVN.js";import{z as Ze,o as Te,v as Nt,w as Mt,s as Lt,u as Vt,r as zt,_ as Ht,a as Gt,C as Pt,D as _t,F as Yt,G as wt,H as Qt}from"./iobroker_javascript__loadShare___mf_0_mui_mf_1_material__loadShare__.mjs-QWG5Arqe.js";import{M as Zt,k as Xt,l as ea,O as Tt,S as ta,J as aa,n as ra,t as na,v as sa,u as oa,T as ia,U as la,V as ca,W as ua}from"./index-C49cpVll.js";import{_ as we}from"./iobroker_javascript__loadShare___mf_0_iobroker_mf_1_adapter_mf_2_react_mf_2_v5__loadShare__.mjs-DkBjPSMw.js";import pa from"./ScriptEditorVanillaMonaco-DSYvOslZ.js";import{r as fa}from"./iobroker_javascript__loadShare__react__loadShare__.mjs_commonjs-proxy-CE9lvhW8.js";function da(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}import"./iobroker_javascript__loadShare__prop_mf_2_types__loadShare__.mjs-BCtSFofY.js";import"./virtual_mf-REMOTE_ENTRY_ID_iobroker_javascript__remoteEntry_js-s4ROfmWJ.js";import"./preload-helper-BDBacUwf.js";import"./iobroker_javascript__loadShare__react_mf_2_dom__loadShare__.mjs_commonjs-proxy-RQRRZMX5.js";import"./iobroker_javascript__loadShare__react_mf_2_dom__loadShare__.mjs-DeVAS-oa.js";import"./inheritsLoose-B0Ba5G9z.js";const ba={editorDiv:{height:"100%",width:"100%",overflow:"hidden",position:"relative"}};class ha extends ft.Component{constructor(v){super(v),this.state={lines:(this.props.script||"").split(/\r\n|\n/)}}render(){return M.jsx("div",{style:ba.editorDiv,children:M.jsx(pa,{triggerPrettier:1,name:this.props.scriptName,adapterName:this.props.adapterName,readOnly:!0,code:this.props.script||"",isDark:this.props.themeType==="dark",socket:this.props.socket,runningInstances:this.props.runningInstances,language:"javascript",breakpoints:this.props.breakpoints,location:this.props.paused?this.props.location:null,onToggleBreakpoint:v=>this.props.onToggleBreakpoint(v)},"scriptEditor2")},"scriptEditorDiv2")}}const Dt=34,Ke={logBox:{width:"100%",height:"100%",position:"relative",overflow:"hidden"},logBoxInner:Z=>({display:"inline-block",color:Z.palette.mode==="dark"?"white":"black",width:`calc(100% - ${Dt}px)`,height:"100%",overflow:"auto",position:"relative",verticalAlign:"top"}),info:Z=>({background:Z.palette.mode==="dark"?"darkgrey":"lightgrey",color:(Z.palette.mode==="dark","black")}),error:Z=>({background:"#FF0000",color:Z.palette.mode==="dark"?"black":"white"}),warn:Z=>({background:"#FF8000",color:Z.palette.mode==="dark"?"black":"white"}),debug:Z=>({background:"gray",opacity:.8,color:Z.palette.mode==="dark"?"black":"white"}),silly:Z=>({background:"gray",opacity:.6,color:Z.palette.mode==="dark"?"black":"white"}),table:{fontFamily:"monospace",width:"100%"},toolbox:{width:Dt,height:"100%",boxShadow:"2px 0px 4px -1px rgba(0, 0, 0, 0.2), 4px 0px 5px 0px rgba(0, 0, 0, 0.14), 1px 0px 10px 0px rgba(0, 0, 0, 0.12)",display:"inline-block",verticalAlign:"top",overflow:"hidden"},trTime:{width:90},trSeverity:{width:40,fontWeight:"bold"},iconButtons:{width:32,height:32,padding:4}};function ma(Z){let v,g=Z.getHours();return g<10&&(g=`0${g.toString()}`),v=`${g}:`,g=Z.getMinutes(),g<10&&(g=`0${g.toString()}`),v+=`${g}:`,g=Z.getSeconds(),g<10&&(g=`0${g.toString()}`),v+=`${g}.`,g=Z.getMilliseconds(),g<10?g=`00${g.toString()}`:g<100&&(g=`0${g.toString()}`),v+=g,v}class Ct extends ft.Component{messagesEnd;constructor(v){super(v),this.state={goBottom:!0},this.messagesEnd=ft.createRef()}static generateLine(v){return M.jsxs(Ze,{component:"tr",sx:Ke[v.severity],children:[M.jsx("td",{style:Ke.trTime,children:ma(new Date(v.ts))}),M.jsx("td",{style:Ke.trSeverity,children:v.severity}),M.jsx("td",{children:v.text})]},`tr_${v.ts}_${v.text.substring(v.text.length-10,v.text.length)}`)}renderLogList(v){return v!=null&&v.length?M.jsxs(Ze,{sx:Ke.logBoxInner,children:[M.jsx("table",{style:Ke.table,children:M.jsx("tbody",{children:v.map(g=>Ct.generateLine(g))})},"logTable"),M.jsx("div",{ref:this.messagesEnd,style:{float:"left",clear:"both"}},"logScrollPoint")]},"logList"):M.jsx(Ze,{sx:Ke.logBoxInner,style:{paddingLeft:10},children:we.I18n.t("Log outputs")},"logList")}onCopy(){we.Utils.copyToClipboard(this.props.console.join(` `))}scrollToBottom(){var v,g;(g=(v=this.messagesEnd)==null?void 0:v.current)==null||g.scrollIntoView({behavior:"smooth"})}componentDidUpdate(){this.state.goBottom&&this.scrollToBottom()}render(){const v=this.props.console;return M.jsxs("div",{style:Ke.logBox,children:[M.jsxs("div",{style:Ke.toolbox,children:[M.jsx(Te,{style:Ke.iconButtons,onClick:()=>this.setState({goBottom:!this.state.goBottom}),color:this.state.goBottom?"secondary":void 0,size:"medium",children:M.jsx(Zt,{})}),v!=null&&v.length?M.jsx(Te,{style:Ke.iconButtons,onClick:()=>this.props.onClearAllLogs(),size:"medium",children:M.jsx(Xt,{})}):null,v!=null&&v.length?M.jsx(Te,{style:Ke.iconButtons,onClick:()=>this.onCopy(),size:"medium",children:M.jsx(ea,{})}):null]},"toolbox"),this.renderLogList(v)]})}}var It={exports:{}},va=It.exports;(function(Z,v){(function(g,a){Z.exports=a(fa)})(va,(function(g){return(function(a){var t={};function e(s){if(t[s])return t[s].exports;var c=t[s]={i:s,l:!1,exports:{}};return a[s].call(c.exports,c,c.exports,e),c.l=!0,c.exports}return e.m=a,e.c=t,e.d=function(s,c,d){e.o(s,c)||Object.defineProperty(s,c,{enumerable:!0,get:d})},e.r=function(s){typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(s,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(s,"__esModule",{value:!0})},e.t=function(s,c){if(1&c&&(s=e(s)),8&c||4&c&&typeof s=="object"&&s&&s.__esModule)return s;var d=Object.create(null);if(e.r(d),Object.defineProperty(d,"default",{enumerable:!0,value:s}),2&c&&typeof s!="string")for(var p in s)e.d(d,p,function(f){return s[f]}.bind(null,p));return d},e.n=function(s){var c=s&&s.__esModule?function(){return s.default}:function(){return s};return e.d(c,"a",c),c},e.o=function(s,c){return Object.prototype.hasOwnProperty.call(s,c)},e.p="",e(e.s=48)})([function(a,t){a.exports=g},function(a,t){var e=a.exports={version:"2.6.12"};typeof __e=="number"&&(__e=e)},function(a,t,e){var s=e(26)("wks"),c=e(17),d=e(3).Symbol,p=typeof d=="function";(a.exports=function(f){return s[f]||(s[f]=p&&d[f]||(p?d:c)("Symbol."+f))}).store=s},function(a,t){var e=a.exports=typeof window<"u"&&window.Math==Math?window:typeof self<"u"&&self.Math==Math?self:Function("return this")();typeof __g=="number"&&(__g=e)},function(a,t,e){a.exports=!e(8)((function(){return Object.defineProperty({},"a",{get:function(){return 7}}).a!=7}))},function(a,t){var e={}.hasOwnProperty;a.exports=function(s,c){return e.call(s,c)}},function(a,t,e){var s=e(7),c=e(16);a.exports=e(4)?function(d,p,f){return s.f(d,p,c(1,f))}:function(d,p,f){return d[p]=f,d}},function(a,t,e){var s=e(10),c=e(35),d=e(23),p=Object.defineProperty;t.f=e(4)?Object.defineProperty:function(f,h,S){if(s(f),h=d(h,!0),s(S),c)try{return p(f,h,S)}catch{}if("get"in S||"set"in S)throw TypeError("Accessors not supported!");return"value"in S&&(f[h]=S.value),f}},function(a,t){a.exports=function(e){try{return!!e()}catch{return!0}}},function(a,t,e){var s=e(40),c=e(22);a.exports=function(d){return s(c(d))}},function(a,t,e){var s=e(11);a.exports=function(c){if(!s(c))throw TypeError(c+" is not an object!");return c}},function(a,t){a.exports=function(e){return typeof e=="object"?e!==null:typeof e=="function"}},function(a,t){a.exports={}},function(a,t,e){var s=e(39),c=e(27);a.exports=Object.keys||function(d){return s(d,c)}},function(a,t){a.exports=!0},function(a,t,e){var s=e(3),c=e(1),d=e(53),p=e(6),f=e(5),h=function(S,b,w){var I,R,H,L=S&h.F,X=S&h.G,r=S&h.S,D=S&h.P,V=S&h.B,z=S&h.W,q=X?c:c[b]||(c[b]={}),k=q.prototype,A=X?s:r?s[b]:(s[b]||{}).prototype;for(I in X&&(w=b),w)(R=!L&&A&&A[I]!==void 0)&&f(q,I)||(H=R?A[I]:w[I],q[I]=X&&typeof A[I]!="function"?w[I]:V&&R?d(H,s):z&&A[I]==H?(function(T){var W=function(E,ee,J){if(this instanceof T){switch(arguments.length){case 0:return new T;case 1:return new T(E);case 2:return new T(E,ee)}return new T(E,ee,J)}return T.apply(this,arguments)};return W.prototype=T.prototype,W})(H):D&&typeof H=="function"?d(Function.call,H):H,D&&((q.virtual||(q.virtual={}))[I]=H,S&h.R&&k&&!k[I]&&p(k,I,H)))};h.F=1,h.G=2,h.S=4,h.P=8,h.B=16,h.W=32,h.U=64,h.R=128,a.exports=h},function(a,t){a.exports=function(e,s){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:s}}},function(a,t){var e=0,s=Math.random();a.exports=function(c){return"Symbol(".concat(c===void 0?"":c,")_",(++e+s).toString(36))}},function(a,t,e){var s=e(22);a.exports=function(c){return Object(s(c))}},function(a,t){t.f={}.propertyIsEnumerable},function(a,t,e){var s=e(52)(!0);e(34)(String,"String",(function(c){this._t=String(c),this._i=0}),(function(){var c,d=this._t,p=this._i;return p>=d.length?{value:void 0,done:!0}:(c=s(d,p),this._i+=c.length,{value:c,done:!1})}))},function(a,t){var e=Math.ceil,s=Math.floor;a.exports=function(c){return isNaN(c=+c)?0:(c>0?s:e)(c)}},function(a,t){a.exports=function(e){if(e==null)throw TypeError("Can't call method on "+e);return e}},function(a,t,e){var s=e(11);a.exports=function(c,d){if(!s(c))return c;var p,f;if(d&&typeof(p=c.toString)=="function"&&!s(f=p.call(c))||typeof(p=c.valueOf)=="function"&&!s(f=p.call(c))||!d&&typeof(p=c.toString)=="function"&&!s(f=p.call(c)))return f;throw TypeError("Can't convert object to primitive value")}},function(a,t){var e={}.toString;a.exports=function(s){return e.call(s).slice(8,-1)}},function(a,t,e){var s=e(26)("keys"),c=e(17);a.exports=function(d){return s[d]||(s[d]=c(d))}},function(a,t,e){var s=e(1),c=e(3),d=c["__core-js_shared__"]||(c["__core-js_shared__"]={});(a.exports=function(p,f){return d[p]||(d[p]=f!==void 0?f:{})})("versions",[]).push({version:s.version,mode:e(14)?"pure":"global",copyright:"© 2020 Denis Pushkarev (zloirock.ru)"})},function(a,t){a.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(a,t,e){var s=e(7).f,c=e(5),d=e(2)("toStringTag");a.exports=function(p,f,h){p&&!c(p=h?p:p.prototype,d)&&s(p,d,{configurable:!0,value:f})}},function(a,t,e){e(62);for(var s=e(3),c=e(6),d=e(12),p=e(2)("toStringTag"),f="CSSRuleList,CSSStyleDeclaration,CSSValueList,ClientRectList,DOMRectList,DOMStringList,DOMTokenList,DataTransferItemList,FileList,HTMLAllCollection,HTMLCollection,HTMLFormElement,HTMLSelectElement,MediaList,MimeTypeArray,NamedNodeMap,NodeList,PaintRequestList,Plugin,PluginArray,SVGLengthList,SVGNumberList,SVGPathSegList,SVGPointList,SVGStringList,SVGTransformList,SourceBufferList,StyleSheetList,TextTrackCueList,TextTrackList,TouchList".split(","),h=0;hdocument.F=Object<\/script>"),S.close(),h=S.F;w--;)delete h.prototype[d[w]];return h()};a.exports=Object.create||function(S,b){var w;return S!==null?(f.prototype=s(S),w=new f,f.prototype=null,w[p]=S):w=h(),b===void 0?w:c(w,b)}},function(a,t,e){var s=e(5),c=e(9),d=e(57)(!1),p=e(25)("IE_PROTO");a.exports=function(f,h){var S,b=c(f),w=0,I=[];for(S in b)S!=p&&s(b,S)&&I.push(S);for(;h.length>w;)s(b,S=h[w++])&&(~d(I,S)||I.push(S));return I}},function(a,t,e){var s=e(24);a.exports=Object("z").propertyIsEnumerable(0)?Object:function(c){return s(c)=="String"?c.split(""):Object(c)}},function(a,t,e){var s=e(39),c=e(27).concat("length","prototype");t.f=Object.getOwnPropertyNames||function(d){return s(d,c)}},function(a,t,e){var s=e(24),c=e(2)("toStringTag"),d=s((function(){return arguments})())=="Arguments";a.exports=function(p){var f,h,S;return p===void 0?"Undefined":p===null?"Null":typeof(h=(function(b,w){try{return b[w]}catch{}})(f=Object(p),c))=="string"?h:d?s(f):(S=s(f))=="Object"&&typeof f.callee=="function"?"Arguments":S}},function(a,t){var e;e=(function(){return this})();try{e=e||new Function("return this")()}catch{typeof window=="object"&&(e=window)}a.exports=e},function(a,t){var e=/-?\d+(\.\d+)?%?/g;a.exports=function(s){return s.match(e)}},function(a,t,e){Object.defineProperty(t,"__esModule",{value:!0}),t.getBase16Theme=t.createStyling=t.invertTheme=void 0;var s=R(e(49)),c=R(e(76)),d=R(e(81)),p=R(e(89)),f=R(e(93)),h=(function(k){if(k&&k.__esModule)return k;var A={};if(k!=null)for(var T in k)Object.prototype.hasOwnProperty.call(k,T)&&(A[T]=k[T]);return A.default=k,A})(e(94)),S=R(e(132)),b=R(e(133)),w=R(e(138)),I=e(139);function R(k){return k&&k.__esModule?k:{default:k}}var H=h.default,L=(0,p.default)(H),X=(0,w.default)(b.default,I.rgb2yuv,(function(k){var A,T=(0,d.default)(k,3),W=T[0],E=T[1],ee=T[2];return[(A=W,A<.25?1:A<.5?.9-A:1.1-A),E,ee]}),I.yuv2rgb,S.default),r=function(k){return function(A){return{className:[A.className,k.className].filter(Boolean).join(" "),style:(0,c.default)({},A.style||{},k.style||{})}}},D=function(k,A){var T=(0,p.default)(A);for(var W in k)T.indexOf(W)===-1&&T.push(W);return T.reduce((function(E,ee){return E[ee]=(function(J,C){if(J===void 0)return C;if(C===void 0)return J;var Y=J===void 0?"undefined":(0,s.default)(J),be=C===void 0?"undefined":(0,s.default)(C);switch(Y){case"string":switch(be){case"string":return[C,J].filter(Boolean).join(" ");case"object":return r({className:J,style:C});case"function":return function(ce){for(var U=arguments.length,le=Array(U>1?U-1:0),Q=1;Q1?U-1:0),Q=1;Q1?U-1:0),Q=1;Q1?U-1:0),Q=1;Q1?U-1:0),Q=1;Q2?T-2:0),E=2;E3?A-3:0),W=3;W1&&arguments[1]!==void 0?arguments[1]:{},ee=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},J=E.defaultBase16,C=J===void 0?H:J,Y=E.base16Themes,be=Y===void 0?null:Y,ce=q(ee,be);ce&&(ee=(0,c.default)({},ce,ee));var U=L.reduce((function(ve,Ne){return ve[Ne]=ee[Ne]||C[Ne],ve}),{}),le=(0,p.default)(ee).reduce((function(ve,Ne){return L.indexOf(Ne)===-1&&(ve[Ne]=ee[Ne]),ve}),{}),Q=k(U),he=D(le,Q);return(0,f.default)(V,2).apply(void 0,[he].concat(T))}),3),t.getBase16Theme=function(k,A){if(k&&k.extend&&(k=k.extend),typeof k=="string"){var T=k.split(":"),W=(0,d.default)(T,2),E=W[0],ee=W[1];k=(A||{})[E]||h[E],ee==="inverted"&&(k=z(k))}return k&&k.hasOwnProperty("base00")?k:void 0})},function(a,t,e){var s,c=typeof Reflect=="object"?Reflect:null,d=c&&typeof c.apply=="function"?c.apply:function(r,D,V){return Function.prototype.apply.call(r,D,V)};s=c&&typeof c.ownKeys=="function"?c.ownKeys:Object.getOwnPropertySymbols?function(r){return Object.getOwnPropertyNames(r).concat(Object.getOwnPropertySymbols(r))}:function(r){return Object.getOwnPropertyNames(r)};var p=Number.isNaN||function(r){return r!=r};function f(){f.init.call(this)}a.exports=f,a.exports.once=function(r,D){return new Promise((function(V,z){function q(){k!==void 0&&r.removeListener("error",k),V([].slice.call(arguments))}var k;D!=="error"&&(k=function(A){r.removeListener(D,q),z(A)},r.once("error",k)),r.once(D,q)}))},f.EventEmitter=f,f.prototype._events=void 0,f.prototype._eventsCount=0,f.prototype._maxListeners=void 0;var h=10;function S(r){if(typeof r!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof r)}function b(r){return r._maxListeners===void 0?f.defaultMaxListeners:r._maxListeners}function w(r,D,V,z){var q,k,A,T;if(S(V),(k=r._events)===void 0?(k=r._events=Object.create(null),r._eventsCount=0):(k.newListener!==void 0&&(r.emit("newListener",D,V.listener?V.listener:V),k=r._events),A=k[D]),A===void 0)A=k[D]=V,++r._eventsCount;else if(typeof A=="function"?A=k[D]=z?[V,A]:[A,V]:z?A.unshift(V):A.push(V),(q=b(r))>0&&A.length>q&&!A.warned){A.warned=!0;var W=new Error("Possible EventEmitter memory leak detected. "+A.length+" "+String(D)+" listeners added. Use emitter.setMaxListeners() to increase limit");W.name="MaxListenersExceededWarning",W.emitter=r,W.type=D,W.count=A.length,T=W,console&&console.warn&&console.warn(T)}return r}function I(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function R(r,D,V){var z={fired:!1,wrapFn:void 0,target:r,type:D,listener:V},q=I.bind(z);return q.listener=V,z.wrapFn=q,q}function H(r,D,V){var z=r._events;if(z===void 0)return[];var q=z[D];return q===void 0?[]:typeof q=="function"?V?[q.listener||q]:[q]:V?(function(k){for(var A=new Array(k.length),T=0;T0&&(k=D[0]),k instanceof Error)throw k;var A=new Error("Unhandled error."+(k?" ("+k.message+")":""));throw A.context=k,A}var T=q[r];if(T===void 0)return!1;if(typeof T=="function")d(T,this,D);else{var W=T.length,E=X(T,W);for(V=0;V=0;k--)if(V[k]===D||V[k].listener===D){A=V[k].listener,q=k;break}if(q<0)return this;q===0?V.shift():(function(T,W){for(;W+1=0;z--)this.removeListener(r,D[z]);return this},f.prototype.listeners=function(r){return H(this,r,!0)},f.prototype.rawListeners=function(r){return H(this,r,!1)},f.listenerCount=function(r,D){return typeof r.listenerCount=="function"?r.listenerCount(D):L.call(r,D)},f.prototype.listenerCount=L,f.prototype.eventNames=function(){return this._eventsCount>0?s(this._events):[]}},function(a,t,e){a.exports.Dispatcher=e(140)},function(a,t,e){a.exports=e(142)},function(a,t,e){t.__esModule=!0;var s=p(e(50)),c=p(e(65)),d=typeof c.default=="function"&&typeof s.default=="symbol"?function(f){return typeof f}:function(f){return f&&typeof c.default=="function"&&f.constructor===c.default&&f!==c.default.prototype?"symbol":typeof f};function p(f){return f&&f.__esModule?f:{default:f}}t.default=typeof c.default=="function"&&d(s.default)==="symbol"?function(f){return f===void 0?"undefined":d(f)}:function(f){return f&&typeof c.default=="function"&&f.constructor===c.default&&f!==c.default.prototype?"symbol":f===void 0?"undefined":d(f)}},function(a,t,e){a.exports={default:e(51),__esModule:!0}},function(a,t,e){e(20),e(29),a.exports=e(30).f("iterator")},function(a,t,e){var s=e(21),c=e(22);a.exports=function(d){return function(p,f){var h,S,b=String(c(p)),w=s(f),I=b.length;return w<0||w>=I?d?"":void 0:(h=b.charCodeAt(w))<55296||h>56319||w+1===I||(S=b.charCodeAt(w+1))<56320||S>57343?d?b.charAt(w):h:d?b.slice(w,w+2):S-56320+(h-55296<<10)+65536}}},function(a,t,e){var s=e(54);a.exports=function(c,d,p){if(s(c),d===void 0)return c;switch(p){case 1:return function(f){return c.call(d,f)};case 2:return function(f,h){return c.call(d,f,h)};case 3:return function(f,h,S){return c.call(d,f,h,S)}}return function(){return c.apply(d,arguments)}}},function(a,t){a.exports=function(e){if(typeof e!="function")throw TypeError(e+" is not a function!");return e}},function(a,t,e){var s=e(38),c=e(16),d=e(28),p={};e(6)(p,e(2)("iterator"),(function(){return this})),a.exports=function(f,h,S){f.prototype=s(p,{next:c(1,S)}),d(f,h+" Iterator")}},function(a,t,e){var s=e(7),c=e(10),d=e(13);a.exports=e(4)?Object.defineProperties:function(p,f){c(p);for(var h,S=d(f),b=S.length,w=0;b>w;)s.f(p,h=S[w++],f[h]);return p}},function(a,t,e){var s=e(9),c=e(58),d=e(59);a.exports=function(p){return function(f,h,S){var b,w=s(f),I=c(w.length),R=d(S,I);if(p&&h!=h){for(;I>R;)if((b=w[R++])!=b)return!0}else for(;I>R;R++)if((p||R in w)&&w[R]===h)return p||R||0;return!p&&-1}}},function(a,t,e){var s=e(21),c=Math.min;a.exports=function(d){return d>0?c(s(d),9007199254740991):0}},function(a,t,e){var s=e(21),c=Math.max,d=Math.min;a.exports=function(p,f){return(p=s(p))<0?c(p+f,0):d(p,f)}},function(a,t,e){var s=e(3).document;a.exports=s&&s.documentElement},function(a,t,e){var s=e(5),c=e(18),d=e(25)("IE_PROTO"),p=Object.prototype;a.exports=Object.getPrototypeOf||function(f){return f=c(f),s(f,d)?f[d]:typeof f.constructor=="function"&&f instanceof f.constructor?f.constructor.prototype:f instanceof Object?p:null}},function(a,t,e){var s=e(63),c=e(64),d=e(12),p=e(9);a.exports=e(34)(Array,"Array",(function(f,h){this._t=p(f),this._i=0,this._k=h}),(function(){var f=this._t,h=this._k,S=this._i++;return!f||S>=f.length?(this._t=void 0,c(1)):c(0,h=="keys"?S:h=="values"?f[S]:[S,f[S]])}),"values"),d.Arguments=d.Array,s("keys"),s("values"),s("entries")},function(a,t){a.exports=function(){}},function(a,t){a.exports=function(e,s){return{value:s,done:!!e}}},function(a,t,e){a.exports={default:e(66),__esModule:!0}},function(a,t,e){e(67),e(73),e(74),e(75),a.exports=e(1).Symbol},function(a,t,e){var s=e(3),c=e(5),d=e(4),p=e(15),f=e(37),h=e(68).KEY,S=e(8),b=e(26),w=e(28),I=e(17),R=e(2),H=e(30),L=e(31),X=e(69),r=e(70),D=e(10),V=e(11),z=e(18),q=e(9),k=e(23),A=e(16),T=e(38),W=e(71),E=e(72),ee=e(32),J=e(7),C=e(13),Y=E.f,be=J.f,ce=W.f,U=s.Symbol,le=s.JSON,Q=le&&le.stringify,he=R("_hidden"),ve=R("toPrimitive"),Ne={}.propertyIsEnumerable,Ee=b("symbol-registry"),Oe=b("symbols"),fe=b("op-symbols"),ge=Object.prototype,De=typeof U=="function"&&!!ee.f,Ue=s.QObject,Xe=!Ue||!Ue.prototype||!Ue.prototype.findChild,et=d&&S((function(){return T(be({},"a",{get:function(){return be(this,"a",{value:7}).a}})).a!=7}))?function(j,N,B){var K=Y(ge,N);K&&delete ge[N],be(j,N,B),K&&j!==ge&&be(ge,N,K)}:be,tt=function(j){var N=Oe[j]=T(U.prototype);return N._k=j,N},at=De&&typeof U.iterator=="symbol"?function(j){return typeof j=="symbol"}:function(j){return j instanceof U},He=function(j,N,B){return j===ge&&He(fe,N,B),D(j),N=k(N,!0),D(B),c(Oe,N)?(B.enumerable?(c(j,he)&&j[he][N]&&(j[he][N]=!1),B=T(B,{enumerable:A(0,!1)})):(c(j,he)||be(j,he,A(1,{})),j[he][N]=!0),et(j,N,B)):be(j,N,B)},st=function(j,N){D(j);for(var B,K=X(N=q(N)),re=0,te=K.length;te>re;)He(j,B=K[re++],N[B]);return j},ot=function(j){var N=Ne.call(this,j=k(j,!0));return!(this===ge&&c(Oe,j)&&!c(fe,j))&&(!(N||!c(this,j)||!c(Oe,j)||c(this,he)&&this[he][j])||N)},rt=function(j,N){if(j=q(j),N=k(N,!0),j!==ge||!c(Oe,N)||c(fe,N)){var B=Y(j,N);return!B||!c(Oe,N)||c(j,he)&&j[he][N]||(B.enumerable=!0),B}},it=function(j){for(var N,B=ce(q(j)),K=[],re=0;B.length>re;)c(Oe,N=B[re++])||N==he||N==h||K.push(N);return K},Ge=function(j){for(var N,B=j===ge,K=ce(B?fe:q(j)),re=[],te=0;K.length>te;)!c(Oe,N=K[te++])||B&&!c(ge,N)||re.push(Oe[N]);return re};De||(f((U=function(){if(this instanceof U)throw TypeError("Symbol is not a constructor!");var j=I(arguments.length>0?arguments[0]:void 0),N=function(B){this===ge&&N.call(fe,B),c(this,he)&&c(this[he],j)&&(this[he][j]=!1),et(this,j,A(1,B))};return d&&Xe&&et(ge,j,{configurable:!0,set:N}),tt(j)}).prototype,"toString",(function(){return this._k})),E.f=rt,J.f=He,e(41).f=W.f=it,e(19).f=ot,ee.f=Ge,d&&!e(14)&&f(ge,"propertyIsEnumerable",ot,!0),H.f=function(j){return tt(R(j))}),p(p.G+p.W+p.F*!De,{Symbol:U});for(var Ve="hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables".split(","),Ce=0;Ve.length>Ce;)R(Ve[Ce++]);for(var nt=C(R.store),F=0;nt.length>F;)L(nt[F++]);p(p.S+p.F*!De,"Symbol",{for:function(j){return c(Ee,j+="")?Ee[j]:Ee[j]=U(j)},keyFor:function(j){if(!at(j))throw TypeError(j+" is not a symbol!");for(var N in Ee)if(Ee[N]===j)return N},useSetter:function(){Xe=!0},useSimple:function(){Xe=!1}}),p(p.S+p.F*!De,"Object",{create:function(j,N){return N===void 0?T(j):st(T(j),N)},defineProperty:He,defineProperties:st,getOwnPropertyDescriptor:rt,getOwnPropertyNames:it,getOwnPropertySymbols:Ge});var x=S((function(){ee.f(1)}));p(p.S+p.F*x,"Object",{getOwnPropertySymbols:function(j){return ee.f(z(j))}}),le&&p(p.S+p.F*(!De||S((function(){var j=U();return Q([j])!="[null]"||Q({a:j})!="{}"||Q(Object(j))!="{}"}))),"JSON",{stringify:function(j){for(var N,B,K=[j],re=1;arguments.length>re;)K.push(arguments[re++]);if(B=N=K[1],(V(N)||j!==void 0)&&!at(j))return r(N)||(N=function(te,ue){if(typeof B=="function"&&(ue=B.call(this,te,ue)),!at(ue))return ue}),K[1]=N,Q.apply(le,K)}}),U.prototype[ve]||e(6)(U.prototype,ve,U.prototype.valueOf),w(U,"Symbol"),w(Math,"Math",!0),w(s.JSON,"JSON",!0)},function(a,t,e){var s=e(17)("meta"),c=e(11),d=e(5),p=e(7).f,f=0,h=Object.isExtensible||function(){return!0},S=!e(8)((function(){return h(Object.preventExtensions({}))})),b=function(I){p(I,s,{value:{i:"O"+ ++f,w:{}}})},w=a.exports={KEY:s,NEED:!1,fastKey:function(I,R){if(!c(I))return typeof I=="symbol"?I:(typeof I=="string"?"S":"P")+I;if(!d(I,s)){if(!h(I))return"F";if(!R)return"E";b(I)}return I[s].i},getWeak:function(I,R){if(!d(I,s)){if(!h(I))return!0;if(!R)return!1;b(I)}return I[s].w},onFreeze:function(I){return S&&w.NEED&&h(I)&&!d(I,s)&&b(I),I}}},function(a,t,e){var s=e(13),c=e(32),d=e(19);a.exports=function(p){var f=s(p),h=c.f;if(h)for(var S,b=h(p),w=d.f,I=0;b.length>I;)w.call(p,S=b[I++])&&f.push(S);return f}},function(a,t,e){var s=e(24);a.exports=Array.isArray||function(c){return s(c)=="Array"}},function(a,t,e){var s=e(9),c=e(41).f,d={}.toString,p=typeof window=="object"&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[];a.exports.f=function(f){return p&&d.call(f)=="[object Window]"?(function(h){try{return c(h)}catch{return p.slice()}})(f):c(s(f))}},function(a,t,e){var s=e(19),c=e(16),d=e(9),p=e(23),f=e(5),h=e(35),S=Object.getOwnPropertyDescriptor;t.f=e(4)?S:function(b,w){if(b=d(b),w=p(w,!0),h)try{return S(b,w)}catch{}if(f(b,w))return c(!s.f.call(b,w),b[w])}},function(a,t){},function(a,t,e){e(31)("asyncIterator")},function(a,t,e){e(31)("observable")},function(a,t,e){t.__esModule=!0;var s,c=e(77),d=(s=c)&&s.__esModule?s:{default:s};t.default=d.default||function(p){for(var f=1;fH;)for(var r,D=h(arguments[H++]),V=L?c(D).concat(L(D)):c(D),z=V.length,q=0;z>q;)r=V[q++],s&&!X.call(D,r)||(I[r]=D[r]);return I}:S},function(a,t,e){t.__esModule=!0;var s=d(e(82)),c=d(e(85));function d(p){return p&&p.__esModule?p:{default:p}}t.default=function(p,f){if(Array.isArray(p))return p;if((0,s.default)(Object(p)))return(function(h,S){var b=[],w=!0,I=!1,R=void 0;try{for(var H,L=(0,c.default)(h);!(w=(H=L.next()).done)&&(b.push(H.value),!S||b.length!==S);w=!0);}catch(X){I=!0,R=X}finally{try{!w&&L.return&&L.return()}finally{if(I)throw R}}return b})(p,f);throw new TypeError("Invalid attempt to destructure non-iterable instance")}},function(a,t,e){a.exports={default:e(83),__esModule:!0}},function(a,t,e){e(29),e(20),a.exports=e(84)},function(a,t,e){var s=e(42),c=e(2)("iterator"),d=e(12);a.exports=e(1).isIterable=function(p){var f=Object(p);return f[c]!==void 0||"@@iterator"in f||d.hasOwnProperty(s(f))}},function(a,t,e){a.exports={default:e(86),__esModule:!0}},function(a,t,e){e(29),e(20),a.exports=e(87)},function(a,t,e){var s=e(10),c=e(88);a.exports=e(1).getIterator=function(d){var p=c(d);if(typeof p!="function")throw TypeError(d+" is not iterable!");return s(p.call(d))}},function(a,t,e){var s=e(42),c=e(2)("iterator"),d=e(12);a.exports=e(1).getIteratorMethod=function(p){if(p!=null)return p[c]||p["@@iterator"]||d[s(p)]}},function(a,t,e){a.exports={default:e(90),__esModule:!0}},function(a,t,e){e(91),a.exports=e(1).Object.keys},function(a,t,e){var s=e(18),c=e(13);e(92)("keys",(function(){return function(d){return c(s(d))}}))},function(a,t,e){var s=e(15),c=e(1),d=e(8);a.exports=function(p,f){var h=(c.Object||{})[p]||Object[p],S={};S[p]=f(h),s(s.S+s.F*d((function(){h(1)})),"Object",S)}},function(a,t,e){(function(s){var c=[["ary",128],["bind",1],["bindKey",2],["curry",8],["curryRight",16],["flip",512],["partial",32],["partialRight",64],["rearg",256]],d=/^\s+|\s+$/g,p=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,f=/\{\n\/\* \[wrapped with (.+)\] \*/,h=/,? & /,S=/^[-+]0x[0-9a-f]+$/i,b=/^0b[01]+$/i,w=/^\[object .+?Constructor\]$/,I=/^0o[0-7]+$/i,R=/^(?:0|[1-9]\d*)$/,H=parseInt,L=typeof s=="object"&&s&&s.Object===Object&&s,X=typeof self=="object"&&self&&self.Object===Object&&self,r=L||X||Function("return this")();function D(F,x,j){switch(j.length){case 0:return F.call(x);case 1:return F.call(x,j[0]);case 2:return F.call(x,j[0],j[1]);case 3:return F.call(x,j[0],j[1],j[2])}return F.apply(x,j)}function V(F,x){return!!(F&&F.length)&&(function(j,N,B){if(N!=N)return(function(te,ue,ye,xe){for(var Ie=te.length,me=ye+-1;++me-1}function z(F){return F!=F}function q(F,x){for(var j=F.length,N=0;j--;)F[j]===x&&N++;return N}function k(F,x){for(var j=-1,N=F.length,B=0,K=[];++j2?T:void 0);function Ne(F){return Ve(F)?le(F):{}}function Ee(F){return!(!Ve(F)||(function(x){return!!C&&C in x})(F))&&((function(x){var j=Ve(x)?ce.call(x):"";return j=="[object Function]"||j=="[object GeneratorFunction]"})(F)||(function(x){var j=!1;if(x!=null&&typeof x.toString!="function")try{j=!!(x+"")}catch{}return j})(F)?U:w).test((function(x){if(x!=null){try{return Y.call(x)}catch{}try{return x+""}catch{}}return""})(F))}function Oe(F,x,j,N){for(var B=-1,K=F.length,re=j.length,te=-1,ue=x.length,ye=Q(K-re,0),xe=Array(ue+ye),Ie=!N;++te1&&se.reverse(),xe&&ue1?"& ":"")+x[N],x=x.join(j>2?", ":" "),F.replace(p,`{ /* [wrapped with `+x+`] */ `)}function st(F,x){return!!(x=x??9007199254740991)&&(typeof F=="number"||R.test(F))&&F>-1&&F%1==0&&F1&&d--,f=6*d<1?s+6*(c-s)*d:2*d<1?c:3*d<2?s+(c-s)*(2/3-d)*6:s,p[w]=255*f;return p}},function(a,t,e){(function(s){var c=typeof s=="object"&&s&&s.Object===Object&&s,d=typeof self=="object"&&self&&self.Object===Object&&self,p=c||d||Function("return this")();function f(k,A,T){switch(T.length){case 0:return k.call(A);case 1:return k.call(A,T[0]);case 2:return k.call(A,T[0],T[1]);case 3:return k.call(A,T[0],T[1],T[2])}return k.apply(A,T)}function h(k,A){for(var T=-1,W=A.length,E=k.length;++T-1&&E%1==0&&E<=9007199254740991})(W.length)&&!(function(E){var ee=(function(J){var C=typeof J;return!!J&&(C=="object"||C=="function")})(E)?w.call(E):"";return ee=="[object Function]"||ee=="[object GeneratorFunction]"})(W)})(T)})(A)&&b.call(A,"callee")&&(!R.call(A,"callee")||w.call(A)=="[object Arguments]")})(k)||!!(H&&k&&k[H])}var r=Array.isArray,D,V,z,q=(V=function(k){var A=(k=(function(E,ee,J,C,Y){var be=-1,ce=E.length;for(J||(J=X),Y||(Y=[]);++be2?d-2:0),f=2;f"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch{return!1}})();return function(){var n,o=w(l);if(u){var i=w(this).constructor;n=Reflect.construct(o,arguments,i)}else n=o.apply(this,arguments);return H(this,n)}}e.r(t);var X=e(0),r=e.n(X);function D(){var l=this.constructor.getDerivedStateFromProps(this.props,this.state);l!=null&&this.setState(l)}function V(l){this.setState(function(u){var n=this.constructor.getDerivedStateFromProps(l,u);return n??null}.bind(this))}function z(l,u){try{var n=this.props,o=this.state;this.props=l,this.state=u,this.__reactInternalSnapshotFlag=!0,this.__reactInternalSnapshot=this.getSnapshotBeforeUpdate(n,o)}finally{this.props=n,this.state=o}}function q(l){var u=l.prototype;if(!u||!u.isReactComponent)throw new Error("Can only polyfill class components");if(typeof l.getDerivedStateFromProps!="function"&&typeof u.getSnapshotBeforeUpdate!="function")return l;var n=null,o=null,i=null;if(typeof u.componentWillMount=="function"?n="componentWillMount":typeof u.UNSAFE_componentWillMount=="function"&&(n="UNSAFE_componentWillMount"),typeof u.componentWillReceiveProps=="function"?o="componentWillReceiveProps":typeof u.UNSAFE_componentWillReceiveProps=="function"&&(o="UNSAFE_componentWillReceiveProps"),typeof u.componentWillUpdate=="function"?i="componentWillUpdate":typeof u.UNSAFE_componentWillUpdate=="function"&&(i="UNSAFE_componentWillUpdate"),n!==null||o!==null||i!==null){var y=l.displayName||l.name,O=typeof l.getDerivedStateFromProps=="function"?"getDerivedStateFromProps()":"getSnapshotBeforeUpdate()";throw Error(`Unsafe legacy lifecycles will not be called for components using new component APIs. diff --git a/admin/assets/index-B0ByV4SK.js b/admin/assets/index-DqPwE1_T.js similarity index 99% rename from admin/assets/index-B0ByV4SK.js rename to admin/assets/index-DqPwE1_T.js index 25e2be3e8..7a7afc965 100644 --- a/admin/assets/index-B0ByV4SK.js +++ b/admin/assets/index-DqPwE1_T.js @@ -1 +1 @@ -import{j as n}from"./createSvgIcon-DPvF8xqu.js";import{c as E,h as yt,j as M,m as nt,k as lt,l as Dt,b as ut,o as xt}from"./iobroker_javascript__loadShare__react__loadShare__.mjs-CTZOFJS2.js";import{_ as u}from"./iobroker_javascript__loadShare___mf_0_iobroker_mf_1_adapter_mf_2_react_mf_2_v5__loadShare__.mjs-DkBjPSMw.js";import{u as kt,a as St,M as Y,C as et,G as Nt,b as $t,c as bt,I as qt,S as J,d as Bt,e as ft,j as Mt,D as Ht,f as Wt}from"./index-bny2V8S2.js";import{_ as wt,b as Ct,h as vt,i as jt,p as Tt,f as Et,g as mt,o as Pt,Y as Ut,Z as Ft,C as Jt,D as st}from"./iobroker_javascript__loadShare___mf_0_mui_mf_1_material__loadShare__.mjs-QWG5Arqe.js";import{I as Lt}from"./index-C49cpVll.js";import"./iobroker_javascript__loadShare__react__loadShare__.mjs_commonjs-proxy-CE9lvhW8.js";import"./iobroker_javascript__loadShare__prop_mf_2_types__loadShare__.mjs-BCtSFofY.js";import"./virtual_mf-REMOTE_ENTRY_ID_iobroker_javascript__remoteEntry_js-s4ROfmWJ.js";import"./preload-helper-BDBacUwf.js";import"./iobroker_javascript__loadShare__react_mf_2_dom__loadShare__.mjs_commonjs-proxy-RQRRZMX5.js";import"./iobroker_javascript__loadShare__react_mf_2_dom__loadShare__.mjs-DeVAS-oa.js";import"./inheritsLoose-B0Ba5G9z.js";function zt(e){const s=kt().getMonitor(),[i,a]=St(s,e);return E(()=>s.subscribeToOffsetChange(a)),E(()=>s.subscribeToStateChange(a)),i}let V;function Gt(){return V||(V=new Image,V.src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="),V}const Kt="_wrapperRules_nnott_1",Qt="_rootWrapper_nnott_9",Yt="_addClass_nnott_14",ot={wrapperRules:Kt,rootWrapper:Qt,addClass:Yt},Zt="_switchesItem_10ls3_1",Xt="_switchesItemActive_10ls3_28",Vt="_iconTheme_10ls3_36",it={switchesItem:Zt,switchesItemActive:Xt,iconTheme:Vt},It=({name:e,id:t,active:s,icon:i,adapter:a,socket:o,onDoubleClick:c,title:l,onTouchMove:d,style:j})=>n.jsxs("div",{onDoubleClick:c,onTouchMove:d,title:l?u.I18n.t(l):void 0,className:u.Utils.clsx(it.switchesItem,s&&it.switchesItemActive,`block-${t}`),children:[n.jsx(Y,{iconName:i,className:it.iconTheme,adapter:a,socket:o,style:j}),n.jsx("span",{children:e?u.I18n.t(e):""})]},t),Rt="_cardStyle_8rq8v_1",tn="_cardStyleActive_8rq8v_17",nn="_controlMenu_8rq8v_22",en="_closeBtn_8rq8v_31",sn="_isDelete_8rq8v_73",on="_drag_mobile_8rq8v_90",G={cardStyle:Rt,cardStyleActive:tn,controlMenu:nn,closeBtn:en,isDelete:sn,drag_mobile:on};function K(e,t,s){let i;switch(e){case"actions":if(s==="else")return i={...t,actions:{...t[e],else:[...t[e].else]}},i;if(s==="then")return i={...t,actions:{...t[e],then:[...t[e].then]}},i;throw console.error(`Unknown additionalParameter: ${s}`),new Error(`Unknown additionalParameter: ${s}`);case"triggers":return i={...t,triggers:[...t.triggers]},i;case"conditions":return i={...t,conditions:[...t.conditions]},i;default:throw new Error(`Unknown name: ${e}`)}}function z(e,t,s,i){var a;switch(e){case"actions":return t.actions[s]=t.actions[s].filter(o=>o._id!==i),t;case"conditions":return t.conditions[s]=(a=t.conditions[s])==null?void 0:a.filter(o=>o._id!==i),t;default:return t.triggers=t.triggers.filter(o=>o._id!==i),t}}function cn(e,t,s){const{_id:i,acceptedBy:a}=e;let o;if(!a||!t[a])return console.warn(`Cannot find ${a}`),t;switch(a){case"actions":if(o=t.actions[s].find(c=>c._id===i),!o)console.warn(`Cannot find ${i}`);else{const c=t.actions[s].indexOf(o);t.actions[s][c]=e}return t;case"conditions":if(o=t.conditions[s].find(c=>c._id===i),!o)console.warn(`Cannot find ${i}`);else{const c=t.conditions[s].indexOf(o);t.conditions[s][c]=e}return t;default:if(o=t.triggers.find(c=>c._id===i),!o)console.warn(`Cannot find ${i}`);else{const c=t.triggers.indexOf(o);t.triggers[c]=e}return t}}const Ot=yt(e=>{var N;const{setUserRules:t,userRules:s,_id:i,id:a,blockValue:o,active:c,acceptedBy:l,isTourOpen:d,setTourStep:j,tourStep:O}=e,[I,_]=M(null),{blocks:r,socket:k,onUpdate:H,setOnUpdate:w,onDebugMessage:f,enableSimulation:x}=nt(et),p=lt(h=>r==null?void 0:r.find(b=>b.getStaticData().id===h),[r]),g=lt(h=>{const b=cn(h,s,o);b&&t(b)},[s]),C=h=>{h.currentTarget!==I&&_(h.currentTarget)},q=()=>_(null),T=Dt(()=>{const h=p(a)||Nt;return n.jsx(h,{...e,notFound:!p(a),isTourOpen:d,setTourStep:j,tourStep:O,onUpdate:H,setOnUpdate:w,enableSimulation:x,onDebugMessage:f,onChange:g,className:void 0,socket:k})},[s,H,f,x]),[S,B]=M(!1);return n.jsxs("div",{onMouseMove:C,onMouseEnter:C,onMouseLeave:q,onMouseDown:h=>{if(h.ctrlKey){let b;const v=K(l,s,o);l==="conditions"?(b=v.conditions[o].find(m=>m._id===i),b&&v.conditions[o].splice(v.conditions[o].indexOf(b),0,{...b,_id:Date.now()})):l==="actions"?(b=v.actions[o].find(m=>m._id===i),b&&v.actions[o].splice(v.actions[o].indexOf(b),0,{...b,_id:Date.now()})):(b=v.triggers.find(m=>m._id===i),b&&v.triggers.splice(v[l].indexOf(b),0,{...b,_id:Date.now()})),t(v)}},id:"height",style:c?{width:(((N=document.getElementById("width"))==null?void 0:N.clientWidth)||0)-70}:void 0,className:`${G.cardStyle} ${c?G.cardStyleActive:null} ${S?G.isDelete:null}`,children:[n.jsx("div",{className:G.drag_mobile}),T,t&&n.jsx("div",{className:G.controlMenu,style:I?{opacity:1}:{opacity:0},children:n.jsx("div",{onClick:()=>{let h=K(l,s,o);h=z(l,h,o,i),B(!0),setTimeout(()=>{l==="triggers"&&w(!0),t(h)},300)},className:G.closeBtn})})]})}),rn={position:"fixed",pointerEvents:"none",zIndex:100,left:0,top:0,width:"100%",height:"100%"},an=(e,t,s)=>{if(!e||!t)return{display:"none"};let{x:i,y:a}=t;const o=`translate(${i}px, ${a}px)`;return{transform:o,WebkitTransform:o}},ln=e=>{const{itemType:t,isDragging:s,item:i,initialOffset:a,currentOffset:o,targetIds:c}=zt(d=>({item:d.getItem(),itemType:d.getItemType(),initialOffset:d.getInitialSourceClientOffset(),currentOffset:d.getSourceClientOffset(),isDragging:d.isDragging(),targetIds:d.getTargetIds()})),l=()=>t==="box"?c.length?n.jsx(Ot,{active:!0,...i,allBlocks:e.allBlocks}):n.jsx(It,{active:!0,...i,socket:e.socket}):null;return s?n.jsx("div",{style:rn,children:n.jsx("div",{style:an(a,o),children:l()})}):null},dn="_border_wrpm3_1",fn="_emptyBlockStyle_wrpm3_6",mn="_emptyBlock_wrpm3_6",gn="_selectOnChange_wrpm3_22",hn="_selectOnChangeHelp_wrpm3_28",_n="_selectOnChangeHelpIcon_wrpm3_34",pn="_emptyBlockNone_wrpm3_49",un="_mainBlockItemRules_wrpm3_55",xn="_nameBlockItems_wrpm3_63",bn="_contentBlockItem_wrpm3_73",wn="_wrapperMargin_wrpm3_81",Cn="_contentHeightOn_wrpm3_87",vn="_contentHeightOff_wrpm3_99",jn="_cardAdd_wrpm3_105",In="_blockCardAdd_wrpm3_125",On="_addClassOverflow_wrpm3_136",An="_addClassHeight_wrpm3_140",D={border:dn,emptyBlockStyle:fn,emptyBlock:mn,selectOnChange:gn,selectOnChangeHelp:hn,selectOnChangeHelpIcon:_n,emptyBlockNone:pn,mainBlockItemRules:un,nameBlockItems:xn,contentBlockItem:bn,wrapperMargin:wn,contentHeightOn:Cn,contentHeightOff:vn,cardAdd:jn,blockCardAdd:In,addClassOverflow:On,addClassHeight:An};function dt(e,t){const[s,i]=M(window.localStorage.getItem(t)?JSON.parse(window.localStorage.getItem(t)||""):e);return[s,o=>{window.localStorage.setItem(t,JSON.stringify(o)),i(o)},!!window.localStorage.getItem(t)]}function yn(e,t){let s=0,i=null,a;return function(...o){const c=Date.now();a=o,c-s>=t?(s=c,e.apply(this,o)):i||(i=setTimeout(()=>{s=Date.now(),i=null,e.apply(this,a)},t-(c-s)))}}function tt(e){if(Array.isArray(e))return e.map(t=>tt(t));if(typeof e=="function")return e.bind(null);if(e&&typeof e=="object"){const t={};return Object.keys(e).forEach(s=>{t[s]=tt(e[s])}),t}return e}const ct=yn((e,t)=>e(t),0);function R(e,t){const s=t.find(i=>i._id===e);return{card:s,index:s?t.indexOf(s):-1}}function rt(e,t,s,i,a,o,c,l,d){const{card:j,index:O}=R(e,s);if(!(Ot&&l>d)&&j&&O!==t){const I=tt(s);I.splice(O,1),I.splice(t,0,j);const _=tt(a);switch(o){case"actions":_.actions[c]=I,ct(i,_);return;case"conditions":_.conditions[c]=I,ct(i,_);return;default:_.triggers=I,ct(i,_);return}}}const Dn="_drag_7xfhc_1",kn="_root_7xfhc_11",gt={drag:Dn,root:kn},At=({typeBlock:e,allProperties:t,id:s,isActive:i,setUserRules:a,userRules:o,children:c,_id:l,blockValue:d})=>{const{setOnUpdate:j}=nt(et),[{opacity:O},I,_]=$t({type:"box",item:()=>({...t,id:s,isActive:i,_id:l}),end:(w,f)=>{const{acceptedBy:x}=w,p=f.getDropResult();let g;if(!p)return typeof l=="number"&&!f.getTargetIds().length&&(g=K(x,o,d),g=z(x,g,d,l),a(g)),null;if(p.blockValue!==d){const C=typeof l=="number"?l:Date.now();g=K(x,o,p.blockValue);const q={id:w.id,acceptedBy:w.acceptedBy};switch(x){case"actions":return d&&(g=z("actions",g,d,C)),g=z("actions",g,p.blockValue,C),g.actions[p.blockValue].push({...q,_id:C}),a(g);case"conditions":return typeof d=="number"&&(g=z("conditions",g,d,C)),g=z("conditions",g,p.blockValue,C),g.conditions[p.blockValue].push({...q,_id:C}),a(g);default:return j(!0),g=z("triggers",g,p.blockValue,C),g.triggers.push({...q,_id:C}),a(g)}}},collect:w=>({opacity:w.isDragging()?.4:1,isDragging:w.isDragging()})}),r=ut(null),[,k]=bt({accept:"box",canDrop:()=>!1,hover({_id:w,acceptedBy:f},x){var T;if(!r.current||e!==f)return;const p=(T=r.current)==null?void 0:T.getBoundingClientRect(),g=(p.bottom-p.top)/2,C=x.getClientOffset(),q=((C==null?void 0:C.y)||0)-p.top;if(l&&w!==l)switch(f){case"actions":if(d==="then"||d==="else"){const{index:S}=R(l,o.actions[d]);S!==w&&rt(w,S,o[f][d],a,o,f,d,q,g)}return;case"conditions":if(typeof d=="number"){const{index:S}=R(l,o[f][d]);S!==w&&rt(w,S,o[f][d],a,o,f,d,q,g)}return;default:{const{index:S}=R(l,o[f]);S!==w&&rt(w,S,o[f],a,o,f,void 0,q,g);return}}}});E(()=>{_(Gt(),{captureDraggingState:!0})},[]),I(k(r));const H=window.innerWidth<600;return n.jsxs("div",{ref:H&&l?null:r,className:gt.root,style:{opacity:O},children:[n.jsx("div",{className:l?gt.drag:null,ref:l&&H?r:null}),c]})},Sn=({onClose:e,open:t})=>n.jsxs(wt,{open:t,onClose:e,"aria-labelledby":"alert-dialog-title","aria-describedby":"alert-dialog-description",children:[n.jsx(Ct,{children:n.jsxs("div",{style:{fontSize:"1rem",fontFamily:'"Roboto", "Helvetica", "Arial", sans-serif',fontWeight:400,lineHeight:1.5,letterSpacing:"0.00938em"},children:[n.jsx("h3",{children:u.I18n.t("On condition change")}),n.jsx("div",{children:u.I18n.t("help_on_change")}),n.jsx("h3",{children:u.I18n.t("Just check")}),n.jsx("div",{children:u.I18n.t("help_just_check")})]})}),n.jsx(vt,{children:n.jsx(jt,{onClick:e,color:"primary",autoFocus:!0,startIcon:n.jsx(Lt,{}),children:u.I18n.t("OK")})})]}),Nn=({onClose:e,open:t})=>n.jsxs(wt,{open:t,onClose:e,"aria-labelledby":"alert-dialog-title","aria-describedby":"alert-dialog-description",children:[n.jsx(Ct,{children:n.jsxs(Tt,{id:"alert-dialog-description",children:[n.jsx("h3",{children:u.I18n.t("On condition change")}),n.jsx("div",{children:u.I18n.t("help_on_change")}),n.jsx("h3",{children:u.I18n.t("Just check")}),n.jsx("div",{children:u.I18n.t("help_just_check")})]})}),n.jsx(vt,{children:n.jsx(jt,{onClick:e,color:"primary",autoFocus:!0,children:u.I18n.t("OK")})})]}),ht=({size:e,blockValue:t,boolean:s,typeBlock:i,userRules:a,setUserRules:o,animation:c,setTourStep:l,tourStep:d,isTourOpen:j,theme:O,themeType:I,themeName:_})=>{var W;const[r,k]=M(!1),[H,w]=M(!1),[f,x]=M(!1),[p,g]=M("");s===void 0&&(s=!0);const C=bt({accept:"box",drop:()=>({blockValue:t}),hover:({acceptedBy:A,_id:L},Z)=>{k(A===i),x(!!L),g(Z.getHandlerId()||"")},canDrop:({acceptedBy:A})=>(w(A===i),A===i),collect:A=>{var L;return{isOver:A.isOver(),canDrop:((L=A.getItem())==null?void 0:L.acceptedBy)===i,offset:A.getClientOffset(),targetId:A.getHandlerId()}}}),q=C[0],{canDrop:T,isOver:S,offset:B,targetId:N}=q,h=C[1];E(()=>{g("")},[B]);const b=T&&S;let v="";b?v=r?"#00fb003d":"#fb00002e":T?v=H?"#00fb003d":"#fb00002e":B&&(v=N===p?"#fb00002e":"");let m;return i==="actions"?m=a.actions[t]:i==="conditions"?m=a.conditions[t]:m=a.triggers,n.jsx("div",{ref:h,style:{backgroundColor:v},className:`${u.Utils.clsx(D.contentBlockItem,e&&D.addClassHeight)} ${s?c?D.contentHeightOn:null:D.contentHeightOff}`,children:n.jsxs("div",{className:D.wrapperMargin,children:[m.map(A=>n.jsx(At,{typeBlock:i,...A,blockValue:t,allProperties:A,userRules:a,setUserRules:o,children:n.jsx(Ot,{...A,isTourOpen:j,setTourStep:l,tourStep:d,settings:A,blockValue:t,userRules:a,setUserRules:o,theme:O,themeType:I,themeName:_})},A._id)),n.jsx("div",{style:b&&r&&!f?{height:((W=document.getElementById("height"))==null?void 0:W.clientHeight)||200}:void 0,className:`${D.emptyBlockStyle} ${b&&r&&!f?D.emptyBlock:D.emptyBlockNone}`})]})})},at=({size:e,typeBlock:t,name:s,nameAdditionally:i,additionally:a,border:o,userRules:c,setUserRules:l,iconName:d,adapter:j,socket:O,setTourStep:I,tourStep:_,isTourOpen:r,theme:k,themeType:H,themeName:w})=>{const[f,x,p]=dt(t==="actions"?!1:[],`additionallyClickItems_${t}`),[g,C]=M(!1),[q,T]=M(!1);E(()=>{if(t==="conditions"&&(f==null?void 0:f.length)!==c.conditions.length-1){const N=[];c.conditions.forEach((h,b)=>{b>0&&N.push({_id:Date.now(),open:!0})}),x([...f,...N])}t==="actions"&&!p&&c.actions.else.length&&x(!0)},[]);const[S,B]=M(!1);return n.jsxs("div",{className:`${u.Utils.clsx(D.mainBlockItemRules,e&&D.addClassOverflow)} ${o&&!e?D.border:null}`,children:[n.jsxs("span",{id:"width",className:D.nameBlockItems,children:[n.jsx(Y,{iconName:d,className:D.iconThemCard,adapter:j,socket:O}),s]}),t==="conditions"?n.jsxs("div",{style:{width:"100%"},children:[n.jsxs(Et,{variant:"standard",className:D.selectOnChange,value:c.justCheck||!1,onChange:N=>{const h=K("conditions",c);h.justCheck=N.target.value==="true",l(h)},children:[n.jsx(mt,{value:"false",children:u.I18n.t("on condition change")}),n.jsx(mt,{value:"true",children:u.I18n.t("just check")})]}),n.jsx(Pt,{size:"small",title:u.I18n.t("Explanation"),className:D.selectOnChangeHelp,onClick:()=>C(!0),children:n.jsx(qt,{className:D.selectOnChangeHelpIcon})})]}):null,n.jsx(ht,{setTourStep:I,tourStep:_,isTourOpen:r,blockValue:t==="actions"?"then":t==="conditions"?0:t,typeBlock:t,setUserRules:l,userRules:c,theme:k,themeName:w,themeType:H,size:e}),a&&[...Array(t==="actions"?1:c.conditions.length-1)].map((N,h)=>{const b=(v=h)=>t==="actions"?!!f:!!f.find((m,W)=>W===v&&m.open);return n.jsxs(xt,{children:[n.jsxs("div",{onClick:()=>{if(t==="actions")return x(!f),null;let v=JSON.parse(JSON.stringify(f));if(c.conditions[h+1].length)return v[h].open=!v[h].open,x(v),null;v=v.filter((m,W)=>W!==h),x(v),B(h),setTimeout(()=>{B(!1),l({...c,conditions:[...c.conditions.filter((m,W)=>W!==h+1)]})},250)},className:D.blockCardAdd,children:[b()?"-":"+",n.jsx("div",{className:D.cardAdd,children:i})]},h),n.jsx(ht,{blockValue:t==="actions"?"else":t==="conditions"?h+1:t,typeBlock:t,setUserRules:l,userRules:c,boolean:b(),animation:S===h,size:e,theme:k,themeName:w,themeType:H})]},`${h}_block_${t}`)}),a&&t==="conditions"&&n.jsxs("div",{onClick:()=>{x([...f,{_id:Date.now(),open:!0}]),l({...c,conditions:[...c.conditions,[]]}),B(c.conditions.length-1),setTimeout(()=>B(!1),1e3)},className:D.blockCardAdd,children:["+",n.jsx("div",{className:D.cardAdd,children:i})]}),n.jsx(Sn,{open:g,onClose:()=>C(!1)}),n.jsx(Nn,{open:q,onClose:()=>T(!1)})]})},$n="_menuRules_1qqcb_1",qn="_switchesRenderWrapper_1qqcb_13",Bn="_menuOff_1qqcb_22",Mn="_menuTitle_1qqcb_28",Hn="_marginAuto_1qqcb_42",Wn="_inputWidth_1qqcb_47",Tn="_menuWrapper_1qqcb_52",En="_hamburgerWrapper_1qqcb_57",Pn="_hamburgerOff_1qqcb_74",Un="_nothingFound_1qqcb_82",Fn="_resetSearch_1qqcb_89",Jn="_controlPanel_1qqcb_101",Ln="_controlPanelAppBar_1qqcb_112",zn="_addClassMenu_1qqcb_126",Gn="_addClassBackground_1qqcb_132",Kn="_addClassPosition_1qqcb_136",$={menuRules:$n,switchesRenderWrapper:qn,menuOff:Bn,menuTitle:Mn,marginAuto:Hn,inputWidth:Wn,menuWrapper:Tn,hamburgerWrapper:En,hamburgerOff:Pn,nothingFound:Un,resetSearch:Fn,controlPanel:Jn,controlPanelAppBar:Ln,addClassMenu:zn,addClassBackground:Gn,addClassPosition:Kn},Qn=e=>{const{allProperties:t,allProperties:{acceptedBy:s,id:i},setUserRules:a,userRules:o,setTourStep:c,tourStep:l,isTourOpen:d,onTouchMove:j,isActive:O}=e;return n.jsx(At,{allProperties:t,id:t.id,isActive:O,setUserRules:a,userRules:o,children:n.jsx(It,{onDoubleClick:()=>{d&&l===J.addScheduleByDoubleClick&&i==="TriggerScheduleBlock"&&c(J.openTagsMenu),d&&l===J.addActionPrintText&&i==="ActionPrintText"&&c(J.showJavascript);const I=Date.now();let _;switch(s){case"actions":_="then";break;case"conditions":_=o[s].length-1;break}const r=K(s,o,_),k={id:i,_id:I,acceptedBy:s};_!==void 0?s==="actions"?r.actions[_].push({...k}):s==="conditions"&&r.conditions[_].push({...k}):r.triggers.push({...k}),a(r)},...e,...t,onTouchMove:j})})},Yn="_hamburgerMenu_hqnsm_8",Zn="_animate_hqnsm_21",_t={hamburgerMenu:Yn,animate:Zn};function Xn({bool:e}){return n.jsx("div",{className:`${_t.hamburgerMenu} ${e?_t.animate:""}`})}const Vn=({addClass:e,setAllBlocks:t,allBlocks:s,userRules:i,onChangeBlocks:a,setTourStep:o,tourStep:c,isTourOpen:l})=>{const{blocks:d,socket:j}=nt(et),[O,I]=dt(!1,"hamburgerOnOff"),[_,r]=dt({text:"",type:"triggers",index:0},"filterControlPanel"),k=(f=_.text,x=_.type)=>{if(!d)return;let p=[...d];p=p.filter(g=>{if(!f)return!0;const{name:C}=g.getStaticData();return C&&u.I18n.t(C).toLowerCase().includes(f.toLowerCase())}),p=p.filter(g=>x===g.getStaticData().acceptedBy),t(p)},H=(f,x)=>{l&&x===0&&c===J.selectTriggers&&o(J.addScheduleByDoubleClick),l&&x===2&&c===J.selectActions&&o(J.addActionPrintText),r({..._,index:x,type:["triggers","conditions","actions"][x]}),k(_.text,["triggers","conditions","actions"][x])},w=f=>({id:`scrollable-force-tab-${f}`,"aria-controls":`scrollable-force-tabpanel-${f}`});return E(()=>{k()},[d]),n.jsx(Ut,{mouseEvent:!1,touchEvent:"onTouchStart",onClickAway:()=>I(!0),children:n.jsxs("div",{className:u.Utils.clsx($.menuWrapper,e[1035]&&$.addClassMenu),children:[n.jsx("div",{className:`${$.hamburgerWrapper} ${O?$.hamburgerOff:null}`,onClick:()=>I(!O),children:n.jsx(Xn,{bool:!O})}),n.jsxs("div",{className:`${u.Utils.clsx($.menuRules,e[1035]&&$.addClassBackground,e[835]&&$.addClassPosition)} ${O?$.menuOff:null}`,children:[n.jsx("div",{className:$.controlPanel,children:n.jsx(Ft,{className:$.controlPanelAppBar,position:"static",children:n.jsxs(Jt,{value:_.index,onChange:H,children:[n.jsx(st,{className:"blocks-triggers",title:u.I18n.t("Triggers"),icon:n.jsx(Y,{iconName:"FlashOn"}),...w(0)}),n.jsx(st,{title:u.I18n.t("Conditions"),className:"blocks-conditions",icon:n.jsx(Y,{iconName:"Help"}),...w(1)}),n.jsx(st,{title:u.I18n.t("Actions"),className:"blocks-actions",icon:n.jsx(Y,{iconName:"PlayForWork"}),...w(2)})]})})}),n.jsx("div",{className:$.switchesRenderWrapper,children:n.jsxs("span",{children:[s.map(f=>{const{name:x,id:p,icon:g,adapter:C}=f.getStaticData();return n.jsx(xt,{children:n.jsx(Qn,{adapter:C,allProperties:f.getStaticData(),icon:g,id:p,isActive:!1,isTourOpen:l,name:x,onTouchMove:()=>I(!0),setTourStep:o,setUserRules:a,socket:j,tourStep:c,userRules:i})},p)}),!s.length&&n.jsxs("div",{className:$.nothingFound,children:[u.I18n.t("Nothing found"),"...",n.jsx("div",{className:$.resetSearch,onClick:()=>{r({..._,text:""}),k("")},children:u.I18n.t("reset search")})]})]})}),n.jsx("div",{className:u.Utils.clsx($.menuTitle,$.marginAuto)}),n.jsx(Bt,{className:$.inputWidth,fullWidth:!0,customValue:!0,value:_.text,size:"small",autoComplete:"off",label:u.I18n.t("search"),variant:"outlined",onChange:f=>{r({..._,text:f}),k(f)}})]})]})})};let pt=[];const me=({code:e,onChange:t,themeName:s,themeType:i,theme:a,setTourStep:o,tourStep:c,isTourOpen:l,command:d,scriptId:j,changed:O,running:I})=>{var v;const{blocks:_,socket:r,setOnUpdate:k,setOnDebugMessage:H,setEnableSimulation:w}=nt(et),[f,x]=M([]),[p,g]=M(ft(e)),[C,q]=M(""),[T,S]=M(!1);E(()=>{let m,W;const A=(P,y)=>{P===`${m}.alive`&&W!==(y==null?void 0:y.val)&&(W=!!(y!=null&&y.val),W&&m&&(r==null||r.sendTo(m.replace(/^system\.adapter\./,""),"rulesOn",j)))},L=(P,y)=>{var U,Q;r&&m!==((U=y==null?void 0:y.common)==null?void 0:U.engine)&&(m&&(r.unsubscribeState(`${m}.alive`,A),W&&r.sendTo(m.replace(/^system\.adapter\./,""),"rulesOn",j)),m=(Q=y==null?void 0:y.common)==null?void 0:Q.engine,m&&m&&r.subscribeState(`${m}.alive`,A))},Z=(P,y)=>{if(y)try{const U=JSON.parse(y.val),Q=Date.now();if(U.ruleId===j&&Q-U.ts<1e3){const F=[...pt,{blockId:U.blockId,data:U.data,ts:U.ts}];F.length>200&&F.splice(0,200-F.length);for(let X=F.length-1;X>=0;X--)if(F[X].ts{var y;m=(y=P==null?void 0:P.common)==null?void 0:y.engine,r.subscribeObject(j,L),m&&(r.subscribeState(`${m}.alive`,A),r.subscribeState(`${m.replace(/^system\.adapter\./,"")}.debug.rules`,Z))}),function(){r==null||r.unsubscribeObject(j,L),m&&(r==null||r.unsubscribeState(`${m}.alive`,A),W&&(r==null||r.sendTo(m.replace(/^system\.adapter\./,""),"rulesOff",j)),r==null||r.unsubscribeState(`${m.replace(/^system\.adapter\./,"")}.debug.rules`,Z))}},[]),E(()=>{w(!O&&I)},[O,I,w]),E(()=>{d&&(q(d),T||S(!0))},[d]),E(()=>{const m=ft(e);JSON.stringify(m)!==JSON.stringify(p)&&(g(m),k(!0))},[e]),E(()=>{document.getElementsByTagName("HTML")[0].className=s||"blue"},[s]);const B=lt(m=>{g(m),_&&t(Mt(m,_))},[_,t]),N=ut(null),[h,b]=M({835:!1,1035:!1});return E(()=>{N.current&&(N.current.clientWidth<=1035&&b({835:!1,1035:!0}),N.current.clientWidth<=835&&b({1035:!0,835:!0}),N.current.clientWidth>1035&&b({835:!1,1035:!1}))},[((v=N.current)==null?void 0:v.clientWidth)||0]),!_||!r?null:n.jsxs("div",{className:ot.wrapperRules,ref:N,children:[n.jsx(ln,{allBlocks:f,socket:r}),T?C==="export"?n.jsx(Ht,{scriptId:j,themeType:i,onClose:()=>S(!1),text:JSON.stringify(p,null,2)}):n.jsx(Wt,{themeType:i,onClose:m=>{S(!1),m&&B(JSON.parse(m))}}):null,n.jsxs("div",{className:u.Utils.clsx(ot.rootWrapper,h[835]&&ot.addClass),children:[n.jsx(Vn,{setAllBlocks:x,allBlocks:f,userRules:p,onChangeBlocks:B,setTourStep:o,tourStep:c,addClass:h,isTourOpen:l}),n.jsx(at,{socket:r,setUserRules:B,userRules:p,isTourOpen:l,setTourStep:o,tourStep:c,name:`${u.I18n.t("when")}...`,typeBlock:"triggers",iconName:"FlashOn",size:h[835],themeType:i,themeName:s,theme:a}),n.jsx(at,{socket:r,setUserRules:B,isTourOpen:l,setTourStep:o,tourStep:c,userRules:p,name:`...${u.I18n.t("and")}...`,typeBlock:"conditions",iconName:"Help",nameAdditionally:u.I18n.t("or"),additionally:!0,border:!0,size:h[835],themeType:i,themeName:s,theme:a}),n.jsx(at,{socket:r,setUserRules:B,isTourOpen:l,setTourStep:o,tourStep:c,userRules:p,name:`...${u.I18n.t("then")}`,typeBlock:"actions",iconName:"PlayForWork",nameAdditionally:u.I18n.t("else"),additionally:!0,size:h[835],themeType:i,themeName:s,theme:a})]})]},"rulesEditor")};export{me as default}; +import{j as n}from"./createSvgIcon-DPvF8xqu.js";import{c as E,h as yt,j as M,m as nt,k as lt,l as Dt,b as ut,o as xt}from"./iobroker_javascript__loadShare__react__loadShare__.mjs-CTZOFJS2.js";import{_ as u}from"./iobroker_javascript__loadShare___mf_0_iobroker_mf_1_adapter_mf_2_react_mf_2_v5__loadShare__.mjs-DkBjPSMw.js";import{u as kt,a as St,M as Y,C as et,G as Nt,b as $t,c as bt,I as qt,S as J,d as Bt,e as ft,j as Mt,D as Ht,f as Wt}from"./index-DvPtUWVN.js";import{_ as wt,b as Ct,h as vt,i as jt,p as Tt,f as Et,g as mt,o as Pt,Y as Ut,Z as Ft,C as Jt,D as st}from"./iobroker_javascript__loadShare___mf_0_mui_mf_1_material__loadShare__.mjs-QWG5Arqe.js";import{I as Lt}from"./index-C49cpVll.js";import"./iobroker_javascript__loadShare__react__loadShare__.mjs_commonjs-proxy-CE9lvhW8.js";import"./iobroker_javascript__loadShare__prop_mf_2_types__loadShare__.mjs-BCtSFofY.js";import"./virtual_mf-REMOTE_ENTRY_ID_iobroker_javascript__remoteEntry_js-s4ROfmWJ.js";import"./preload-helper-BDBacUwf.js";import"./iobroker_javascript__loadShare__react_mf_2_dom__loadShare__.mjs_commonjs-proxy-RQRRZMX5.js";import"./iobroker_javascript__loadShare__react_mf_2_dom__loadShare__.mjs-DeVAS-oa.js";import"./inheritsLoose-B0Ba5G9z.js";function zt(e){const s=kt().getMonitor(),[i,a]=St(s,e);return E(()=>s.subscribeToOffsetChange(a)),E(()=>s.subscribeToStateChange(a)),i}let V;function Gt(){return V||(V=new Image,V.src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="),V}const Kt="_wrapperRules_nnott_1",Qt="_rootWrapper_nnott_9",Yt="_addClass_nnott_14",ot={wrapperRules:Kt,rootWrapper:Qt,addClass:Yt},Zt="_switchesItem_10ls3_1",Xt="_switchesItemActive_10ls3_28",Vt="_iconTheme_10ls3_36",it={switchesItem:Zt,switchesItemActive:Xt,iconTheme:Vt},It=({name:e,id:t,active:s,icon:i,adapter:a,socket:o,onDoubleClick:c,title:l,onTouchMove:d,style:j})=>n.jsxs("div",{onDoubleClick:c,onTouchMove:d,title:l?u.I18n.t(l):void 0,className:u.Utils.clsx(it.switchesItem,s&&it.switchesItemActive,`block-${t}`),children:[n.jsx(Y,{iconName:i,className:it.iconTheme,adapter:a,socket:o,style:j}),n.jsx("span",{children:e?u.I18n.t(e):""})]},t),Rt="_cardStyle_8rq8v_1",tn="_cardStyleActive_8rq8v_17",nn="_controlMenu_8rq8v_22",en="_closeBtn_8rq8v_31",sn="_isDelete_8rq8v_73",on="_drag_mobile_8rq8v_90",G={cardStyle:Rt,cardStyleActive:tn,controlMenu:nn,closeBtn:en,isDelete:sn,drag_mobile:on};function K(e,t,s){let i;switch(e){case"actions":if(s==="else")return i={...t,actions:{...t[e],else:[...t[e].else]}},i;if(s==="then")return i={...t,actions:{...t[e],then:[...t[e].then]}},i;throw console.error(`Unknown additionalParameter: ${s}`),new Error(`Unknown additionalParameter: ${s}`);case"triggers":return i={...t,triggers:[...t.triggers]},i;case"conditions":return i={...t,conditions:[...t.conditions]},i;default:throw new Error(`Unknown name: ${e}`)}}function z(e,t,s,i){var a;switch(e){case"actions":return t.actions[s]=t.actions[s].filter(o=>o._id!==i),t;case"conditions":return t.conditions[s]=(a=t.conditions[s])==null?void 0:a.filter(o=>o._id!==i),t;default:return t.triggers=t.triggers.filter(o=>o._id!==i),t}}function cn(e,t,s){const{_id:i,acceptedBy:a}=e;let o;if(!a||!t[a])return console.warn(`Cannot find ${a}`),t;switch(a){case"actions":if(o=t.actions[s].find(c=>c._id===i),!o)console.warn(`Cannot find ${i}`);else{const c=t.actions[s].indexOf(o);t.actions[s][c]=e}return t;case"conditions":if(o=t.conditions[s].find(c=>c._id===i),!o)console.warn(`Cannot find ${i}`);else{const c=t.conditions[s].indexOf(o);t.conditions[s][c]=e}return t;default:if(o=t.triggers.find(c=>c._id===i),!o)console.warn(`Cannot find ${i}`);else{const c=t.triggers.indexOf(o);t.triggers[c]=e}return t}}const Ot=yt(e=>{var N;const{setUserRules:t,userRules:s,_id:i,id:a,blockValue:o,active:c,acceptedBy:l,isTourOpen:d,setTourStep:j,tourStep:O}=e,[I,_]=M(null),{blocks:r,socket:k,onUpdate:H,setOnUpdate:w,onDebugMessage:f,enableSimulation:x}=nt(et),p=lt(h=>r==null?void 0:r.find(b=>b.getStaticData().id===h),[r]),g=lt(h=>{const b=cn(h,s,o);b&&t(b)},[s]),C=h=>{h.currentTarget!==I&&_(h.currentTarget)},q=()=>_(null),T=Dt(()=>{const h=p(a)||Nt;return n.jsx(h,{...e,notFound:!p(a),isTourOpen:d,setTourStep:j,tourStep:O,onUpdate:H,setOnUpdate:w,enableSimulation:x,onDebugMessage:f,onChange:g,className:void 0,socket:k})},[s,H,f,x]),[S,B]=M(!1);return n.jsxs("div",{onMouseMove:C,onMouseEnter:C,onMouseLeave:q,onMouseDown:h=>{if(h.ctrlKey){let b;const v=K(l,s,o);l==="conditions"?(b=v.conditions[o].find(m=>m._id===i),b&&v.conditions[o].splice(v.conditions[o].indexOf(b),0,{...b,_id:Date.now()})):l==="actions"?(b=v.actions[o].find(m=>m._id===i),b&&v.actions[o].splice(v.actions[o].indexOf(b),0,{...b,_id:Date.now()})):(b=v.triggers.find(m=>m._id===i),b&&v.triggers.splice(v[l].indexOf(b),0,{...b,_id:Date.now()})),t(v)}},id:"height",style:c?{width:(((N=document.getElementById("width"))==null?void 0:N.clientWidth)||0)-70}:void 0,className:`${G.cardStyle} ${c?G.cardStyleActive:null} ${S?G.isDelete:null}`,children:[n.jsx("div",{className:G.drag_mobile}),T,t&&n.jsx("div",{className:G.controlMenu,style:I?{opacity:1}:{opacity:0},children:n.jsx("div",{onClick:()=>{let h=K(l,s,o);h=z(l,h,o,i),B(!0),setTimeout(()=>{l==="triggers"&&w(!0),t(h)},300)},className:G.closeBtn})})]})}),rn={position:"fixed",pointerEvents:"none",zIndex:100,left:0,top:0,width:"100%",height:"100%"},an=(e,t,s)=>{if(!e||!t)return{display:"none"};let{x:i,y:a}=t;const o=`translate(${i}px, ${a}px)`;return{transform:o,WebkitTransform:o}},ln=e=>{const{itemType:t,isDragging:s,item:i,initialOffset:a,currentOffset:o,targetIds:c}=zt(d=>({item:d.getItem(),itemType:d.getItemType(),initialOffset:d.getInitialSourceClientOffset(),currentOffset:d.getSourceClientOffset(),isDragging:d.isDragging(),targetIds:d.getTargetIds()})),l=()=>t==="box"?c.length?n.jsx(Ot,{active:!0,...i,allBlocks:e.allBlocks}):n.jsx(It,{active:!0,...i,socket:e.socket}):null;return s?n.jsx("div",{style:rn,children:n.jsx("div",{style:an(a,o),children:l()})}):null},dn="_border_wrpm3_1",fn="_emptyBlockStyle_wrpm3_6",mn="_emptyBlock_wrpm3_6",gn="_selectOnChange_wrpm3_22",hn="_selectOnChangeHelp_wrpm3_28",_n="_selectOnChangeHelpIcon_wrpm3_34",pn="_emptyBlockNone_wrpm3_49",un="_mainBlockItemRules_wrpm3_55",xn="_nameBlockItems_wrpm3_63",bn="_contentBlockItem_wrpm3_73",wn="_wrapperMargin_wrpm3_81",Cn="_contentHeightOn_wrpm3_87",vn="_contentHeightOff_wrpm3_99",jn="_cardAdd_wrpm3_105",In="_blockCardAdd_wrpm3_125",On="_addClassOverflow_wrpm3_136",An="_addClassHeight_wrpm3_140",D={border:dn,emptyBlockStyle:fn,emptyBlock:mn,selectOnChange:gn,selectOnChangeHelp:hn,selectOnChangeHelpIcon:_n,emptyBlockNone:pn,mainBlockItemRules:un,nameBlockItems:xn,contentBlockItem:bn,wrapperMargin:wn,contentHeightOn:Cn,contentHeightOff:vn,cardAdd:jn,blockCardAdd:In,addClassOverflow:On,addClassHeight:An};function dt(e,t){const[s,i]=M(window.localStorage.getItem(t)?JSON.parse(window.localStorage.getItem(t)||""):e);return[s,o=>{window.localStorage.setItem(t,JSON.stringify(o)),i(o)},!!window.localStorage.getItem(t)]}function yn(e,t){let s=0,i=null,a;return function(...o){const c=Date.now();a=o,c-s>=t?(s=c,e.apply(this,o)):i||(i=setTimeout(()=>{s=Date.now(),i=null,e.apply(this,a)},t-(c-s)))}}function tt(e){if(Array.isArray(e))return e.map(t=>tt(t));if(typeof e=="function")return e.bind(null);if(e&&typeof e=="object"){const t={};return Object.keys(e).forEach(s=>{t[s]=tt(e[s])}),t}return e}const ct=yn((e,t)=>e(t),0);function R(e,t){const s=t.find(i=>i._id===e);return{card:s,index:s?t.indexOf(s):-1}}function rt(e,t,s,i,a,o,c,l,d){const{card:j,index:O}=R(e,s);if(!(Ot&&l>d)&&j&&O!==t){const I=tt(s);I.splice(O,1),I.splice(t,0,j);const _=tt(a);switch(o){case"actions":_.actions[c]=I,ct(i,_);return;case"conditions":_.conditions[c]=I,ct(i,_);return;default:_.triggers=I,ct(i,_);return}}}const Dn="_drag_7xfhc_1",kn="_root_7xfhc_11",gt={drag:Dn,root:kn},At=({typeBlock:e,allProperties:t,id:s,isActive:i,setUserRules:a,userRules:o,children:c,_id:l,blockValue:d})=>{const{setOnUpdate:j}=nt(et),[{opacity:O},I,_]=$t({type:"box",item:()=>({...t,id:s,isActive:i,_id:l}),end:(w,f)=>{const{acceptedBy:x}=w,p=f.getDropResult();let g;if(!p)return typeof l=="number"&&!f.getTargetIds().length&&(g=K(x,o,d),g=z(x,g,d,l),a(g)),null;if(p.blockValue!==d){const C=typeof l=="number"?l:Date.now();g=K(x,o,p.blockValue);const q={id:w.id,acceptedBy:w.acceptedBy};switch(x){case"actions":return d&&(g=z("actions",g,d,C)),g=z("actions",g,p.blockValue,C),g.actions[p.blockValue].push({...q,_id:C}),a(g);case"conditions":return typeof d=="number"&&(g=z("conditions",g,d,C)),g=z("conditions",g,p.blockValue,C),g.conditions[p.blockValue].push({...q,_id:C}),a(g);default:return j(!0),g=z("triggers",g,p.blockValue,C),g.triggers.push({...q,_id:C}),a(g)}}},collect:w=>({opacity:w.isDragging()?.4:1,isDragging:w.isDragging()})}),r=ut(null),[,k]=bt({accept:"box",canDrop:()=>!1,hover({_id:w,acceptedBy:f},x){var T;if(!r.current||e!==f)return;const p=(T=r.current)==null?void 0:T.getBoundingClientRect(),g=(p.bottom-p.top)/2,C=x.getClientOffset(),q=((C==null?void 0:C.y)||0)-p.top;if(l&&w!==l)switch(f){case"actions":if(d==="then"||d==="else"){const{index:S}=R(l,o.actions[d]);S!==w&&rt(w,S,o[f][d],a,o,f,d,q,g)}return;case"conditions":if(typeof d=="number"){const{index:S}=R(l,o[f][d]);S!==w&&rt(w,S,o[f][d],a,o,f,d,q,g)}return;default:{const{index:S}=R(l,o[f]);S!==w&&rt(w,S,o[f],a,o,f,void 0,q,g);return}}}});E(()=>{_(Gt(),{captureDraggingState:!0})},[]),I(k(r));const H=window.innerWidth<600;return n.jsxs("div",{ref:H&&l?null:r,className:gt.root,style:{opacity:O},children:[n.jsx("div",{className:l?gt.drag:null,ref:l&&H?r:null}),c]})},Sn=({onClose:e,open:t})=>n.jsxs(wt,{open:t,onClose:e,"aria-labelledby":"alert-dialog-title","aria-describedby":"alert-dialog-description",children:[n.jsx(Ct,{children:n.jsxs("div",{style:{fontSize:"1rem",fontFamily:'"Roboto", "Helvetica", "Arial", sans-serif',fontWeight:400,lineHeight:1.5,letterSpacing:"0.00938em"},children:[n.jsx("h3",{children:u.I18n.t("On condition change")}),n.jsx("div",{children:u.I18n.t("help_on_change")}),n.jsx("h3",{children:u.I18n.t("Just check")}),n.jsx("div",{children:u.I18n.t("help_just_check")})]})}),n.jsx(vt,{children:n.jsx(jt,{onClick:e,color:"primary",autoFocus:!0,startIcon:n.jsx(Lt,{}),children:u.I18n.t("OK")})})]}),Nn=({onClose:e,open:t})=>n.jsxs(wt,{open:t,onClose:e,"aria-labelledby":"alert-dialog-title","aria-describedby":"alert-dialog-description",children:[n.jsx(Ct,{children:n.jsxs(Tt,{id:"alert-dialog-description",children:[n.jsx("h3",{children:u.I18n.t("On condition change")}),n.jsx("div",{children:u.I18n.t("help_on_change")}),n.jsx("h3",{children:u.I18n.t("Just check")}),n.jsx("div",{children:u.I18n.t("help_just_check")})]})}),n.jsx(vt,{children:n.jsx(jt,{onClick:e,color:"primary",autoFocus:!0,children:u.I18n.t("OK")})})]}),ht=({size:e,blockValue:t,boolean:s,typeBlock:i,userRules:a,setUserRules:o,animation:c,setTourStep:l,tourStep:d,isTourOpen:j,theme:O,themeType:I,themeName:_})=>{var W;const[r,k]=M(!1),[H,w]=M(!1),[f,x]=M(!1),[p,g]=M("");s===void 0&&(s=!0);const C=bt({accept:"box",drop:()=>({blockValue:t}),hover:({acceptedBy:A,_id:L},Z)=>{k(A===i),x(!!L),g(Z.getHandlerId()||"")},canDrop:({acceptedBy:A})=>(w(A===i),A===i),collect:A=>{var L;return{isOver:A.isOver(),canDrop:((L=A.getItem())==null?void 0:L.acceptedBy)===i,offset:A.getClientOffset(),targetId:A.getHandlerId()}}}),q=C[0],{canDrop:T,isOver:S,offset:B,targetId:N}=q,h=C[1];E(()=>{g("")},[B]);const b=T&&S;let v="";b?v=r?"#00fb003d":"#fb00002e":T?v=H?"#00fb003d":"#fb00002e":B&&(v=N===p?"#fb00002e":"");let m;return i==="actions"?m=a.actions[t]:i==="conditions"?m=a.conditions[t]:m=a.triggers,n.jsx("div",{ref:h,style:{backgroundColor:v},className:`${u.Utils.clsx(D.contentBlockItem,e&&D.addClassHeight)} ${s?c?D.contentHeightOn:null:D.contentHeightOff}`,children:n.jsxs("div",{className:D.wrapperMargin,children:[m.map(A=>n.jsx(At,{typeBlock:i,...A,blockValue:t,allProperties:A,userRules:a,setUserRules:o,children:n.jsx(Ot,{...A,isTourOpen:j,setTourStep:l,tourStep:d,settings:A,blockValue:t,userRules:a,setUserRules:o,theme:O,themeType:I,themeName:_})},A._id)),n.jsx("div",{style:b&&r&&!f?{height:((W=document.getElementById("height"))==null?void 0:W.clientHeight)||200}:void 0,className:`${D.emptyBlockStyle} ${b&&r&&!f?D.emptyBlock:D.emptyBlockNone}`})]})})},at=({size:e,typeBlock:t,name:s,nameAdditionally:i,additionally:a,border:o,userRules:c,setUserRules:l,iconName:d,adapter:j,socket:O,setTourStep:I,tourStep:_,isTourOpen:r,theme:k,themeType:H,themeName:w})=>{const[f,x,p]=dt(t==="actions"?!1:[],`additionallyClickItems_${t}`),[g,C]=M(!1),[q,T]=M(!1);E(()=>{if(t==="conditions"&&(f==null?void 0:f.length)!==c.conditions.length-1){const N=[];c.conditions.forEach((h,b)=>{b>0&&N.push({_id:Date.now(),open:!0})}),x([...f,...N])}t==="actions"&&!p&&c.actions.else.length&&x(!0)},[]);const[S,B]=M(!1);return n.jsxs("div",{className:`${u.Utils.clsx(D.mainBlockItemRules,e&&D.addClassOverflow)} ${o&&!e?D.border:null}`,children:[n.jsxs("span",{id:"width",className:D.nameBlockItems,children:[n.jsx(Y,{iconName:d,className:D.iconThemCard,adapter:j,socket:O}),s]}),t==="conditions"?n.jsxs("div",{style:{width:"100%"},children:[n.jsxs(Et,{variant:"standard",className:D.selectOnChange,value:c.justCheck||!1,onChange:N=>{const h=K("conditions",c);h.justCheck=N.target.value==="true",l(h)},children:[n.jsx(mt,{value:"false",children:u.I18n.t("on condition change")}),n.jsx(mt,{value:"true",children:u.I18n.t("just check")})]}),n.jsx(Pt,{size:"small",title:u.I18n.t("Explanation"),className:D.selectOnChangeHelp,onClick:()=>C(!0),children:n.jsx(qt,{className:D.selectOnChangeHelpIcon})})]}):null,n.jsx(ht,{setTourStep:I,tourStep:_,isTourOpen:r,blockValue:t==="actions"?"then":t==="conditions"?0:t,typeBlock:t,setUserRules:l,userRules:c,theme:k,themeName:w,themeType:H,size:e}),a&&[...Array(t==="actions"?1:c.conditions.length-1)].map((N,h)=>{const b=(v=h)=>t==="actions"?!!f:!!f.find((m,W)=>W===v&&m.open);return n.jsxs(xt,{children:[n.jsxs("div",{onClick:()=>{if(t==="actions")return x(!f),null;let v=JSON.parse(JSON.stringify(f));if(c.conditions[h+1].length)return v[h].open=!v[h].open,x(v),null;v=v.filter((m,W)=>W!==h),x(v),B(h),setTimeout(()=>{B(!1),l({...c,conditions:[...c.conditions.filter((m,W)=>W!==h+1)]})},250)},className:D.blockCardAdd,children:[b()?"-":"+",n.jsx("div",{className:D.cardAdd,children:i})]},h),n.jsx(ht,{blockValue:t==="actions"?"else":t==="conditions"?h+1:t,typeBlock:t,setUserRules:l,userRules:c,boolean:b(),animation:S===h,size:e,theme:k,themeName:w,themeType:H})]},`${h}_block_${t}`)}),a&&t==="conditions"&&n.jsxs("div",{onClick:()=>{x([...f,{_id:Date.now(),open:!0}]),l({...c,conditions:[...c.conditions,[]]}),B(c.conditions.length-1),setTimeout(()=>B(!1),1e3)},className:D.blockCardAdd,children:["+",n.jsx("div",{className:D.cardAdd,children:i})]}),n.jsx(Sn,{open:g,onClose:()=>C(!1)}),n.jsx(Nn,{open:q,onClose:()=>T(!1)})]})},$n="_menuRules_1qqcb_1",qn="_switchesRenderWrapper_1qqcb_13",Bn="_menuOff_1qqcb_22",Mn="_menuTitle_1qqcb_28",Hn="_marginAuto_1qqcb_42",Wn="_inputWidth_1qqcb_47",Tn="_menuWrapper_1qqcb_52",En="_hamburgerWrapper_1qqcb_57",Pn="_hamburgerOff_1qqcb_74",Un="_nothingFound_1qqcb_82",Fn="_resetSearch_1qqcb_89",Jn="_controlPanel_1qqcb_101",Ln="_controlPanelAppBar_1qqcb_112",zn="_addClassMenu_1qqcb_126",Gn="_addClassBackground_1qqcb_132",Kn="_addClassPosition_1qqcb_136",$={menuRules:$n,switchesRenderWrapper:qn,menuOff:Bn,menuTitle:Mn,marginAuto:Hn,inputWidth:Wn,menuWrapper:Tn,hamburgerWrapper:En,hamburgerOff:Pn,nothingFound:Un,resetSearch:Fn,controlPanel:Jn,controlPanelAppBar:Ln,addClassMenu:zn,addClassBackground:Gn,addClassPosition:Kn},Qn=e=>{const{allProperties:t,allProperties:{acceptedBy:s,id:i},setUserRules:a,userRules:o,setTourStep:c,tourStep:l,isTourOpen:d,onTouchMove:j,isActive:O}=e;return n.jsx(At,{allProperties:t,id:t.id,isActive:O,setUserRules:a,userRules:o,children:n.jsx(It,{onDoubleClick:()=>{d&&l===J.addScheduleByDoubleClick&&i==="TriggerScheduleBlock"&&c(J.openTagsMenu),d&&l===J.addActionPrintText&&i==="ActionPrintText"&&c(J.showJavascript);const I=Date.now();let _;switch(s){case"actions":_="then";break;case"conditions":_=o[s].length-1;break}const r=K(s,o,_),k={id:i,_id:I,acceptedBy:s};_!==void 0?s==="actions"?r.actions[_].push({...k}):s==="conditions"&&r.conditions[_].push({...k}):r.triggers.push({...k}),a(r)},...e,...t,onTouchMove:j})})},Yn="_hamburgerMenu_hqnsm_8",Zn="_animate_hqnsm_21",_t={hamburgerMenu:Yn,animate:Zn};function Xn({bool:e}){return n.jsx("div",{className:`${_t.hamburgerMenu} ${e?_t.animate:""}`})}const Vn=({addClass:e,setAllBlocks:t,allBlocks:s,userRules:i,onChangeBlocks:a,setTourStep:o,tourStep:c,isTourOpen:l})=>{const{blocks:d,socket:j}=nt(et),[O,I]=dt(!1,"hamburgerOnOff"),[_,r]=dt({text:"",type:"triggers",index:0},"filterControlPanel"),k=(f=_.text,x=_.type)=>{if(!d)return;let p=[...d];p=p.filter(g=>{if(!f)return!0;const{name:C}=g.getStaticData();return C&&u.I18n.t(C).toLowerCase().includes(f.toLowerCase())}),p=p.filter(g=>x===g.getStaticData().acceptedBy),t(p)},H=(f,x)=>{l&&x===0&&c===J.selectTriggers&&o(J.addScheduleByDoubleClick),l&&x===2&&c===J.selectActions&&o(J.addActionPrintText),r({..._,index:x,type:["triggers","conditions","actions"][x]}),k(_.text,["triggers","conditions","actions"][x])},w=f=>({id:`scrollable-force-tab-${f}`,"aria-controls":`scrollable-force-tabpanel-${f}`});return E(()=>{k()},[d]),n.jsx(Ut,{mouseEvent:!1,touchEvent:"onTouchStart",onClickAway:()=>I(!0),children:n.jsxs("div",{className:u.Utils.clsx($.menuWrapper,e[1035]&&$.addClassMenu),children:[n.jsx("div",{className:`${$.hamburgerWrapper} ${O?$.hamburgerOff:null}`,onClick:()=>I(!O),children:n.jsx(Xn,{bool:!O})}),n.jsxs("div",{className:`${u.Utils.clsx($.menuRules,e[1035]&&$.addClassBackground,e[835]&&$.addClassPosition)} ${O?$.menuOff:null}`,children:[n.jsx("div",{className:$.controlPanel,children:n.jsx(Ft,{className:$.controlPanelAppBar,position:"static",children:n.jsxs(Jt,{value:_.index,onChange:H,children:[n.jsx(st,{className:"blocks-triggers",title:u.I18n.t("Triggers"),icon:n.jsx(Y,{iconName:"FlashOn"}),...w(0)}),n.jsx(st,{title:u.I18n.t("Conditions"),className:"blocks-conditions",icon:n.jsx(Y,{iconName:"Help"}),...w(1)}),n.jsx(st,{title:u.I18n.t("Actions"),className:"blocks-actions",icon:n.jsx(Y,{iconName:"PlayForWork"}),...w(2)})]})})}),n.jsx("div",{className:$.switchesRenderWrapper,children:n.jsxs("span",{children:[s.map(f=>{const{name:x,id:p,icon:g,adapter:C}=f.getStaticData();return n.jsx(xt,{children:n.jsx(Qn,{adapter:C,allProperties:f.getStaticData(),icon:g,id:p,isActive:!1,isTourOpen:l,name:x,onTouchMove:()=>I(!0),setTourStep:o,setUserRules:a,socket:j,tourStep:c,userRules:i})},p)}),!s.length&&n.jsxs("div",{className:$.nothingFound,children:[u.I18n.t("Nothing found"),"...",n.jsx("div",{className:$.resetSearch,onClick:()=>{r({..._,text:""}),k("")},children:u.I18n.t("reset search")})]})]})}),n.jsx("div",{className:u.Utils.clsx($.menuTitle,$.marginAuto)}),n.jsx(Bt,{className:$.inputWidth,fullWidth:!0,customValue:!0,value:_.text,size:"small",autoComplete:"off",label:u.I18n.t("search"),variant:"outlined",onChange:f=>{r({..._,text:f}),k(f)}})]})]})})};let pt=[];const me=({code:e,onChange:t,themeName:s,themeType:i,theme:a,setTourStep:o,tourStep:c,isTourOpen:l,command:d,scriptId:j,changed:O,running:I})=>{var v;const{blocks:_,socket:r,setOnUpdate:k,setOnDebugMessage:H,setEnableSimulation:w}=nt(et),[f,x]=M([]),[p,g]=M(ft(e)),[C,q]=M(""),[T,S]=M(!1);E(()=>{let m,W;const A=(P,y)=>{P===`${m}.alive`&&W!==(y==null?void 0:y.val)&&(W=!!(y!=null&&y.val),W&&m&&(r==null||r.sendTo(m.replace(/^system\.adapter\./,""),"rulesOn",j)))},L=(P,y)=>{var U,Q;r&&m!==((U=y==null?void 0:y.common)==null?void 0:U.engine)&&(m&&(r.unsubscribeState(`${m}.alive`,A),W&&r.sendTo(m.replace(/^system\.adapter\./,""),"rulesOn",j)),m=(Q=y==null?void 0:y.common)==null?void 0:Q.engine,m&&m&&r.subscribeState(`${m}.alive`,A))},Z=(P,y)=>{if(y)try{const U=JSON.parse(y.val),Q=Date.now();if(U.ruleId===j&&Q-U.ts<1e3){const F=[...pt,{blockId:U.blockId,data:U.data,ts:U.ts}];F.length>200&&F.splice(0,200-F.length);for(let X=F.length-1;X>=0;X--)if(F[X].ts{var y;m=(y=P==null?void 0:P.common)==null?void 0:y.engine,r.subscribeObject(j,L),m&&(r.subscribeState(`${m}.alive`,A),r.subscribeState(`${m.replace(/^system\.adapter\./,"")}.debug.rules`,Z))}),function(){r==null||r.unsubscribeObject(j,L),m&&(r==null||r.unsubscribeState(`${m}.alive`,A),W&&(r==null||r.sendTo(m.replace(/^system\.adapter\./,""),"rulesOff",j)),r==null||r.unsubscribeState(`${m.replace(/^system\.adapter\./,"")}.debug.rules`,Z))}},[]),E(()=>{w(!O&&I)},[O,I,w]),E(()=>{d&&(q(d),T||S(!0))},[d]),E(()=>{const m=ft(e);JSON.stringify(m)!==JSON.stringify(p)&&(g(m),k(!0))},[e]),E(()=>{document.getElementsByTagName("HTML")[0].className=s||"blue"},[s]);const B=lt(m=>{g(m),_&&t(Mt(m,_))},[_,t]),N=ut(null),[h,b]=M({835:!1,1035:!1});return E(()=>{N.current&&(N.current.clientWidth<=1035&&b({835:!1,1035:!0}),N.current.clientWidth<=835&&b({1035:!0,835:!0}),N.current.clientWidth>1035&&b({835:!1,1035:!1}))},[((v=N.current)==null?void 0:v.clientWidth)||0]),!_||!r?null:n.jsxs("div",{className:ot.wrapperRules,ref:N,children:[n.jsx(ln,{allBlocks:f,socket:r}),T?C==="export"?n.jsx(Ht,{scriptId:j,themeType:i,onClose:()=>S(!1),text:JSON.stringify(p,null,2)}):n.jsx(Wt,{themeType:i,onClose:m=>{S(!1),m&&B(JSON.parse(m))}}):null,n.jsxs("div",{className:u.Utils.clsx(ot.rootWrapper,h[835]&&ot.addClass),children:[n.jsx(Vn,{setAllBlocks:x,allBlocks:f,userRules:p,onChangeBlocks:B,setTourStep:o,tourStep:c,addClass:h,isTourOpen:l}),n.jsx(at,{socket:r,setUserRules:B,userRules:p,isTourOpen:l,setTourStep:o,tourStep:c,name:`${u.I18n.t("when")}...`,typeBlock:"triggers",iconName:"FlashOn",size:h[835],themeType:i,themeName:s,theme:a}),n.jsx(at,{socket:r,setUserRules:B,isTourOpen:l,setTourStep:o,tourStep:c,userRules:p,name:`...${u.I18n.t("and")}...`,typeBlock:"conditions",iconName:"Help",nameAdditionally:u.I18n.t("or"),additionally:!0,border:!0,size:h[835],themeType:i,themeName:s,theme:a}),n.jsx(at,{socket:r,setUserRules:B,isTourOpen:l,setTourStep:o,tourStep:c,userRules:p,name:`...${u.I18n.t("then")}`,typeBlock:"actions",iconName:"PlayForWork",nameAdditionally:u.I18n.t("else"),additionally:!0,size:h[835],themeType:i,themeName:s,theme:a})]})]},"rulesEditor")};export{me as default}; diff --git a/admin/assets/index-bny2V8S2.js b/admin/assets/index-DvPtUWVN.js similarity index 60% rename from admin/assets/index-bny2V8S2.js rename to admin/assets/index-DvPtUWVN.js index 5cd8a8aa8..7398b59d1 100644 --- a/admin/assets/index-bny2V8S2.js +++ b/admin/assets/index-DvPtUWVN.js @@ -1,5 +1,5 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-B0ByV4SK.js","./createSvgIcon-DPvF8xqu.js","./iobroker_javascript__loadShare__react__loadShare__.mjs-CTZOFJS2.js","./iobroker_javascript__loadShare__react__loadShare__.mjs_commonjs-proxy-CE9lvhW8.js","./iobroker_javascript__loadShare__prop_mf_2_types__loadShare__.mjs-BCtSFofY.js","./iobroker_javascript__loadShare___mf_0_iobroker_mf_1_adapter_mf_2_react_mf_2_v5__loadShare__.mjs-DkBjPSMw.js","./iobroker_javascript__loadShare___mf_0_mui_mf_1_material__loadShare__.mjs-QWG5Arqe.js","./index-C49cpVll.js","./virtual_mf-REMOTE_ENTRY_ID_iobroker_javascript__remoteEntry_js-s4ROfmWJ.js","./preload-helper-BDBacUwf.js","./iobroker_javascript__loadShare__react_mf_2_dom__loadShare__.mjs_commonjs-proxy-RQRRZMX5.js","./iobroker_javascript__loadShare__react_mf_2_dom__loadShare__.mjs-DeVAS-oa.js","./inheritsLoose-B0Ba5G9z.js","./index-BCK6q-N6.css","./index-ns4mNOlq.js","./ScriptEditorVanillaMonaco-DSYvOslZ.js","./ScriptEditor-C-fO5h68.js","./Save-Cld9qv9i.js","./OpenAiDialog-CANTLp4d.js","./index-gIA8x-8f.js"])))=>i.map(i=>d[i]); -import{d as e_}from"./virtual_mf-REMOTE_ENTRY_ID_iobroker_javascript__remoteEntry_js-s4ROfmWJ.js";import{j as m,c as $t,g as Tw,r as Sw,_ as Ig,i as t_}from"./createSvgIcon-DPvF8xqu.js";import{r as DT}from"./iobroker_javascript__loadShare__react_mf_2_dom__loadShare__.mjs_commonjs-proxy-RQRRZMX5.js";import{a as _e,_ as AT,b as Ko,c as Lt,d as RT,e as Ew,f as xg,g as um,h as dm,i as hm,j as kt,k as xn,l as us,m as ia,n as Iw,o as Dg,p as OT,q as NT,r as xw,s as MT,t as _n}from"./iobroker_javascript__loadShare__react__loadShare__.mjs-CTZOFJS2.js";import{_ as Pt,a as Xt,b as Wt,c as Eo,d as Di,e as Ag,f as Ai,g as it,h as Bt,i as Ue,j as Xl,k as Zl,l as Ql,m as ec,n as tc,o as qe,p as Dw,q as Si,r as Rg,s as s_,t as Og,u as Ng,v as Pn,w as Aw,x as LT,y as pm,z as wt,A as PT,B as o_,C as BT,D as qp,E as wc,F as jT,G as FT,H as zT,I as UT,J as Rw,K as HT,L as WT,M as i_,N as wn,O as GT,P as VT,Q as KT,R as YT,S as JT,T as Ow,U as qT,V as Mg,W as Nw,X as XT}from"./iobroker_javascript__loadShare___mf_0_mui_mf_1_material__loadShare__.mjs-QWG5Arqe.js";import{_ as x}from"./iobroker_javascript__loadShare___mf_0_iobroker_mf_1_adapter_mf_2_react_mf_2_v5__loadShare__.mjs-DkBjPSMw.js";import{I as qo,a as so,b as mc,C as ZT,c as Mw,F as QT,d as eS,e as kc,f as Lg,g as tS,h as sS,i as oS,j as iS,M as nS,k as rS,l as aS,m as lS,_ as cS,n as sc,o as uS,p as dS,q as oc,r as n_,s as hS,t as pS,u as gS,v as mS,w as r_,x as Yc,y as fS,z as $S,A as bS,B as vS,D as yS,E as _S,G as wS,H as Lw,J as Pw,K as Bw,L as kS,N as CS,O as TS,P as SS,Q as ES,R as IS}from"./index-C49cpVll.js";import{y as xS,_ as DS,a as AS,m as RS,S as a_,T as l_}from"./inheritsLoose-B0Ba5G9z.js";import{c as eo}from"./iobroker_javascript__loadShare__react__loadShare__.mjs_commonjs-proxy-CE9lvhW8.js";function Xo(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}import{_ as Fn}from"./preload-helper-BDBacUwf.js";import{P as ke}from"./iobroker_javascript__loadShare__prop_mf_2_types__loadShare__.mjs-BCtSFofY.js";import{_ as OS}from"./iobroker_javascript__loadShare__react_mf_2_dom__loadShare__.mjs-DeVAS-oa.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const l of document.querySelectorAll('link[rel="modulepreload"]'))r(l);new MutationObserver(l=>{for(const c of l)if(c.type==="childList")for(const d of c.addedNodes)d.tagName==="LINK"&&d.rel==="modulepreload"&&r(d)}).observe(document,{childList:!0,subtree:!0});function i(l){const c={};return l.integrity&&(c.integrity=l.integrity),l.referrerPolicy&&(c.referrerPolicy=l.referrerPolicy),l.crossOrigin==="use-credentials"?c.credentials="include":l.crossOrigin==="anonymous"?c.credentials="omit":c.credentials="same-origin",c}function r(l){if(l.ep)return;l.ep=!0;const c=i(l);fetch(l.href,c)}})();var jw,c_=DT;jw=c_.createRoot,c_.hydrateRoot;var Fw={exports:{}},ht={};var Jc=60103,qc=60106,na=60107,ra=60108,aa=60114,la=60109,ca=60110,ua=60112,da=60113,gm=60120,ha=60115,pa=60116,zw=60121,Uw=60122,Hw=60117,Ww=60129,Gw=60131;if(typeof Symbol=="function"&&Symbol.for){var Nt=Symbol.for;Jc=Nt("react.element"),qc=Nt("react.portal"),na=Nt("react.fragment"),ra=Nt("react.strict_mode"),aa=Nt("react.profiler"),la=Nt("react.provider"),ca=Nt("react.context"),ua=Nt("react.forward_ref"),da=Nt("react.suspense"),gm=Nt("react.suspense_list"),ha=Nt("react.memo"),pa=Nt("react.lazy"),zw=Nt("react.block"),Uw=Nt("react.server.block"),Hw=Nt("react.fundamental"),Ww=Nt("react.debug_trace_mode"),Gw=Nt("react.legacy_hidden")}function Ms(a){if(typeof a=="object"&&a!==null){var s=a.$$typeof;switch(s){case Jc:switch(a=a.type,a){case na:case aa:case ra:case da:case gm:return a;default:switch(a=a&&a.$$typeof,a){case ca:case ua:case pa:case ha:case la:return a;default:return s}}case qc:return s}}}var NS=la,MS=Jc,LS=ua,PS=na,BS=pa,jS=ha,FS=qc,zS=aa,US=ra,HS=da;ht.ContextConsumer=ca;ht.ContextProvider=NS;ht.Element=MS;ht.ForwardRef=LS;ht.Fragment=PS;ht.Lazy=BS;ht.Memo=jS;ht.Portal=FS;ht.Profiler=zS;ht.StrictMode=US;ht.Suspense=HS;ht.isAsyncMode=function(){return!1};ht.isConcurrentMode=function(){return!1};ht.isContextConsumer=function(a){return Ms(a)===ca};ht.isContextProvider=function(a){return Ms(a)===la};ht.isElement=function(a){return typeof a=="object"&&a!==null&&a.$$typeof===Jc};ht.isForwardRef=function(a){return Ms(a)===ua};ht.isFragment=function(a){return Ms(a)===na};ht.isLazy=function(a){return Ms(a)===pa};ht.isMemo=function(a){return Ms(a)===ha};ht.isPortal=function(a){return Ms(a)===qc};ht.isProfiler=function(a){return Ms(a)===aa};ht.isStrictMode=function(a){return Ms(a)===ra};ht.isSuspense=function(a){return Ms(a)===da};ht.isValidElementType=function(a){return typeof a=="string"||typeof a=="function"||a===na||a===aa||a===Ww||a===ra||a===da||a===gm||a===Gw||typeof a=="object"&&a!==null&&(a.$$typeof===pa||a.$$typeof===ha||a.$$typeof===la||a.$$typeof===ca||a.$$typeof===ua||a.$$typeof===Hw||a.$$typeof===zw||a[0]===Uw)};ht.typeOf=Ms;Fw.exports=ht;var WS=Fw.exports;function Cc(a,s){const i=getComputedStyle(s);if(!i)return;let r=a===ft.Horizontal?s.clientWidth:s.clientHeight;return r!==0?(a===ft.Horizontal?r-=parseFloat(i.paddingLeft)+parseFloat(i.paddingRight):r-=parseFloat(i.paddingTop)+parseFloat(i.paddingBottom),r):void 0}function ic(a,s,i=[],r={condition:!0}){const{condition:l}=r,c=(function(d,h){var p={};for(var f in d)Object.prototype.hasOwnProperty.call(d,f)&&h.indexOf(f)<0&&(p[f]=d[f]);if(d!=null&&typeof Object.getOwnPropertySymbols=="function"){var b=0;for(f=Object.getOwnPropertySymbols(d);b(l&&window.addEventListener(a,s,c),()=>{l&&window.removeEventListener(a,s)})),[a,s,l,...i])}(function(a,s){s===void 0&&(s={});var i=s.insertAt;if(typeof document<"u"){var r=document.head||document.getElementsByTagName("head")[0],l=document.createElement("style");l.type="text/css",i==="top"&&r.firstChild?r.insertBefore(l,r.firstChild):r.appendChild(l),l.styleSheet?l.styleSheet.cssText=a:l.appendChild(document.createTextNode(a))}})(`/* === Main Container === */ +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-DqPwE1_T.js","./createSvgIcon-DPvF8xqu.js","./iobroker_javascript__loadShare__react__loadShare__.mjs-CTZOFJS2.js","./iobroker_javascript__loadShare__react__loadShare__.mjs_commonjs-proxy-CE9lvhW8.js","./iobroker_javascript__loadShare__prop_mf_2_types__loadShare__.mjs-BCtSFofY.js","./iobroker_javascript__loadShare___mf_0_iobroker_mf_1_adapter_mf_2_react_mf_2_v5__loadShare__.mjs-DkBjPSMw.js","./iobroker_javascript__loadShare___mf_0_mui_mf_1_material__loadShare__.mjs-QWG5Arqe.js","./index-C49cpVll.js","./virtual_mf-REMOTE_ENTRY_ID_iobroker_javascript__remoteEntry_js-s4ROfmWJ.js","./preload-helper-BDBacUwf.js","./iobroker_javascript__loadShare__react_mf_2_dom__loadShare__.mjs_commonjs-proxy-RQRRZMX5.js","./iobroker_javascript__loadShare__react_mf_2_dom__loadShare__.mjs-DeVAS-oa.js","./inheritsLoose-B0Ba5G9z.js","./index-BCK6q-N6.css","./index-Dl-EtX3d.js","./ScriptEditorVanillaMonaco-DSYvOslZ.js","./ScriptEditor-C-fO5h68.js","./Save-Cld9qv9i.js","./OpenAiDialog-CdW_zvS-.js","./index-gIA8x-8f.js"])))=>i.map(i=>d[i]); +import{d as s_}from"./virtual_mf-REMOTE_ENTRY_ID_iobroker_javascript__remoteEntry_js-s4ROfmWJ.js";import{j as m,c as $t,g as Sw,r as Ew,_ as Dg,i as o_}from"./createSvgIcon-DPvF8xqu.js";import{r as AT}from"./iobroker_javascript__loadShare__react_mf_2_dom__loadShare__.mjs_commonjs-proxy-RQRRZMX5.js";import{a as _e,_ as OT,b as Yo,c as Lt,d as RT,e as Iw,f as Ag,g as pm,h as gm,i as mm,j as kt,k as xn,l as us,m as na,n as xw,o as Og,p as MT,q as NT,r as Dw,s as LT,t as _n}from"./iobroker_javascript__loadShare__react__loadShare__.mjs-CTZOFJS2.js";import{_ as Pt,a as qt,b as Wt,c as Eo,d as Di,e as Rg,f as Ai,g as tt,h as Bt,i as Ue,j as Zl,k as Ql,l as ec,m as tc,n as sc,o as qe,p as Aw,q as Si,r as Mg,s as i_,t as Ng,u as Lg,v as Pn,w as Ow,x as PT,y as kc,z as wt,A as BT,B as Pg,C as jT,D as qp,E as Yr,F as FT,G as zT,H as UT,I as HT,J as Rw,K as WT,L as GT,M as n_,N as wn,O as VT,P as YT,Q as KT,R as JT,S as XT,T as Mw,U as qT,V as Bg,W as Nw,X as ZT}from"./iobroker_javascript__loadShare___mf_0_mui_mf_1_material__loadShare__.mjs-QWG5Arqe.js";import{_ as x}from"./iobroker_javascript__loadShare___mf_0_iobroker_mf_1_adapter_mf_2_react_mf_2_v5__loadShare__.mjs-DkBjPSMw.js";import{I as Xo,a as so,b as fc,C as QT,c as Lw,F as eS,d as tS,e as Cc,f as jg,g as sS,h as oS,i as iS,j as nS,M as rS,k as aS,l as lS,m as cS,_ as uS,n as oc,o as dS,p as hS,q as ic,r as r_,s as pS,t as gS,u as mS,v as fS,w as a_,x as Jc,y as $S,z as bS,A as vS,B as yS,D as _S,E as wS,G as kS,H as Pw,J as Bw,K as jw,L as CS,N as TS,O as SS,P as ES,Q as IS,R as xS}from"./index-C49cpVll.js";import{y as DS,_ as AS,a as OS,m as RS,S as l_,T as c_}from"./inheritsLoose-B0Ba5G9z.js";import{c as eo}from"./iobroker_javascript__loadShare__react__loadShare__.mjs_commonjs-proxy-CE9lvhW8.js";function qo(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}import{_ as Fn}from"./preload-helper-BDBacUwf.js";import{P as ke}from"./iobroker_javascript__loadShare__prop_mf_2_types__loadShare__.mjs-BCtSFofY.js";import{_ as MS}from"./iobroker_javascript__loadShare__react_mf_2_dom__loadShare__.mjs-DeVAS-oa.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const l of document.querySelectorAll('link[rel="modulepreload"]'))r(l);new MutationObserver(l=>{for(const c of l)if(c.type==="childList")for(const d of c.addedNodes)d.tagName==="LINK"&&d.rel==="modulepreload"&&r(d)}).observe(document,{childList:!0,subtree:!0});function i(l){const c={};return l.integrity&&(c.integrity=l.integrity),l.referrerPolicy&&(c.referrerPolicy=l.referrerPolicy),l.crossOrigin==="use-credentials"?c.credentials="include":l.crossOrigin==="anonymous"?c.credentials="omit":c.credentials="same-origin",c}function r(l){if(l.ep)return;l.ep=!0;const c=i(l);fetch(l.href,c)}})();var Fw,u_=AT;Fw=u_.createRoot,u_.hydrateRoot;var zw={exports:{}},ht={};var Xc=60103,qc=60106,ra=60107,aa=60108,la=60114,ca=60109,ua=60110,da=60112,ha=60113,fm=60120,pa=60115,ga=60116,Uw=60121,Hw=60122,Ww=60117,Gw=60129,Vw=60131;if(typeof Symbol=="function"&&Symbol.for){var Mt=Symbol.for;Xc=Mt("react.element"),qc=Mt("react.portal"),ra=Mt("react.fragment"),aa=Mt("react.strict_mode"),la=Mt("react.profiler"),ca=Mt("react.provider"),ua=Mt("react.context"),da=Mt("react.forward_ref"),ha=Mt("react.suspense"),fm=Mt("react.suspense_list"),pa=Mt("react.memo"),ga=Mt("react.lazy"),Uw=Mt("react.block"),Hw=Mt("react.server.block"),Ww=Mt("react.fundamental"),Gw=Mt("react.debug_trace_mode"),Vw=Mt("react.legacy_hidden")}function Ns(a){if(typeof a=="object"&&a!==null){var s=a.$$typeof;switch(s){case Xc:switch(a=a.type,a){case ra:case la:case aa:case ha:case fm:return a;default:switch(a=a&&a.$$typeof,a){case ua:case da:case ga:case pa:case ca:return a;default:return s}}case qc:return s}}}var NS=ca,LS=Xc,PS=da,BS=ra,jS=ga,FS=pa,zS=qc,US=la,HS=aa,WS=ha;ht.ContextConsumer=ua;ht.ContextProvider=NS;ht.Element=LS;ht.ForwardRef=PS;ht.Fragment=BS;ht.Lazy=jS;ht.Memo=FS;ht.Portal=zS;ht.Profiler=US;ht.StrictMode=HS;ht.Suspense=WS;ht.isAsyncMode=function(){return!1};ht.isConcurrentMode=function(){return!1};ht.isContextConsumer=function(a){return Ns(a)===ua};ht.isContextProvider=function(a){return Ns(a)===ca};ht.isElement=function(a){return typeof a=="object"&&a!==null&&a.$$typeof===Xc};ht.isForwardRef=function(a){return Ns(a)===da};ht.isFragment=function(a){return Ns(a)===ra};ht.isLazy=function(a){return Ns(a)===ga};ht.isMemo=function(a){return Ns(a)===pa};ht.isPortal=function(a){return Ns(a)===qc};ht.isProfiler=function(a){return Ns(a)===la};ht.isStrictMode=function(a){return Ns(a)===aa};ht.isSuspense=function(a){return Ns(a)===ha};ht.isValidElementType=function(a){return typeof a=="string"||typeof a=="function"||a===ra||a===la||a===Gw||a===aa||a===ha||a===fm||a===Vw||typeof a=="object"&&a!==null&&(a.$$typeof===ga||a.$$typeof===pa||a.$$typeof===ca||a.$$typeof===ua||a.$$typeof===da||a.$$typeof===Ww||a.$$typeof===Uw||a[0]===Hw)};ht.typeOf=Ns;zw.exports=ht;var GS=zw.exports;function Tc(a,s){const i=getComputedStyle(s);if(!i)return;let r=a===ft.Horizontal?s.clientWidth:s.clientHeight;return r!==0?(a===ft.Horizontal?r-=parseFloat(i.paddingLeft)+parseFloat(i.paddingRight):r-=parseFloat(i.paddingTop)+parseFloat(i.paddingBottom),r):void 0}function nc(a,s,i=[],r={condition:!0}){const{condition:l}=r,c=(function(d,h){var p={};for(var f in d)Object.prototype.hasOwnProperty.call(d,f)&&h.indexOf(f)<0&&(p[f]=d[f]);if(d!=null&&typeof Object.getOwnPropertySymbols=="function"){var b=0;for(f=Object.getOwnPropertySymbols(d);b(l&&window.addEventListener(a,s,c),()=>{l&&window.removeEventListener(a,s)})),[a,s,l,...i])}(function(a,s){s===void 0&&(s={});var i=s.insertAt;if(typeof document<"u"){var r=document.head||document.getElementsByTagName("head")[0],l=document.createElement("style");l.type="text/css",i==="top"&&r.firstChild?r.insertBefore(l,r.firstChild):r.appendChild(l),l.styleSheet?l.styleSheet.cssText=a:l.appendChild(document.createTextNode(a))}})(`/* === Main Container === */ .__dbk__container { height: 100%; width: 100%; @@ -88,28 +88,28 @@ import{d as e_}from"./virtual_mf-REMOTE_ENTRY_ID_iobroker_javascript__remoteEntr .__dbk__dragger.Dark { background: #434252; } -/* ====== */`);const GS=_e.forwardRef((({className:a,theme:s,draggerClassName:i,direction:r=ft.Vertical,onDragging:l},c)=>{const d=`__dbk__gutter ${r} ${a||s}`,h=`__dbk__dragger ${r} ${i||s}`;return m.jsx("div",Object.assign({className:d,ref:c,dir:r,onMouseDown:l,onTouchStart:fc?l:void 0},{children:m.jsx("div",{className:h},void 0)}),void 0)}));var ws;function Pg(a,s,i){let r,l;return s?(r=a/2,l=a):i?(r=a,l=a/2):(r=a,l=a),{aGutterSize:r,bGutterSize:l}}function VS(a,s){switch(s.type){case ws.SetIsReadyToCompute:return Object.assign(Object.assign({},a),{isReady:s.payload.isReady});case ws.CreatePairs:{const{direction:i,children:r,gutters:l}=s.payload,c=r[0].parentNode;if(!c)throw new Error("Cannot create pairs - parent is undefined.");const d=Cc(i,c);if(d===void 0)throw new Error(`Cannot create pairs - parent has undefined or zero size: ${d}.`);const h=[];return r.forEach(((p,f)=>{if(f>0){const b=r[f-1],y=r[f],w=l[f-1],v=i===ft.Horizontal?b.getBoundingClientRect().left:b.getBoundingClientRect().top,_=i===ft.Horizontal?y.getBoundingClientRect().right:y.getBoundingClientRect().bottom,$=i===ft.Horizontal?b.getBoundingClientRect().width+w.getBoundingClientRect().width+y.getBoundingClientRect().width:b.getBoundingClientRect().height+w.getBoundingClientRect().height+y.getBoundingClientRect().height,S=i===ft.Horizontal?w.getBoundingClientRect().width:w.getBoundingClientRect().height,T={idx:f-1,a:b,b:y,gutter:w,parent:c,start:v,end:_,size:$,gutterSize:S,aSizePct:100/r.length,bSizePct:100/r.length};h.push(T)}})),Object.assign(Object.assign({},a),{pairs:h})}case ws.StartDragging:{const{gutterIdx:i}=s.payload;return Object.assign(Object.assign({},a),{isDragging:!0,draggingIdx:i})}case ws.StopDragging:return Object.assign(Object.assign({},a),{isDragging:!1});case ws.CalculateSizes:{const{direction:i,gutterIdx:r}=s.payload,l=a.pairs[r],c=Cc(i,l.parent);if(!c)throw new Error("Cannot calculate sizes - 'pair.parent' has undefined or zero size.");const d=l.gutter[i===ft.Horizontal?"clientWidth":"clientHeight"],h=r===0,p=r===a.pairs.length-1,{aGutterSize:f,bGutterSize:b}=Pg(d,h,p);let y,w,v,_,$;return i===ft.Horizontal?(y=l.a.getBoundingClientRect().left,w=l.b.getBoundingClientRect().right,_=(l.a.getBoundingClientRect().width+f)/c*100,$=(l.b.getBoundingClientRect().width+b)/c*100,v=l.a.getBoundingClientRect().width+f+b+l.b.getBoundingClientRect().width):(y=l.a.getBoundingClientRect().top,w=l.b.getBoundingClientRect().bottom,_=(l.a.getBoundingClientRect().height+f)/c*100,$=(l.b.getBoundingClientRect().height+b)/c*100,v=l.a.getBoundingClientRect().height+f+b+l.b.getBoundingClientRect().height),a.pairs[r]=Object.assign(Object.assign({},l),{start:y,end:w,size:v,aSizePct:_,bSizePct:$,gutterSize:d}),Object.assign({},a)}default:return a}}function Vw(a,s=0,i=[]){return RT.toArray(a).reduce(((r,l,c)=>(WS.isFragment(l)?r.push.apply(r,Vw(l.props.children,s+1,i.concat(l.key||c))):Ew(l)?r.push(xg(l,{key:i.concat(String(l.key)).join(".")})):typeof l!="string"&&typeof l!="number"||r.push(l),r)),[])}(function(a){a[a.SetIsReadyToCompute=0]="SetIsReadyToCompute",a[a.CreatePairs=1]="CreatePairs",a[a.CalculateSizes=2]="CalculateSizes",a[a.StartDragging=3]="StartDragging",a[a.StopDragging=4]="StopDragging"})(ws||(ws={}));const u_=a=>"changedTouches"in a;var ft,Bg;(function(a){a.Horizontal="Horizontal",a.Vertical="Vertical"})(ft||(ft={})),(function(a){a.Light="Light",a.Dark="Dark"})(Bg||(Bg={}));const fc=typeof window<"u"&&"ontouchstart"in window;function Xp(a){return a===ft.Horizontal?"col-resize":"row-resize"}const KS={isReady:!1,isDragging:!1,pairs:[]};function d_({direction:a=ft.Horizontal,minWidths:s=[],minHeights:i=[],initialSizes:r,gutterTheme:l=Bg.Dark,gutterClassName:c,draggerClassName:d,children:h,onResizeStarted:p,onResizeFinished:f,classes:b=[]}){const y=Vw(h),[w,v]=AT(VS,KS),_=Ko(null),$=Ko([]),S=Ko([]);$.current=[],S.current=[];const T=_e.useCallback((O=>{v({type:ws.SetIsReadyToCompute,payload:{isReady:O}})}),[]),E=_e.useCallback(((O,K)=>{v({type:ws.StartDragging,payload:{gutterIdx:K}});const C=w.pairs[K];p==null||p(C.idx),C.a.style.userSelect="none",C.b.style.userSelect="none",C.gutter.style.cursor=Xp(O),C.parent.style.cursor=Xp(O),document.body.style.cursor=Xp(O)}),[w.pairs]),D=_e.useCallback((()=>{v({type:ws.StopDragging});const O=[];for(let C=0;C{v({type:ws.CalculateSizes,payload:{direction:O,gutterIdx:K}})}),[]),P=_e.useCallback(((O,K,C)=>{v({type:ws.CreatePairs,payload:{direction:O,children:K,gutters:C}})}),[]),W=_e.useCallback(((O,K,C,Q)=>{const ve=K[0].parentNode;if(!ve)throw new Error("Cannot set initial sizes - parent is undefined");if(Cc(O,ve)===void 0)throw new Error("Cannot set initial sizes - parent has undefined size");K.forEach(((ce,ne)=>{const me=ne===0,re=ne===K.length-1;let B,N=0;K.length>1&&(N=C[re?ne-1:ne].getBoundingClientRect()[O===ft.Horizontal?"width":"height"],N=me||re?N/2:N),B=Q&&ne{if(w.draggingIdx===void 0)throw new Error("Cannot adjust size - 'draggingIdx' is undefined");const C=w.pairs[w.draggingIdx];if(C.size===void 0)throw new Error("Cannot adjust size - 'pair.size' is undefined");if(C.gutterSize===void 0)throw new Error("Cannot adjust size - 'pair.gutterSize' is undefined");const Q=C.aSizePct+C.bSizePct,ve=K/C.size*Q,ce=Q-K/C.size*Q,ne=w.draggingIdx===0,me=w.draggingIdx===w.pairs.length-1,{aGutterSize:re,bGutterSize:B}=Pg(C.gutterSize,ne,me),N=`calc(${ve}% - ${re}px)`,te=`calc(${ce}% - ${B}px)`;O===ft.Horizontal?(C.a.style.width=N,C.b.style.width=te):(C.a.style.height=N,C.b.style.height=te)}),[w.draggingIdx,w.pairs,a]),z=_e.useCallback(((O,K,C)=>{if(!w.isDragging)return;if(w.draggingIdx===void 0)throw new Error("Cannot drag - 'draggingIdx' is undefined");const Q=w.pairs[w.draggingIdx];if(Q.start===void 0)throw new Error("Cannot drag - 'pair.start' is undefined");if(Q.size===void 0)throw new Error("Cannot drag - 'pair.size' is undefined");if(Q.gutterSize===void 0)throw new Error("Cannot drag - 'pair.gutterSize' is undefined");let ve=(function(me,re){const B=u_(re)?re.changedTouches[0]:re;return me===ft.Horizontal?B.clientX:B.clientY})(K,O)-Q.start,ce=16,ne=16;C.length>w.draggingIdx&&(ce=C[w.draggingIdx]),C.length>=w.draggingIdx+1&&(ne=C[w.draggingIdx+1]),ve=Q.size-(Q.gutterSize+ne)&&(ve=Q.size-(Q.gutterSize+ne)),G(K,ve)}),[w.isDragging,w.draggingIdx,w.pairs,G]),Z=()=>{if(w.isDragging){if(w.draggingIdx===void 0)throw new Error("Cannot calculate sizes after dragging = 'state.draggingIdx' is undefined");M(a,w.draggingIdx),D()}},he=O=>{w.isDragging&&(u_(O)&&O.preventDefault(),z(O,a,a===ft.Horizontal?s:i))};function Ce(O,K){if(!O.current)throw new Error("Can't add element to ref object - ref isn't initialized");K&&!O.current.includes(K)&&O.current.push(K)}return ic("mouseup",Z,[w.isDragging,D]),ic("mousemove",he,[a,w.isDragging,z,s,i]),ic("touchend",Z,[w.isDragging,D],{condition:fc}),ic("touchmove",he,[a,w.isDragging,z,s,i],{condition:fc,passive:!fc}),Lt((function(){if(!_.current)return;const O=_.current.parentElement;if(!O)return;const K=new ResizeObserver((()=>{const C=getComputedStyle(O),Q=a===ft.Horizontal?O.clientWidth:O.clientHeight;T(!!C&&!!Q)}));return K.observe(O),()=>{K.disconnect()}}),[_.current,a]),Lt((function(){if(w.isReady&&(!$.current||$.current[0].offsetParent)){if(!$.current||!S.current)throw new Error("Cannot create pairs - either variable 'childRefs' or 'gutterRefs' is undefined");y.length<=1?W(a,$.current,S.current,r):(W(a,$.current,S.current,r),P(a,$.current,S.current))}}),[h,w.isReady,a,W,P,r]),m.jsx("div",Object.assign({className:`__dbk__container ${a}`,ref:_},{children:w.isReady&&y.map(((O,K)=>m.jsxs(_e.Fragment,{children:[m.jsx("div",Object.assign({ref:C=>Ce($,C),className:"__dbk__child-wrapper "+(KCe(S,C),className:c,theme:l,draggerClassName:d,direction:a,onDragging:()=>{return M(a,C=K),void E(a,C);var C}},void 0)]},K)))}),void 0)}const Kw=um({dragDropManager:void 0});function Qr(a){"@babel/helpers - typeof";return Qr=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(s){return typeof s}:function(s){return s&&typeof Symbol=="function"&&s.constructor===Symbol&&s!==Symbol.prototype?"symbol":typeof s},Qr(a)}function YS(a,s){if(Qr(a)!="object"||!a)return a;var i=a[Symbol.toPrimitive];if(i!==void 0){var r=i.call(a,s);if(Qr(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(s==="string"?String:Number)(a)}function JS(a){var s=YS(a,"string");return Qr(s)=="symbol"?s:s+""}function qS(a,s,i){return(s=JS(s))in a?Object.defineProperty(a,s,{value:i,enumerable:!0,configurable:!0,writable:!0}):a[s]=i,a}function bs(a){return"Minified Redux error #"+a+"; visit https://redux.js.org/Errors?code="+a+" for the full message or use the non-minified dev environment for full errors. "}var h_=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})(),p_=function(){return Math.random().toString(36).substring(7).split("").join(".")},g_={INIT:"@@redux/INIT"+p_(),REPLACE:"@@redux/REPLACE"+p_()};function XS(a){if(typeof a!="object"||a===null)return!1;for(var s=a;Object.getPrototypeOf(s)!==null;)s=Object.getPrototypeOf(s);return Object.getPrototypeOf(a)===s}function Yw(a,s,i){var r;if(typeof s=="function"&&typeof i=="function"||typeof i=="function"&&typeof arguments[3]=="function")throw new Error(bs(0));if(typeof s=="function"&&typeof i>"u"&&(i=s,s=void 0),typeof i<"u"){if(typeof i!="function")throw new Error(bs(1));return i(Yw)(a,s)}if(typeof a!="function")throw new Error(bs(2));var l=a,c=s,d=[],h=d,p=!1;function f(){h===d&&(h=d.slice())}function b(){if(p)throw new Error(bs(3));return c}function y($){if(typeof $!="function")throw new Error(bs(4));if(p)throw new Error(bs(5));var S=!0;return f(),h.push($),function(){if(S){if(p)throw new Error(bs(6));S=!1,f();var E=h.indexOf($);h.splice(E,1),d=null}}}function w($){if(!XS($))throw new Error(bs(7));if(typeof $.type>"u")throw new Error(bs(8));if(p)throw new Error(bs(9));try{p=!0,c=l(c,$)}finally{p=!1}for(var S=d=h,T=0;Tr&&r[l]?r[l]:i||null,a)}function eE(a,s){return a.filter(i=>i!==s)}function Jw(a){return typeof a=="object"}function tE(a,s){const i=new Map,r=c=>{i.set(c,i.has(c)?i.get(c)+1:1)};a.forEach(r),s.forEach(r);const l=[];return i.forEach((c,d)=>{c===1&&l.push(d)}),l}function sE(a,s){return a.filter(i=>s.indexOf(i)>-1)}const mm="dnd-core/INIT_COORDS",Xc="dnd-core/BEGIN_DRAG",fm="dnd-core/PUBLISH_DRAG_SOURCE",Zc="dnd-core/HOVER",Qc="dnd-core/DROP",eu="dnd-core/END_DRAG";function m_(a,s){return{type:mm,payload:{sourceClientOffset:s||null,clientOffset:a||null}}}const oE={type:mm,payload:{clientOffset:null,sourceClientOffset:null}};function iE(a){return function(i=[],r={publishSource:!0}){const{publishSource:l=!0,clientOffset:c,getSourceClientOffset:d}=r,h=a.getMonitor(),p=a.getRegistry();a.dispatch(m_(c)),nE(i,h,p);const f=lE(i,h);if(f==null){a.dispatch(oE);return}let b=null;if(c){if(!d)throw new Error("getSourceClientOffset must be defined");rE(d),b=d(f)}a.dispatch(m_(c,b));const w=p.getSource(f).beginDrag(h,f);if(w==null)return;aE(w),p.pinSource(f);const v=p.getSourceType(f);return{type:Xc,payload:{itemType:v,item:w,sourceId:f,clientOffset:c||null,sourceClientOffset:b||null,isSourcePublic:!!l}}}}function nE(a,s,i){Ve(!s.isDragging(),"Cannot call beginDrag while dragging."),a.forEach(function(r){Ve(i.getSource(r),"Expected sourceIds to be registered.")})}function rE(a){Ve(typeof a=="function","When clientOffset is provided, getSourceClientOffset must be a function.")}function aE(a){Ve(Jw(a),"Item must be an object.")}function lE(a,s){let i=null;for(let r=a.length-1;r>=0;r--)if(s.canDragSource(a[r])){i=a[r];break}return i}function cE(a,s,i){return s in a?Object.defineProperty(a,s,{value:i,enumerable:!0,configurable:!0,writable:!0}):a[s]=i,a}function uE(a){for(var s=1;s{const p=pE(d,h,l,r),f={type:Qc,payload:{dropResult:uE({},i,p)}};a.dispatch(f)})}}function hE(a){Ve(a.isDragging(),"Cannot call drop while not dragging."),Ve(!a.didDrop(),"Cannot call drop twice during one drag operation.")}function pE(a,s,i,r){const l=i.getTarget(a);let c=l?l.drop(r,a):void 0;return gE(c),typeof c>"u"&&(c=s===0?{}:r.getDropResult()),c}function gE(a){Ve(typeof a>"u"||Jw(a),"Drop result must either be an object or undefined.")}function mE(a){const s=a.getTargetIds().filter(a.canDropOnTarget,a);return s.reverse(),s}function fE(a){return function(){const i=a.getMonitor(),r=a.getRegistry();$E(i);const l=i.getSourceId();return l!=null&&(r.getSource(l,!0).endDrag(i,l),r.unpinSource()),{type:eu}}}function $E(a){Ve(a.isDragging(),"Cannot call endDrag while not dragging.")}function jg(a,s){return s===null?a===null:Array.isArray(a)?a.some(i=>i===s):a===s}function bE(a){return function(i,{clientOffset:r}={}){vE(i);const l=i.slice(0),c=a.getMonitor(),d=a.getRegistry(),h=c.getItemType();return _E(l,d,h),yE(l,c,d),wE(l,c,d),{type:Zc,payload:{targetIds:l,clientOffset:r||null}}}}function vE(a){Ve(Array.isArray(a),"Expected targetIds to be an array.")}function yE(a,s,i){Ve(s.isDragging(),"Cannot call hover while not dragging."),Ve(!s.didDrop(),"Cannot call hover after drop.");for(let r=0;r=0;r--){const l=a[r],c=s.getTargetType(l);jg(c,i)||a.splice(r,1)}}function wE(a,s,i){a.forEach(function(r){i.getTarget(r).hover(s,r)})}function kE(a){return function(){if(a.getMonitor().isDragging())return{type:fm}}}function CE(a){return{beginDrag:iE(a),publishDragSource:kE(a),hover:bE(a),drop:dE(a),endDrag:fE(a)}}class TE{receiveBackend(s){this.backend=s}getMonitor(){return this.monitor}getBackend(){return this.backend}getRegistry(){return this.monitor.registry}getActions(){const s=this,{dispatch:i}=this.store;function r(c){return(...d)=>{const h=c.apply(s,d);typeof h<"u"&&i(h)}}const l=CE(this);return Object.keys(l).reduce((c,d)=>{const h=l[d];return c[d]=r(h),c},{})}dispatch(s){this.store.dispatch(s)}constructor(s,i){this.isSetUp=!1,this.handleRefCountChange=()=>{const r=this.store.getState().refCount>0;this.backend&&(r&&!this.isSetUp?(this.backend.setup(),this.isSetUp=!0):!r&&this.isSetUp&&(this.backend.teardown(),this.isSetUp=!1))},this.store=s,this.monitor=i,s.subscribe(this.handleRefCountChange)}}function SE(a,s){return{x:a.x+s.x,y:a.y+s.y}}function qw(a,s){return{x:a.x-s.x,y:a.y-s.y}}function EE(a){const{clientOffset:s,initialClientOffset:i,initialSourceClientOffset:r}=a;return!s||!i||!r?null:qw(SE(s,r),i)}function IE(a){const{clientOffset:s,initialClientOffset:i}=a;return!s||!i?null:qw(s,i)}const Kr=[],$m=[];Kr.__IS_NONE__=!0;$m.__IS_ALL__=!0;function xE(a,s){return a===Kr?!1:a===$m||typeof s>"u"?!0:sE(s,a).length>0}class DE{subscribeToStateChange(s,i={}){const{handlerIds:r}=i;Ve(typeof s=="function","listener must be a function."),Ve(typeof r>"u"||Array.isArray(r),"handlerIds, when specified, must be an array of strings.");let l=this.store.getState().stateId;const c=()=>{const d=this.store.getState(),h=d.stateId;try{h===l||h===l+1&&!xE(d.dirtyHandlerIds,r)||s()}finally{l=h}};return this.store.subscribe(c)}subscribeToOffsetChange(s){Ve(typeof s=="function","listener must be a function.");let i=this.store.getState().dragOffset;const r=()=>{const l=this.store.getState().dragOffset;l!==i&&(i=l,s())};return this.store.subscribe(r)}canDragSource(s){if(!s)return!1;const i=this.registry.getSource(s);return Ve(i,`Expected to find a valid source. sourceId=${s}`),this.isDragging()?!1:i.canDrag(this,s)}canDropOnTarget(s){if(!s)return!1;const i=this.registry.getTarget(s);if(Ve(i,`Expected to find a valid target. targetId=${s}`),!this.isDragging()||this.didDrop())return!1;const r=this.registry.getTargetType(s),l=this.getItemType();return jg(r,l)&&i.canDrop(this,s)}isDragging(){return!!this.getItemType()}isDraggingSource(s){if(!s)return!1;const i=this.registry.getSource(s,!0);if(Ve(i,`Expected to find a valid source. sourceId=${s}`),!this.isDragging()||!this.isSourcePublic())return!1;const r=this.registry.getSourceType(s),l=this.getItemType();return r!==l?!1:i.isDragging(this,s)}isOverTarget(s,i={shallow:!1}){if(!s)return!1;const{shallow:r}=i;if(!this.isDragging())return!1;const l=this.registry.getTargetType(s),c=this.getItemType();if(c&&!jg(l,c))return!1;const d=this.getTargetIds();if(!d.length)return!1;const h=d.indexOf(s);return r?h===d.length-1:h>-1}getItemType(){return this.store.getState().dragOperation.itemType}getItem(){return this.store.getState().dragOperation.item}getSourceId(){return this.store.getState().dragOperation.sourceId}getTargetIds(){return this.store.getState().dragOperation.targetIds}getDropResult(){return this.store.getState().dragOperation.dropResult}didDrop(){return this.store.getState().dragOperation.didDrop}isSourcePublic(){return!!this.store.getState().dragOperation.isSourcePublic}getInitialClientOffset(){return this.store.getState().dragOffset.initialClientOffset}getInitialSourceClientOffset(){return this.store.getState().dragOffset.initialSourceClientOffset}getClientOffset(){return this.store.getState().dragOffset.clientOffset}getSourceClientOffset(){return EE(this.store.getState().dragOffset)}getDifferenceFromInitialOffset(){return IE(this.store.getState().dragOffset)}constructor(s,i){this.store=s,this.registry=i}}const f_=typeof global<"u"?global:self,Xw=f_.MutationObserver||f_.WebKitMutationObserver;function Zw(a){return function(){const i=setTimeout(l,0),r=setInterval(l,50);function l(){clearTimeout(i),clearInterval(r),a()}}}function AE(a){let s=1;const i=new Xw(a),r=document.createTextNode("");return i.observe(r,{characterData:!0}),function(){s=-s,r.data=s}}const RE=typeof Xw=="function"?AE:Zw;class OE{enqueueTask(s){const{queue:i,requestFlush:r}=this;i.length||(r(),this.flushing=!0),i[i.length]=s}constructor(){this.queue=[],this.pendingErrors=[],this.flushing=!1,this.index=0,this.capacity=1024,this.flush=()=>{const{queue:s}=this;for(;this.indexthis.capacity){for(let r=0,l=s.length-this.index;r{this.pendingErrors.push(s),this.requestErrorThrow()},this.requestFlush=RE(this.flush),this.requestErrorThrow=Zw(()=>{if(this.pendingErrors.length)throw this.pendingErrors.shift()})}}class NE{call(){try{this.task&&this.task()}catch(s){this.onError(s)}finally{this.task=null,this.release(this)}}constructor(s,i){this.onError=s,this.release=i,this.task=null}}class ME{create(s){const i=this.freeTasks,r=i.length?i.pop():new NE(this.onError,l=>i[i.length]=l);return r.task=s,r}constructor(s){this.onError=s,this.freeTasks=[]}}const Qw=new OE,LE=new ME(Qw.registerPendingError);function PE(a){Qw.enqueueTask(LE.create(a))}const bm="dnd-core/ADD_SOURCE",vm="dnd-core/ADD_TARGET",ym="dnd-core/REMOVE_SOURCE",tu="dnd-core/REMOVE_TARGET";function BE(a){return{type:bm,payload:{sourceId:a}}}function jE(a){return{type:vm,payload:{targetId:a}}}function FE(a){return{type:ym,payload:{sourceId:a}}}function zE(a){return{type:tu,payload:{targetId:a}}}function UE(a){Ve(typeof a.canDrag=="function","Expected canDrag to be a function."),Ve(typeof a.beginDrag=="function","Expected beginDrag to be a function."),Ve(typeof a.endDrag=="function","Expected endDrag to be a function.")}function HE(a){Ve(typeof a.canDrop=="function","Expected canDrop to be a function."),Ve(typeof a.hover=="function","Expected hover to be a function."),Ve(typeof a.drop=="function","Expected beginDrag to be a function.")}function Fg(a,s){if(s&&Array.isArray(a)){a.forEach(i=>Fg(i,!1));return}Ve(typeof a=="string"||typeof a=="symbol",s?"Type can only be a string, a symbol, or an array of either.":"Type can only be a string or a symbol.")}var _s;(function(a){a.SOURCE="SOURCE",a.TARGET="TARGET"})(_s||(_s={}));let WE=0;function GE(){return WE++}function VE(a){const s=GE().toString();switch(a){case _s.SOURCE:return`S${s}`;case _s.TARGET:return`T${s}`;default:throw new Error(`Unknown Handler Role: ${a}`)}}function $_(a){switch(a[0]){case"S":return _s.SOURCE;case"T":return _s.TARGET;default:throw new Error(`Cannot parse handler ID: ${a}`)}}function b_(a,s){const i=a.entries();let r=!1;do{const{done:l,value:[,c]}=i.next();if(c===s)return!0;r=!!l}while(!r);return!1}class KE{addSource(s,i){Fg(s),UE(i);const r=this.addHandler(_s.SOURCE,s,i);return this.store.dispatch(BE(r)),r}addTarget(s,i){Fg(s,!0),HE(i);const r=this.addHandler(_s.TARGET,s,i);return this.store.dispatch(jE(r)),r}containsHandler(s){return b_(this.dragSources,s)||b_(this.dropTargets,s)}getSource(s,i=!1){return Ve(this.isSourceId(s),"Expected a valid source ID."),i&&s===this.pinnedSourceId?this.pinnedSource:this.dragSources.get(s)}getTarget(s){return Ve(this.isTargetId(s),"Expected a valid target ID."),this.dropTargets.get(s)}getSourceType(s){return Ve(this.isSourceId(s),"Expected a valid source ID."),this.types.get(s)}getTargetType(s){return Ve(this.isTargetId(s),"Expected a valid target ID."),this.types.get(s)}isSourceId(s){return $_(s)===_s.SOURCE}isTargetId(s){return $_(s)===_s.TARGET}removeSource(s){Ve(this.getSource(s),"Expected an existing source."),this.store.dispatch(FE(s)),PE(()=>{this.dragSources.delete(s),this.types.delete(s)})}removeTarget(s){Ve(this.getTarget(s),"Expected an existing target."),this.store.dispatch(zE(s)),this.dropTargets.delete(s),this.types.delete(s)}pinSource(s){const i=this.getSource(s);Ve(i,"Expected an existing source."),this.pinnedSourceId=s,this.pinnedSource=i}unpinSource(){Ve(this.pinnedSource,"No source is pinned at the time."),this.pinnedSourceId=null,this.pinnedSource=null}addHandler(s,i,r){const l=VE(s);return this.types.set(l,i),s===_s.SOURCE?this.dragSources.set(l,r):s===_s.TARGET&&this.dropTargets.set(l,r),l}constructor(s){this.types=new Map,this.dragSources=new Map,this.dropTargets=new Map,this.pinnedSourceId=null,this.pinnedSource=null,this.store=s}}const YE=(a,s)=>a===s;function JE(a,s){return!a&&!s?!0:!a||!s?!1:a.x===s.x&&a.y===s.y}function qE(a,s,i=YE){if(a.length!==s.length)return!1;for(let r=0;r0||!qE(i,r)))return Kr;const d=r[r.length-1],h=i[i.length-1];return d!==h&&(d&&l.push(d),h&&l.push(h)),l}function ZE(a,s,i){return s in a?Object.defineProperty(a,s,{value:i,enumerable:!0,configurable:!0,writable:!0}):a[s]=i,a}function QE(a){for(var s=1;s=0)&&Object.prototype.propertyIsEnumerable.call(a,r)&&(i[r]=a[r])}return i}function hI(a,s){if(a==null)return{};var i={},r=Object.keys(a),l,c;for(c=0;c=0)&&(i[l]=a[l]);return i}let y_=0;const $c=Symbol.for("__REACT_DND_CONTEXT_INSTANCE__");var ek=dm(function(s){var{children:i}=s,r=dI(s,["children"]);const[l,c]=pI(r);return Lt(()=>{if(c){const d=tk();return++y_,()=>{--y_===0&&(d[$c]=null)}}},[]),m.jsx(Kw.Provider,{value:l,children:i})});function pI(a){if("manager"in a)return[{dragDropManager:a.manager},!1];const s=gI(a.backend,a.context,a.options,a.debugMode),i=!a.context;return[s,i]}function gI(a,s=tk(),i,r){const l=s;return l[$c]||(l[$c]={dragDropManager:cI(a,s,i,r)}),l[$c]}function tk(){return typeof global<"u"?global:window}var mI=function a(s,i){if(s===i)return!0;if(s&&i&&typeof s=="object"&&typeof i=="object"){if(s.constructor!==i.constructor)return!1;var r,l,c;if(Array.isArray(s)){if(r=s.length,r!=i.length)return!1;for(l=r;l--!==0;)if(!a(s[l],i[l]))return!1;return!0}if(s.constructor===RegExp)return s.source===i.source&&s.flags===i.flags;if(s.valueOf!==Object.prototype.valueOf)return s.valueOf()===i.valueOf();if(s.toString!==Object.prototype.toString)return s.toString()===i.toString();if(c=Object.keys(s),r=c.length,r!==Object.keys(i).length)return!1;for(l=r;l--!==0;)if(!Object.prototype.hasOwnProperty.call(i,c[l]))return!1;for(l=r;l--!==0;){var d=c[l];if(!a(s[d],i[d]))return!1}return!0}return s!==s&&i!==i};const fI=Xo(mI),Ri=typeof window<"u"?hm:Lt;function $I(a,s,i){const[r,l]=kt(()=>s(a)),c=xn(()=>{const d=s(a);fI(r,d)||(l(d),i&&i())},[r,a,i]);return Ri(c),[r,c]}function bI(a,s,i){const[r,l]=$I(a,s,i);return Ri(function(){const d=a.getHandlerId();if(d!=null)return a.subscribeToStateChange(l,{handlerIds:[d]})},[a,l]),r}function sk(a,s,i){return bI(s,a||(()=>({})),()=>i.reconnect())}function ok(a,s){const i=[];return typeof a!="function"&&i.push(a),us(()=>typeof a=="function"?a():a,i)}function vI(a){return us(()=>a.hooks.dragSource(),[a])}function yI(a){return us(()=>a.hooks.dragPreview(),[a])}let Zp=!1,Qp=!1;class _I{receiveHandlerId(s){this.sourceId=s}getHandlerId(){return this.sourceId}canDrag(){Ve(!Zp,"You may not call monitor.canDrag() inside your canDrag() implementation. Read more: http://react-dnd.github.io/react-dnd/docs/api/drag-source-monitor");try{return Zp=!0,this.internalMonitor.canDragSource(this.sourceId)}finally{Zp=!1}}isDragging(){if(!this.sourceId)return!1;Ve(!Qp,"You may not call monitor.isDragging() inside your isDragging() implementation. Read more: http://react-dnd.github.io/react-dnd/docs/api/drag-source-monitor");try{return Qp=!0,this.internalMonitor.isDraggingSource(this.sourceId)}finally{Qp=!1}}subscribeToStateChange(s,i){return this.internalMonitor.subscribeToStateChange(s,i)}isDraggingSource(s){return this.internalMonitor.isDraggingSource(s)}isOverTarget(s,i){return this.internalMonitor.isOverTarget(s,i)}getTargetIds(){return this.internalMonitor.getTargetIds()}isSourcePublic(){return this.internalMonitor.isSourcePublic()}getSourceId(){return this.internalMonitor.getSourceId()}subscribeToOffsetChange(s){return this.internalMonitor.subscribeToOffsetChange(s)}canDragSource(s){return this.internalMonitor.canDragSource(s)}canDropOnTarget(s){return this.internalMonitor.canDropOnTarget(s)}getItemType(){return this.internalMonitor.getItemType()}getItem(){return this.internalMonitor.getItem()}getDropResult(){return this.internalMonitor.getDropResult()}didDrop(){return this.internalMonitor.didDrop()}getInitialClientOffset(){return this.internalMonitor.getInitialClientOffset()}getInitialSourceClientOffset(){return this.internalMonitor.getInitialSourceClientOffset()}getSourceClientOffset(){return this.internalMonitor.getSourceClientOffset()}getClientOffset(){return this.internalMonitor.getClientOffset()}getDifferenceFromInitialOffset(){return this.internalMonitor.getDifferenceFromInitialOffset()}constructor(s){this.sourceId=null,this.internalMonitor=s.getMonitor()}}let eg=!1;class wI{receiveHandlerId(s){this.targetId=s}getHandlerId(){return this.targetId}subscribeToStateChange(s,i){return this.internalMonitor.subscribeToStateChange(s,i)}canDrop(){if(!this.targetId)return!1;Ve(!eg,"You may not call monitor.canDrop() inside your canDrop() implementation. Read more: http://react-dnd.github.io/react-dnd/docs/api/drop-target-monitor");try{return eg=!0,this.internalMonitor.canDropOnTarget(this.targetId)}finally{eg=!1}}isOver(s){return this.targetId?this.internalMonitor.isOverTarget(this.targetId,s):!1}getItemType(){return this.internalMonitor.getItemType()}getItem(){return this.internalMonitor.getItem()}getDropResult(){return this.internalMonitor.getDropResult()}didDrop(){return this.internalMonitor.didDrop()}getInitialClientOffset(){return this.internalMonitor.getInitialClientOffset()}getInitialSourceClientOffset(){return this.internalMonitor.getInitialSourceClientOffset()}getSourceClientOffset(){return this.internalMonitor.getSourceClientOffset()}getClientOffset(){return this.internalMonitor.getClientOffset()}getDifferenceFromInitialOffset(){return this.internalMonitor.getDifferenceFromInitialOffset()}constructor(s){this.targetId=null,this.internalMonitor=s.getMonitor()}}function kI(a,s,i){const r=i.getRegistry(),l=r.addTarget(a,s);return[l,()=>r.removeTarget(l)]}function CI(a,s,i){const r=i.getRegistry(),l=r.addSource(a,s);return[l,()=>r.removeSource(l)]}function zg(a,s,i,r){let l;if(l!==void 0)return!!l;if(a===s)return!0;if(typeof a!="object"||!a||typeof s!="object"||!s)return!1;const c=Object.keys(a),d=Object.keys(s);if(c.length!==d.length)return!1;const h=Object.prototype.hasOwnProperty.bind(s);for(let p=0;p, or turn it into a drag source or a drop target itself.`)}function SI(a){return(s=null,i=null)=>{if(!Ew(s)){const c=s;return a(c,i),c}const r=s;return TI(r),EI(r,i?c=>a(c,i):a)}}function ik(a){const s={};return Object.keys(a).forEach(i=>{const r=a[i];if(i.endsWith("Ref"))s[i]=a[i];else{const l=SI(r);s[i]=()=>l}}),s}function __(a,s){typeof a=="function"?a(s):a.current=s}function EI(a,s){const i=a.ref;return Ve(typeof i!="string","Cannot connect React DnD to an element with an existing string ref. Please convert it to use a callback ref instead, or wrap it into a or
. Read more: https://reactjs.org/docs/refs-and-the-dom.html#callback-refs"),i?xg(a,{ref:r=>{__(i,r),__(s,r)}}):xg(a,{ref:s})}class II{receiveHandlerId(s){this.handlerId!==s&&(this.handlerId=s,this.reconnect())}get connectTarget(){return this.dragSource}get dragSourceOptions(){return this.dragSourceOptionsInternal}set dragSourceOptions(s){this.dragSourceOptionsInternal=s}get dragPreviewOptions(){return this.dragPreviewOptionsInternal}set dragPreviewOptions(s){this.dragPreviewOptionsInternal=s}reconnect(){const s=this.reconnectDragSource();this.reconnectDragPreview(s)}reconnectDragSource(){const s=this.dragSource,i=this.didHandlerIdChange()||this.didConnectedDragSourceChange()||this.didDragSourceOptionsChange();return i&&this.disconnectDragSource(),this.handlerId?s?(i&&(this.lastConnectedHandlerId=this.handlerId,this.lastConnectedDragSource=s,this.lastConnectedDragSourceOptions=this.dragSourceOptions,this.dragSourceUnsubscribe=this.backend.connectDragSource(this.handlerId,s,this.dragSourceOptions)),i):(this.lastConnectedDragSource=s,i):i}reconnectDragPreview(s=!1){const i=this.dragPreview,r=s||this.didHandlerIdChange()||this.didConnectedDragPreviewChange()||this.didDragPreviewOptionsChange();if(r&&this.disconnectDragPreview(),!!this.handlerId){if(!i){this.lastConnectedDragPreview=i;return}r&&(this.lastConnectedHandlerId=this.handlerId,this.lastConnectedDragPreview=i,this.lastConnectedDragPreviewOptions=this.dragPreviewOptions,this.dragPreviewUnsubscribe=this.backend.connectDragPreview(this.handlerId,i,this.dragPreviewOptions))}}didHandlerIdChange(){return this.lastConnectedHandlerId!==this.handlerId}didConnectedDragSourceChange(){return this.lastConnectedDragSource!==this.dragSource}didConnectedDragPreviewChange(){return this.lastConnectedDragPreview!==this.dragPreview}didDragSourceOptionsChange(){return!zg(this.lastConnectedDragSourceOptions,this.dragSourceOptions)}didDragPreviewOptionsChange(){return!zg(this.lastConnectedDragPreviewOptions,this.dragPreviewOptions)}disconnectDragSource(){this.dragSourceUnsubscribe&&(this.dragSourceUnsubscribe(),this.dragSourceUnsubscribe=void 0)}disconnectDragPreview(){this.dragPreviewUnsubscribe&&(this.dragPreviewUnsubscribe(),this.dragPreviewUnsubscribe=void 0,this.dragPreviewNode=null,this.dragPreviewRef=null)}get dragSource(){return this.dragSourceNode||this.dragSourceRef&&this.dragSourceRef.current}get dragPreview(){return this.dragPreviewNode||this.dragPreviewRef&&this.dragPreviewRef.current}clearDragSource(){this.dragSourceNode=null,this.dragSourceRef=null}clearDragPreview(){this.dragPreviewNode=null,this.dragPreviewRef=null}constructor(s){this.hooks=ik({dragSource:(i,r)=>{this.clearDragSource(),this.dragSourceOptions=r||null,Ug(i)?this.dragSourceRef=i:this.dragSourceNode=i,this.reconnectDragSource()},dragPreview:(i,r)=>{this.clearDragPreview(),this.dragPreviewOptions=r||null,Ug(i)?this.dragPreviewRef=i:this.dragPreviewNode=i,this.reconnectDragPreview()}}),this.handlerId=null,this.dragSourceRef=null,this.dragSourceOptionsInternal=null,this.dragPreviewRef=null,this.dragPreviewOptionsInternal=null,this.lastConnectedHandlerId=null,this.lastConnectedDragSource=null,this.lastConnectedDragSourceOptions=null,this.lastConnectedDragPreview=null,this.lastConnectedDragPreviewOptions=null,this.backend=s}}class xI{get connectTarget(){return this.dropTarget}reconnect(){const s=this.didHandlerIdChange()||this.didDropTargetChange()||this.didOptionsChange();s&&this.disconnectDropTarget();const i=this.dropTarget;if(this.handlerId){if(!i){this.lastConnectedDropTarget=i;return}s&&(this.lastConnectedHandlerId=this.handlerId,this.lastConnectedDropTarget=i,this.lastConnectedDropTargetOptions=this.dropTargetOptions,this.unsubscribeDropTarget=this.backend.connectDropTarget(this.handlerId,i,this.dropTargetOptions))}}receiveHandlerId(s){s!==this.handlerId&&(this.handlerId=s,this.reconnect())}get dropTargetOptions(){return this.dropTargetOptionsInternal}set dropTargetOptions(s){this.dropTargetOptionsInternal=s}didHandlerIdChange(){return this.lastConnectedHandlerId!==this.handlerId}didDropTargetChange(){return this.lastConnectedDropTarget!==this.dropTarget}didOptionsChange(){return!zg(this.lastConnectedDropTargetOptions,this.dropTargetOptions)}disconnectDropTarget(){this.unsubscribeDropTarget&&(this.unsubscribeDropTarget(),this.unsubscribeDropTarget=void 0)}get dropTarget(){return this.dropTargetNode||this.dropTargetRef&&this.dropTargetRef.current}clearDropTarget(){this.dropTargetRef=null,this.dropTargetNode=null}constructor(s){this.hooks=ik({dropTarget:(i,r)=>{this.clearDropTarget(),this.dropTargetOptions=r,Ug(i)?this.dropTargetRef=i:this.dropTargetNode=i,this.reconnect()}}),this.handlerId=null,this.dropTargetRef=null,this.dropTargetOptionsInternal=null,this.lastConnectedHandlerId=null,this.lastConnectedDropTarget=null,this.lastConnectedDropTargetOptions=null,this.backend=s}}function zn(){const{dragDropManager:a}=ia(Kw);return Ve(a!=null,"Expected drag drop context"),a}function DI(a,s){const i=zn(),r=us(()=>new II(i.getBackend()),[i]);return Ri(()=>(r.dragSourceOptions=a||null,r.reconnect(),()=>r.disconnectDragSource()),[r,a]),Ri(()=>(r.dragPreviewOptions=s||null,r.reconnect(),()=>r.disconnectDragPreview()),[r,s]),r}function AI(){const a=zn();return us(()=>new _I(a),[a])}class RI{beginDrag(){const s=this.spec,i=this.monitor;let r=null;return typeof s.item=="object"?r=s.item:typeof s.item=="function"?r=s.item(i):r={},r??null}canDrag(){const s=this.spec,i=this.monitor;return typeof s.canDrag=="boolean"?s.canDrag:typeof s.canDrag=="function"?s.canDrag(i):!0}isDragging(s,i){const r=this.spec,l=this.monitor,{isDragging:c}=r;return c?c(l):i===s.getSourceId()}endDrag(){const s=this.spec,i=this.monitor,r=this.connector,{end:l}=s;l&&l(i.getItem(),i),r.reconnect()}constructor(s,i,r){this.spec=s,this.monitor=i,this.connector=r}}function OI(a,s,i){const r=us(()=>new RI(a,s,i),[s,i]);return Lt(()=>{r.spec=a},[a]),r}function NI(a){return us(()=>{const s=a.type;return Ve(s!=null,"spec.type must be defined"),s},[a])}function MI(a,s,i){const r=zn(),l=OI(a,s,i),c=NI(a);Ri(function(){if(c!=null){const[h,p]=CI(c,l,r);return s.receiveHandlerId(h),i.receiveHandlerId(h),p}},[r,s,i,l,c])}function LI(a,s){const i=ok(a);Ve(!i.begin,"useDrag::spec.begin was deprecated in v14. Replace spec.begin() with spec.item(). (see more here - https://react-dnd.github.io/react-dnd/docs/api/use-drag)");const r=AI(),l=DI(i.options,i.previewOptions);return MI(i,r,l),[sk(i.collect,r,l),vI(l),yI(l)]}function PI(a){return us(()=>a.hooks.dropTarget(),[a])}function BI(a){const s=zn(),i=us(()=>new xI(s.getBackend()),[s]);return Ri(()=>(i.dropTargetOptions=a||null,i.reconnect(),()=>i.disconnectDropTarget()),[a]),i}function jI(){const a=zn();return us(()=>new wI(a),[a])}function FI(a){const{accept:s}=a;return us(()=>(Ve(a.accept!=null,"accept must be defined"),Array.isArray(s)?s:[s]),[s])}class zI{canDrop(){const s=this.spec,i=this.monitor;return s.canDrop?s.canDrop(i.getItem(),i):!0}hover(){const s=this.spec,i=this.monitor;s.hover&&s.hover(i.getItem(),i)}drop(){const s=this.spec,i=this.monitor;if(s.drop)return s.drop(i.getItem(),i)}constructor(s,i){this.spec=s,this.monitor=i}}function UI(a,s){const i=us(()=>new zI(a,s),[s]);return Lt(()=>{i.spec=a},[a]),i}function HI(a,s,i){const r=zn(),l=UI(a,s),c=FI(a);Ri(function(){const[h,p]=kI(c,l,r);return s.receiveHandlerId(h),i.receiveHandlerId(h),p},[r,s,l,i,c.map(d=>d.toString()).join("|")])}function WI(a,s){const i=ok(a),r=jI(),l=BI(i.options);return HI(i,r,l),[sk(i.collect,r,l),PI(l)]}function nk(a){let s=null;return()=>(s==null&&(s=a()),s)}function GI(a,s){return a.filter(i=>i!==s)}function VI(a,s){const i=new Set,r=c=>i.add(c);a.forEach(r),s.forEach(r);const l=[];return i.forEach(c=>l.push(c)),l}class KI{enter(s){const i=this.entered.length,r=l=>this.isNodeInDocument(l)&&(!l.contains||l.contains(s));return this.entered=VI(this.entered.filter(r),[s]),i===0&&this.entered.length>0}leave(s){const i=this.entered.length;return this.entered=GI(this.entered.filter(this.isNodeInDocument),s),i>0&&this.entered.length===0}reset(){this.entered=[]}constructor(s){this.entered=[],this.isNodeInDocument=s}}class YI{initializeExposedProperties(){Object.keys(this.config.exposeProperties).forEach(s=>{Object.defineProperty(this.item,s,{configurable:!0,enumerable:!0,get(){return console.warn(`Browser doesn't allow reading "${s}" until the drop event.`),null}})})}loadDataTransfer(s){if(s){const i={};Object.keys(this.config.exposeProperties).forEach(r=>{const l=this.config.exposeProperties[r];l!=null&&(i[r]={value:l(s,this.config.matchesTypes),configurable:!0,enumerable:!0})}),Object.defineProperties(this.item,i)}}canDrag(){return!0}beginDrag(){return this.item}isDragging(s,i){return i===s.getSourceId()}endDrag(){}constructor(s){this.config=s,this.item={},this.initializeExposedProperties()}}const rk="__NATIVE_FILE__",ak="__NATIVE_URL__",lk="__NATIVE_TEXT__",ck="__NATIVE_HTML__",w_=Object.freeze(Object.defineProperty({__proto__:null,FILE:rk,HTML:ck,TEXT:lk,URL:ak},Symbol.toStringTag,{value:"Module"}));function tg(a,s,i){const r=s.reduce((l,c)=>l||a.getData(c),"");return r??i}const Hg={[rk]:{exposeProperties:{files:a=>Array.prototype.slice.call(a.files),items:a=>a.items,dataTransfer:a=>a},matchesTypes:["Files"]},[ck]:{exposeProperties:{html:(a,s)=>tg(a,s,""),dataTransfer:a=>a},matchesTypes:["Html","text/html"]},[ak]:{exposeProperties:{urls:(a,s)=>tg(a,s,"").split(` -`),dataTransfer:a=>a},matchesTypes:["Url","text/uri-list"]},[lk]:{exposeProperties:{text:(a,s)=>tg(a,s,""),dataTransfer:a=>a},matchesTypes:["Text","text/plain"]}};function JI(a,s){const i=Hg[a];if(!i)throw new Error(`native type ${a} has no configuration`);const r=new YI(i);return r.loadDataTransfer(s),r}function sg(a){if(!a)return null;const s=Array.prototype.slice.call(a.types||[]);return Object.keys(Hg).filter(i=>{const r=Hg[i];return r!=null&&r.matchesTypes?r.matchesTypes.some(l=>s.indexOf(l)>-1):!1})[0]||null}const qI=nk(()=>/firefox/i.test(navigator.userAgent)),uk=nk(()=>!!window.safari);class k_{interpolate(s){const{xs:i,ys:r,c1s:l,c2s:c,c3s:d}=this;let h=i.length-1;if(s===i[h])return r[h];let p=0,f=d.length-1,b;for(;p<=f;){b=Math.floor(.5*(p+f));const v=i[b];if(vs)f=b-1;else return r[b]}h=Math.max(0,f);const y=s-i[h],w=y*y;return r[h]+l[h]*y+c[h]*w+d[h]*y*w}constructor(s,i){const{length:r}=s,l=[];for(let v=0;vs[v]{let W=new k_([0,.5,1],[p.y,p.y/b*_,p.y+_-b]).interpolate(w);return uk()&&c&&(W+=(window.devicePixelRatio-1)*_),W},S=()=>new k_([0,.5,1],[p.x,p.x/f*v,p.x+v-f]).interpolate(y),{offsetX:T,offsetY:E}=l,D=T===0||T,M=E===0||E;return{x:D?T:S(),y:M?E:$()}}let tx=class{get window(){if(this.globalContext)return this.globalContext;if(typeof window<"u")return window}get document(){var s;return!((s=this.globalContext)===null||s===void 0)&&s.document?this.globalContext.document:this.window?this.window.document:void 0}get rootElement(){var s;return((s=this.optionsArgs)===null||s===void 0?void 0:s.rootElement)||this.window}constructor(s,i){this.ownerDocument=null,this.globalContext=s,this.optionsArgs=i}};function sx(a,s,i){return s in a?Object.defineProperty(a,s,{value:i,enumerable:!0,configurable:!0,writable:!0}):a[s]=i,a}function C_(a){for(var s=1;s{this.sourcePreviewNodes.delete(s),this.sourcePreviewNodeOptions.delete(s)}}connectDragSource(s,i,r){this.sourceNodes.set(s,i),this.sourceNodeOptions.set(s,r);const l=d=>this.handleDragStart(d,s),c=d=>this.handleSelectStart(d);return i.setAttribute("draggable","true"),i.addEventListener("dragstart",l),i.addEventListener("selectstart",c),()=>{this.sourceNodes.delete(s),this.sourceNodeOptions.delete(s),i.removeEventListener("dragstart",l),i.removeEventListener("selectstart",c),i.setAttribute("draggable","false")}}connectDropTarget(s,i){const r=d=>this.handleDragEnter(d,s),l=d=>this.handleDragOver(d,s),c=d=>this.handleDrop(d,s);return i.addEventListener("dragenter",r),i.addEventListener("dragover",l),i.addEventListener("drop",c),()=>{i.removeEventListener("dragenter",r),i.removeEventListener("dragover",l),i.removeEventListener("drop",c)}}addEventListeners(s){s.addEventListener&&(s.addEventListener("dragstart",this.handleTopDragStart),s.addEventListener("dragstart",this.handleTopDragStartCapture,!0),s.addEventListener("dragend",this.handleTopDragEndCapture,!0),s.addEventListener("dragenter",this.handleTopDragEnter),s.addEventListener("dragenter",this.handleTopDragEnterCapture,!0),s.addEventListener("dragleave",this.handleTopDragLeaveCapture,!0),s.addEventListener("dragover",this.handleTopDragOver),s.addEventListener("dragover",this.handleTopDragOverCapture,!0),s.addEventListener("drop",this.handleTopDrop),s.addEventListener("drop",this.handleTopDropCapture,!0))}removeEventListeners(s){s.removeEventListener&&(s.removeEventListener("dragstart",this.handleTopDragStart),s.removeEventListener("dragstart",this.handleTopDragStartCapture,!0),s.removeEventListener("dragend",this.handleTopDragEndCapture,!0),s.removeEventListener("dragenter",this.handleTopDragEnter),s.removeEventListener("dragenter",this.handleTopDragEnterCapture,!0),s.removeEventListener("dragleave",this.handleTopDragLeaveCapture,!0),s.removeEventListener("dragover",this.handleTopDragOver),s.removeEventListener("dragover",this.handleTopDragOverCapture,!0),s.removeEventListener("drop",this.handleTopDrop),s.removeEventListener("drop",this.handleTopDropCapture,!0))}getCurrentSourceNodeOptions(){const s=this.monitor.getSourceId(),i=this.sourceNodeOptions.get(s);return C_({dropEffect:this.altKeyPressed?"copy":"move"},i||{})}getCurrentDropEffect(){return this.isDraggingNativeItem()?"copy":this.getCurrentSourceNodeOptions().dropEffect}getCurrentSourcePreviewNodeOptions(){const s=this.monitor.getSourceId(),i=this.sourcePreviewNodeOptions.get(s);return C_({anchorX:.5,anchorY:.5,captureDraggingState:!1},i||{})}isDraggingNativeItem(){const s=this.monitor.getItemType();return Object.keys(w_).some(i=>w_[i]===s)}beginDragNativeItem(s,i){this.clearCurrentDragSourceNode(),this.currentNativeSource=JI(s,i),this.currentNativeHandle=this.registry.addSource(s,this.currentNativeSource),this.actions.beginDrag([this.currentNativeHandle])}setCurrentDragSourceNode(s){this.clearCurrentDragSourceNode(),this.currentDragSourceNode=s;const i=1e3;this.mouseMoveTimeoutTimer=setTimeout(()=>{var r;return(r=this.rootElement)===null||r===void 0?void 0:r.addEventListener("mousemove",this.endDragIfSourceWasRemovedFromDOM,!0)},i)}clearCurrentDragSourceNode(){if(this.currentDragSourceNode){if(this.currentDragSourceNode=null,this.rootElement){var s;(s=this.window)===null||s===void 0||s.clearTimeout(this.mouseMoveTimeoutTimer||void 0),this.rootElement.removeEventListener("mousemove",this.endDragIfSourceWasRemovedFromDOM,!0)}return this.mouseMoveTimeoutTimer=null,!0}return!1}handleDragStart(s,i){s.defaultPrevented||(this.dragStartSourceIds||(this.dragStartSourceIds=[]),this.dragStartSourceIds.unshift(i))}handleDragEnter(s,i){this.dragEnterTargetIds.unshift(i)}handleDragOver(s,i){this.dragOverTargetIds===null&&(this.dragOverTargetIds=[]),this.dragOverTargetIds.unshift(i)}handleDrop(s,i){this.dropTargetIds.unshift(i)}constructor(s,i,r){this.sourcePreviewNodes=new Map,this.sourcePreviewNodeOptions=new Map,this.sourceNodes=new Map,this.sourceNodeOptions=new Map,this.dragStartSourceIds=null,this.dropTargetIds=[],this.dragEnterTargetIds=[],this.currentNativeSource=null,this.currentNativeHandle=null,this.currentDragSourceNode=null,this.altKeyPressed=!1,this.mouseMoveTimeoutTimer=null,this.asyncEndDragFrameId=null,this.dragOverTargetIds=null,this.lastClientOffset=null,this.hoverRafId=null,this.getSourceClientOffset=l=>{const c=this.sourceNodes.get(l);return c&&dk(c)||null},this.endDragNativeItem=()=>{this.isDraggingNativeItem()&&(this.actions.endDrag(),this.currentNativeHandle&&this.registry.removeSource(this.currentNativeHandle),this.currentNativeHandle=null,this.currentNativeSource=null)},this.isNodeInDocument=l=>!!(l&&this.document&&this.document.body&&this.document.body.contains(l)),this.endDragIfSourceWasRemovedFromDOM=()=>{const l=this.currentDragSourceNode;l==null||this.isNodeInDocument(l)||(this.clearCurrentDragSourceNode()&&this.monitor.isDragging()&&this.actions.endDrag(),this.cancelHover())},this.scheduleHover=l=>{this.hoverRafId===null&&typeof requestAnimationFrame<"u"&&(this.hoverRafId=requestAnimationFrame(()=>{this.monitor.isDragging()&&this.actions.hover(l||[],{clientOffset:this.lastClientOffset}),this.hoverRafId=null}))},this.cancelHover=()=>{this.hoverRafId!==null&&typeof cancelAnimationFrame<"u"&&(cancelAnimationFrame(this.hoverRafId),this.hoverRafId=null)},this.handleTopDragStartCapture=()=>{this.clearCurrentDragSourceNode(),this.dragStartSourceIds=[]},this.handleTopDragStart=l=>{if(l.defaultPrevented)return;const{dragStartSourceIds:c}=this;this.dragStartSourceIds=null;const d=nc(l);this.monitor.isDragging()&&(this.actions.endDrag(),this.cancelHover()),this.actions.beginDrag(c||[],{publishSource:!1,getSourceClientOffset:this.getSourceClientOffset,clientOffset:d});const{dataTransfer:h}=l,p=sg(h);if(this.monitor.isDragging()){if(h&&typeof h.setDragImage=="function"){const b=this.monitor.getSourceId(),y=this.sourceNodes.get(b),w=this.sourcePreviewNodes.get(b)||y;if(w){const{anchorX:v,anchorY:_,offsetX:$,offsetY:S}=this.getCurrentSourcePreviewNodeOptions(),D=ex(y,w,d,{anchorX:v,anchorY:_},{offsetX:$,offsetY:S});h.setDragImage(w,D.x,D.y)}}try{h==null||h.setData("application/json",{})}catch{}this.setCurrentDragSourceNode(l.target);const{captureDraggingState:f}=this.getCurrentSourcePreviewNodeOptions();f?this.actions.publishDragSource():setTimeout(()=>this.actions.publishDragSource(),0)}else if(p)this.beginDragNativeItem(p);else{if(h&&!h.types&&(l.target&&!l.target.hasAttribute||!l.target.hasAttribute("draggable")))return;l.preventDefault()}},this.handleTopDragEndCapture=()=>{this.clearCurrentDragSourceNode()&&this.monitor.isDragging()&&this.actions.endDrag(),this.cancelHover()},this.handleTopDragEnterCapture=l=>{if(this.dragEnterTargetIds=[],this.isDraggingNativeItem()){var c;(c=this.currentNativeSource)===null||c===void 0||c.loadDataTransfer(l.dataTransfer)}if(!this.enterLeaveCounter.enter(l.target)||this.monitor.isDragging())return;const{dataTransfer:h}=l,p=sg(h);p&&this.beginDragNativeItem(p,h)},this.handleTopDragEnter=l=>{const{dragEnterTargetIds:c}=this;if(this.dragEnterTargetIds=[],!this.monitor.isDragging())return;this.altKeyPressed=l.altKey,c.length>0&&this.actions.hover(c,{clientOffset:nc(l)}),c.some(h=>this.monitor.canDropOnTarget(h))&&(l.preventDefault(),l.dataTransfer&&(l.dataTransfer.dropEffect=this.getCurrentDropEffect()))},this.handleTopDragOverCapture=l=>{if(this.dragOverTargetIds=[],this.isDraggingNativeItem()){var c;(c=this.currentNativeSource)===null||c===void 0||c.loadDataTransfer(l.dataTransfer)}},this.handleTopDragOver=l=>{const{dragOverTargetIds:c}=this;if(this.dragOverTargetIds=[],!this.monitor.isDragging()){l.preventDefault(),l.dataTransfer&&(l.dataTransfer.dropEffect="none");return}this.altKeyPressed=l.altKey,this.lastClientOffset=nc(l),this.scheduleHover(c),(c||[]).some(h=>this.monitor.canDropOnTarget(h))?(l.preventDefault(),l.dataTransfer&&(l.dataTransfer.dropEffect=this.getCurrentDropEffect())):this.isDraggingNativeItem()?l.preventDefault():(l.preventDefault(),l.dataTransfer&&(l.dataTransfer.dropEffect="none"))},this.handleTopDragLeaveCapture=l=>{this.isDraggingNativeItem()&&l.preventDefault(),this.enterLeaveCounter.leave(l.target)&&(this.isDraggingNativeItem()&&setTimeout(()=>this.endDragNativeItem(),0),this.cancelHover())},this.handleTopDropCapture=l=>{if(this.dropTargetIds=[],this.isDraggingNativeItem()){var c;l.preventDefault(),(c=this.currentNativeSource)===null||c===void 0||c.loadDataTransfer(l.dataTransfer)}else sg(l.dataTransfer)&&l.preventDefault();this.enterLeaveCounter.reset()},this.handleTopDrop=l=>{const{dropTargetIds:c}=this;this.dropTargetIds=[],this.actions.hover(c,{clientOffset:nc(l)}),this.actions.drop({dropEffect:this.getCurrentDropEffect()}),this.isDraggingNativeItem()?this.endDragNativeItem():this.monitor.isDragging()&&this.actions.endDrag(),this.cancelHover()},this.handleSelectStart=l=>{const c=l.target;typeof c.dragDrop=="function"&&(c.tagName==="INPUT"||c.tagName==="SELECT"||c.tagName==="TEXTAREA"||c.isContentEditable||(l.preventDefault(),c.dragDrop()))},this.options=new tx(i,r),this.actions=s.getActions(),this.monitor=s.getMonitor(),this.registry=s.getRegistry(),this.enterLeaveCounter=new KI(this.isNodeInDocument)}}const hk=function(s,i,r){return new ox(s,i,r)},ix=$t([m.jsx("path",{d:"M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2M12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8"},"0"),m.jsx("path",{d:"M12.5 7H11v6l5.25 3.15.75-1.23-4.5-2.67z"},"1")],"AccessTime"),nx=$t(m.jsx("path",{d:"M19 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2m-2 10h-4v4h-2v-4H7v-2h4V7h2v4h4z"}),"AddBox"),rx=$t(m.jsx("path",{d:"M4 8h4V4H4zm6 12h4v-4h-4zm-6 0h4v-4H4zm0-6h4v-4H4zm6 0h4v-4h-4zm6-10v4h4V4zm-6 4h4V4h-4zm6 6h4v-4h-4zm0 6h4v-4h-4z"}),"Apps"),ax=$t(m.jsx("path",{d:"M9 2c-1.05 0-2.05.16-3 .46 4.06 1.27 7 5.06 7 9.54s-2.94 8.27-7 9.54c.95.3 1.95.46 3 .46 5.52 0 10-4.48 10-10S14.52 2 9 2"}),"Brightness3"),lx=$t(m.jsx("path",{d:"M20 8h-2.81c-.45-.78-1.07-1.45-1.82-1.96L17 4.41 15.59 3l-2.17 2.17C12.96 5.06 12.49 5 12 5s-.96.06-1.41.17L8.41 3 7 4.41l1.62 1.63C7.88 6.55 7.26 7.22 6.81 8H4v2h2.09c-.05.33-.09.66-.09 1v1H4v2h2v1c0 .34.04.67.09 1H4v2h2.81c1.04 1.79 2.97 3 5.19 3s4.15-1.21 5.19-3H20v-2h-2.09c.05-.33.09-.66.09-1v-1h2v-2h-2v-1c0-.34-.04-.67-.09-1H20zm-6 8h-4v-2h4zm0-4h-4v-2h4z"}),"BugReport"),cx=$t(m.jsx("path",{d:"M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12zm-1 4 6 6v10c0 1.1-.9 2-2 2H7.99C6.89 23 6 22.1 6 21l.01-14c0-1.1.89-2 1.99-2zm-1 7h5.5L14 6.5z"}),"FileCopy"),ux=$t(m.jsx("path",{d:"M7 2v11h3v9l7-12h-4l4-8z"}),"FlashOn"),dx=$t(m.jsx("path",{d:"M3.27 5 2 6.27l6.97 6.97L6.5 19h3l1.57-3.66L16.73 21 18 19.73 3.55 5.27zM6 5v.18L8.82 8h2.4l-.72 1.68 2.1 2.1L14.21 8H20V5z"}),"FormatClear"),hx=$t(m.jsx("path",{d:"M18 4H6v2l6.5 6L6 18v2h12v-3h-7l5-5-5-5h7z"}),"Functions"),pk=$t(m.jsx("path",{d:"M11 18h2v-2h-2zm1-16C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2m0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8m0-14c-2.21 0-4 1.79-4 4h2c0-1.1.9-2 2-2s2 .9 2 2c0 2-3 1.75-3 5h2c0-2.25 3-2.5 3-5 0-2.21-1.79-4-4-4"}),"HelpOutline"),px=$t(m.jsx("path",{d:"M21 3.01H3c-1.1 0-2 .9-2 2V9h2V4.99h18v14.03H3V15H1v4.01c0 1.1.9 1.98 2 1.98h18c1.1 0 2-.88 2-1.98v-14c0-1.11-.9-2-2-2M11 16l4-4-4-4v3H1v2h10z"}),"Input"),T_=$t(m.jsx("path",{d:"M18 8h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2m-6 9c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2m3.1-9H8.9V6c0-1.71 1.39-3.1 3.1-3.1s3.1 1.39 3.1 3.1z"}),"Lock"),gx=$t(m.jsx("path",{d:"M12 8c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2m0 2c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2m0 6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2"}),"MoreVert"),mx=$t(m.jsx("path",{d:"M12 2C6.49 2 2 6.49 2 12s4.49 10 10 10c1.38 0 2.5-1.12 2.5-2.5 0-.61-.23-1.2-.64-1.67-.08-.1-.13-.21-.13-.33 0-.28.22-.5.5-.5H16c3.31 0 6-2.69 6-6 0-4.96-4.49-9-10-9m5.5 11c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5m-3-4c-.83 0-1.5-.67-1.5-1.5S13.67 6 14.5 6s1.5.67 1.5 1.5S15.33 9 14.5 9M5 11.5c0-.83.67-1.5 1.5-1.5s1.5.67 1.5 1.5S7.33 13 6.5 13 5 12.33 5 11.5m6-4c0 .83-.67 1.5-1.5 1.5S8 8.33 8 7.5 8.67 6 9.5 6s1.5.67 1.5 1.5"}),"Palette"),bc=$t(m.jsx("path",{d:"M6 19h4V5H6zm8-14v14h4V5z"}),"Pause"),Wg=$t(m.jsx("path",{d:"M8 5v14l11-7z"}),"PlayArrow"),fx=$t(m.jsx("path",{d:"M11 5v5.59H7.5l4.5 4.5 4.5-4.5H13V5zm-5 9c0 3.31 2.69 6 6 6s6-2.69 6-6h-2c0 2.21-1.79 4-4 4s-4-1.79-4-4z"}),"PlayForWork"),$x=$t(m.jsx("path",{d:"M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14"}),"Search"),bx=$t(m.jsx("path",{d:"M10.59 9.17 5.41 4 4 5.41l5.17 5.17zM14.5 4l2.04 2.04L4 18.59 5.41 20 17.96 7.46 20 9.5V4zm.33 9.41-1.41 1.41 3.13 3.13L14.5 20H20v-5.5l-2.04 2.04z"}),"Shuffle"),vx=$t(m.jsx("path",{d:"M2 20h20v-4H2zm2-3h2v2H4zM2 4v4h20V4zm4 3H4V5h2zm-4 7h20v-4H2zm2-3h2v2H4z"}),"Storage"),yx=$t(m.jsx("path",{d:"M14 17H4v2h10zm6-8H4v2h16zM4 15h16v-2H4zM4 5v2h16V5z"}),"Subject"),_x=$t(m.jsx("path",{d:"M16 17.01V10h-2v7.01h-3L15 21l4-3.99zM9 3 5 6.99h3V14h2V6.99h3z"}),"SwapVert"),wx=$t(m.jsx("path",{d:"M7.41 18.59 8.83 20 12 16.83 15.17 20l1.41-1.41L12 14zm9.18-13.18L15.17 4 12 7.17 8.83 4 7.41 5.41 12 10z"}),"UnfoldLess"),kx=$t(m.jsx("path",{d:"M12 5.83 15.17 9l1.41-1.41L12 3 7.41 7.59 8.83 9zm0 12.34L8.83 15l-1.41 1.41L12 21l4.59-4.59L15.17 15z"}),"UnfoldMore"),Tc="data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20width='512'%20height='512'%20shape-rendering='geometricPrecision'%20image-rendering='optimizeQuality'%20fill-rule='evenodd'%20xmlns:v='https://vecta.io/nano'%3e%3cpath%20fill='%23efda4e'%20d='M-.5-.5h512v512H-.5V-.5z'/%3e%3cpath%20fill='%23020100'%20d='M308.5%20287.5c1.777-3.005%202.777-6.338%203-10%209.147-21.963%2025.48-35.463%2049-40.5%2021.999-4.173%2043.666-2.84%2065%204%2014.575%205.411%2025.575%2014.911%2033%2028.5l-1%202c-12.413%205.624-24.58%2011.624-36.5%2018-5.321-8.25-12.821-13.417-22.5-15.5-13.957-3.122-27.29-1.455-40%205-8.125%205.36-10.958%2012.86-8.5%2022.5%203.223%206.223%208.057%2010.723%2014.5%2013.5l64%2020c38.459%2016.085%2052.626%2044.585%2042.5%2085.5-7.572%2026.208-24.738%2042.041-51.5%2047.5-25.102%205.733-49.768%204.4-74-4-19.291-8.625-32.291-22.958-39-43%2011.266-8.887%2023.433-16.387%2036.5-22.5%203.117%206.896%206.784%2013.563%2011%2020%2012.705%2012.307%2027.872%2016.807%2045.5%2013.5%2022.189-3.504%2032.355-16.338%2030.5-38.5-2.833-6.833-7.667-11.667-14.5-14.5l-57-17c-36.004-11.84-52.67-36.673-50-74.5z'/%3e%3cpath%20fill='%23020200'%20d='M222.5%20238.5h43l-.5%20159c-2.688%2052.355-30.188%2076.855-82.5%2073.5-24.871-3.543-41.204-17.21-49-41l.5-2.5a12.14%2012.14%200%200%200%204.5-3.5c10.653-5.825%2021.32-11.325%2032-16.5%204.763%2021.72%2017.763%2028.887%2039%2021.5%204.616-2.618%207.783-6.451%209.5-11.5%201.163-5.968%202.163-11.968%203-18l.5-161z'/%3e%3cpath%20fill='%23615820'%20d='M311.5%20277.5c-.223%203.662-1.223%206.995-3%2010%20.223-3.662%201.223-6.995%203-10z'/%3e%3c/svg%3e",gk="data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20500%20500'%3e%3cpath%20fill='%234285f4'%20d='M44.271%2027.275l206.5%201v170l-58.5-36.5c-7.005-.916-12.505%201.584-16.5%207.5v147c4.625%204.412%2010.125%206.245%2016.5%205.5l57.5-35.5c.833%2054.003%201.356%20108.003.189%20162-1.272.546-45.599-.242-48.689%201.121-3.674%207.844-4.79%2011.207-13%2023.879-4.372%205.527-2.19%204.097-10.689%2012.258-5.166%202.748-4.191%203.45-14.311%206.242-17.67%201.983-35.336%201.983-53%200-9.535-3.774-10.879-4.163-18.526-11.22-5.562-4.39-11.131-11.803-11.974-15.28-4.068-7.881-3.42-9.116-5.5-13.5-3.672-1.503-35.798.203-40.746-1.335-5.823-2.314-2.946-.422-7.954-3.689-2.888-2.668-2.255-3.221-2.421-9.904L20.771%2050.275c.36-2.108-.41-5.806%202.522-11.615%204.343-5.852%205.374-7%2010.061-9.146%206.083-2.73%208.677-1.475%2010.917-2.239z'/%3e%3cpath%20d='M258.271%2030.275l154.63.407c5.654.559%2010.783%203.17%2014.37%207.093%204.907%204.408%206.204%208.723%207.5%2013.5v373c-.208%205.716-.297%207.982-4.848%2015.404-7.078%206.393-9.879%206.39-15.652%206.692-24.804%201.296-50.079%201.189-74.96%201.041-24.516-.014-68.46.89-81.5.391l-2.512-172.528c-20.083%2012.625-42.777%2025.125-63.028%2037.5-4.127%201.292-7.294.125-9.5-3.5l1-137c1.864-2.707%204.364-3.541%207.5-2.5%2020.366%2013.427%2064.35%2038.947%2065.581%2038.339l1.419-177.839z'%20fill='%23DDD'/%3e%3c/svg%3e",mk="data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20512%20512'%20width='32'%20height='32'%3e%3cpath%20fill='%23007acc'%20d='M-.5-.5h503l-1%20179h10v333h-421v-7h-91V-.5z'/%3e%3cpath%20fill='%230f81cf'%20d='M502.5-.5h9v179h-10l1-179z'/%3e%3cpath%20fill='%23fdfefe'%20d='M470.5%20227.5c.33%2017.508-.003%2034.841-1%2052-23.486-15.709-48.82-19.875-76-12.5-15.89%208.078-19.39%2019.911-10.5%2035.5%204.673%205.577%2010.173%2010.077%2016.5%2013.5l38%2019c17.945%209.278%2031.112%2023.112%2039.5%2041.5%201.352%203.22%202.186%206.553%202.5%2010a305.16%20305.16%200%200%201%201%2026c-3.553%2033.726-21.886%2054.559-55%2062.5-34.769%207.363-68.435%204.196-101-9.5-.167-19.003%200-38.003.5-57%2022.903%2021.314%2049.736%2029.147%2080.5%2023.5%2019.435-5.701%2025.268-17.868%2017.5-36.5-4.718-6.44-10.552-11.606-17.5-15.5a1552.42%201552.42%200%200%201-47-24c-27.679-19.331-38.846-45.831-33.5-79.5%206.43-26.433%2022.597-43.933%2048.5-52.5%2026.131-6.625%2052.464-7.292%2079-2a565.56%20565.56%200%200%201%2018%205.5z'/%3e%3cpath%20fill='%23fefefe'%20d='M122.5%20222.5h182v46h-65v206h-52v-206h-65v-46z'/%3e%3cpath%20fill='%2370b3e1'%20d='M470.5%20227.5c1.327%2017.505%201.327%2035.171%200%2053-.607-.124-.94-.457-1-1%20.997-17.159%201.33-34.492%201-52z'/%3e%3cpath%20fill='%236cafe0'%20d='M479.5%20386.5c1.465%205.09%202.132%2010.423%202%2016-.002%203.518-.335%206.851-1%2010a305.16%20305.16%200%200%200-1-26z'/%3e%3cpath%20fill='%231283cf'%20d='M-.5%20504.5h91v7h-91v-7z'/%3e%3c/svg%3e",fk="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI1MTIiIGhlaWdodD0iNTEyIj4KICAgIDxyYWRpYWxHcmFkaWVudCBpZD0ibXlHcmFkaWVudCI+CiAgICAgICAgPHN0b3Agb2Zmc2V0PSIxMCUiIHN0b3AtY29sb3I9IiMxQzJENUYiIC8+CiAgICAgICAgPHN0b3Agb2Zmc2V0PSI5NSUiIHN0b3AtY29sb3I9IiMwQ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QuOTQuNDU3IDEgMXoiLz4KPC9zdmc+";class _m extends _e.Component{isShowInstance;oldId;constructor(s){super(s),this.state={name:s.name,id:s.id,instance:s.instance||0,prefix:_m.getPrefix(s.id)},this.isShowInstance=!s.folder&&!!s.instances&&(!!s.instance||!!s.instances[0]||s.instances.length>1),this.oldId=s.id}static getPrefix(s){const i=(s||"").split(".");return i.pop(),i.join(".")}getId(s){return s=(s||"").replace(/[\\/\][*,;'"`<>?\s]/g,"_"),`${this.state.prefix}.${s}`}handleCancel=()=>{this.props.onClose()};handleOk=()=>{this.props.onRename(this.oldId,this.state.id,this.state.name,this.state.instance===0?0:this.state.instance||void 0),this.props.onClose()};handleChange=s=>{this.setState({name:s,id:this.getId(s)})};render(){return m.jsxs(Pt,{onClose:()=>!1,maxWidth:"md",fullWidth:!0,open:!0,"aria-labelledby":"confirmation-dialog-title",children:[m.jsx(Xt,{id:"confirmation-dialog-title",children:x.I18n.t("Rename")}),m.jsx(Wt,{children:m.jsxs("form",{noValidate:!0,autoComplete:"off",children:[m.jsx(Eo,{variant:"standard",style:{width:"100%"},id:"standard-name",autoFocus:!0,label:x.I18n.t("Name"),value:this.state.name,onKeyUp:s=>{s.key==="Enter"&&(s.preventDefault(),setTimeout(()=>this.handleOk(),200))},onChange:s=>this.handleChange(s.target.value),margin:"normal"}),m.jsx(Eo,{variant:"standard",id:"standard-name-id",style:{width:"100%"},label:x.I18n.t("ID"),value:this.state.id,disabled:!0,margin:"normal"}),this.isShowInstance&&m.jsxs(Di,{variant:"standard",children:[m.jsx(Ag,{htmlFor:"instance",children:x.I18n.t("Instance")}),m.jsx(Ai,{variant:"standard",value:this.state.instance,onChange:s=>this.setState({instance:parseInt(s.target.value,10)}),inputProps:{name:"instance",id:"instance"},children:this.props.instances.map(s=>m.jsx(it,{value:s,children:s||"0"},s))})]})]})}),m.jsxs(Bt,{children:[m.jsx(Ue,{variant:"contained",onClick:this.handleOk,color:"primary",startIcon:m.jsx(qo,{}),children:x.I18n.t("Ok")}),m.jsx(Ue,{color:"grey",variant:"contained",onClick:this.handleCancel,startIcon:m.jsx(so,{}),children:x.I18n.t("Cancel")})]})]})}}class Cx extends _e.Component{constructor(s){super(s),this.state={name:s.name,id:s.id}}handleCancel=()=>{this.props.onClose()};handleOk=()=>{this.props.onDelete(this.state.id),this.props.onClose()};render(){return m.jsxs(Pt,{onClose:()=>!1,maxWidth:"md",open:!0,"aria-labelledby":"confirmation-dialog-title",children:[m.jsx(Xt,{id:"confirmation-dialog-title",children:x.I18n.t("Are you sure?")}),m.jsxs(Wt,{children:[m.jsx(mc,{}),m.jsx("span",{style:{fontSize:14,fontWeight:"bold"},children:x.I18n.t("Delete %s",this.state.name)})]}),m.jsxs(Bt,{children:[m.jsx(Ue,{variant:"contained",onClick:this.handleOk,color:"primary",startIcon:m.jsx(qo,{}),children:x.I18n.t("Ok")}),m.jsx(Ue,{color:"grey",variant:"contained",onClick:this.handleCancel,startIcon:m.jsx(so,{}),children:x.I18n.t("Cancel")})]})]})}}const Tx=""+new URL("tileJS-C48gYbHw.png",import.meta.url).href,Sx=""+new URL("tileTS-CsXmgy4B.png",import.meta.url).href,Ex=""+new URL("tileBlockly-BMpdinN3.png",import.meta.url).href,Ix=""+new URL("tileRules-BkbaFIhs.png",import.meta.url).href,Ut={card:{maxWidth:345,minWidth:250,display:"inline-block",margin:"0 10px 0 10px"},media:{height:122},text:{maxWidth:218,minHeight:30},complexity:{fontWeight:"bold",fontStyle:"italic",marginBottom:8}};class Dn extends _e.Component{handleCancel=()=>{this.props.onClose()};static openHtml(s){const i=x.I18n.getLanguage();!s.includes("javascript.md")&&(i==="de"||i==="ru")&&(s=s.replace(/\/en\//,`/${i}/`));const r=window.open(s,"_blank");r==null||r.focus()}getJSCard(){return m.jsxs(Xl,{style:Ut.card,children:[m.jsxs(Zl,{onClick:()=>this.props.onClose&&this.props.onClose("Javascript/js"),children:[m.jsx(Ql,{style:Ut.media,image:Tx,title:"JavaScript"}),m.jsxs(ec,{children:[m.jsx("h2",{children:"JavaScript"}),m.jsx("div",{style:Ut.complexity,children:x.I18n.t("for programmers")}),m.jsx("div",{style:Ut.text,children:x.I18n.t("JS description")})]})]}),m.jsxs(tc,{children:[m.jsx(Ue,{size:"small",color:"primary",variant:"contained",onClick:()=>this.props.onClose&&this.props.onClose("Javascript/js"),children:x.I18n.t("Add")}),m.jsx(Ue,{size:"small",color:"secondary",onClick:()=>Dn.openHtml("https://github.com/ioBroker/ioBroker.javascript/blob/master/docs/en/javascript.md"),children:x.I18n.t("Learn More")})]})]})}getTSCard(){return m.jsxs(Xl,{style:Ut.card,children:[m.jsxs(Zl,{onClick:()=>this.props.onClose&&this.props.onClose("TypeScript/ts"),children:[m.jsx(Ql,{style:Ut.media,image:Sx,title:"TypeScript"}),m.jsxs(ec,{children:[m.jsx("h2",{children:"TypeScript"}),m.jsx("div",{style:Ut.complexity,children:x.I18n.t("for professionals")}),m.jsx("div",{style:Ut.text,children:x.I18n.t("TS description")})]})]}),m.jsxs(tc,{children:[m.jsx(Ue,{size:"small",color:"primary",variant:"contained",onClick:()=>this.props.onClose&&this.props.onClose("TypeScript/ts"),children:x.I18n.t("Add")}),m.jsx(Ue,{size:"small",color:"secondary",onClick:()=>Dn.openHtml("https://github.com/ioBroker/ioBroker.javascript/blob/master/docs/en/javascript.md"),children:x.I18n.t("Learn More")})]})]})}getBlocklyCard(){return m.jsxs(Xl,{style:Ut.card,children:[m.jsxs(Zl,{onClick:()=>this.props.onClose&&this.props.onClose("Blockly"),children:[m.jsx(Ql,{style:Ut.media,image:Ex,title:"Blockly"}),m.jsxs(ec,{children:[m.jsx("h2",{children:"Blockly"}),m.jsx("div",{style:Ut.complexity,children:x.I18n.t("normal")}),m.jsx("div",{style:Ut.text,children:x.I18n.t("Blockly description")})]})]}),m.jsxs(tc,{children:[m.jsx(Ue,{size:"small",color:"primary",variant:"contained",onClick:()=>this.props.onClose&&this.props.onClose("Blockly"),children:x.I18n.t("Add")}),m.jsx(Ue,{size:"small",color:"secondary",onClick:()=>Dn.openHtml("https://github.com/ioBroker/ioBroker.javascript/blob/master/docs/en/blockly.md"),children:x.I18n.t("Learn More")})]})]})}getRulesCard(){return m.jsxs(Xl,{style:Ut.card,children:[m.jsxs(Zl,{onClick:()=>this.props.onClose&&this.props.onClose("Rules"),children:[m.jsx(Ql,{style:Ut.media,image:Ix,title:"Rules"}),m.jsxs(ec,{children:[m.jsx("h2",{children:"Rules"}),m.jsx("div",{style:Ut.complexity,children:x.I18n.t("easy")}),m.jsx("div",{style:Ut.text,children:x.I18n.t("Rules description")})]})]}),m.jsxs(tc,{children:[m.jsx(Ue,{size:"small",color:"primary",variant:"contained",onClick:()=>this.props.onClose&&this.props.onClose("Rules"),children:x.I18n.t("Add")}),m.jsx(Ue,{size:"small",color:"secondary",onClick:()=>Dn.openHtml("https://github.com/ioBroker/ioBroker.javascript/blob/master/docs/en/javascript.md"),children:x.I18n.t("Learn More")})]})]})}render(){return m.jsxs(Pt,{onClose:()=>!1,maxWidth:"lg",fullWidth:!0,open:!0,"aria-labelledby":"confirmation-dialog-title",children:[m.jsx(Xt,{id:"confirmation-dialog-title",children:x.I18n.t("Add new script")}),m.jsxs(Wt,{style:{textAlign:"center"},children:[this.getRulesCard(),this.getBlocklyCard(),this.getJSCard(),this.getTSCard()]}),m.jsx(Bt,{children:m.jsx(Ue,{color:"grey",onClick:this.handleCancel,startIcon:m.jsx(so,{}),children:x.I18n.t("Cancel")})})]})}}class og extends _e.Component{isShowInstance;constructor(s){super(s),this.state={name:s.name||"Script",instance:s.instance||0,parent:s.parent,error:"",id:""},this.isShowInstance=!s.folder&&!!s.instances&&(!!s.instance||!!s.instances[0]||s.instances.length>1)}getId(s){return s=s||this.state.name||"",s=s.replace(/[\\/\][.*,;'"`<>?\s]/g,"_").trim().replace(/\.$/,"_"),`${this.state?this.state.parent:this.props.parent}.${s}`}handleOk=()=>{this.props.onAdd(this.getId(this.state.name),this.state.name,this.state.instance,this.props.type),this.props.onClose()};render(){var s;return m.jsxs(Pt,{onClose:()=>!1,maxWidth:"md",fullWidth:!0,open:!0,"aria-labelledby":"confirmation-dialog-title",children:[m.jsx(Xt,{id:"confirmation-dialog-title",children:this.props.title||x.I18n.t("Create new")}),m.jsx(Wt,{children:m.jsxs("form",{noValidate:!0,autoComplete:"off",children:[m.jsx(Eo,{variant:"standard",style:{width:"100%"},id:"standard-name",autoFocus:!0,error:!!this.state.error,label:x.I18n.t("Name"),value:this.state.name||"",helperText:this.state.error,slotProps:{input:{endAdornment:this.state.name?m.jsx(qe,{size:"small",onClick:()=>this.setState({name:""}),children:m.jsx(ZT,{})}):void 0}},onKeyUp:i=>{i.preventDefault(),i.key==="Enter"&&!this.state.error&&setTimeout(()=>this.handleOk(),200)},onChange:i=>{var c;const r=i.target.value,l=this.getId(r);r?(c=this.props.existingItems)!=null&&c.includes(l)?this.setState({name:r,id:l,error:x.I18n.t("Duplicate name")}):this.setState({name:r,id:l,error:""}):this.setState({name:r,id:l,error:x.I18n.t("Empty name is not allowed")})},margin:"normal"}),m.jsxs(Di,{variant:"standard",style:{width:"100%"},children:[m.jsx(Ag,{htmlFor:"parent",children:x.I18n.t("Folder")}),m.jsx(Ai,{variant:"standard",style:{width:"100%"},value:this.state.parent,onChange:i=>this.setState({parent:i.target.value}),inputProps:{name:"parent",id:"parent"},children:this.props.parents.map(i=>{const r=i.id.split(".");r.splice(0,2);const l=[];let c="script.js";return r.forEach(d=>{c+=`.${d}`;const h=this.props.parents.find(p=>p.id===c);h?l.push(h.name):l.push(d)}),l.length||l.push(i.name),m.jsx(it,{value:i.id,children:l.join(" / ")},i.id)})})]}),m.jsx(Eo,{variant:"standard",id:"standard-name-id",style:{width:"100%"},label:x.I18n.t("ID"),value:this.getId(),disabled:!0,margin:"normal"}),this.isShowInstance&&m.jsxs(Di,{variant:"standard",children:[m.jsx(Ag,{htmlFor:"instance",children:x.I18n.t("Instance")}),m.jsx(Ai,{variant:"standard",value:this.state.instance,onChange:i=>this.setState({instance:parseInt(i.target.value,10)}),inputProps:{name:"instance",id:"instance"},children:(s=this.props.instances)==null?void 0:s.map(i=>m.jsx(it,{value:i,children:i||"0"},`instance${i}`))})]})]})}),m.jsxs(Bt,{children:[m.jsx(Ue,{variant:"contained",onClick:this.handleOk,disabled:!!this.state.error,color:"primary",startIcon:m.jsx(qo,{}),children:x.I18n.t("Ok")}),m.jsx(Ue,{color:"grey",variant:"contained",onClick:()=>this.props.onClose(),startIcon:m.jsx(so,{}),children:x.I18n.t("Cancel")})]})]})}}const xx={title:a=>({background:a.palette.error.main,color:a.palette.error.contrastText,"&>h2":{color:a.palette.error.contrastText}})};class su extends _e.Component{handleOk=()=>{this.props.onClose()};render(){return m.jsxs(Pt,{open:!0,maxWidth:"sm",fullWidth:!0,onClose:()=>this.handleOk(),"aria-labelledby":"alert-dialog-title","aria-describedby":"alert-dialog-description",children:[m.jsx(Xt,{sx:xx.title,id:"alert-dialog-title",children:this.props.title||x.I18n.t("Error")}),m.jsx(Wt,{children:m.jsx(Dw,{id:"alert-dialog-description",children:this.props.text||x.I18n.t("Unknown error!")})}),m.jsx(Bt,{children:m.jsx(Ue,{variant:"contained",onClick:()=>this.handleOk(),color:"primary",autoFocus:!0,startIcon:m.jsx(qo,{}),children:x.I18n.t("Ok")})})]})}}const zr={icon:{width:24,height:24},filterWithButton:{width:"100%"},title:{fontWeight:"bold",marginTop:16}};class Dx extends _e.Component{constructor(s){super(s),this.state={instances:[],filter:window.localStorage.getItem("javascript.debug.filter")||"",showAskForStop:!1,jsInstance:window.localStorage.getItem("javascript.debug.instance")||"",jsInstanceHost:"",adapterToDebug:window.localStorage.getItem("javascript.debug.adapter")||""}}componentDidMount(){this.props.socket.getAdapterInstances().then(s=>{const i=s.filter(h=>{var p;return h&&!((p=h.common)!=null&&p.onlyWWW)}).map(h=>{var b,y,w;const p=h._id.replace(/^system\.adapter\./,""),[f]=p.split(".");return{id:p,enabled:(b=h.common)==null?void 0:b.enabled,host:(y=h.common)==null?void 0:y.host,icon:(w=h.common)!=null&&w.icon?`../../adapter/${f}/${h.common.icon}`:""}});i.sort((h,p)=>h.id>p.id?1:h.idh.id===this.state.jsInstance):null;let c;if(!this.state.jsInstance||!l){const h=i.find(p=>p.id.startsWith("javascript."));c=(h==null?void 0:h.host)||"",r=(h==null?void 0:h.id)||""}else c=(l==null?void 0:l.host)||"";let d=this.state.adapterToDebug||"";d&&!i.find(h=>h.id===d)&&(d=""),this.setState({instances:i,jsInstance:r,adapterToDebug:d,jsInstanceHost:c})})}handleOk=()=>{var s;if((s=this.state.instances.find(i=>i.id===this.state.adapterToDebug))!=null&&s.enabled){this.props.socket.getObject(`system.adapter.${this.state.adapterToDebug}`).then(i=>{i&&(i.common.enabled=!1,this.props.socket.setObject(i._id,i).then(()=>this.props.onDebug(this.state.jsInstance,this.state.adapterToDebug)))});return}this.props.onDebug(this.state.jsInstance,this.state.adapterToDebug)};renderJavascriptList(){const s=this.state.instances.filter(i=>i.id.startsWith("javascript."));return s.length<2?null:m.jsxs(Si,{children:[m.jsx("div",{style:zr.title,children:x.I18n.t("Host")}),m.jsx(Rg,{component:"nav",children:s.map(i=>m.jsxs(s_,{component:"div",selected:this.state.jsInstance===i.id,onClick:()=>this.setState({jsInstance:i.id,jsInstanceHost:i.host}),children:[m.jsx(Og,{children:m.jsx("img",{src:i.icon,alt:i.id,style:zr.icon})}),m.jsx(Ng,{primary:i.id})]},i.id))})]})}renderInstances(){if(!this.state.jsInstance)return m.jsx(Si,{});const s=this.state.instances.filter(i=>i.id!==this.state.jsInstance&&i.host===this.state.jsInstanceHost&&(!this.state.filter||i.id.includes(this.state.filter.toLowerCase())));return m.jsxs(Si,{children:[m.jsx("div",{style:zr.title,children:x.I18n.t("Instances")}),m.jsx(Rg,{component:"nav",children:s.map(i=>m.jsxs(s_,{selected:this.state.adapterToDebug===i.id,onDoubleClick:()=>this.setState({adapterToDebug:i.id},()=>this.handleOk()),onClick:()=>this.setState({adapterToDebug:i.id}),children:[m.jsx(Og,{children:m.jsx("img",{src:i.icon,alt:i.id,style:zr.icon})}),m.jsx(Ng,{primary:i.id})]},i.id))})]})}render(){return m.jsxs(Pt,{maxWidth:"md",fullWidth:!1,open:!0,onClose:()=>!1,"aria-labelledby":"confirmation-dialog-title",children:[m.jsx(Xt,{id:"confirmation-dialog-title",children:this.props.title||x.I18n.t("Debug instance")}),m.jsx(Wt,{children:m.jsxs(Si,{container:!0,direction:"column",children:[m.jsx(Si,{children:m.jsx(Pn,{style:zr.filterWithButton,value:this.state.filter,placeholder:x.I18n.t("Filter"),onChange:s=>{this.setState({filter:s.target.value}),window.localStorage.setItem("javascript.debug.filter",s.target.value)},endAdornment:m.jsx(Aw,{position:"end",children:this.state.filter?m.jsx(qe,{size:"small","aria-label":"toggle password visibility",onClick:()=>this.setState({filter:""}),children:m.jsx(Mw,{})}):""})})}),m.jsx(Si,{children:m.jsxs(Si,{container:!0,children:[this.renderJavascriptList(),this.renderInstances()]})})]})}),m.jsxs(Bt,{children:[m.jsx(Ue,{variant:"contained",onClick:this.handleOk,disabled:!this.state.jsInstance||!this.state.adapterToDebug,color:"primary",startIcon:m.jsx(qo,{}),children:x.I18n.t("Start")}),m.jsx(Ue,{color:"grey",variant:"contained",onClick:()=>this.props.onClose(),startIcon:m.jsx(so,{}),children:x.I18n.t("Close")})]})]})}}function $k(a){if(!a)throw new Error("Password must be a non-empty string.")}function Gg(a){return new TextEncoder().encode(a)}function Ax(a){return new TextDecoder().decode(a)}function Rx(a){let s="";for(let i=0;i({height:a.toolbar.height}),toolbarButtons:a=>({color:a.palette.mode==="dark"?"white !important":"black !important"}),iconButtonsDisabled:{filter:"grayscale(100%)",opacity:.5},toolbarSearch:{width:"calc(100% - 105px)",lineHeight:"34px",marginLeft:5},iconButtons:{width:32,height:32,padding:2},iconDropdownMenu:{paddingRight:5},menu:{width:"100%",height:"100%"},innerMenu:{width:"100%",height:"calc(100% - 76px)",overflowX:"hidden",overflowY:"auto"},listItemIcon:{minWidth:32},scriptIcon:{width:18,height:18,borderRadius:2,marginTop:4,marginBottom:4,marginLeft:8,marginRight:4},folder:{cursor:"pointer",padding:0,userSelect:"none"},folderReorder:{opacity:.3,transitionDuration:"0.5s",transitionProperty:"opacity"},folderIcon:{width:20,height:20},folderIconReorder:{paddingTop:4,paddingBottom:4,paddingLeft:8,paddingRight:4},folderIconNoReorder:{cursor:"pointer",paddingTop:4,paddingBottom:4,paddingLeft:8,paddingRight:4},script:{cursor:"pointer",padding:0,userSelect:"none"},scriptReorder:{opacity:1,transitionDuration:"0.5s",transitionProperty:"opacity"},reorder:{},selected:window.vendorPrefix?a=>({backgroundColor:a.palette.primary.main,color:a.palette.text.primary}):{backgroundColor:"#164477",color:"white"},instances:{fontSize:"smaller",fontWeight:"bold",marginRight:4},childrenCount:{fontSize:10,opacity:.4},footer:{height:24,display:"flex"},footerButtons:a=>({"& img":{color:a.palette.mode==="dark"?"#ffffff":"#111111",cursor:"pointer",mt:"1px",mr:"2px",height:22,width:22,"&:hover":{backgroundColor:"#dbdbdb"}},"& svg":{color:a.palette.mode==="dark"?"#ffffff":"#111111",cursor:"pointer",mt:"1px",mr:"2px",height:22,width:22,"&:hover":{backgroundColor:"#dbdbdb"}}}),footerButtonsRight:{float:"right"}},Tn={Blockly:gk,"Javascript/js":Tc,def:Tc,Rules:fk,"TypeScript/ts":mk};function Kg(a,s,i){var r;return i=i||x.I18n.getLanguage(),(r=s==null?void 0:s.common)!=null&&r.name?typeof s.common.name=="object"?(s.common.name[i]||s.common.name.en||a.replace(/^script\.js./,"")).toString():s.common.name.toString():a.replace(/^script\.js./,"")}function E_(a){var l;const s=[{id:qt,depth:0,index:0,parent:null,title:"root",type:"folder",parentIndex:null}],i=Object.keys(a);for(let c=0;c1?h.join("."):null,instance:d.common.engine?parseInt(d.common.engine.split(".").pop(),10)||0:null,index:0,parentIndex:0}):s.push({id:i[c],title:Kg(i[c],d),depth:h.length-1,type:"folder",parent:h.length>1?h.join("."):null,index:0,parentIndex:null})}let r;do r=!1,s.forEach(c=>{if(c.parent&&!s.find(h=>h.id===c.parent)){const h=c.parent.split(".");h.pop(),s.push({id:c.parent,title:c.parent.split(".").pop()||"",depth:h.length-1,type:"folder",parent:h.length>1?h.join("."):null,index:0,parentIndex:null}),r=!0}});while(r);return s.sort((c,d)=>{const h=c.id.toLowerCase(),p=d.id.toLowerCase();return c.type==="folder"&&d.type!=="folder"?-1:d.type==="folder"&&c.type!=="folder"||h>p?1:hc.index=d),s.forEach(c=>{if(c.parent){const d=s.find(h=>h.id===c.parent);d&&(c.parentIndex=d.index)}}),s}function Lx(a){const{onDrop:s}=a,[{isOver:i,isOverAny:r},l]=WI({accept:"script",drop:c=>i?s(c):void 0,collect:c=>({isOver:c.isOver({shallow:!0}),isOverAny:c.isOver()})});return m.jsx("div",{ref:l,style:{background:i?"#40adff":void 0,opacity:r?.7:void 0},children:a.children},a.folderName)}function I_(a){const{name:s}=a,[{opacity:i},r]=LI({type:"script",item:()=>({name:s}),collect:l=>({opacity:l.isDragging()?.3:1})});return m.jsx("div",{ref:r,style:{opacity:i,transform:"translate3d(0, 0, 0)"},children:a.children},s)}class So extends _e.Component{inputRef;filterTimer;problems;problemsTimer;onProblemUpdatedBound;parent=null;constructor(s){super(s);const i=window.localStorage?window.localStorage.getItem("SideMenu.expanded"):"[]";let r;try{r=JSON.parse(i||"[]")||[]}catch{r=[]}this.inputRef=_e.createRef(),this.state={listItems:E_(s.scripts||{}),expanded:r,problems:[],reorder:!1,themeName:this.props.themeName,selected:window.localStorage&&window.localStorage.getItem("SideMenu.selected")||null,creatingScript:null,creatingFolder:!1,copingScript:"",renaming:null,deleting:null,choosingType:!1,errorText:"",instances:s.instances||[],menuOpened:!1,menuAnchorEl:null,menuAnchorFilterEl:null,searchMode:!1,expertMode:this.props.expertMode,searchText:"",width:this.props.width||300,typeFilter:window.localStorage&&window.localStorage.getItem("SideMenu.typeFilter")||"",statusFilter:window.localStorage&&window.localStorage.getItem("SideMenu.statusFilter")||"",runningInstances:this.props.runningInstances||{},scriptsHash:s.scriptsHash,showAdapterDebug:!1,isAllZeroInstances:!1,showExportDialog:!1};const l=this.ensureSelectedIsVisible();l&&Object.assign(this.state,{expanded:l}),this.filterTimer=null,Object.assign(this.state,{isAllZeroInstances:this.getIsAllZeroInstances()}),this.problems=null,this.problemsTimer=null,this.onProblemUpdatedBound=this.onProblemUpdated.bind(this)}readProblems(s,i){var r,l;if(i||(i=Object.keys(this.props.scripts)),!i||!i.length)s&&s();else{const c=i.shift(),d=this.props.scripts[c];if(((r=this.props.scripts)==null?void 0:r[c].type)==="script"&&((l=d.common)!=null&&l.enabled)&&!c.match(/^script\.js\.global\./)){const h=d.common.engine.split(".").pop(),p=this,f=`javascript.${h}.scriptProblem.${c.substring(qt.length+1)}`;this.props.socket.getState(f).then(b=>{p.onProblemUpdated(f,b),setTimeout(()=>p.readProblems(s,i),0)})}else setTimeout(()=>this.readProblems(s,i),0)}}componentDidMount(){this.readProblems(()=>{this.props.instances.forEach(s=>{this.props.socket.subscribeState(`javascript.${s}.scriptProblem.*`,this.onProblemUpdatedBound)})})}componentWillUnmount(){this.props.instances.forEach(s=>{this.props.socket.unsubscribeState(`javascript.${s}.scriptProblem.*`,this.onProblemUpdatedBound)})}onProblemUpdated(s,i){if(!i||!s)return;s=`${qt}.${s.replace(/^javascript\.\d+\.scriptProblem\./,"")}`,this.problems||(this.problems=JSON.parse(JSON.stringify(this.state.problems))||[]);let r=!1;if(i.val)this.problems.includes(s)||(this.problems.push(s),r=!0);else{const l=this.problems.indexOf(s);l!==-1&&(this.problems.splice(l,1),r=!0)}r&&!this.problemsTimer&&(this.problemsTimer=setTimeout(()=>{this.problemsTimer=null,this.setState({problems:this.problems}),this.problems=null},300))}static filterListStatic(s,i,r,l,c){i=JSON.parse(JSON.stringify(i));let d=!1;const h={listItems:i};if(s&&r&&l){const p=l.toLowerCase();if(i.forEach(f=>{var v;const b=f.title.toLowerCase();f.filteredPartly=!1;let y=b.includes(p);const w=(v=c==null?void 0:c[f.id])==null?void 0:v.common;if(!y&&(w!=null&&w.source))if(w.engineType==="Blockly"){const _=w.source.lastIndexOf("//");y=w.source.substring(0,_).toLowerCase().includes(p)}else y=w.source.toLowerCase().includes(p);y?f.filtered&&(f.filtered=!1,d=!0):f.filtered||(f.filtered=!0,d=!0)}),d)for(let f=i.length-1;f>=0;f--){const b=i[f];if(!b.filtered||b.filteredPartly){let y=b;do y!=null&&y.parent&&i[y.parentIndex]&&(d=!0,i[y.parentIndex].filteredPartly=!0),y=y!=null&&y.parent&&i[y.parentIndex]?i[y.parentIndex]:null;while(y)}}}else i.forEach(p=>{(p.filtered||p.filteredPartly)&&(p.filtered=!1,p.filteredPartly=!1,d=!0)}),s||(h.searchText="",h.searchMode=!1,d=!0);return d?h:null}filterList(s,i){const r=So.filterListStatic(s,this.state.listItems,this.state.searchMode,this.state.searchText,this.props.scripts);r?this.setState(r,()=>i&&i()):i&&i()}static ensureSelectedIsVisibleStatic(s,i,r){i=JSON.parse(JSON.stringify(i));let l=!1,c=typeof s=="object"?s:r.find(d=>d.id===s);do{if(c!=null&&c.parent){const d=c.parent;c=r.find(h=>h.id===d)}else c=void 0;c&&(i.includes(c.id)||(i.push(c.id),l=!0))}while(c);return l?i:null}ensureSelectedIsVisible(s,i){return So.ensureSelectedIsVisibleStatic(s||this.state.selected,i||this.state.expanded,this.state.listItems)}static getDerivedStateFromProps(s,i){const r={};let l=!1;if(i.expertMode!==s.expertMode&&(l=!0,r.expertMode=s.expertMode),i.scriptsHash!==s.scriptsHash&&s.scripts){const c=E_(s.scripts||{});if(r.listItems=c,i.searchText){const p=So.filterListStatic(!0,c,i.searchMode,i.searchText,s.scripts);p&&Object.assign(r,p)}const d=So.getIsAllZeroInstancesStatic(c,s.instances||[]),h=So.ensureSelectedIsVisibleStatic(i.selected,i.expanded,i.listItems);r.isAllZeroInstances=d,h&&(r.expanded=h),l=!0}if(i.width!==s.width&&(l=!0,r.width=s.width),i.themeName!==s.themeName&&(l=!0,r.themeName=s.themeName),s.selectId&&i.selected!==s.selectId){const c=i.listItems.find(d=>d.id===s.selectId);if(!i.reorder&&c){const d=So.ensureSelectedIsVisibleStatic(c,i.expanded,i.listItems);r.selected=c.id,d&&(r.expanded=d),l=!0,window.localStorage&&window.localStorage.setItem("SideMenu.selected",c.id)}}return l?r:null}static getIsAllZeroInstancesStatic(s,i){let r=!i[0]&&i.length<=1;return r&&s.forEach(l=>{l.type!=="folder"&&l.instance!==0&&(r=!1)}),r}getIsAllZeroInstances(s,i){return s=s||this.state.listItems,i=i||this.state.instances,So.getIsAllZeroInstancesStatic(s||this.state.listItems,i||this.state.instances)}saveExpanded(s){window.localStorage.setItem("SideMenu.expanded",JSON.stringify(s||this.state.expanded))}showError(s){this.setState({errorText:s})}onToggle(s,i){if(i==null||i.stopPropagation(),s===qt)return;const r=[...this.state.expanded],l=r.indexOf(s);l!==-1?(r.splice(l,1),this.state.selected&&this.state.selected.startsWith(`${s}.`)&&window.localStorage&&window.localStorage.setItem("SideMenu.selected",s)):(r.push(s),r.sort()),this.setState({expanded:r}),this.saveExpanded(r)}renderItemButtonsOnEnd(s,i){if(this.state.reorder)return null;if(s.type!=="folder"){let r=s.enabled?ig:ng;return s.enabled&&this.state.problems.includes(s.id)&&(r=S_),[m.jsx(qe,{onClick:l=>{l.stopPropagation(),this.props.onEnableDisable&&this.props.onEnableDisable(s.id,!s.enabled)},title:s.enabled?x.I18n.t("Pause script"):x.I18n.t("Run script"),disabled:this.props.debugMode,style:{...Pe.iconButtons,...this.props.debugMode?Pe.iconButtonsDisabled:void 0,color:r},size:"medium",children:s.enabled?m.jsx(bc,{}):m.jsx(Wg,{})},"startStop"),this.state.width>Ur?m.jsx(qe,{style:this.props.debugMode?Pe.iconButtonsDisabled:void 0,title:x.I18n.t("Delete script"),disabled:s.id===To||s.id===Cn||this.props.debugMode,onClick:l=>this.onDelete(s,l),size:"medium",children:m.jsx(mc,{})},"delete"):null,m.jsx(qe,{style:this.props.debugMode?Pe.iconButtonsDisabled:void 0,disabled:this.props.debugMode,title:x.I18n.t("Edit script or just double click"),onClick:l=>this.onEdit(s,l),size:"medium",children:m.jsx(px,{})},"openInEdit")]}return this.state.width>Ur&&s.id!==qt&&s.id!==Cn&&s.id!==To&&!(i!=null&&i.length)?m.jsx(qe,{style:this.props.debugMode?Pe.iconButtonsDisabled:void 0,title:x.I18n.t("Delete folder"),disabled:s.id===To||s.id===Cn||this.props.debugMode,onClick:r=>this.onDelete(s,r),size:"medium",children:m.jsx(mc,{})},"delete"):null}onDelete(s,i){return i==null||i.stopPropagation(),new Promise(r=>{if(!s){r();return}typeof s!="object"?this.setState({deleting:s},()=>r()):this.setState({deleting:s.id},()=>r())})}onEdit(s,i){this.onClick(s,i),this.props.onEdit&&this.props.onEdit(s.id)}getTextStyle(s){return!this.state.reorder&&s.type!=="folder"?{width:`calc(100% - ${this.state.width>Ur?185:137}px)`,overflow:"hidden",whiteSpace:"nowrap",flex:"none",padding:"0 16px 0 0"}:{whiteSpace:"nowrap",padding:"0 16px 0 0"}}onClick(s,i){if(i==null||i.stopPropagation(),!this.state.reorder&&s){const r=this.ensureSelectedIsVisible(s),l={selected:s.id};r&&(l.expanded=r),this.setState(l),window.localStorage&&window.localStorage.setItem("SideMenu.selected",s.id)}}onDblClick(s,i){i==null||i.stopPropagation(),!this.state.reorder&&(s.type==="folder"?this.onToggle(s.id):this.onEdit(s))}isFilteredOut(s){var i,r;return s.filtered&&!s.filteredPartly||this.state.typeFilter&&s.type!=="folder"&&s.type.toLowerCase()!==this.state.typeFilter.toLowerCase()||!this.state.expertMode&&((r=(i=this.props.scripts[s.id])==null?void 0:i.native)!=null&&r.protected)||this.state.statusFilter&&s.type!=="folder"&&(this.state.statusFilter==="running"&&!s.enabled||this.state.statusFilter==="paused"&&s.enabled||this.state.statusFilter==="problems"&&(!s.enabled||this.state.problems.indexOf(s.id)===-1))?!0:s.id===To&&!this.state.expertMode}renderListItem(s,i,r){var w,v;if(s.id===qt&&!this.state.reorder)return null;const l=(this.state.reorder?s.depth:s.depth-1)*Mx;let c=s.title;if(this.state.searchText){const _=c.toLowerCase().indexOf(this.state.searchText.toLowerCase());_!==-1&&(c=[m.jsx("span",{children:c.substring(0,_)},"first"),m.jsx("span",{style:{color:"orange"},children:c.substring(_,_+this.state.searchText.length)},"second"),m.jsx("span",{children:c.substring(_+this.state.searchText.length)},"third")])}if(!this.state.isAllZeroInstances&&s.type!=="folder"){const _=this.state.runningInstances[`system.adapter.javascript.${s.instance}`];c=[m.jsxs("span",{title:`${x.I18n.t("Instance")} ${s.instance}${_?"":` (${x.I18n.t("not running")})`}`,style:{...Pe.instances,color:_?ig:ng},children:["[",s.instance,"]"]},"instance"),m.jsx("span",{children:c},"title")]}const d=this.state.reorder&&!this.props.debugMode,h={marginLeft:l,cursor:s.type==="folder"&&d?"default":"inherit",width:`calc(100% - ${l}px)`};d||(h.opacity=s.filteredPartly?.5:1),s.id===To&&s.id!==this.state.selected&&(h.color="#00a200");let p=s.id===qt;!p&&i&&(p=this.state.expanded.includes(s.id));let f;s.type==="folder"?f={...Pe.folderIcon,...d?Pe.folderIconReorder:Pe.folderIconNoReorder}:f={...Pe.scriptIcon},s.id===To?f.color="#356956":s.id===Cn&&(f.color="#4899e1");let b=null;(r&&r.length||i&&i.length)&&(b=m.jsx("span",{style:Pe.childrenCount,children:r&&r.length!==i.length?`${r.length}(${i.length})`:i.length}));const y={...s.type==="folder"?Pe.folder:Pe.script,...d?Pe.reorder:void 0,...d&&s.type!=="folder"?Pe.scriptReorder:void 0,...d&&s.type==="folder"?Pe.folderReorder:void 0,...h};return m.jsxs(LT,{style:y,sx:s.id===this.state.selected&&!d?Pe.selected:void 0,className:x.Utils.clsx(d&&s.type==="folder"&&"folder-reorder",d&&s.type!=="folder"&&"script-reorder"),onClick:_=>this.onClick(s,_),onDoubleClick:_=>this.onDblClick(s,_),secondaryAction:this.renderItemButtonsOnEnd(s,i),children:[(v=(w=this.props.scripts[s.id])==null?void 0:w.native)!=null&&v.protected?m.jsx(T_,{style:{color:"orange",position:"absolute",right:5,width:10,height:10}}):null,m.jsx(Og,{style:Pe.listItemIcon,children:s.type==="folder"?d||p?m.jsx(QT,{style:f,onClick:_=>!d&&this.onToggle(s.id,_)}):m.jsx(eS,{style:f,onClick:_=>!d&&this.onToggle(s.id,_)}):m.jsx("img",{style:f,alt:s.type,src:Tn[s.type]||Tn.def})}),m.jsx(Ng,{sx:{"& .MuiListItemText-primary":s.id===this.state.selected&&!d?Pe.selected:void 0},style:this.getTextStyle(s),primary:m.jsxs("span",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[c,b]})})]},s.id)}onDragFinish(s,i){let r=`${i}.${s.split(".").pop()}`;r!==s&&(this.state.listItems.find(l=>l.id===r)&&(r+=`_${x.I18n.t("copy")}`),this.props.onRename&&this.props.onRename(s,r))}renderOneItem(s,i){const r=this.state.statusFilter||this.state.typeFilter?s.filter(f=>f.parent===i.id?!this.isFilteredOut(f):!1):[],l=s.filter(f=>f.parent===i.id);if(this.isFilteredOut(i)||i.type==="folder"&&(this.state.statusFilter||this.state.typeFilter)&&!r.length)return null;const c=this.state.reorder&&!this.props.debugMode,d=this.renderListItem(i,l,r),h=[];let p;return l&&(c||this.state.expanded.includes(i.id)||i.id===qt)&&(p=l.map(f=>this.renderOneItem(s,f))),c?i.type==="folder"?h.push(m.jsxs(Lx,{onDrop:f=>this.onDragFinish(f.name,i.id),folderName:i.id,children:[m.jsx(I_,{name:i.id,children:d},`draggable_${i.id}`),p||null]},`droppable_${i.id}`)):h.push(m.jsxs(I_,{name:i.id,children:[d,p||null]},`draggable_${i.id}`)):(h.push(d),p==null||p.forEach(f=>h.push(f))),h}renderAllItems(s){const i=s.filter(r=>!r.parent).map(r=>this.renderOneItem(s,r));return m.jsx(Rg,{dense:!0,disablePadding:!0,sx:Pe.mainList,children:i})}onAddNew(s){s==null||s.stopPropagation();let i=this.state.listItems.find(l=>l.id===this.state.selected),r=qt;for(;i&&i.type!=="folder";)i=this.state.listItems[i.parentIndex];i&&(r=i.id),this.parent=r,this.setState({choosingType:!0})}onCopy(s,i){s==null||s.stopPropagation();let r=this.state.listItems.find(c=>c.id===i),l=qt;for(;r&&r.type!=="folder";)r=this.state.listItems[r.parentIndex];r&&(l=r.id),this.parent=l,this.setState({copingScript:i||""})}onAddNewFolder(s){s==null||s.stopPropagation();let i=this.state.listItems.find(l=>l.id===this.state.selected),r=qt;for(;i&&i.type!=="folder";)i=this.state.listItems[i.parentIndex];i&&(r=i.id),this.parent=r,this.setState({creatingFolder:!0})}onRename(s){s==null||s.stopPropagation(),this.setState({renaming:this.state.selected})}getUniqueName(s){let i=1,r=`${x.I18n.t("Script")} `;if(s){const l=Kg(s,this.props.scripts[s]),c=l.match(/\d+$/);c?(r=l.replace(/\d+$/,""),i=parseInt(c[0],10)+1):r=l}for(;this.state.listItems.find(l=>l.id===`${this.parent}.${r.replace(/\.\s/g,"_")}${i}`);)i++;return r+i}getUniqueFolderName(){let s=1;for(;this.state.listItems.find(i=>i.id===`${this.parent}.${x.I18n.t("Folder")}_${s}`);)s++;return`${x.I18n.t("Folder")} ${s}`}onCloseMenu(s){this.setState({menuOpened:!1,menuAnchorEl:null,menuAnchorFilterEl:null},s)}getMainMenu(s,i){var l,c,d,h;const r=this.state.expertMode&&!!Object.keys(this.props.changedScripts).find(p=>{var f,b;return this.props.changedScripts[p]&&((b=(f=this.props.scripts[p])==null?void 0:f.native)==null?void 0:b.protected)});return m.jsxs(pm,{id:"long-menu",anchorEl:this.state.menuAnchorEl,open:this.state.menuOpened,onClose:()=>this.setState({menuOpened:!1,menuAnchorEl:null}),slotProps:{paper:{style:{maxHeight:Nx*7.5}}},children:[this.state.width<=Ur?m.jsxs(it,{disabled:this.props.debugMode||!this.state.selected||this.state.selected===To||this.state.selected===Cn||!!(s!=null&&s.length),onClick:p=>{if(p.stopPropagation(),p.preventDefault(),this.state.listItems.find(f=>f.parent===this.state.selected)){this.showError(x.I18n.t("Cannot delete non empty item!"));return}this.setState({menuOpened:!1,menuAnchorEl:null},()=>this.onDelete(this.state.selected).then(()=>{}))},children:[m.jsx(mc,{style:{...Pe.iconDropdownMenu,color:"red"}}),x.I18n.t("Delete")]},"delete"):null,m.jsxs(it,{disabled:this.props.debugMode||r,selected:this.state.expertMode,onClick:p=>{p.stopPropagation(),p.preventDefault(),this.onCloseMenu(()=>this.props.onExpertModeChange&&this.props.onExpertModeChange(!this.state.expertMode))},children:[m.jsx(x.IconExpert,{style:{...Pe.iconDropdownMenu,color:this.state.expertMode?"orange":"inherit"}}),x.I18n.t("Expert mode")]},"expertMode"),this.props.onExport&&m.jsxs(it,{onClick:p=>{p.stopPropagation(),p.preventDefault(),this.onCloseMenu(()=>this.setState({showExportDialog:!0}))},children:[m.jsx(kc,{style:Pe.iconDropdownMenu}),x.I18n.t("Export all scripts")]},"exportAll"),this.props.onImport&&m.jsxs(it,{disabled:this.props.debugMode,onClick:p=>{p.stopPropagation(),p.preventDefault(),this.onCloseMenu(()=>this.props.onImport())},children:[m.jsx(Lg,{style:Pe.iconDropdownMenu}),x.I18n.t("Import scripts")]},"import"),this.props.onThemeChange&&m.jsxs(it,{onClick:()=>this.onCloseMenu(()=>{this.props.onThemeChange&&this.props.onThemeChange(x.Utils.toggleTheme(this.state.themeName))}),children:[m.jsx(mx,{style:Pe.iconDropdownMenu}),x.I18n.t('Change theme (actual "%s")',this.state.themeName)]},"dark"),this.props.onAddNew&&m.jsxs(it,{disabled:!this.state.selected||!i||i.type==="folder",onClick:p=>{const f=this.state.selected;this.onCloseMenu(()=>this.onCopy(p,f))},children:[m.jsx(tS,{style:Pe.iconDropdownMenu}),x.I18n.t("Copy script")]},"copy"),this.state.expertMode&&m.jsxs(it,{disabled:this.props.debugMode,onClick:p=>{p.stopPropagation(),p.preventDefault(),this.onCloseMenu(()=>this.setState({showAdapterDebug:!0}))},children:[m.jsx(lx,{style:Pe.iconDropdownMenu}),x.I18n.t("Debug instance")]},"debugInstance"),this.state.selected&&this.props.password&&this.props.scripts[this.state.selected].type==="script"?m.jsxs(it,{disabled:this.props.debugMode||this.props.changedScripts[this.state.selected],onClick:p=>{p.stopPropagation(),p.preventDefault(),this.onCloseMenu(async()=>{var b;const f=await this.props.socket.getObject(this.state.selected);f&&((b=f.native)!=null&&b.protected?(delete f.native.protected,f.common.source=Vg(this.props.password,f.common.source||"")):(f.native||={},f.native.protected=!0,f.common.source=vc(this.props.password,f.common.source||"")),await this.props.socket.setObject(f._id,f))})},children:[m.jsx(T_,{style:{...Pe.iconDropdownMenu,color:"orange"}}),(c=(l=this.props.scripts[this.state.selected])==null?void 0:l.native)!=null&&c.protected?m.jsx("span",{style:{color:(h=(d=this.props.scripts[this.state.selected])==null?void 0:d.native)!=null&&h.protected?"orange":void 0},children:x.I18n.t("Unprotect script")}):x.I18n.t("Protect script")]},"encrypt"):null]},"menu")}getToolbarButtons(){const s=[],i=this.state.reorder&&!this.props.debugMode;if(this.state.searchMode&&!this.props.debugMode)s.push(m.jsx(Pn,{value:this.state.searchText,style:Pe.toolbarSearch,ref:this.inputRef,autoFocus:!0,placeholder:x.I18n.t("Search..."),onChange:r=>{this.setState({searchText:r.target.value}),this.filterTimer&&clearTimeout(this.filterTimer),this.filterTimer=setTimeout(()=>{this.filterTimer=null,this.filterList(!0),this.props.onSearch&&this.props.onSearch(this.state.searchText)},400)}},"searchInput")),s.push(m.jsx(qe,{sx:Pe.toolbarButtons,style:{float:"right"},title:x.I18n.t("End search mode"),onClick:r=>{r.stopPropagation(),this.filterList(!1,()=>this.props.onSearch&&this.props.onSearch(this.state.searchText))},size:"medium",children:m.jsx(dx,{})},"disableSearch")),this.state.searchText&&s.push(m.jsx(qe,{title:x.I18n.t("Clear search input"),sx:Pe.toolbarButtons,style:{marginTop:7,float:"right"},onClick:r=>{r.stopPropagation(),this.setState({searchText:""},()=>{this.filterList(!0),this.props.onSearch&&this.props.onSearch(this.state.searchText)})},size:"medium",children:m.jsx(Mw,{fontSize:"small"})},"cleanSearch"));else{if(!i){s.push(m.jsx(qe,{"aria-label":"More","aria-owns":this.state.menuOpened?"long-menu":void 0,title:x.I18n.t("Menu"),"aria-haspopup":"true",onClick:c=>{c.stopPropagation(),c.preventDefault(),this.setState({menuOpened:!0,menuAnchorEl:c.currentTarget})},size:"medium",children:m.jsx(gx,{})},"menuButton"));const r=this.state.listItems.find(c=>c.id===this.state.selected);let l;r&&this.state.width<=Ur&&r.type==="folder"&&(l=this.state.listItems.filter(c=>c.parent===this.state.selected)),s.push(this.getMainMenu(l,r)),s.push(m.jsx(qe,{disabled:this.props.debugMode,title:x.I18n.t("Create new script"),sx:{...Pe.toolbarButtons,...this.props.debugMode?Pe.iconButtonsDisabled:void 0},style:{color:i?"red":"inherit"},onClick:c=>this.onAddNew(c),size:"medium",children:m.jsx(sS,{})},"new-script")),s.push(m.jsx(qe,{disabled:this.props.debugMode,title:x.I18n.t("Create new folder"),sx:{...Pe.toolbarButtons,...this.props.debugMode?Pe.iconButtonsDisabled:void 0},style:{color:i?"red":"inherit"},onClick:c=>this.onAddNewFolder(c),size:"medium",children:m.jsx(oS,{})},"new-folder"))}s.push(m.jsx(qe,{disabled:i||this.props.debugMode,sx:{...Pe.toolbarButtons,...this.props.debugMode?Pe.iconButtonsDisabled:void 0},title:x.I18n.t("Search in scripts"),style:{float:"right",opacity:this.props.debugMode?.5:i?0:1},onClick:r=>{r.stopPropagation(),this.setState({searchMode:!0})},size:"medium",children:m.jsx($x,{})},"search")),s.push(m.jsx(qe,{disabled:this.props.debugMode,title:x.I18n.t("Reorder scripts in folders"),sx:{...Pe.toolbarButtons,...this.props.debugMode?Pe.iconButtonsDisabled:void 0},style:{color:i?"red":"inherit",float:"right"},onClick:r=>{r.stopPropagation(),this.setState({reorder:!this.state.reorder})},size:"medium",children:m.jsx(_x,{})},"reorder")),!i&&this.state.selected&&this.state.selected!==To&&this.state.selected!==Cn&&s.push(m.jsx(qe,{sx:{...Pe.toolbarButtons,...this.props.debugMode?Pe.iconButtonsDisabled:void 0},disabled:this.props.debugMode,title:x.I18n.t("Rename"),onClick:r=>this.onRename(r),size:"medium",children:m.jsx(iS,{})},"rename")),s.push(m.jsxs("span",{style:{opacity:.5,fontSize:10},children:["v",this.props.version]},"version"))}return s}getFolders(){const s=[{id:qt,name:x.I18n.t("Root folder")}];return this.state.listItems.forEach(i=>{i.type==="folder"&&i.id!==qt&&(!i.id.startsWith(To)||this.state.expertMode)&&s.push({id:i.id,name:i.title})}),s}onCollapseAll(){this.setState({expanded:[]}),this.saveExpanded([])}onExpandAll(){const s=[];this.state.listItems.forEach(i=>this.state.listItems.find(r=>r.parent===i.id)&&s.push(i.id)),this.setState({expanded:s}),this.saveExpanded(s)}getBottomButtons(){return this.state.reorder||this.props.debugMode?null:[m.jsx(wt,{sx:Pe.footerButtons,title:x.I18n.t("Show only running scripts"),onClick:s=>{s.stopPropagation(),s.preventDefault();const i=this.state.statusFilter==="running"?"":"running";window.localStorage&&window.localStorage.setItem("SideMenu.statusFilter",i),this.setState({statusFilter:i})},children:m.jsx(bc,{style:{color:ig,opacity:this.state.statusFilter==="running"?1:.3,background:this.state.statusFilter==="running"?"gray":"inherit"}})},"filterByRunning"),m.jsx(wt,{sx:Pe.footerButtons,title:x.I18n.t("Show only paused scripts"),onClick:()=>{const s=this.state.statusFilter==="paused"?"":"paused";window.localStorage&&window.localStorage.setItem("SideMenu.statusFilter",s),this.setState({statusFilter:s})},children:m.jsx(Wg,{style:{color:ng,opacity:this.state.statusFilter==="paused"?1:.3,background:this.state.statusFilter==="paused"?"gray":"inherit"}})},"filterByPaused"),m.jsx(wt,{sx:Pe.footerButtons,style:{marginRight:16},title:x.I18n.t("Show only scripts with problems"),onClick:()=>{const s=this.state.statusFilter==="problems"?"":"problems";window.localStorage&&window.localStorage.setItem("SideMenu.statusFilter",s),this.setState({statusFilter:s})},children:m.jsx(bc,{style:{color:S_,opacity:this.state.statusFilter==="problems"?1:.3,background:this.state.statusFilter==="problems"?"gray":"inherit"}})},"filterByProblem"),m.jsx(wt,{sx:Pe.footerButtons,children:m.jsx("img",{alt:"Blockly",style:{opacity:this.state.typeFilter==="Blockly"?1:.3,background:this.state.typeFilter==="Blockly"?"gray":"inherit"},src:Tn.Blockly,onClick:()=>{const s=this.state.typeFilter==="Blockly"?"":"Blockly";window.localStorage&&window.localStorage.setItem("SideMenu.typeFilter",s),this.setState({typeFilter:s})}})},"filterBlockly"),m.jsx(wt,{sx:Pe.footerButtons,children:m.jsx("img",{alt:"Javascript",style:{opacity:this.state.typeFilter==="Javascript/js"?1:.3,background:this.state.typeFilter==="Javascript/js"?"gray":"inherit"},src:Tn["Javascript/js"],onClick:()=>{const s=this.state.typeFilter==="Javascript/js"?"":"Javascript/js";window.localStorage&&window.localStorage.setItem("SideMenu.typeFilter",s),this.setState({typeFilter:s})}})},"filterJS"),m.jsx(wt,{sx:Pe.footerButtons,children:m.jsx("img",{alt:"TypeScript",style:{opacity:this.state.typeFilter==="TypeScript/ts"?1:.3,background:this.state.typeFilter==="TypeScript/ts"?"gray":"inherit"},src:Tn["TypeScript/ts"],onClick:()=>{const s=this.state.typeFilter==="TypeScript/ts"?"":"TypeScript/ts";window.localStorage&&window.localStorage.setItem("SideMenu.typeFilter",s),this.setState({typeFilter:s})}})},"filterTS"),m.jsx(wt,{sx:Pe.footerButtons,children:m.jsx("img",{alt:"Rules",style:{opacity:this.state.typeFilter==="Rules"?1:.3,background:this.state.typeFilter==="Rules"?"gray":"inherit"},src:Tn.Rules,onClick:()=>{const s=this.state.typeFilter==="Rules"?"":"Rules";window.localStorage&&window.localStorage.setItem("SideMenu.typeFilter",s),this.setState({typeFilter:s})}})},"filterRules"),m.jsx("div",{style:{flexGrow:1}},"padding"),m.jsx(wt,{sx:Pe.footerButtons,onClick:()=>this.onExpandAll(),title:x.I18n.t("Expand all"),children:m.jsx(kx,{style:Pe.footerButtonsRight})},"expandAll"),this.state.expanded.length?m.jsx(wt,{sx:Pe.footerButtons,onClick:()=>this.onCollapseAll(),title:x.I18n.t("Collapse all"),children:m.jsx(wx,{style:Pe.footerButtonsRight})},"collapseAll"):m.jsx("div",{style:{height:22,width:24}})]}getAdapterDebugDialog(){return this.state.showAdapterDebug?m.jsx(Dx,{socket:this.props.socket,onClose:()=>this.setState({showAdapterDebug:!1}),onDebug:(s,i)=>this.setState({showAdapterDebug:!1},()=>this.props.onDebugInstance({instance:s,adapter:i}))},"debug"):null}render(){var r,l,c;const s=this.state.renaming?this.state.listItems.find(d=>d.id===this.state.renaming):void 0,i=this.state.copingScript&&this.props.scripts[this.state.copingScript].type==="script"?this.props.scripts[this.state.copingScript]:void 0;return[m.jsxs(PT,{variant:"permanent",style:Pe.menu,sx:{"& .MuiDrawer-paper":Pe.drawerPaper},anchor:"left",onClick:()=>this.onClick({id:""}),children:[m.jsx(wt,{sx:Pe.toolbar,children:this.getToolbarButtons()}),m.jsx(o_,{}),m.jsx(ek,{backend:hk,children:m.jsx("div",{style:Pe.innerMenu,children:this.renderAllItems(this.state.listItems)})}),m.jsx(o_,{}),m.jsx("div",{style:Pe.footer,children:this.getBottomButtons()})]},"drawer"),s?m.jsx(_m,{name:s.title,id:this.state.renaming||"",folder:s.type==="folder",instance:s.instance,instances:this.props.instances,onClose:()=>this.setState({renaming:null}),onRename:(d,h,p,f)=>this.props.onRename&&this.props.onRename(d,h,p,f)},"dialog-rename"):null,this.state.deleting?m.jsx(Cx,{name:this.state.listItems.find(d=>d.id===this.state.deleting).title,id:this.state.deleting,onClose:()=>this.setState({deleting:null}),onDelete:d=>this.props.onDelete&&this.props.onDelete(d)},"dialog-delete"):null,this.state.choosingType?m.jsx(Dn,{onClose:d=>{const h={choosingType:!1};d&&(h.creatingScript=d),this.setState(h)}},"dialog-script-type"):null,this.state.creatingScript?m.jsx(og,{onClose:()=>this.setState({creatingScript:null}),title:x.I18n.t("Create new script"),name:this.getUniqueName(),parents:this.getFolders(),folder:!1,existingItems:this.state.listItems.map(d=>d.id),instance:this.props.instances[0]||0,instances:this.props.instances,type:this.state.creatingScript,parent:this.parent,onAdd:(d,h,p,f)=>this.props.onAddNew&&this.props.onAddNew(d,h,!1,p,f)},"dialog-new-script"):null,this.state.copingScript?m.jsx(og,{onClose:()=>this.setState({copingScript:""}),title:x.I18n.t("Copy script"),name:this.getUniqueName(this.state.copingScript),parents:this.getFolders(),folder:!1,instance:parseInt((l=(r=i==null?void 0:i.common)==null?void 0:r.engine)==null?void 0:l.split(".").pop(),10)||0,instances:this.props.instances,type:((c=i==null?void 0:i.common)==null?void 0:c.engineType)||"Javascript/js",parent:this.parent,onAdd:(d,h,p,f)=>{var y;const b=this.state.copingScript&&this.props.scripts[this.state.copingScript].type==="script"?this.props.scripts[this.state.copingScript]:void 0;b!=null&&b.common&&(b.common.enabled=!1),this.props.onAddNew&&this.props.onAddNew(d,h,!1,p,f,(y=b==null?void 0:b.common)==null?void 0:y.source)}},"dialog-copy-script"):null,this.state.creatingFolder?m.jsx(og,{onClose:()=>this.setState({creatingFolder:!1}),title:x.I18n.t("Create new folder"),parents:this.getFolders(),name:this.getUniqueFolderName(),parent:this.parent,onAdd:(d,h)=>this.props.onAddNew&&this.props.onAddNew(d,h,!0)},"dialog-new-folder"):null,this.state.errorText?m.jsx(su,{onClose:()=>this.setState({errorText:""}),text:this.state.errorText},"error"):null,this.getAdapterDebugDialog(),this.state.showExportDialog?m.jsxs(Pt,{open:!0,onClose:()=>this.setState({showExportDialog:!1}),children:[m.jsx(Xt,{children:x.I18n.t("Export all scripts")}),m.jsxs(Bt,{children:[m.jsx(Ue,{variant:"contained",onClick:()=>{this.setState({showExportDialog:!1}),this.props.onExport(!0)},color:"primary",children:x.I18n.t("as JSON")}),m.jsx(Ue,{variant:"contained",onClick:()=>{this.setState({showExportDialog:!1}),this.props.onExport(!1)},color:"grey",children:x.I18n.t("as plain text")}),m.jsx(Ue,{variant:"contained",onClick:()=>this.setState({showExportDialog:!1}),color:"primary",children:x.I18n.t("Cancel")})]})]},"dialog-export-format"):null]}}const Px="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGAAAABgAQMAAADYVuV7AAAABlBMVEUAAAAzMzPI8eYgAAAAAXRSTlMAQObYZgAAACFJREFUeAFjAIJRwP////8PYIKWHCigNQdKj/pn1D+jAABTG16wVQqVpQAAAABJRU5ErkJggg==",Bx="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGAAAABgAQMAAADYVuV7AAAABlBMVEUAAAAzMzPI8eYgAAAAAXRSTlMAQObYZgAAABtJREFUeAFjAIJRwP8fCj7QkENn/4z6Z5QzCgBjbWaoyx1PqQAAAABJRU5ErkJggg==";function jx(a){let s,i=a.getHours();return i<10&&(i=`0${i.toString()}`),s=`${i}:`,i=a.getMinutes(),i<10&&(i=`0${i.toString()}`),s+=`${i}:`,i=a.getSeconds(),i<10&&(i=`0${i.toString()}`),s+=`${i}.`,i=a.getMilliseconds(),i<10?i=`00${i.toString()}`:i<100&&(i=`0${i.toString()}`),s+=i,s}const x_=34,Ht={logBox:{width:"100%",height:"100%",position:"relative",overflow:"hidden"},logBoxInner:a=>({display:"inline-block",color:a.palette.mode==="dark"?"white":"black",width:`calc(100% - ${x_}px)`,height:"100%",overflow:"auto",position:"relative",verticalAlign:"top"}),info:a=>({background:a.palette.mode==="dark"?"darkgrey":"lightgrey",color:(a.palette.mode==="dark","black")}),error:a=>({background:"#FF0000",color:a.palette.mode==="dark"?"black":"white"}),warn:a=>({background:"#FF8000",color:a.palette.mode==="dark"?"black":"white"}),debug:a=>({background:"gray",opacity:.8,color:a.palette.mode==="dark"?"black":"white"}),silly:a=>({background:"gray",opacity:.6,color:a.palette.mode==="dark"?"black":"white"}),table:{fontFamily:"monospace",width:"100%"},toolbox:{width:x_,height:"100%",boxShadow:"2px 0px 4px -1px rgba(0, 0, 0, 0.2), 4px 0px 5px 0px rgba(0, 0, 0, 0.14), 1px 0px 10px 0px rgba(0, 0, 0, 0.12)",display:"inline-block",verticalAlign:"top",overflow:"hidden"},trFrom:{width:90},trTime:{width:90},trSeverity:{width:40,fontWeight:"bold"},trPreMessage:{padding:0,margin:0},iconButtons:{width:32,height:32,padding:4},layoutIcon:a=>({"& img":{width:24,height:24,background:a.palette.mode==="dark"?"#9d9d9d":void 0,borderRadius:a.palette.mode==="dark"?"30px":void 0}})};function Fx(a){return a<10?`00${a}`:a<100?`0${a}`:a.toString()}const Zs={};class wm extends _e.Component{messagesEnd;constructor(s){super(s),this.state={lines:{},goBottom:!0,selected:null,editing:this.props.editing||[]},this.messagesEnd=_e.createRef()}static generateLine(s,i){let r=s.message||"";if(typeof r!="object"){const l=new RegExp(`${s.from.replace(".","\\.").replace(")","\\)").replace("(","\\(")} \\(\\d+\\) `,"g"),c=r.match(l);c?r=r.replace(c[0],""):r=r.replace(`${s.from} `,"")}return r.startsWith(`${i}: `)&&(r=r.substring(i.length+2)),m.jsxs(wt,{component:"tr",sx:Ht[s.severity],children:[m.jsx("td",{style:Ht.trFrom,children:s.from}),m.jsx("td",{style:Ht.trTime,children:jx(new Date(s.ts))}),m.jsx("td",{style:Ht.trSeverity,children:s.severity}),m.jsx("td",{children:m.jsx("pre",{style:Ht.trPreMessage,children:r})})]},`tr_${s.ts}_${s.message.substring(s.message.length-10)}`)}scrollToBottom(){var s,i;(i=(s=this.messagesEnd)==null?void 0:s.current)==null||i.scrollIntoView({behavior:"smooth"})}logHandler=s=>{const i=this.state.lines,r=this.state.editing.filter(f=>s.message.includes(f));let l=null;if(!r.length||(r.length===1?l=r[0]:(r.sort(),l=r[r.length-1]),!l))return;const c=i[l]||[],d=Zs[l]||[];c.push(wm.generateLine(s,l));let h=s.severity;(h==="info"||h==="warn")&&(h+=" ");const p=new Date(s.ts);d.push(`${p.toLocaleString()}.${Fx(p.getMilliseconds())} [${h}]: ${s.message}`),c.length>300&&(c.splice(0,c.length-300),d.splice(0,c.length-300)),Zs[l]=d,i[l]=c,this.setState({lines:i})};componentDidMount(){this.props.socket.registerLogHandler(this.logHandler)}componentWillUnmount(){this.props.socket.unregisterLogHandler(this.logHandler)}componentDidUpdate(){this.state.goBottom&&this.scrollToBottom()}static getDerivedStateFromProps(s,i){let r=!1;const l={};if(s.selected!==i.selected){const c=s.selected,d=i.lines;c&&(d[c]=d[c]||[],Zs[c]=Zs[c]||[]),l.selected=c,r=!0}if(JSON.stringify(s.editing)!==JSON.stringify(i.editing)){const c=JSON.parse(JSON.stringify(s.editing));r=!0;const d=i.lines;for(const h in Zs)Object.prototype.hasOwnProperty.call(Zs,h)&&(c.includes(h)||(delete Zs[h],delete d[h]));l.editing=c}return r?l:null}onCopy(){x.Utils.copyToClipboard((Zs[this.state.selected]||[]).join(` -`))}clearLog(){const s=this.state.lines;s[this.state.selected]&&(s[this.state.selected]=[]),Zs[this.state.selected]&&(Zs[this.state.selected]=[]),this.setState({lines:s})}renderLogList(s){return this.state.selected&&(s!=null&&s.length)?m.jsxs(wt,{sx:Ht.logBoxInner,children:[m.jsx("table",{style:Ht.table,children:m.jsx("tbody",{children:s})},"logTable"),m.jsx("div",{ref:this.messagesEnd,style:{float:"left",clear:"both"}},"logScrollPoint")]},"logList"):m.jsx(wt,{sx:Ht.logBoxInner,style:{paddingLeft:10},children:x.I18n.t("Log outputs")},"logList")}render(){const s=this.state.selected?this.state.lines[this.state.selected]:null;return m.jsxs("div",{style:Ht.logBox,children:[m.jsxs("div",{style:Ht.toolbox,children:[m.jsx(qe,{style:Ht.iconButtons,onClick:()=>this.setState({goBottom:!this.state.goBottom}),color:this.state.goBottom?"secondary":void 0,size:"medium",children:m.jsx(nS,{})}),s!=null&&s.length?m.jsx(qe,{style:Ht.iconButtons,onClick:()=>this.clearLog(),size:"medium",children:m.jsx(rS,{})}):null,s!=null&&s.length?m.jsx(qe,{style:Ht.iconButtons,onClick:()=>this.onCopy(),size:"medium",children:m.jsx(aS,{})}):null,this.props.onLayoutChange?m.jsx(qe,{style:Ht.iconButtons,onClick:()=>this.props.onLayoutChange&&this.props.onLayoutChange(),title:x.I18n.t("Change layout"),size:"medium",sx:Ht.layoutIcon,children:m.jsx("img",{alt:"split",src:this.props.verticalLayout?Px:Bx})}):null,m.jsx(qe,{style:Ht.iconButtons,onClick:()=>this.props.onHideLog(),title:x.I18n.t("Hide logs"),size:"medium",children:m.jsx(lS,{})})]},"toolbox"),this.renderLogList(s)]})}}var D_="focus-outline-hidden";function vk(){var a=this;document.addEventListener("keydown",function(s){a.focusByKeyboard=!0},!0),document.addEventListener("mousedown",function(s){a.focusByKeyboard=!1},!0),document.addEventListener("focus",function(s){a.updateVisibility()},!0),document.addEventListener("focusout",function(s){window.setTimeout(function(){document.hasFocus()||(a.focusByKeyboard=!0,a.updateVisibility())},0)}),this.updateVisibility()}vk.prototype={focusByKeyboard:!0,updateVisibility:function(){this.hidden=!this.focusByKeyboard},set hidden(a){document.documentElement.classList.toggle(D_,a)},get hidden(){return document.documentElement.classList.contains(D_)}};new vk;var yk={exports:{}};(function(a){(function(){var s={}.hasOwnProperty;function i(){for(var r=[],l=0;l4&&arguments[4]!==void 0?arguments[4]:"easeInOutCubic";return r>l?i:s+(i-s)*Ux[c](r/l)};Mi.calcEndPoint=function(s){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:window,r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0;if(Hx(s))return parseInt(s)+r;var l=i===window||i===document.documentElement?window.pageYOffset:i.scrollTop-i.getBoundingClientRect().top,c=s.nodeName.toLowerCase()==="html"?-l:s.getBoundingClientRect().top+l;return c+r};(function(a,s){Object.defineProperty(s,"__esModule",{value:!0});var i=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(l){return typeof l}:function(l){return l&&typeof Symbol=="function"&&l.constructor===Symbol&&l!==Symbol.prototype?"symbol":typeof l},r=Mi;s.default=function(l){var c=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},d=c.duration,h=d===void 0?500:d,p=c.context,f=p===void 0?window:p,b=c.offset,y=b===void 0?0:b,w=c.ease,v=w===void 0?"easeInOutCubic":w,_=c.callback;if((typeof window>"u"?"undefined":i(window))==="object"){var $=f.scrollTop!==null&&f.scrollTop!==void 0?f.scrollTop:window.pageYOffset,S=(0,r.calcEndPoint)(l,f,y),T=performance.now(),E=window.requestAnimationFrame,D=function M(){var P=performance.now()-T,W=(0,r.setPosition)($,S,P,h,v);f!==window?f.scrollTop=W:window.scroll(0,W),P>h?typeof _=="function"&&_(l):E(M)};D()}},a.exports=s.default})(Jg,Jg.exports);var _k=Jg.exports,qg={exports:{}};(function(a,s){Object.defineProperty(s,"__esModule",{value:!0});var i=Object.assign||function(d){for(var h=1;h0&&arguments[0]!==void 0?arguments[0]:{},h=d.query,p=h===void 0?'[href^="#"]:not([href="#"]':h,f=d.match,b=f===void 0?function(S){return document.getElementById(S.hash.substring(1))}:f,y=d.hashChange,w=y===void 0?!0:y,v=d.scrollSmoothConfig,_=document.querySelectorAll(p),$=function(T){T.preventDefault();var E=b(T.target);E&&(w&&history.replaceState(null,null,"#"+E.id),(0,l.default)(E,i({},v)))};Array.from(_).map(function(S){S.addEventListener("click",$,!1)})},a.exports=s.default})(qg,qg.exports);var Wx=qg.exports,Xg={exports:{}};(function(a,s){Object.defineProperty(s,"__esModule",{value:!0});function i(r){if(Array.isArray(r)){for(var l=0,c=Array(r.length);l0&&arguments[0]!==void 0?arguments[0]:{},l=r.activeClass,c=l===void 0?"active":l,d=r.query,h=d===void 0?'[href^="#"]:not([href="#"]):not([href="#0"])':d,p=r.threshold,f=p===void 0?[.25,.5,.75]:p,b=r.detectType,y=b===void 0?"max":b,w={threshold:f},v=function(W){return W.classList.remove(c)},_=function(W){return W.classList.add(c)},$=function(){document.querySelectorAll("."+c).forEach(v)},S=function(W){$(),_(document.querySelector('a[href="#'+W.id+'"]'))},T=function(W){W.forEach(function(G){G.intersectionRatio>=Math[y].apply(Math,i(f))&&S(G.target)})},E=document.querySelectorAll(h),D=new IntersectionObserver(T,w),M=function(W){var G=document.querySelector("#"+W.hash.slice(1));D.observe(G)};E.forEach(M)},a.exports=s.default})(Xg,Xg.exports);var Gx=Xg.exports;(function(a,s){Object.defineProperty(s,"__esModule",{value:!0});var i=_k,r=f(i),l=Mi,c=Wx,d=f(c),h=Gx,p=f(h);function f(b){return b&&b.__esModule?b:{default:b}}s.default={to:r.default,calcEndPoint:l.calcEndPoint,anchorScroll:d.default,observe:p.default},a.exports=s.default})(Yg,Yg.exports);var Vx=Yg.exports;const Kx=Xo(Vx);var km={exports:{}},Yx=km.exports;(function(a){(function(s,i){a.exports?a.exports=i():s.Scrollparent=i()})(Yx,function(){var s=/(auto|scroll)/,i=function(h,p){return h.parentNode===null?p:i(h.parentNode,p.concat([h]))},r=function(h,p){return getComputedStyle(h,null).getPropertyValue(p)},l=function(h){return r(h,"overflow")+r(h,"overflow-y")+r(h,"overflow-x")},c=function(h){return s.test(l(h))},d=function(h){if(h instanceof HTMLElement||h instanceof SVGElement){for(var p=i(h.parentNode,[]),f=0;f=s||G<0||y&&z>=c}function T(){var W=rg();if(S(W))return E(W);h=setTimeout(T,$(W))}function E(W){return h=void 0,w&&r?v(W):(r=l=void 0,d)}function D(){h!==void 0&&clearTimeout(h),f=0,r=p=l=h=void 0}function M(){return h===void 0?d:E(rg())}function P(){var W=rg(),G=S(W);if(r=arguments,l=this,p=W,G){if(h===void 0)return _(p);if(y)return h=setTimeout(T,s),v(p)}return h===void 0&&(h=setTimeout(T,s)),d}return P.cancel=D,P.flush=M,P}function Zg(a){var s=typeof a;return!!a&&(s=="object"||s=="function")}function h0(a){return!!a&&typeof a=="object"}function p0(a){return typeof a=="symbol"||h0(a)&&l0.call(a)==Zx}function O_(a){if(typeof a=="number")return a;if(p0(a))return R_;if(Zg(a)){var s=typeof a.valueOf=="function"?a.valueOf():a;a=Zg(s)?s+"":s}if(typeof a!="string")return a===0?a:+a;a=a.replace(Qx,"");var i=t0.test(a);return i||s0.test(a)?o0(a.slice(2),i?2:8):e0.test(a)?R_:+a}var g0=d0;const m0=Xo(g0);var Qg="data-focus-lock",wk="data-focus-lock-disabled",f0="data-no-focus-lock",$0="data-autofocus-inside",b0="data-no-autofocus";function ag(a,s){return typeof a=="function"?a(s):a&&(a.current=s),a}function v0(a,s){var i=kt(function(){return{value:a,callback:s,facade:{get current(){return i.value},set current(r){var l=i.value;l!==r&&(i.value=r,i.callback(r,l))}}}})[0];return i.callback=s,i.facade}var y0=typeof window<"u"?hm:Lt,N_=new WeakMap;function _0(a,s){var i=v0(null,function(r){return a.forEach(function(l){return ag(l,r)})});return y0(function(){var r=N_.get(i);if(r){var l=new Set(r),c=new Set(a),d=i.current;l.forEach(function(h){c.has(h)||ag(h,null)}),c.forEach(function(h){l.has(h)||ag(h,d)})}N_.set(i,a)},[a]),i}var lg={width:"1px",height:"0px",padding:0,overflow:"hidden",position:"fixed",top:"1px",left:"1px"};function kk(a){return a}function Ck(a,s){s===void 0&&(s=kk);var i=[],r=!1,l={read:function(){if(r)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return i.length?i[i.length-1]:a},useMedium:function(c){var d=s(c,r);return i.push(d),function(){i=i.filter(function(h){return h!==d})}},assignSyncMedium:function(c){for(r=!0;i.length;){var d=i;i=[],d.forEach(c)}i={push:function(h){return c(h)},filter:function(){return i}}},assignMedium:function(c){r=!0;var d=[];if(i.length){var h=i;i=[],h.forEach(c),d=i}var p=function(){var b=d;d=[],b.forEach(c)},f=function(){return Promise.resolve().then(p)};f(),i={push:function(b){d.push(b),f()},filter:function(b){return d=d.filter(b),i}}}};return l}function Cm(a,s){return s===void 0&&(s=kk),Ck(a,s)}function w0(a){a===void 0&&(a={});var s=Ck(null);return s.options=cS({async:!0,ssr:!1},a),s}var Tk=Cm({},function(a){var s=a.target,i=a.currentTarget;return{target:s,currentTarget:i}}),Sk=Cm(),k0=Cm(),C0=w0({async:!0,ssr:typeof document<"u"}),T0=um(void 0),S0=[],Tm=Iw(function(s,i){var r,l=kt(),c=l[0],d=l[1],h=Ko(),p=Ko(!1),f=Ko(null),b=kt({}),y=b[1],w=s.children,v=s.disabled,_=v===void 0?!1:v,$=s.noFocusGuards,S=$===void 0?!1:$,T=s.persistentFocus,E=T===void 0?!1:T,D=s.crossFrame,M=D===void 0?!0:D,P=s.autoFocus,W=P===void 0?!0:P;s.allowTextSelection;var G=s.group,z=s.className,Z=s.whiteList,he=s.hasPositiveIndices,Ce=s.shards,O=Ce===void 0?S0:Ce,K=s.as,C=K===void 0?"div":K,Q=s.lockProps,ve=Q===void 0?{}:Q,ce=s.sideCar,ne=s.returnFocus,me=ne===void 0?!1:ne,re=s.focusOptions,B=s.onActivation,N=s.onDeactivation,te=kt({}),q=te[0],se=xn(function(Y){var R=Y.captureFocusRestore;if(!f.current){var A,U=(A=document)==null?void 0:A.activeElement;f.current=U,U!==document.body&&(f.current=R(U))}h.current&&B&&B(h.current),p.current=!0,y()},[B]),F=xn(function(){p.current=!1,N&&N(h.current),y()},[N]),Te=xn(function(Y){var R=f.current;if(R){var A=(typeof R=="function"?R():R)||document.body,U=typeof me=="function"?me(A):me;if(U){var H=typeof U=="object"?U:void 0;f.current=null,Y?Promise.resolve().then(function(){return A.focus(H)}):A.focus(H)}}},[me]),ae=xn(function(Y){p.current&&Tk.useMedium(Y)},[]),we=Sk.useMedium,Ie=xn(function(Y){h.current!==Y&&(h.current=Y,d(Y))},[]),Ne=Ig((r={},r[wk]=_&&"disabled",r[Qg]=G,r),ve),Ae=S!==!0,We=Ae&&S!=="tail",k=_0([i,Ie]),X=us(function(){return{observed:h,shards:O,enabled:!_,active:p.current}},[_,p.current,O,c]);return _e.createElement(Dg,null,Ae&&[_e.createElement("div",{key:"guard-first","data-focus-guard":!0,tabIndex:_?-1:0,style:lg}),he?_e.createElement("div",{key:"guard-nearest","data-focus-guard":!0,tabIndex:_?-1:1,style:lg}):null],!_&&_e.createElement(ce,{id:q,sideCar:C0,observed:c,disabled:_,persistentFocus:E,crossFrame:M,autoFocus:W,whiteList:Z,shards:O,onActivation:se,onDeactivation:F,returnFocus:Te,focusOptions:re,noFocusGuards:S}),_e.createElement(C,Ig({ref:k},Ne,{className:z,onBlur:we,onFocus:ae}),_e.createElement(T0.Provider,{value:X},w)),We&&_e.createElement("div",{"data-focus-guard":!0,tabIndex:_?-1:0,style:lg}))});Tm.propTypes={};function E0(a,s){function i(r){return r.displayName||r.name||"Component"}return function(l){var c=[],d;function h(){d=a(c.map(function(f){return f.props})),s(d)}var p=(function(f){DS(b,f);function b(){return f.apply(this,arguments)||this}b.peek=function(){return d};var y=b.prototype;return y.componentDidMount=function(){c.push(this),h()},y.componentDidUpdate=function(){h()},y.componentWillUnmount=function(){var v=c.indexOf(this);c.splice(v,1),h()},y.render=function(){return _e.createElement(l,this.props)},b})(OT);return qS(p,"displayName","SideEffect("+i(l)+")"),p}}var oo=function(a){for(var s=Array(a.length),i=0;i=0}).sort(L0)},B0=["button:enabled","select:enabled","textarea:enabled","input:enabled","a[href]","area[href]","summary","iframe","object","embed","audio[controls]","video[controls]","[tabindex]","[contenteditable]","[autofocus]"],Im=B0.join(","),j0="".concat(Im,", [data-focus-guard]"),Mk=function(a,s){return oo((a.shadowRoot||a).children).reduce(function(i,r){return i.concat(r.matches(s?j0:Im)?[r]:[],Mk(r))},[])},F0=function(a,s){var i;return a instanceof HTMLIFrameElement&&(!((i=a.contentDocument)===null||i===void 0)&&i.body)?Bn([a.contentDocument.body],s):[a]},Bn=function(a,s){return a.reduce(function(i,r){var l,c=Mk(r,s),d=(l=[]).concat.apply(l,c.map(function(h){return F0(h,s)}));return i.concat(d,r.parentNode?oo(r.parentNode.querySelectorAll(Im)).filter(function(h){return h===r}):[])},[])},z0=function(a){var s=a.querySelectorAll("[".concat($0,"]"));return oo(s).map(function(i){return Bn([i])}).reduce(function(i,r){return i.concat(r)},[])},xm=function(a,s){return oo(a).filter(function(i){return Dk(s,i)}).filter(function(i){return O0(i)})},M_=function(a,s){return s===void 0&&(s=new Map),oo(a).filter(function(i){return Ak(s,i)})},Dm=function(a,s,i){return Em(xm(Bn(a,i),s),!0,i)},ea=function(a,s){return Em(xm(Bn(a),s),!1)},U0=function(a,s){return xm(z0(a),s)},xi=function(a,s){return a.shadowRoot?xi(a.shadowRoot,s):Object.getPrototypeOf(a).contains!==void 0&&Object.getPrototypeOf(a).contains.call(a,s)?!0:oo(a.children).some(function(i){var r;if(i instanceof HTMLIFrameElement){var l=(r=i.contentDocument)===null||r===void 0?void 0:r.body;return l?xi(l,s):!1}return xi(i,s)})},H0=function(a){for(var s=new Set,i=a.length,r=0;r0&&s.add(l),(c&Node.DOCUMENT_POSITION_CONTAINS)>0&&s.add(r)}return a.filter(function(d,h){return!s.has(h)})},Lk=function(a){return a.parentNode?Lk(a.parentNode):a},Am=function(a){var s=Oi(a);return s.filter(Boolean).reduce(function(i,r){var l=r.getAttribute(Qg);return i.push.apply(i,l?H0(oo(Lk(r).querySelectorAll("[".concat(Qg,'="').concat(l,'"]:not([').concat(wk,'="disabled"])')))):[r]),i},[])},W0=function(a){try{return a()}catch{return}},ta=function(a){if(a===void 0&&(a=document),!(!a||!a.activeElement)){var s=a.activeElement;return s.shadowRoot?ta(s.shadowRoot):s instanceof HTMLIFrameElement&&W0(function(){return s.contentWindow.document})?ta(s.contentWindow.document):s}},G0=function(a,s){return a===s},V0=function(a,s){return!!oo(a.querySelectorAll("iframe")).some(function(i){return G0(i,s)})},Pk=function(a,s){return s===void 0&&(s=ta(Ek(a).ownerDocument)),!s||s.dataset&&s.dataset.focusGuard?!1:Am(a).some(function(i){return xi(i,s)||V0(i,s)})},K0=function(a){a===void 0&&(a=document);var s=ta(a);return s?oo(a.querySelectorAll("[".concat(f0,"]"))).some(function(i){return xi(i,s)}):!1},Y0=function(a,s){return s.filter(Nk).filter(function(i){return i.name===a.name}).filter(function(i){return i.checked})[0]||a},Rm=function(a,s){return Nk(a)&&a.name?Y0(a,s):a},J0=function(a){var s=new Set;return a.forEach(function(i){return s.add(Rm(i,a))}),a.filter(function(i){return s.has(i)})},L_=function(a){return a[0]&&a.length>1?Rm(a[0],a):a[0]},P_=function(a,s){return a.indexOf(Rm(s,a))},tm="NEW_FOCUS",q0=function(a,s,i,r,l){var c=a.length,d=a[0],h=a[c-1],p=Sm(r);if(!(r&&a.indexOf(r)>=0)){var f=r!==void 0?i.indexOf(r):-1,b=l?i.indexOf(l):f,y=l?a.indexOf(l):-1;if(f===-1)return y!==-1?y:tm;if(y===-1)return tm;var w=f-b,v=i.indexOf(d),_=i.indexOf(h),$=J0(i),S=r!==void 0?$.indexOf(r):-1,T=l?$.indexOf(l):S,E=$.filter(function(z){return z.tabIndex>=0}),D=r!==void 0?E.indexOf(r):-1,M=l?E.indexOf(l):D,P=D>=0&&M>=0?M-D:T-S;if(!w&&y>=0||s.length===0)return y;var W=P_(a,s[0]),G=P_(a,s[s.length-1]);if(f<=v&&p&&Math.abs(w)>1)return G;if(f>=_&&p&&Math.abs(w)>1)return W;if(w&&Math.abs(P)>1)return y;if(f<=v)return G;if(f>_)return W;if(w)return Math.abs(w)>1?y:(c+y+w)%c}},X0=function(a){return function(s){var i,r=(i=Rk(s))===null||i===void 0?void 0:i.autofocus;return s.autofocus||r!==void 0&&r!=="false"||a.indexOf(s)>=0}},B_=function(a,s,i){var r=a.map(function(c){var d=c.node;return d}),l=M_(r.filter(X0(i)));return l&&l.length?L_(l):L_(M_(s))},sm=function(a,s){return s===void 0&&(s=[]),s.push(a),a.parentNode&&sm(a.parentNode.host||a.parentNode,s),s},cg=function(a,s){for(var i=sm(a),r=sm(s),l=0;l=0)return c}return!1},Bk=function(a,s,i){var r=Oi(a),l=Oi(s),c=r[0],d=!1;return l.filter(Boolean).forEach(function(h){d=cg(d||h,h)||d,i.filter(Boolean).forEach(function(p){var f=cg(c,p);f&&(!d||xi(f,d)?d=f:d=cg(f,d))})}),d},j_=function(a,s){return a.reduce(function(i,r){return i.concat(U0(r,s))},[])},Z0=function(a,s){var i=new Map;return s.forEach(function(r){return i.set(r.node,r)}),a.map(function(r){return i.get(r)}).filter(M0)},Q0=function(a,s){var i=ta(Oi(a).length>0?document:Ek(a).ownerDocument),r=Am(a).filter(em),l=Bk(i||a,a,r),c=new Map,d=ea(r,c),h=d.filter(function(_){var $=_.node;return em($)});if(h[0]){var p=ea([l],c).map(function(_){var $=_.node;return $}),f=Z0(p,h),b=f.map(function(_){var $=_.node;return $}),y=f.filter(function(_){var $=_.tabIndex;return $>=0}).map(function(_){var $=_.node;return $}),w=q0(b,y,p,i,s);if(w===tm){var v=B_(d,y,j_(r,c))||B_(d,b,j_(r,c));if(v)return{node:v};console.warn("focus-lock: cannot find any node to move focus into");return}return w===void 0?w:f[w]}},eD=function(a){var s=Am(a).filter(em),i=Bk(a,a,s),r=Em(Bn([i],!0),!0,!0),l=Bn(s,!1);return r.map(function(c){var d=c.node,h=c.index;return{node:d,index:h,lockItem:l.indexOf(d)>=0,guard:Sm(d)}})},Om=function(a,s){a&&("focus"in a&&a.focus(s),"contentWindow"in a&&a.contentWindow&&a.contentWindow.focus())},ug=0,dg=!1,jk=function(a,s,i){i===void 0&&(i={});var r=Q0(a,s);if(!dg&&r){if(ug>2){console.error("FocusLock: focus-fighting detected. Only one focus management system could be active. See https://github.com/theKashey/focus-lock/#focus-fighting"),dg=!0,setTimeout(function(){dg=!1},1);return}ug++,Om(r.node,i.focusOptions),ug--}};function Hr(a){if(!a)return null;if(typeof WeakRef>"u")return function(){return a||null};var s=a?new WeakRef(a):null;return function(){return(s==null?void 0:s.deref())||null}}var tD=function(a){if(!a)return null;for(var s=[],i=a;i&&i!==document.body;)s.push({current:Hr(i),parent:Hr(i.parentElement),left:Hr(i.previousElementSibling),right:Hr(i.nextElementSibling)}),i=i.parentElement;return{element:Hr(a),stack:s,ownerDocument:a.ownerDocument}},sD=function(a){var s,i,r,l,c;if(a)for(var d=a.stack,h=a.ownerDocument,p=new Map,f=0,b=d;f-1&&(S.filter(function(E){var D=E.guard,M=E.node;return D&&M.dataset.focusAutoGuard}).forEach(function(E){var D=E.node;return D.removeAttribute("tabIndex")}),z_(T,S.length,1,S),z_(T,-1,-1,S))}}}return s},Gk=function(s){Sc()&&s&&(s.stopPropagation(),s.preventDefault())},Lm=function(){return Nm(Sc)},yD=function(s){var i=s.target,r=s.currentTarget;r.contains(i)||gD(r,i)},_D=function(){return null},Vk=function(){Mm=!0},Kk=function(){Mm=!1,sa="just",Nm(function(){sa="meanwhile"})},wD=function(){document.addEventListener("focusin",Gk),document.addEventListener("focusout",Lm),window.addEventListener("focus",Vk),window.addEventListener("blur",Kk)},kD=function(){document.removeEventListener("focusin",Gk),document.removeEventListener("focusout",Lm),window.removeEventListener("focus",Vk),window.removeEventListener("blur",Kk)};function CD(a){return a.filter(function(s){var i=s.disabled;return!i})}var Yk={moveFocusInside:jk,focusInside:Pk,focusNextElement:rD,focusPrevElement:aD,focusFirstElement:lD,focusLastElement:cD,captureFocusRestore:Fk};function TD(a){var s=a.slice(-1)[0];s&&!On&&wD();var i=On,r=i&&s&&s.id===i.id;On=s,i&&!r&&(i.onDeactivation(),a.filter(function(l){var c=l.id;return c===i.id}).length||i.returnFocus(!s)),s?(ss=null,(!r||i.observed!==s.observed)&&s.onActivation(Yk),Sc(),Nm(Sc)):(kD(),ss=null)}Tk.assignSyncMedium(yD);Sk.assignMedium(Lm);k0.assignMedium(function(a){return a(Yk)});const SD=E0(CD,TD)(_D);var Jk=Iw(function(s,i){return _e.createElement(Tm,Ig({sideCar:SD,ref:i},s))}),qk=Tm.propTypes||{};qk.sideCar;AS(qk,["sideCar"]);Jk.propTypes={};var Xk={exports:{}},ct={};var Pm=Symbol.for("react.element"),Bm=Symbol.for("react.portal"),ou=Symbol.for("react.fragment"),iu=Symbol.for("react.strict_mode"),nu=Symbol.for("react.profiler"),ru=Symbol.for("react.provider"),au=Symbol.for("react.context"),ED=Symbol.for("react.server_context"),lu=Symbol.for("react.forward_ref"),cu=Symbol.for("react.suspense"),uu=Symbol.for("react.suspense_list"),du=Symbol.for("react.memo"),hu=Symbol.for("react.lazy"),ID=Symbol.for("react.offscreen"),Zk;Zk=Symbol.for("react.module.reference");function Cs(a){if(typeof a=="object"&&a!==null){var s=a.$$typeof;switch(s){case Pm:switch(a=a.type,a){case ou:case nu:case iu:case cu:case uu:return a;default:switch(a=a&&a.$$typeof,a){case ED:case au:case lu:case hu:case du:case ru:return a;default:return s}}case Bm:return s}}}ct.ContextConsumer=au;ct.ContextProvider=ru;ct.Element=Pm;ct.ForwardRef=lu;ct.Fragment=ou;ct.Lazy=hu;ct.Memo=du;ct.Portal=Bm;ct.Profiler=nu;ct.StrictMode=iu;ct.Suspense=cu;ct.SuspenseList=uu;ct.isAsyncMode=function(){return!1};ct.isConcurrentMode=function(){return!1};ct.isContextConsumer=function(a){return Cs(a)===au};ct.isContextProvider=function(a){return Cs(a)===ru};ct.isElement=function(a){return typeof a=="object"&&a!==null&&a.$$typeof===Pm};ct.isForwardRef=function(a){return Cs(a)===lu};ct.isFragment=function(a){return Cs(a)===ou};ct.isLazy=function(a){return Cs(a)===hu};ct.isMemo=function(a){return Cs(a)===du};ct.isPortal=function(a){return Cs(a)===Bm};ct.isProfiler=function(a){return Cs(a)===nu};ct.isStrictMode=function(a){return Cs(a)===iu};ct.isSuspense=function(a){return Cs(a)===cu};ct.isSuspenseList=function(a){return Cs(a)===uu};ct.isValidElementType=function(a){return typeof a=="string"||typeof a=="function"||a===ou||a===nu||a===iu||a===cu||a===uu||a===ID||typeof a=="object"&&a!==null&&(a.$$typeof===hu||a.$$typeof===du||a.$$typeof===ru||a.$$typeof===au||a.$$typeof===lu||a.$$typeof===Zk||a.getModuleId!==void 0)};ct.typeOf=Cs;Xk.exports=ct;var Qk=Xk.exports;function xD(a){function s(N,te,q,se,F){for(var Te=0,ae=0,we=0,Ie=0,Ne,Ae,We=0,k=0,X,Y=X=Ne=0,R=0,A=0,U=0,H=0,ue=q.length,V=ue-1,be,pe="",fe="",Le="",He="",Be;RNe)&&(H=(pe=pe.replace(" ",":")).length),0se&&(se=(te=te.trim()).charCodeAt(0)),se){case 38:return te.replace(T,"$1"+N.trim());case 58:return N.trim()+te.replace(T,"$1"+N.trim());default:if(0<1*q&&0ae.charCodeAt(8))break;case 115:F=F.replace(ae,"-webkit-"+ae)+";"+F;break;case 207:case 102:F=F.replace(ae,"-webkit-"+(102q.charCodeAt(0)&&(q=q.trim()),B=q,q=[B],01?s-1:0),r=1;r0?" Args: "+i.join(", "):""))}var OD=(function(){function a(i){this.groupSizes=new Uint32Array(512),this.length=512,this.tag=i}var s=a.prototype;return s.indexOfGroup=function(i){for(var r=0,l=0;l=this.groupSizes.length){for(var l=this.groupSizes,c=l.length,d=c;i>=d;)(d<<=1)<0&&ga(16,""+i);this.groupSizes=new Uint32Array(d),this.groupSizes.set(l),this.length=d;for(var h=c;h=this.length||this.groupSizes[i]===0)return r;for(var l=this.groupSizes[i],c=this.indexOfGroup(i),d=c+l,h=c;h=Yr&&(Yr=s+1),yc.set(a,s),Ic.set(s,a)},LD="style["+jn+'][data-styled-version="5.3.11"]',PD=new RegExp("^"+jn+'\\.g(\\d+)\\[id="([\\w\\d-]+)"\\].*?"([^"]*)'),BD=function(a,s,i){for(var r,l=i.split(","),c=0,d=l.length;c=0;f--){var b=p[f];if(b&&b.nodeType===1&&b.hasAttribute(jn))return b}})(i),c=l!==void 0?l.nextSibling:null;r.setAttribute(jn,"active"),r.setAttribute("data-styled-version","5.3.11");var d=FD();return d&&r.setAttribute("nonce",d),i.insertBefore(r,c),r},zD=(function(){function a(i){var r=this.element=eC(i);r.appendChild(document.createTextNode("")),this.sheet=(function(l){if(l.sheet)return l.sheet;for(var c=document.styleSheets,d=0,h=c.length;d=0){var l=document.createTextNode(r),c=this.nodes[i];return this.element.insertBefore(l,c||null),this.length++,!0}return!1},s.deleteRule=function(i){this.element.removeChild(this.nodes[i]),this.length--},s.getRule=function(i){return i0&&(y+=w+",")})),c+=""+f+b+'{content:"'+y+`"}/*!sc*/ -`}}}return c})(this)},a})(),GD=/(a)(d)/gi,G_=function(a){return String.fromCharCode(a+(a>25?39:97))};function im(a){var s,i="";for(s=Math.abs(a);s>52;s=s/52|0)i=G_(s%52)+i;return(G_(s%52)+i).replace(GD,"$1-$2")}var An=function(a,s){for(var i=s.length;i;)a=33*a^s.charCodeAt(--i);return a},tC=function(a){return An(5381,a)};function sC(a){for(var s=0;s>>0);if(!i.hasNameForId(l,h)){var p=r(d,"."+h,void 0,l);i.insertRules(l,h,p)}c.push(h),this.staticRulesId=h}else{for(var f=this.rules.length,b=An(this.baseHash,r.hash),y="",w=0;w>>0);if(!i.hasNameForId(l,S)){var T=r(y,"."+S,void 0,l);i.insertRules(l,S,T)}c.push(S)}}return c.join(" ")},a})(),YD=/^\s*\/\/.*$/gm,JD=[":","[",".","#"];function qD(a){var s,i,r,l,c=Yo,d=c.options,h=d===void 0?Yo:d,p=c.plugins,f=p===void 0?Ec:p,b=new xD(h),y=[],w=(function($){function S(T){if(T)try{$(T+"}")}catch{}}return function(T,E,D,M,P,W,G,z,Z,he){switch(T){case 1:if(Z===0&&E.charCodeAt(0)===64)return $(E+";"),"";break;case 2:if(z===0)return E+"/*|*/";break;case 3:switch(z){case 102:case 112:return $(D[0]+E),"";default:return E+(he===0?"/*|*/":"")}case-2:E.split("/*|*/}").forEach(S)}}})((function($){y.push($)})),v=function($,S,T){return S===0&&JD.indexOf(T[i.length])!==-1||T.match(l)?$:"."+s};function _($,S,T,E){E===void 0&&(E="&");var D=$.replace(YD,""),M=S&&T?T+" "+S+" { "+D+" }":D;return s=E,i=S,r=new RegExp("\\"+i+"\\b","g"),l=new RegExp("(\\"+i+"\\b){2,}"),b(T||!S?"":S,M)}return b.use([].concat(f,[function($,S,T){$===2&&T.length&&T[0].lastIndexOf(i)>0&&(T[0]=T[0].replace(r,v))},w,function($){if($===-2){var S=y;return y=[],S}}])),_.hash=f.length?f.reduce((function($,S){return S.name||ga(15),An($,S.name)}),5381).toString():"",_}var oC=_e.createContext();oC.Consumer;var iC=_e.createContext(),XD=(iC.Consumer,new xc),nm=qD();function nC(){return ia(oC)||XD}function rC(){return ia(iC)||nm}var ZD=(function(){function a(s,i){var r=this;this.inject=function(l,c){c===void 0&&(c=nm);var d=r.name+c.hash;l.hasNameForId(r.id,d)||l.insertRules(r.id,d,c(r.rules,d,"@keyframes"))},this.toString=function(){return ga(12,String(r.name))},this.name=s,this.id="sc-keyframes-"+s,this.rules=i}return a.prototype.getName=function(s){return s===void 0&&(s=nm),this.name+s.hash},a})(),QD=/([A-Z])/,eA=/([A-Z])/g,tA=/^ms-/,sA=function(a){return"-"+a.toLowerCase()};function V_(a){return QD.test(a)?a.replace(eA,sA).replace(tA,"-ms-"):a}var K_=function(a){return a==null||a===!1||a===""};function Ni(a,s,i,r){if(Array.isArray(a)){for(var l,c=[],d=0,h=a.length;d1?s-1:0),r=1;r?@[\\\]^`{|}~-]+/g,iA=/(^-|-$)/g;function hg(a){return a.replace(oA,"-").replace(iA,"")}var cC=function(a){return im(tC(a)>>>0)};function ac(a){return typeof a=="string"&&!0}var rm=function(a){return typeof a=="function"||typeof a=="object"&&a!==null&&!Array.isArray(a)},nA=function(a){return a!=="__proto__"&&a!=="constructor"&&a!=="prototype"};function rA(a,s,i){var r=a[i];rm(s)&&rm(r)?uC(r,s):a[i]=s}function uC(a){for(var s=arguments.length,i=new Array(s>1?s-1:0),r=1;r=0||(he[z]=W[z]);return he})(s,["componentId"]),P=D&&D+"-"+(ac(E)?E:hg(H_(E)));return dC(E,to({},M,{attrs:w,componentId:P}),i)},Object.defineProperty(_,"defaultProps",{get:function(){return this._foldedDefaultProps},set:function(E){this._foldedDefaultProps=r?uC({},a.defaultProps,E):E}}),Object.defineProperty(_,"toString",{value:function(){return"."+_.styledComponentId}}),l&&RS(_,a,{attrs:!0,componentStyle:!0,displayName:!0,foldedComponentIds:!0,shouldForwardProp:!0,styledComponentId:!0,target:!0,withComponent:!0}),_}var ks=function(a){return(function s(i,r,l){if(l===void 0&&(l=Yo),!Qk.isValidElementType(r))return ga(1,String(r));var c=function(){return i(r,l,aC.apply(void 0,arguments))};return c.withConfig=function(d){return s(i,r,to({},l,{},d))},c.attrs=function(d){return s(i,r,to({},l,{attrs:Array.prototype.concat(l.attrs,d).filter(Boolean)}))},c})(dC,a)};["a","abbr","address","area","article","aside","audio","b","base","bdi","bdo","big","blockquote","body","br","button","canvas","caption","cite","code","col","colgroup","data","datalist","dd","del","details","dfn","dialog","div","dl","dt","em","embed","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","iframe","img","input","ins","kbd","keygen","label","legend","li","link","main","map","mark","marquee","menu","menuitem","meta","meter","nav","noscript","object","ol","optgroup","option","output","p","param","picture","pre","progress","q","rp","rt","ruby","s","samp","script","section","select","small","source","span","strong","style","sub","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","title","tr","track","u","ul","var","video","wbr","circle","clipPath","defs","ellipse","foreignObject","g","image","line","linearGradient","marker","mask","path","pattern","polygon","polyline","radialGradient","rect","stop","svg","text","textPath","tspan"].forEach((function(a){ks[a]=ks(a)}));var aA=(function(){function a(i,r){this.rules=i,this.componentId=r,this.isStatic=sC(i),xc.registerId(this.componentId+1)}var s=a.prototype;return s.createStyles=function(i,r,l,c){var d=c(Ni(this.rules,r,l,c).join(""),""),h=this.componentId+i;l.insertRules(h,h,d)},s.removeStyles=function(i,r){r.clearRules(this.componentId+i)},s.renderStyles=function(i,r,l,c){i>2&&xc.registerId(this.componentId+i),this.removeStyles(i,l),this.createStyles(i,r,l,c)},a})();function lA(a){for(var s=arguments.length,i=new Array(s>1?s-1:0),r=1;ra.length)&&(s=a.length);for(var i=0,r=Array(s);i=a.length?{done:!0}:{done:!1,value:a[r++]}},e:function(p){throw p},f:l}}throw new TypeError(`Invalid attempt to iterate non-iterable instance. -In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var c,d=!0,h=!1;return{s:function(){i=i.call(a)},n:function(){var p=i.next();return d=p.done,p},e:function(p){h=!0,c=p},f:function(){try{d||i.return==null||i.return()}finally{if(h)throw c}}}}function vs(a,s,i){return(s=pC(s))in a?Object.defineProperty(a,s,{value:i,enumerable:!0,configurable:!0,writable:!0}):a[s]=i,a}function Dc(a){return Dc=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(s){return s.__proto__||Object.getPrototypeOf(s)},Dc(a)}function mA(a,s){if(typeof s!="function"&&s!==null)throw new TypeError("Super expression must either be null or a function");a.prototype=Object.create(s&&s.prototype,{constructor:{value:a,writable:!0,configurable:!0}}),Object.defineProperty(a,"prototype",{writable:!1}),s&&am(a,s)}function hC(){try{var a=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(hC=function(){return!!a})()}function fA(a,s){var i=a==null?null:typeof Symbol<"u"&&a[Symbol.iterator]||a["@@iterator"];if(i!=null){var r,l,c,d,h=[],p=!0,f=!1;try{if(c=(i=i.call(a)).next,s!==0)for(;!(p=(r=c.call(i)).done)&&(h.push(r.value),h.length!==s);p=!0);}catch(b){f=!0,l=b}finally{try{if(!p&&i.return!=null&&(d=i.return(),Object(d)!==d))return}finally{if(f)throw l}}return h}}function $A(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. -In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function q_(a,s){var i=Object.keys(a);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(a);s&&(r=r.filter(function(l){return Object.getOwnPropertyDescriptor(a,l).enumerable})),i.push.apply(i,r)}return i}function Ac(a){for(var s=1;s{const d=`__dbk__gutter ${r} ${a||s}`,h=`__dbk__dragger ${r} ${i||s}`;return m.jsx("div",Object.assign({className:d,ref:c,dir:r,onMouseDown:l,onTouchStart:$c?l:void 0},{children:m.jsx("div",{className:h},void 0)}),void 0)}));var ws;function Fg(a,s,i){let r,l;return s?(r=a/2,l=a):i?(r=a,l=a/2):(r=a,l=a),{aGutterSize:r,bGutterSize:l}}function YS(a,s){switch(s.type){case ws.SetIsReadyToCompute:return Object.assign(Object.assign({},a),{isReady:s.payload.isReady});case ws.CreatePairs:{const{direction:i,children:r,gutters:l}=s.payload,c=r[0].parentNode;if(!c)throw new Error("Cannot create pairs - parent is undefined.");const d=Tc(i,c);if(d===void 0)throw new Error(`Cannot create pairs - parent has undefined or zero size: ${d}.`);const h=[];return r.forEach(((p,f)=>{if(f>0){const b=r[f-1],y=r[f],w=l[f-1],v=i===ft.Horizontal?b.getBoundingClientRect().left:b.getBoundingClientRect().top,_=i===ft.Horizontal?y.getBoundingClientRect().right:y.getBoundingClientRect().bottom,$=i===ft.Horizontal?b.getBoundingClientRect().width+w.getBoundingClientRect().width+y.getBoundingClientRect().width:b.getBoundingClientRect().height+w.getBoundingClientRect().height+y.getBoundingClientRect().height,T=i===ft.Horizontal?w.getBoundingClientRect().width:w.getBoundingClientRect().height,S={idx:f-1,a:b,b:y,gutter:w,parent:c,start:v,end:_,size:$,gutterSize:T,aSizePct:100/r.length,bSizePct:100/r.length};h.push(S)}})),Object.assign(Object.assign({},a),{pairs:h})}case ws.StartDragging:{const{gutterIdx:i}=s.payload;return Object.assign(Object.assign({},a),{isDragging:!0,draggingIdx:i})}case ws.StopDragging:return Object.assign(Object.assign({},a),{isDragging:!1});case ws.CalculateSizes:{const{direction:i,gutterIdx:r}=s.payload,l=a.pairs[r],c=Tc(i,l.parent);if(!c)throw new Error("Cannot calculate sizes - 'pair.parent' has undefined or zero size.");const d=l.gutter[i===ft.Horizontal?"clientWidth":"clientHeight"],h=r===0,p=r===a.pairs.length-1,{aGutterSize:f,bGutterSize:b}=Fg(d,h,p);let y,w,v,_,$;return i===ft.Horizontal?(y=l.a.getBoundingClientRect().left,w=l.b.getBoundingClientRect().right,_=(l.a.getBoundingClientRect().width+f)/c*100,$=(l.b.getBoundingClientRect().width+b)/c*100,v=l.a.getBoundingClientRect().width+f+b+l.b.getBoundingClientRect().width):(y=l.a.getBoundingClientRect().top,w=l.b.getBoundingClientRect().bottom,_=(l.a.getBoundingClientRect().height+f)/c*100,$=(l.b.getBoundingClientRect().height+b)/c*100,v=l.a.getBoundingClientRect().height+f+b+l.b.getBoundingClientRect().height),a.pairs[r]=Object.assign(Object.assign({},l),{start:y,end:w,size:v,aSizePct:_,bSizePct:$,gutterSize:d}),Object.assign({},a)}default:return a}}function Yw(a,s=0,i=[]){return RT.toArray(a).reduce(((r,l,c)=>(GS.isFragment(l)?r.push.apply(r,Yw(l.props.children,s+1,i.concat(l.key||c))):Iw(l)?r.push(Ag(l,{key:i.concat(String(l.key)).join(".")})):typeof l!="string"&&typeof l!="number"||r.push(l),r)),[])}(function(a){a[a.SetIsReadyToCompute=0]="SetIsReadyToCompute",a[a.CreatePairs=1]="CreatePairs",a[a.CalculateSizes=2]="CalculateSizes",a[a.StartDragging=3]="StartDragging",a[a.StopDragging=4]="StopDragging"})(ws||(ws={}));const d_=a=>"changedTouches"in a;var ft,zg;(function(a){a.Horizontal="Horizontal",a.Vertical="Vertical"})(ft||(ft={})),(function(a){a.Light="Light",a.Dark="Dark"})(zg||(zg={}));const $c=typeof window<"u"&&"ontouchstart"in window;function Zp(a){return a===ft.Horizontal?"col-resize":"row-resize"}const KS={isReady:!1,isDragging:!1,pairs:[]};function h_({direction:a=ft.Horizontal,minWidths:s=[],minHeights:i=[],initialSizes:r,gutterTheme:l=zg.Dark,gutterClassName:c,draggerClassName:d,children:h,onResizeStarted:p,onResizeFinished:f,classes:b=[]}){const y=Yw(h),[w,v]=OT(YS,KS),_=Yo(null),$=Yo([]),T=Yo([]);$.current=[],T.current=[];const S=_e.useCallback((M=>{v({type:ws.SetIsReadyToCompute,payload:{isReady:M}})}),[]),E=_e.useCallback(((M,Y)=>{v({type:ws.StartDragging,payload:{gutterIdx:Y}});const C=w.pairs[Y];p==null||p(C.idx),C.a.style.userSelect="none",C.b.style.userSelect="none",C.gutter.style.cursor=Zp(M),C.parent.style.cursor=Zp(M),document.body.style.cursor=Zp(M)}),[w.pairs]),D=_e.useCallback((()=>{v({type:ws.StopDragging});const M=[];for(let C=0;C{v({type:ws.CalculateSizes,payload:{direction:M,gutterIdx:Y}})}),[]),L=_e.useCallback(((M,Y,C)=>{v({type:ws.CreatePairs,payload:{direction:M,children:Y,gutters:C}})}),[]),H=_e.useCallback(((M,Y,C,Q)=>{const ve=Y[0].parentNode;if(!ve)throw new Error("Cannot set initial sizes - parent is undefined");if(Tc(M,ve)===void 0)throw new Error("Cannot set initial sizes - parent has undefined size");Y.forEach(((ce,ne)=>{const me=ne===0,re=ne===Y.length-1;let B,N=0;Y.length>1&&(N=C[re?ne-1:ne].getBoundingClientRect()[M===ft.Horizontal?"width":"height"],N=me||re?N/2:N),B=Q&&ne{if(w.draggingIdx===void 0)throw new Error("Cannot adjust size - 'draggingIdx' is undefined");const C=w.pairs[w.draggingIdx];if(C.size===void 0)throw new Error("Cannot adjust size - 'pair.size' is undefined");if(C.gutterSize===void 0)throw new Error("Cannot adjust size - 'pair.gutterSize' is undefined");const Q=C.aSizePct+C.bSizePct,ve=Y/C.size*Q,ce=Q-Y/C.size*Q,ne=w.draggingIdx===0,me=w.draggingIdx===w.pairs.length-1,{aGutterSize:re,bGutterSize:B}=Fg(C.gutterSize,ne,me),N=`calc(${ve}% - ${re}px)`,te=`calc(${ce}% - ${B}px)`;M===ft.Horizontal?(C.a.style.width=N,C.b.style.width=te):(C.a.style.height=N,C.b.style.height=te)}),[w.draggingIdx,w.pairs,a]),z=_e.useCallback(((M,Y,C)=>{if(!w.isDragging)return;if(w.draggingIdx===void 0)throw new Error("Cannot drag - 'draggingIdx' is undefined");const Q=w.pairs[w.draggingIdx];if(Q.start===void 0)throw new Error("Cannot drag - 'pair.start' is undefined");if(Q.size===void 0)throw new Error("Cannot drag - 'pair.size' is undefined");if(Q.gutterSize===void 0)throw new Error("Cannot drag - 'pair.gutterSize' is undefined");let ve=(function(me,re){const B=d_(re)?re.changedTouches[0]:re;return me===ft.Horizontal?B.clientX:B.clientY})(Y,M)-Q.start,ce=16,ne=16;C.length>w.draggingIdx&&(ce=C[w.draggingIdx]),C.length>=w.draggingIdx+1&&(ne=C[w.draggingIdx+1]),ve=Q.size-(Q.gutterSize+ne)&&(ve=Q.size-(Q.gutterSize+ne)),G(Y,ve)}),[w.isDragging,w.draggingIdx,w.pairs,G]),Z=()=>{if(w.isDragging){if(w.draggingIdx===void 0)throw new Error("Cannot calculate sizes after dragging = 'state.draggingIdx' is undefined");R(a,w.draggingIdx),D()}},he=M=>{w.isDragging&&(d_(M)&&M.preventDefault(),z(M,a,a===ft.Horizontal?s:i))};function Ce(M,Y){if(!M.current)throw new Error("Can't add element to ref object - ref isn't initialized");Y&&!M.current.includes(Y)&&M.current.push(Y)}return nc("mouseup",Z,[w.isDragging,D]),nc("mousemove",he,[a,w.isDragging,z,s,i]),nc("touchend",Z,[w.isDragging,D],{condition:$c}),nc("touchmove",he,[a,w.isDragging,z,s,i],{condition:$c,passive:!$c}),Lt((function(){if(!_.current)return;const M=_.current.parentElement;if(!M)return;const Y=new ResizeObserver((()=>{const C=getComputedStyle(M),Q=a===ft.Horizontal?M.clientWidth:M.clientHeight;S(!!C&&!!Q)}));return Y.observe(M),()=>{Y.disconnect()}}),[_.current,a]),Lt((function(){if(w.isReady&&(!$.current||$.current[0].offsetParent)){if(!$.current||!T.current)throw new Error("Cannot create pairs - either variable 'childRefs' or 'gutterRefs' is undefined");y.length<=1?H(a,$.current,T.current,r):(H(a,$.current,T.current,r),L(a,$.current,T.current))}}),[h,w.isReady,a,H,L,r]),m.jsx("div",Object.assign({className:`__dbk__container ${a}`,ref:_},{children:w.isReady&&y.map(((M,Y)=>m.jsxs(_e.Fragment,{children:[m.jsx("div",Object.assign({ref:C=>Ce($,C),className:"__dbk__child-wrapper "+(YCe(T,C),className:c,theme:l,draggerClassName:d,direction:a,onDragging:()=>{return R(a,C=Y),void E(a,C);var C}},void 0)]},Y)))}),void 0)}const Kw=pm({dragDropManager:void 0});function ea(a){"@babel/helpers - typeof";return ea=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(s){return typeof s}:function(s){return s&&typeof Symbol=="function"&&s.constructor===Symbol&&s!==Symbol.prototype?"symbol":typeof s},ea(a)}function JS(a,s){if(ea(a)!="object"||!a)return a;var i=a[Symbol.toPrimitive];if(i!==void 0){var r=i.call(a,s);if(ea(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(s==="string"?String:Number)(a)}function XS(a){var s=JS(a,"string");return ea(s)=="symbol"?s:s+""}function qS(a,s,i){return(s=XS(s))in a?Object.defineProperty(a,s,{value:i,enumerable:!0,configurable:!0,writable:!0}):a[s]=i,a}function bs(a){return"Minified Redux error #"+a+"; visit https://redux.js.org/Errors?code="+a+" for the full message or use the non-minified dev environment for full errors. "}var p_=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})(),g_=function(){return Math.random().toString(36).substring(7).split("").join(".")},m_={INIT:"@@redux/INIT"+g_(),REPLACE:"@@redux/REPLACE"+g_()};function ZS(a){if(typeof a!="object"||a===null)return!1;for(var s=a;Object.getPrototypeOf(s)!==null;)s=Object.getPrototypeOf(s);return Object.getPrototypeOf(a)===s}function Jw(a,s,i){var r;if(typeof s=="function"&&typeof i=="function"||typeof i=="function"&&typeof arguments[3]=="function")throw new Error(bs(0));if(typeof s=="function"&&typeof i>"u"&&(i=s,s=void 0),typeof i<"u"){if(typeof i!="function")throw new Error(bs(1));return i(Jw)(a,s)}if(typeof a!="function")throw new Error(bs(2));var l=a,c=s,d=[],h=d,p=!1;function f(){h===d&&(h=d.slice())}function b(){if(p)throw new Error(bs(3));return c}function y($){if(typeof $!="function")throw new Error(bs(4));if(p)throw new Error(bs(5));var T=!0;return f(),h.push($),function(){if(T){if(p)throw new Error(bs(6));T=!1,f();var E=h.indexOf($);h.splice(E,1),d=null}}}function w($){if(!ZS($))throw new Error(bs(7));if(typeof $.type>"u")throw new Error(bs(8));if(p)throw new Error(bs(9));try{p=!0,c=l(c,$)}finally{p=!1}for(var T=d=h,S=0;Sr&&r[l]?r[l]:i||null,a)}function tE(a,s){return a.filter(i=>i!==s)}function Xw(a){return typeof a=="object"}function sE(a,s){const i=new Map,r=c=>{i.set(c,i.has(c)?i.get(c)+1:1)};a.forEach(r),s.forEach(r);const l=[];return i.forEach((c,d)=>{c===1&&l.push(d)}),l}function oE(a,s){return a.filter(i=>s.indexOf(i)>-1)}const $m="dnd-core/INIT_COORDS",Zc="dnd-core/BEGIN_DRAG",bm="dnd-core/PUBLISH_DRAG_SOURCE",Qc="dnd-core/HOVER",eu="dnd-core/DROP",tu="dnd-core/END_DRAG";function f_(a,s){return{type:$m,payload:{sourceClientOffset:s||null,clientOffset:a||null}}}const iE={type:$m,payload:{clientOffset:null,sourceClientOffset:null}};function nE(a){return function(i=[],r={publishSource:!0}){const{publishSource:l=!0,clientOffset:c,getSourceClientOffset:d}=r,h=a.getMonitor(),p=a.getRegistry();a.dispatch(f_(c)),rE(i,h,p);const f=cE(i,h);if(f==null){a.dispatch(iE);return}let b=null;if(c){if(!d)throw new Error("getSourceClientOffset must be defined");aE(d),b=d(f)}a.dispatch(f_(c,b));const w=p.getSource(f).beginDrag(h,f);if(w==null)return;lE(w),p.pinSource(f);const v=p.getSourceType(f);return{type:Zc,payload:{itemType:v,item:w,sourceId:f,clientOffset:c||null,sourceClientOffset:b||null,isSourcePublic:!!l}}}}function rE(a,s,i){Ve(!s.isDragging(),"Cannot call beginDrag while dragging."),a.forEach(function(r){Ve(i.getSource(r),"Expected sourceIds to be registered.")})}function aE(a){Ve(typeof a=="function","When clientOffset is provided, getSourceClientOffset must be a function.")}function lE(a){Ve(Xw(a),"Item must be an object.")}function cE(a,s){let i=null;for(let r=a.length-1;r>=0;r--)if(s.canDragSource(a[r])){i=a[r];break}return i}function uE(a,s,i){return s in a?Object.defineProperty(a,s,{value:i,enumerable:!0,configurable:!0,writable:!0}):a[s]=i,a}function dE(a){for(var s=1;s{const p=gE(d,h,l,r),f={type:eu,payload:{dropResult:dE({},i,p)}};a.dispatch(f)})}}function pE(a){Ve(a.isDragging(),"Cannot call drop while not dragging."),Ve(!a.didDrop(),"Cannot call drop twice during one drag operation.")}function gE(a,s,i,r){const l=i.getTarget(a);let c=l?l.drop(r,a):void 0;return mE(c),typeof c>"u"&&(c=s===0?{}:r.getDropResult()),c}function mE(a){Ve(typeof a>"u"||Xw(a),"Drop result must either be an object or undefined.")}function fE(a){const s=a.getTargetIds().filter(a.canDropOnTarget,a);return s.reverse(),s}function $E(a){return function(){const i=a.getMonitor(),r=a.getRegistry();bE(i);const l=i.getSourceId();return l!=null&&(r.getSource(l,!0).endDrag(i,l),r.unpinSource()),{type:tu}}}function bE(a){Ve(a.isDragging(),"Cannot call endDrag while not dragging.")}function Ug(a,s){return s===null?a===null:Array.isArray(a)?a.some(i=>i===s):a===s}function vE(a){return function(i,{clientOffset:r}={}){yE(i);const l=i.slice(0),c=a.getMonitor(),d=a.getRegistry(),h=c.getItemType();return wE(l,d,h),_E(l,c,d),kE(l,c,d),{type:Qc,payload:{targetIds:l,clientOffset:r||null}}}}function yE(a){Ve(Array.isArray(a),"Expected targetIds to be an array.")}function _E(a,s,i){Ve(s.isDragging(),"Cannot call hover while not dragging."),Ve(!s.didDrop(),"Cannot call hover after drop.");for(let r=0;r=0;r--){const l=a[r],c=s.getTargetType(l);Ug(c,i)||a.splice(r,1)}}function kE(a,s,i){a.forEach(function(r){i.getTarget(r).hover(s,r)})}function CE(a){return function(){if(a.getMonitor().isDragging())return{type:bm}}}function TE(a){return{beginDrag:nE(a),publishDragSource:CE(a),hover:vE(a),drop:hE(a),endDrag:$E(a)}}class SE{receiveBackend(s){this.backend=s}getMonitor(){return this.monitor}getBackend(){return this.backend}getRegistry(){return this.monitor.registry}getActions(){const s=this,{dispatch:i}=this.store;function r(c){return(...d)=>{const h=c.apply(s,d);typeof h<"u"&&i(h)}}const l=TE(this);return Object.keys(l).reduce((c,d)=>{const h=l[d];return c[d]=r(h),c},{})}dispatch(s){this.store.dispatch(s)}constructor(s,i){this.isSetUp=!1,this.handleRefCountChange=()=>{const r=this.store.getState().refCount>0;this.backend&&(r&&!this.isSetUp?(this.backend.setup(),this.isSetUp=!0):!r&&this.isSetUp&&(this.backend.teardown(),this.isSetUp=!1))},this.store=s,this.monitor=i,s.subscribe(this.handleRefCountChange)}}function EE(a,s){return{x:a.x+s.x,y:a.y+s.y}}function qw(a,s){return{x:a.x-s.x,y:a.y-s.y}}function IE(a){const{clientOffset:s,initialClientOffset:i,initialSourceClientOffset:r}=a;return!s||!i||!r?null:qw(EE(s,r),i)}function xE(a){const{clientOffset:s,initialClientOffset:i}=a;return!s||!i?null:qw(s,i)}const Kr=[],vm=[];Kr.__IS_NONE__=!0;vm.__IS_ALL__=!0;function DE(a,s){return a===Kr?!1:a===vm||typeof s>"u"?!0:oE(s,a).length>0}class AE{subscribeToStateChange(s,i={}){const{handlerIds:r}=i;Ve(typeof s=="function","listener must be a function."),Ve(typeof r>"u"||Array.isArray(r),"handlerIds, when specified, must be an array of strings.");let l=this.store.getState().stateId;const c=()=>{const d=this.store.getState(),h=d.stateId;try{h===l||h===l+1&&!DE(d.dirtyHandlerIds,r)||s()}finally{l=h}};return this.store.subscribe(c)}subscribeToOffsetChange(s){Ve(typeof s=="function","listener must be a function.");let i=this.store.getState().dragOffset;const r=()=>{const l=this.store.getState().dragOffset;l!==i&&(i=l,s())};return this.store.subscribe(r)}canDragSource(s){if(!s)return!1;const i=this.registry.getSource(s);return Ve(i,`Expected to find a valid source. sourceId=${s}`),this.isDragging()?!1:i.canDrag(this,s)}canDropOnTarget(s){if(!s)return!1;const i=this.registry.getTarget(s);if(Ve(i,`Expected to find a valid target. targetId=${s}`),!this.isDragging()||this.didDrop())return!1;const r=this.registry.getTargetType(s),l=this.getItemType();return Ug(r,l)&&i.canDrop(this,s)}isDragging(){return!!this.getItemType()}isDraggingSource(s){if(!s)return!1;const i=this.registry.getSource(s,!0);if(Ve(i,`Expected to find a valid source. sourceId=${s}`),!this.isDragging()||!this.isSourcePublic())return!1;const r=this.registry.getSourceType(s),l=this.getItemType();return r!==l?!1:i.isDragging(this,s)}isOverTarget(s,i={shallow:!1}){if(!s)return!1;const{shallow:r}=i;if(!this.isDragging())return!1;const l=this.registry.getTargetType(s),c=this.getItemType();if(c&&!Ug(l,c))return!1;const d=this.getTargetIds();if(!d.length)return!1;const h=d.indexOf(s);return r?h===d.length-1:h>-1}getItemType(){return this.store.getState().dragOperation.itemType}getItem(){return this.store.getState().dragOperation.item}getSourceId(){return this.store.getState().dragOperation.sourceId}getTargetIds(){return this.store.getState().dragOperation.targetIds}getDropResult(){return this.store.getState().dragOperation.dropResult}didDrop(){return this.store.getState().dragOperation.didDrop}isSourcePublic(){return!!this.store.getState().dragOperation.isSourcePublic}getInitialClientOffset(){return this.store.getState().dragOffset.initialClientOffset}getInitialSourceClientOffset(){return this.store.getState().dragOffset.initialSourceClientOffset}getClientOffset(){return this.store.getState().dragOffset.clientOffset}getSourceClientOffset(){return IE(this.store.getState().dragOffset)}getDifferenceFromInitialOffset(){return xE(this.store.getState().dragOffset)}constructor(s,i){this.store=s,this.registry=i}}const $_=typeof global<"u"?global:self,Zw=$_.MutationObserver||$_.WebKitMutationObserver;function Qw(a){return function(){const i=setTimeout(l,0),r=setInterval(l,50);function l(){clearTimeout(i),clearInterval(r),a()}}}function OE(a){let s=1;const i=new Zw(a),r=document.createTextNode("");return i.observe(r,{characterData:!0}),function(){s=-s,r.data=s}}const RE=typeof Zw=="function"?OE:Qw;class ME{enqueueTask(s){const{queue:i,requestFlush:r}=this;i.length||(r(),this.flushing=!0),i[i.length]=s}constructor(){this.queue=[],this.pendingErrors=[],this.flushing=!1,this.index=0,this.capacity=1024,this.flush=()=>{const{queue:s}=this;for(;this.indexthis.capacity){for(let r=0,l=s.length-this.index;r{this.pendingErrors.push(s),this.requestErrorThrow()},this.requestFlush=RE(this.flush),this.requestErrorThrow=Qw(()=>{if(this.pendingErrors.length)throw this.pendingErrors.shift()})}}class NE{call(){try{this.task&&this.task()}catch(s){this.onError(s)}finally{this.task=null,this.release(this)}}constructor(s,i){this.onError=s,this.release=i,this.task=null}}class LE{create(s){const i=this.freeTasks,r=i.length?i.pop():new NE(this.onError,l=>i[i.length]=l);return r.task=s,r}constructor(s){this.onError=s,this.freeTasks=[]}}const ek=new ME,PE=new LE(ek.registerPendingError);function BE(a){ek.enqueueTask(PE.create(a))}const ym="dnd-core/ADD_SOURCE",_m="dnd-core/ADD_TARGET",wm="dnd-core/REMOVE_SOURCE",su="dnd-core/REMOVE_TARGET";function jE(a){return{type:ym,payload:{sourceId:a}}}function FE(a){return{type:_m,payload:{targetId:a}}}function zE(a){return{type:wm,payload:{sourceId:a}}}function UE(a){return{type:su,payload:{targetId:a}}}function HE(a){Ve(typeof a.canDrag=="function","Expected canDrag to be a function."),Ve(typeof a.beginDrag=="function","Expected beginDrag to be a function."),Ve(typeof a.endDrag=="function","Expected endDrag to be a function.")}function WE(a){Ve(typeof a.canDrop=="function","Expected canDrop to be a function."),Ve(typeof a.hover=="function","Expected hover to be a function."),Ve(typeof a.drop=="function","Expected beginDrag to be a function.")}function Hg(a,s){if(s&&Array.isArray(a)){a.forEach(i=>Hg(i,!1));return}Ve(typeof a=="string"||typeof a=="symbol",s?"Type can only be a string, a symbol, or an array of either.":"Type can only be a string or a symbol.")}var _s;(function(a){a.SOURCE="SOURCE",a.TARGET="TARGET"})(_s||(_s={}));let GE=0;function VE(){return GE++}function YE(a){const s=VE().toString();switch(a){case _s.SOURCE:return`S${s}`;case _s.TARGET:return`T${s}`;default:throw new Error(`Unknown Handler Role: ${a}`)}}function b_(a){switch(a[0]){case"S":return _s.SOURCE;case"T":return _s.TARGET;default:throw new Error(`Cannot parse handler ID: ${a}`)}}function v_(a,s){const i=a.entries();let r=!1;do{const{done:l,value:[,c]}=i.next();if(c===s)return!0;r=!!l}while(!r);return!1}class KE{addSource(s,i){Hg(s),HE(i);const r=this.addHandler(_s.SOURCE,s,i);return this.store.dispatch(jE(r)),r}addTarget(s,i){Hg(s,!0),WE(i);const r=this.addHandler(_s.TARGET,s,i);return this.store.dispatch(FE(r)),r}containsHandler(s){return v_(this.dragSources,s)||v_(this.dropTargets,s)}getSource(s,i=!1){return Ve(this.isSourceId(s),"Expected a valid source ID."),i&&s===this.pinnedSourceId?this.pinnedSource:this.dragSources.get(s)}getTarget(s){return Ve(this.isTargetId(s),"Expected a valid target ID."),this.dropTargets.get(s)}getSourceType(s){return Ve(this.isSourceId(s),"Expected a valid source ID."),this.types.get(s)}getTargetType(s){return Ve(this.isTargetId(s),"Expected a valid target ID."),this.types.get(s)}isSourceId(s){return b_(s)===_s.SOURCE}isTargetId(s){return b_(s)===_s.TARGET}removeSource(s){Ve(this.getSource(s),"Expected an existing source."),this.store.dispatch(zE(s)),BE(()=>{this.dragSources.delete(s),this.types.delete(s)})}removeTarget(s){Ve(this.getTarget(s),"Expected an existing target."),this.store.dispatch(UE(s)),this.dropTargets.delete(s),this.types.delete(s)}pinSource(s){const i=this.getSource(s);Ve(i,"Expected an existing source."),this.pinnedSourceId=s,this.pinnedSource=i}unpinSource(){Ve(this.pinnedSource,"No source is pinned at the time."),this.pinnedSourceId=null,this.pinnedSource=null}addHandler(s,i,r){const l=YE(s);return this.types.set(l,i),s===_s.SOURCE?this.dragSources.set(l,r):s===_s.TARGET&&this.dropTargets.set(l,r),l}constructor(s){this.types=new Map,this.dragSources=new Map,this.dropTargets=new Map,this.pinnedSourceId=null,this.pinnedSource=null,this.store=s}}const JE=(a,s)=>a===s;function XE(a,s){return!a&&!s?!0:!a||!s?!1:a.x===s.x&&a.y===s.y}function qE(a,s,i=JE){if(a.length!==s.length)return!1;for(let r=0;r0||!qE(i,r)))return Kr;const d=r[r.length-1],h=i[i.length-1];return d!==h&&(d&&l.push(d),h&&l.push(h)),l}function QE(a,s,i){return s in a?Object.defineProperty(a,s,{value:i,enumerable:!0,configurable:!0,writable:!0}):a[s]=i,a}function eI(a){for(var s=1;s=0)&&Object.prototype.propertyIsEnumerable.call(a,r)&&(i[r]=a[r])}return i}function pI(a,s){if(a==null)return{};var i={},r=Object.keys(a),l,c;for(c=0;c=0)&&(i[l]=a[l]);return i}let __=0;const bc=Symbol.for("__REACT_DND_CONTEXT_INSTANCE__");var tk=gm(function(s){var{children:i}=s,r=hI(s,["children"]);const[l,c]=gI(r);return Lt(()=>{if(c){const d=sk();return++__,()=>{--__===0&&(d[bc]=null)}}},[]),m.jsx(Kw.Provider,{value:l,children:i})});function gI(a){if("manager"in a)return[{dragDropManager:a.manager},!1];const s=mI(a.backend,a.context,a.options,a.debugMode),i=!a.context;return[s,i]}function mI(a,s=sk(),i,r){const l=s;return l[bc]||(l[bc]={dragDropManager:uI(a,s,i,r)}),l[bc]}function sk(){return typeof global<"u"?global:window}var fI=function a(s,i){if(s===i)return!0;if(s&&i&&typeof s=="object"&&typeof i=="object"){if(s.constructor!==i.constructor)return!1;var r,l,c;if(Array.isArray(s)){if(r=s.length,r!=i.length)return!1;for(l=r;l--!==0;)if(!a(s[l],i[l]))return!1;return!0}if(s.constructor===RegExp)return s.source===i.source&&s.flags===i.flags;if(s.valueOf!==Object.prototype.valueOf)return s.valueOf()===i.valueOf();if(s.toString!==Object.prototype.toString)return s.toString()===i.toString();if(c=Object.keys(s),r=c.length,r!==Object.keys(i).length)return!1;for(l=r;l--!==0;)if(!Object.prototype.hasOwnProperty.call(i,c[l]))return!1;for(l=r;l--!==0;){var d=c[l];if(!a(s[d],i[d]))return!1}return!0}return s!==s&&i!==i};const $I=qo(fI),Oi=typeof window<"u"?mm:Lt;function bI(a,s,i){const[r,l]=kt(()=>s(a)),c=xn(()=>{const d=s(a);$I(r,d)||(l(d),i&&i())},[r,a,i]);return Oi(c),[r,c]}function vI(a,s,i){const[r,l]=bI(a,s,i);return Oi(function(){const d=a.getHandlerId();if(d!=null)return a.subscribeToStateChange(l,{handlerIds:[d]})},[a,l]),r}function ok(a,s,i){return vI(s,a||(()=>({})),()=>i.reconnect())}function ik(a,s){const i=[];return typeof a!="function"&&i.push(a),us(()=>typeof a=="function"?a():a,i)}function yI(a){return us(()=>a.hooks.dragSource(),[a])}function _I(a){return us(()=>a.hooks.dragPreview(),[a])}let Qp=!1,eg=!1;class wI{receiveHandlerId(s){this.sourceId=s}getHandlerId(){return this.sourceId}canDrag(){Ve(!Qp,"You may not call monitor.canDrag() inside your canDrag() implementation. Read more: http://react-dnd.github.io/react-dnd/docs/api/drag-source-monitor");try{return Qp=!0,this.internalMonitor.canDragSource(this.sourceId)}finally{Qp=!1}}isDragging(){if(!this.sourceId)return!1;Ve(!eg,"You may not call monitor.isDragging() inside your isDragging() implementation. Read more: http://react-dnd.github.io/react-dnd/docs/api/drag-source-monitor");try{return eg=!0,this.internalMonitor.isDraggingSource(this.sourceId)}finally{eg=!1}}subscribeToStateChange(s,i){return this.internalMonitor.subscribeToStateChange(s,i)}isDraggingSource(s){return this.internalMonitor.isDraggingSource(s)}isOverTarget(s,i){return this.internalMonitor.isOverTarget(s,i)}getTargetIds(){return this.internalMonitor.getTargetIds()}isSourcePublic(){return this.internalMonitor.isSourcePublic()}getSourceId(){return this.internalMonitor.getSourceId()}subscribeToOffsetChange(s){return this.internalMonitor.subscribeToOffsetChange(s)}canDragSource(s){return this.internalMonitor.canDragSource(s)}canDropOnTarget(s){return this.internalMonitor.canDropOnTarget(s)}getItemType(){return this.internalMonitor.getItemType()}getItem(){return this.internalMonitor.getItem()}getDropResult(){return this.internalMonitor.getDropResult()}didDrop(){return this.internalMonitor.didDrop()}getInitialClientOffset(){return this.internalMonitor.getInitialClientOffset()}getInitialSourceClientOffset(){return this.internalMonitor.getInitialSourceClientOffset()}getSourceClientOffset(){return this.internalMonitor.getSourceClientOffset()}getClientOffset(){return this.internalMonitor.getClientOffset()}getDifferenceFromInitialOffset(){return this.internalMonitor.getDifferenceFromInitialOffset()}constructor(s){this.sourceId=null,this.internalMonitor=s.getMonitor()}}let tg=!1;class kI{receiveHandlerId(s){this.targetId=s}getHandlerId(){return this.targetId}subscribeToStateChange(s,i){return this.internalMonitor.subscribeToStateChange(s,i)}canDrop(){if(!this.targetId)return!1;Ve(!tg,"You may not call monitor.canDrop() inside your canDrop() implementation. Read more: http://react-dnd.github.io/react-dnd/docs/api/drop-target-monitor");try{return tg=!0,this.internalMonitor.canDropOnTarget(this.targetId)}finally{tg=!1}}isOver(s){return this.targetId?this.internalMonitor.isOverTarget(this.targetId,s):!1}getItemType(){return this.internalMonitor.getItemType()}getItem(){return this.internalMonitor.getItem()}getDropResult(){return this.internalMonitor.getDropResult()}didDrop(){return this.internalMonitor.didDrop()}getInitialClientOffset(){return this.internalMonitor.getInitialClientOffset()}getInitialSourceClientOffset(){return this.internalMonitor.getInitialSourceClientOffset()}getSourceClientOffset(){return this.internalMonitor.getSourceClientOffset()}getClientOffset(){return this.internalMonitor.getClientOffset()}getDifferenceFromInitialOffset(){return this.internalMonitor.getDifferenceFromInitialOffset()}constructor(s){this.targetId=null,this.internalMonitor=s.getMonitor()}}function CI(a,s,i){const r=i.getRegistry(),l=r.addTarget(a,s);return[l,()=>r.removeTarget(l)]}function TI(a,s,i){const r=i.getRegistry(),l=r.addSource(a,s);return[l,()=>r.removeSource(l)]}function Wg(a,s,i,r){let l;if(l!==void 0)return!!l;if(a===s)return!0;if(typeof a!="object"||!a||typeof s!="object"||!s)return!1;const c=Object.keys(a),d=Object.keys(s);if(c.length!==d.length)return!1;const h=Object.prototype.hasOwnProperty.bind(s);for(let p=0;p, or turn it into a drag source or a drop target itself.`)}function EI(a){return(s=null,i=null)=>{if(!Iw(s)){const c=s;return a(c,i),c}const r=s;return SI(r),II(r,i?c=>a(c,i):a)}}function nk(a){const s={};return Object.keys(a).forEach(i=>{const r=a[i];if(i.endsWith("Ref"))s[i]=a[i];else{const l=EI(r);s[i]=()=>l}}),s}function w_(a,s){typeof a=="function"?a(s):a.current=s}function II(a,s){const i=a.ref;return Ve(typeof i!="string","Cannot connect React DnD to an element with an existing string ref. Please convert it to use a callback ref instead, or wrap it into a or
. Read more: https://reactjs.org/docs/refs-and-the-dom.html#callback-refs"),i?Ag(a,{ref:r=>{w_(i,r),w_(s,r)}}):Ag(a,{ref:s})}class xI{receiveHandlerId(s){this.handlerId!==s&&(this.handlerId=s,this.reconnect())}get connectTarget(){return this.dragSource}get dragSourceOptions(){return this.dragSourceOptionsInternal}set dragSourceOptions(s){this.dragSourceOptionsInternal=s}get dragPreviewOptions(){return this.dragPreviewOptionsInternal}set dragPreviewOptions(s){this.dragPreviewOptionsInternal=s}reconnect(){const s=this.reconnectDragSource();this.reconnectDragPreview(s)}reconnectDragSource(){const s=this.dragSource,i=this.didHandlerIdChange()||this.didConnectedDragSourceChange()||this.didDragSourceOptionsChange();return i&&this.disconnectDragSource(),this.handlerId?s?(i&&(this.lastConnectedHandlerId=this.handlerId,this.lastConnectedDragSource=s,this.lastConnectedDragSourceOptions=this.dragSourceOptions,this.dragSourceUnsubscribe=this.backend.connectDragSource(this.handlerId,s,this.dragSourceOptions)),i):(this.lastConnectedDragSource=s,i):i}reconnectDragPreview(s=!1){const i=this.dragPreview,r=s||this.didHandlerIdChange()||this.didConnectedDragPreviewChange()||this.didDragPreviewOptionsChange();if(r&&this.disconnectDragPreview(),!!this.handlerId){if(!i){this.lastConnectedDragPreview=i;return}r&&(this.lastConnectedHandlerId=this.handlerId,this.lastConnectedDragPreview=i,this.lastConnectedDragPreviewOptions=this.dragPreviewOptions,this.dragPreviewUnsubscribe=this.backend.connectDragPreview(this.handlerId,i,this.dragPreviewOptions))}}didHandlerIdChange(){return this.lastConnectedHandlerId!==this.handlerId}didConnectedDragSourceChange(){return this.lastConnectedDragSource!==this.dragSource}didConnectedDragPreviewChange(){return this.lastConnectedDragPreview!==this.dragPreview}didDragSourceOptionsChange(){return!Wg(this.lastConnectedDragSourceOptions,this.dragSourceOptions)}didDragPreviewOptionsChange(){return!Wg(this.lastConnectedDragPreviewOptions,this.dragPreviewOptions)}disconnectDragSource(){this.dragSourceUnsubscribe&&(this.dragSourceUnsubscribe(),this.dragSourceUnsubscribe=void 0)}disconnectDragPreview(){this.dragPreviewUnsubscribe&&(this.dragPreviewUnsubscribe(),this.dragPreviewUnsubscribe=void 0,this.dragPreviewNode=null,this.dragPreviewRef=null)}get dragSource(){return this.dragSourceNode||this.dragSourceRef&&this.dragSourceRef.current}get dragPreview(){return this.dragPreviewNode||this.dragPreviewRef&&this.dragPreviewRef.current}clearDragSource(){this.dragSourceNode=null,this.dragSourceRef=null}clearDragPreview(){this.dragPreviewNode=null,this.dragPreviewRef=null}constructor(s){this.hooks=nk({dragSource:(i,r)=>{this.clearDragSource(),this.dragSourceOptions=r||null,Gg(i)?this.dragSourceRef=i:this.dragSourceNode=i,this.reconnectDragSource()},dragPreview:(i,r)=>{this.clearDragPreview(),this.dragPreviewOptions=r||null,Gg(i)?this.dragPreviewRef=i:this.dragPreviewNode=i,this.reconnectDragPreview()}}),this.handlerId=null,this.dragSourceRef=null,this.dragSourceOptionsInternal=null,this.dragPreviewRef=null,this.dragPreviewOptionsInternal=null,this.lastConnectedHandlerId=null,this.lastConnectedDragSource=null,this.lastConnectedDragSourceOptions=null,this.lastConnectedDragPreview=null,this.lastConnectedDragPreviewOptions=null,this.backend=s}}class DI{get connectTarget(){return this.dropTarget}reconnect(){const s=this.didHandlerIdChange()||this.didDropTargetChange()||this.didOptionsChange();s&&this.disconnectDropTarget();const i=this.dropTarget;if(this.handlerId){if(!i){this.lastConnectedDropTarget=i;return}s&&(this.lastConnectedHandlerId=this.handlerId,this.lastConnectedDropTarget=i,this.lastConnectedDropTargetOptions=this.dropTargetOptions,this.unsubscribeDropTarget=this.backend.connectDropTarget(this.handlerId,i,this.dropTargetOptions))}}receiveHandlerId(s){s!==this.handlerId&&(this.handlerId=s,this.reconnect())}get dropTargetOptions(){return this.dropTargetOptionsInternal}set dropTargetOptions(s){this.dropTargetOptionsInternal=s}didHandlerIdChange(){return this.lastConnectedHandlerId!==this.handlerId}didDropTargetChange(){return this.lastConnectedDropTarget!==this.dropTarget}didOptionsChange(){return!Wg(this.lastConnectedDropTargetOptions,this.dropTargetOptions)}disconnectDropTarget(){this.unsubscribeDropTarget&&(this.unsubscribeDropTarget(),this.unsubscribeDropTarget=void 0)}get dropTarget(){return this.dropTargetNode||this.dropTargetRef&&this.dropTargetRef.current}clearDropTarget(){this.dropTargetRef=null,this.dropTargetNode=null}constructor(s){this.hooks=nk({dropTarget:(i,r)=>{this.clearDropTarget(),this.dropTargetOptions=r,Gg(i)?this.dropTargetRef=i:this.dropTargetNode=i,this.reconnect()}}),this.handlerId=null,this.dropTargetRef=null,this.dropTargetOptionsInternal=null,this.lastConnectedHandlerId=null,this.lastConnectedDropTarget=null,this.lastConnectedDropTargetOptions=null,this.backend=s}}function zn(){const{dragDropManager:a}=na(Kw);return Ve(a!=null,"Expected drag drop context"),a}function AI(a,s){const i=zn(),r=us(()=>new xI(i.getBackend()),[i]);return Oi(()=>(r.dragSourceOptions=a||null,r.reconnect(),()=>r.disconnectDragSource()),[r,a]),Oi(()=>(r.dragPreviewOptions=s||null,r.reconnect(),()=>r.disconnectDragPreview()),[r,s]),r}function OI(){const a=zn();return us(()=>new wI(a),[a])}class RI{beginDrag(){const s=this.spec,i=this.monitor;let r=null;return typeof s.item=="object"?r=s.item:typeof s.item=="function"?r=s.item(i):r={},r??null}canDrag(){const s=this.spec,i=this.monitor;return typeof s.canDrag=="boolean"?s.canDrag:typeof s.canDrag=="function"?s.canDrag(i):!0}isDragging(s,i){const r=this.spec,l=this.monitor,{isDragging:c}=r;return c?c(l):i===s.getSourceId()}endDrag(){const s=this.spec,i=this.monitor,r=this.connector,{end:l}=s;l&&l(i.getItem(),i),r.reconnect()}constructor(s,i,r){this.spec=s,this.monitor=i,this.connector=r}}function MI(a,s,i){const r=us(()=>new RI(a,s,i),[s,i]);return Lt(()=>{r.spec=a},[a]),r}function NI(a){return us(()=>{const s=a.type;return Ve(s!=null,"spec.type must be defined"),s},[a])}function LI(a,s,i){const r=zn(),l=MI(a,s,i),c=NI(a);Oi(function(){if(c!=null){const[h,p]=TI(c,l,r);return s.receiveHandlerId(h),i.receiveHandlerId(h),p}},[r,s,i,l,c])}function PI(a,s){const i=ik(a);Ve(!i.begin,"useDrag::spec.begin was deprecated in v14. Replace spec.begin() with spec.item(). (see more here - https://react-dnd.github.io/react-dnd/docs/api/use-drag)");const r=OI(),l=AI(i.options,i.previewOptions);return LI(i,r,l),[ok(i.collect,r,l),yI(l),_I(l)]}function BI(a){return us(()=>a.hooks.dropTarget(),[a])}function jI(a){const s=zn(),i=us(()=>new DI(s.getBackend()),[s]);return Oi(()=>(i.dropTargetOptions=a||null,i.reconnect(),()=>i.disconnectDropTarget()),[a]),i}function FI(){const a=zn();return us(()=>new kI(a),[a])}function zI(a){const{accept:s}=a;return us(()=>(Ve(a.accept!=null,"accept must be defined"),Array.isArray(s)?s:[s]),[s])}class UI{canDrop(){const s=this.spec,i=this.monitor;return s.canDrop?s.canDrop(i.getItem(),i):!0}hover(){const s=this.spec,i=this.monitor;s.hover&&s.hover(i.getItem(),i)}drop(){const s=this.spec,i=this.monitor;if(s.drop)return s.drop(i.getItem(),i)}constructor(s,i){this.spec=s,this.monitor=i}}function HI(a,s){const i=us(()=>new UI(a,s),[s]);return Lt(()=>{i.spec=a},[a]),i}function WI(a,s,i){const r=zn(),l=HI(a,s),c=zI(a);Oi(function(){const[h,p]=CI(c,l,r);return s.receiveHandlerId(h),i.receiveHandlerId(h),p},[r,s,l,i,c.map(d=>d.toString()).join("|")])}function GI(a,s){const i=ik(a),r=FI(),l=jI(i.options);return WI(i,r,l),[ok(i.collect,r,l),BI(l)]}function rk(a){let s=null;return()=>(s==null&&(s=a()),s)}function VI(a,s){return a.filter(i=>i!==s)}function YI(a,s){const i=new Set,r=c=>i.add(c);a.forEach(r),s.forEach(r);const l=[];return i.forEach(c=>l.push(c)),l}class KI{enter(s){const i=this.entered.length,r=l=>this.isNodeInDocument(l)&&(!l.contains||l.contains(s));return this.entered=YI(this.entered.filter(r),[s]),i===0&&this.entered.length>0}leave(s){const i=this.entered.length;return this.entered=VI(this.entered.filter(this.isNodeInDocument),s),i>0&&this.entered.length===0}reset(){this.entered=[]}constructor(s){this.entered=[],this.isNodeInDocument=s}}class JI{initializeExposedProperties(){Object.keys(this.config.exposeProperties).forEach(s=>{Object.defineProperty(this.item,s,{configurable:!0,enumerable:!0,get(){return console.warn(`Browser doesn't allow reading "${s}" until the drop event.`),null}})})}loadDataTransfer(s){if(s){const i={};Object.keys(this.config.exposeProperties).forEach(r=>{const l=this.config.exposeProperties[r];l!=null&&(i[r]={value:l(s,this.config.matchesTypes),configurable:!0,enumerable:!0})}),Object.defineProperties(this.item,i)}}canDrag(){return!0}beginDrag(){return this.item}isDragging(s,i){return i===s.getSourceId()}endDrag(){}constructor(s){this.config=s,this.item={},this.initializeExposedProperties()}}const ak="__NATIVE_FILE__",lk="__NATIVE_URL__",ck="__NATIVE_TEXT__",uk="__NATIVE_HTML__",k_=Object.freeze(Object.defineProperty({__proto__:null,FILE:ak,HTML:uk,TEXT:ck,URL:lk},Symbol.toStringTag,{value:"Module"}));function sg(a,s,i){const r=s.reduce((l,c)=>l||a.getData(c),"");return r??i}const Vg={[ak]:{exposeProperties:{files:a=>Array.prototype.slice.call(a.files),items:a=>a.items,dataTransfer:a=>a},matchesTypes:["Files"]},[uk]:{exposeProperties:{html:(a,s)=>sg(a,s,""),dataTransfer:a=>a},matchesTypes:["Html","text/html"]},[lk]:{exposeProperties:{urls:(a,s)=>sg(a,s,"").split(` +`),dataTransfer:a=>a},matchesTypes:["Url","text/uri-list"]},[ck]:{exposeProperties:{text:(a,s)=>sg(a,s,""),dataTransfer:a=>a},matchesTypes:["Text","text/plain"]}};function XI(a,s){const i=Vg[a];if(!i)throw new Error(`native type ${a} has no configuration`);const r=new JI(i);return r.loadDataTransfer(s),r}function og(a){if(!a)return null;const s=Array.prototype.slice.call(a.types||[]);return Object.keys(Vg).filter(i=>{const r=Vg[i];return r!=null&&r.matchesTypes?r.matchesTypes.some(l=>s.indexOf(l)>-1):!1})[0]||null}const qI=rk(()=>/firefox/i.test(navigator.userAgent)),dk=rk(()=>!!window.safari);class C_{interpolate(s){const{xs:i,ys:r,c1s:l,c2s:c,c3s:d}=this;let h=i.length-1;if(s===i[h])return r[h];let p=0,f=d.length-1,b;for(;p<=f;){b=Math.floor(.5*(p+f));const v=i[b];if(vs)f=b-1;else return r[b]}h=Math.max(0,f);const y=s-i[h],w=y*y;return r[h]+l[h]*y+c[h]*w+d[h]*y*w}constructor(s,i){const{length:r}=s,l=[];for(let v=0;vs[v]{let H=new C_([0,.5,1],[p.y,p.y/b*_,p.y+_-b]).interpolate(w);return dk()&&c&&(H+=(window.devicePixelRatio-1)*_),H},T=()=>new C_([0,.5,1],[p.x,p.x/f*v,p.x+v-f]).interpolate(y),{offsetX:S,offsetY:E}=l,D=S===0||S,R=E===0||E;return{x:D?S:T(),y:R?E:$()}}let sx=class{get window(){if(this.globalContext)return this.globalContext;if(typeof window<"u")return window}get document(){var s;return!((s=this.globalContext)===null||s===void 0)&&s.document?this.globalContext.document:this.window?this.window.document:void 0}get rootElement(){var s;return((s=this.optionsArgs)===null||s===void 0?void 0:s.rootElement)||this.window}constructor(s,i){this.ownerDocument=null,this.globalContext=s,this.optionsArgs=i}};function ox(a,s,i){return s in a?Object.defineProperty(a,s,{value:i,enumerable:!0,configurable:!0,writable:!0}):a[s]=i,a}function T_(a){for(var s=1;s{this.sourcePreviewNodes.delete(s),this.sourcePreviewNodeOptions.delete(s)}}connectDragSource(s,i,r){this.sourceNodes.set(s,i),this.sourceNodeOptions.set(s,r);const l=d=>this.handleDragStart(d,s),c=d=>this.handleSelectStart(d);return i.setAttribute("draggable","true"),i.addEventListener("dragstart",l),i.addEventListener("selectstart",c),()=>{this.sourceNodes.delete(s),this.sourceNodeOptions.delete(s),i.removeEventListener("dragstart",l),i.removeEventListener("selectstart",c),i.setAttribute("draggable","false")}}connectDropTarget(s,i){const r=d=>this.handleDragEnter(d,s),l=d=>this.handleDragOver(d,s),c=d=>this.handleDrop(d,s);return i.addEventListener("dragenter",r),i.addEventListener("dragover",l),i.addEventListener("drop",c),()=>{i.removeEventListener("dragenter",r),i.removeEventListener("dragover",l),i.removeEventListener("drop",c)}}addEventListeners(s){s.addEventListener&&(s.addEventListener("dragstart",this.handleTopDragStart),s.addEventListener("dragstart",this.handleTopDragStartCapture,!0),s.addEventListener("dragend",this.handleTopDragEndCapture,!0),s.addEventListener("dragenter",this.handleTopDragEnter),s.addEventListener("dragenter",this.handleTopDragEnterCapture,!0),s.addEventListener("dragleave",this.handleTopDragLeaveCapture,!0),s.addEventListener("dragover",this.handleTopDragOver),s.addEventListener("dragover",this.handleTopDragOverCapture,!0),s.addEventListener("drop",this.handleTopDrop),s.addEventListener("drop",this.handleTopDropCapture,!0))}removeEventListeners(s){s.removeEventListener&&(s.removeEventListener("dragstart",this.handleTopDragStart),s.removeEventListener("dragstart",this.handleTopDragStartCapture,!0),s.removeEventListener("dragend",this.handleTopDragEndCapture,!0),s.removeEventListener("dragenter",this.handleTopDragEnter),s.removeEventListener("dragenter",this.handleTopDragEnterCapture,!0),s.removeEventListener("dragleave",this.handleTopDragLeaveCapture,!0),s.removeEventListener("dragover",this.handleTopDragOver),s.removeEventListener("dragover",this.handleTopDragOverCapture,!0),s.removeEventListener("drop",this.handleTopDrop),s.removeEventListener("drop",this.handleTopDropCapture,!0))}getCurrentSourceNodeOptions(){const s=this.monitor.getSourceId(),i=this.sourceNodeOptions.get(s);return T_({dropEffect:this.altKeyPressed?"copy":"move"},i||{})}getCurrentDropEffect(){return this.isDraggingNativeItem()?"copy":this.getCurrentSourceNodeOptions().dropEffect}getCurrentSourcePreviewNodeOptions(){const s=this.monitor.getSourceId(),i=this.sourcePreviewNodeOptions.get(s);return T_({anchorX:.5,anchorY:.5,captureDraggingState:!1},i||{})}isDraggingNativeItem(){const s=this.monitor.getItemType();return Object.keys(k_).some(i=>k_[i]===s)}beginDragNativeItem(s,i){this.clearCurrentDragSourceNode(),this.currentNativeSource=XI(s,i),this.currentNativeHandle=this.registry.addSource(s,this.currentNativeSource),this.actions.beginDrag([this.currentNativeHandle])}setCurrentDragSourceNode(s){this.clearCurrentDragSourceNode(),this.currentDragSourceNode=s;const i=1e3;this.mouseMoveTimeoutTimer=setTimeout(()=>{var r;return(r=this.rootElement)===null||r===void 0?void 0:r.addEventListener("mousemove",this.endDragIfSourceWasRemovedFromDOM,!0)},i)}clearCurrentDragSourceNode(){if(this.currentDragSourceNode){if(this.currentDragSourceNode=null,this.rootElement){var s;(s=this.window)===null||s===void 0||s.clearTimeout(this.mouseMoveTimeoutTimer||void 0),this.rootElement.removeEventListener("mousemove",this.endDragIfSourceWasRemovedFromDOM,!0)}return this.mouseMoveTimeoutTimer=null,!0}return!1}handleDragStart(s,i){s.defaultPrevented||(this.dragStartSourceIds||(this.dragStartSourceIds=[]),this.dragStartSourceIds.unshift(i))}handleDragEnter(s,i){this.dragEnterTargetIds.unshift(i)}handleDragOver(s,i){this.dragOverTargetIds===null&&(this.dragOverTargetIds=[]),this.dragOverTargetIds.unshift(i)}handleDrop(s,i){this.dropTargetIds.unshift(i)}constructor(s,i,r){this.sourcePreviewNodes=new Map,this.sourcePreviewNodeOptions=new Map,this.sourceNodes=new Map,this.sourceNodeOptions=new Map,this.dragStartSourceIds=null,this.dropTargetIds=[],this.dragEnterTargetIds=[],this.currentNativeSource=null,this.currentNativeHandle=null,this.currentDragSourceNode=null,this.altKeyPressed=!1,this.mouseMoveTimeoutTimer=null,this.asyncEndDragFrameId=null,this.dragOverTargetIds=null,this.lastClientOffset=null,this.hoverRafId=null,this.getSourceClientOffset=l=>{const c=this.sourceNodes.get(l);return c&&hk(c)||null},this.endDragNativeItem=()=>{this.isDraggingNativeItem()&&(this.actions.endDrag(),this.currentNativeHandle&&this.registry.removeSource(this.currentNativeHandle),this.currentNativeHandle=null,this.currentNativeSource=null)},this.isNodeInDocument=l=>!!(l&&this.document&&this.document.body&&this.document.body.contains(l)),this.endDragIfSourceWasRemovedFromDOM=()=>{const l=this.currentDragSourceNode;l==null||this.isNodeInDocument(l)||(this.clearCurrentDragSourceNode()&&this.monitor.isDragging()&&this.actions.endDrag(),this.cancelHover())},this.scheduleHover=l=>{this.hoverRafId===null&&typeof requestAnimationFrame<"u"&&(this.hoverRafId=requestAnimationFrame(()=>{this.monitor.isDragging()&&this.actions.hover(l||[],{clientOffset:this.lastClientOffset}),this.hoverRafId=null}))},this.cancelHover=()=>{this.hoverRafId!==null&&typeof cancelAnimationFrame<"u"&&(cancelAnimationFrame(this.hoverRafId),this.hoverRafId=null)},this.handleTopDragStartCapture=()=>{this.clearCurrentDragSourceNode(),this.dragStartSourceIds=[]},this.handleTopDragStart=l=>{if(l.defaultPrevented)return;const{dragStartSourceIds:c}=this;this.dragStartSourceIds=null;const d=rc(l);this.monitor.isDragging()&&(this.actions.endDrag(),this.cancelHover()),this.actions.beginDrag(c||[],{publishSource:!1,getSourceClientOffset:this.getSourceClientOffset,clientOffset:d});const{dataTransfer:h}=l,p=og(h);if(this.monitor.isDragging()){if(h&&typeof h.setDragImage=="function"){const b=this.monitor.getSourceId(),y=this.sourceNodes.get(b),w=this.sourcePreviewNodes.get(b)||y;if(w){const{anchorX:v,anchorY:_,offsetX:$,offsetY:T}=this.getCurrentSourcePreviewNodeOptions(),D=tx(y,w,d,{anchorX:v,anchorY:_},{offsetX:$,offsetY:T});h.setDragImage(w,D.x,D.y)}}try{h==null||h.setData("application/json",{})}catch{}this.setCurrentDragSourceNode(l.target);const{captureDraggingState:f}=this.getCurrentSourcePreviewNodeOptions();f?this.actions.publishDragSource():setTimeout(()=>this.actions.publishDragSource(),0)}else if(p)this.beginDragNativeItem(p);else{if(h&&!h.types&&(l.target&&!l.target.hasAttribute||!l.target.hasAttribute("draggable")))return;l.preventDefault()}},this.handleTopDragEndCapture=()=>{this.clearCurrentDragSourceNode()&&this.monitor.isDragging()&&this.actions.endDrag(),this.cancelHover()},this.handleTopDragEnterCapture=l=>{if(this.dragEnterTargetIds=[],this.isDraggingNativeItem()){var c;(c=this.currentNativeSource)===null||c===void 0||c.loadDataTransfer(l.dataTransfer)}if(!this.enterLeaveCounter.enter(l.target)||this.monitor.isDragging())return;const{dataTransfer:h}=l,p=og(h);p&&this.beginDragNativeItem(p,h)},this.handleTopDragEnter=l=>{const{dragEnterTargetIds:c}=this;if(this.dragEnterTargetIds=[],!this.monitor.isDragging())return;this.altKeyPressed=l.altKey,c.length>0&&this.actions.hover(c,{clientOffset:rc(l)}),c.some(h=>this.monitor.canDropOnTarget(h))&&(l.preventDefault(),l.dataTransfer&&(l.dataTransfer.dropEffect=this.getCurrentDropEffect()))},this.handleTopDragOverCapture=l=>{if(this.dragOverTargetIds=[],this.isDraggingNativeItem()){var c;(c=this.currentNativeSource)===null||c===void 0||c.loadDataTransfer(l.dataTransfer)}},this.handleTopDragOver=l=>{const{dragOverTargetIds:c}=this;if(this.dragOverTargetIds=[],!this.monitor.isDragging()){l.preventDefault(),l.dataTransfer&&(l.dataTransfer.dropEffect="none");return}this.altKeyPressed=l.altKey,this.lastClientOffset=rc(l),this.scheduleHover(c),(c||[]).some(h=>this.monitor.canDropOnTarget(h))?(l.preventDefault(),l.dataTransfer&&(l.dataTransfer.dropEffect=this.getCurrentDropEffect())):this.isDraggingNativeItem()?l.preventDefault():(l.preventDefault(),l.dataTransfer&&(l.dataTransfer.dropEffect="none"))},this.handleTopDragLeaveCapture=l=>{this.isDraggingNativeItem()&&l.preventDefault(),this.enterLeaveCounter.leave(l.target)&&(this.isDraggingNativeItem()&&setTimeout(()=>this.endDragNativeItem(),0),this.cancelHover())},this.handleTopDropCapture=l=>{if(this.dropTargetIds=[],this.isDraggingNativeItem()){var c;l.preventDefault(),(c=this.currentNativeSource)===null||c===void 0||c.loadDataTransfer(l.dataTransfer)}else og(l.dataTransfer)&&l.preventDefault();this.enterLeaveCounter.reset()},this.handleTopDrop=l=>{const{dropTargetIds:c}=this;this.dropTargetIds=[],this.actions.hover(c,{clientOffset:rc(l)}),this.actions.drop({dropEffect:this.getCurrentDropEffect()}),this.isDraggingNativeItem()?this.endDragNativeItem():this.monitor.isDragging()&&this.actions.endDrag(),this.cancelHover()},this.handleSelectStart=l=>{const c=l.target;typeof c.dragDrop=="function"&&(c.tagName==="INPUT"||c.tagName==="SELECT"||c.tagName==="TEXTAREA"||c.isContentEditable||(l.preventDefault(),c.dragDrop()))},this.options=new sx(i,r),this.actions=s.getActions(),this.monitor=s.getMonitor(),this.registry=s.getRegistry(),this.enterLeaveCounter=new KI(this.isNodeInDocument)}}const pk=function(s,i,r){return new ix(s,i,r)},nx=$t([m.jsx("path",{d:"M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2M12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8"},"0"),m.jsx("path",{d:"M12.5 7H11v6l5.25 3.15.75-1.23-4.5-2.67z"},"1")],"AccessTime"),rx=$t(m.jsx("path",{d:"M19 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2m-2 10h-4v4h-2v-4H7v-2h4V7h2v4h4z"}),"AddBox"),ax=$t(m.jsx("path",{d:"M4 8h4V4H4zm6 12h4v-4h-4zm-6 0h4v-4H4zm0-6h4v-4H4zm6 0h4v-4h-4zm6-10v4h4V4zm-6 4h4V4h-4zm6 6h4v-4h-4zm0 6h4v-4h-4z"}),"Apps"),lx=$t(m.jsx("path",{d:"M9 2c-1.05 0-2.05.16-3 .46 4.06 1.27 7 5.06 7 9.54s-2.94 8.27-7 9.54c.95.3 1.95.46 3 .46 5.52 0 10-4.48 10-10S14.52 2 9 2"}),"Brightness3"),cx=$t(m.jsx("path",{d:"M20 8h-2.81c-.45-.78-1.07-1.45-1.82-1.96L17 4.41 15.59 3l-2.17 2.17C12.96 5.06 12.49 5 12 5s-.96.06-1.41.17L8.41 3 7 4.41l1.62 1.63C7.88 6.55 7.26 7.22 6.81 8H4v2h2.09c-.05.33-.09.66-.09 1v1H4v2h2v1c0 .34.04.67.09 1H4v2h2.81c1.04 1.79 2.97 3 5.19 3s4.15-1.21 5.19-3H20v-2h-2.09c.05-.33.09-.66.09-1v-1h2v-2h-2v-1c0-.34-.04-.67-.09-1H20zm-6 8h-4v-2h4zm0-4h-4v-2h4z"}),"BugReport"),ux=$t(m.jsx("path",{d:"M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12zm-1 4 6 6v10c0 1.1-.9 2-2 2H7.99C6.89 23 6 22.1 6 21l.01-14c0-1.1.89-2 1.99-2zm-1 7h5.5L14 6.5z"}),"FileCopy"),dx=$t(m.jsx("path",{d:"M7 2v11h3v9l7-12h-4l4-8z"}),"FlashOn"),hx=$t(m.jsx("path",{d:"M3.27 5 2 6.27l6.97 6.97L6.5 19h3l1.57-3.66L16.73 21 18 19.73 3.55 5.27zM6 5v.18L8.82 8h2.4l-.72 1.68 2.1 2.1L14.21 8H20V5z"}),"FormatClear"),px=$t(m.jsx("path",{d:"M18 4H6v2l6.5 6L6 18v2h12v-3h-7l5-5-5-5h7z"}),"Functions"),gk=$t(m.jsx("path",{d:"M11 18h2v-2h-2zm1-16C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2m0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8m0-14c-2.21 0-4 1.79-4 4h2c0-1.1.9-2 2-2s2 .9 2 2c0 2-3 1.75-3 5h2c0-2.25 3-2.5 3-5 0-2.21-1.79-4-4-4"}),"HelpOutline"),gx=$t(m.jsx("path",{d:"M21 3.01H3c-1.1 0-2 .9-2 2V9h2V4.99h18v14.03H3V15H1v4.01c0 1.1.9 1.98 2 1.98h18c1.1 0 2-.88 2-1.98v-14c0-1.11-.9-2-2-2M11 16l4-4-4-4v3H1v2h10z"}),"Input"),S_=$t(m.jsx("path",{d:"M18 8h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2m-6 9c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2m3.1-9H8.9V6c0-1.71 1.39-3.1 3.1-3.1s3.1 1.39 3.1 3.1z"}),"Lock"),mx=$t(m.jsx("path",{d:"M12 8c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2m0 2c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2m0 6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2"}),"MoreVert"),fx=$t(m.jsx("path",{d:"M12 2C6.49 2 2 6.49 2 12s4.49 10 10 10c1.38 0 2.5-1.12 2.5-2.5 0-.61-.23-1.2-.64-1.67-.08-.1-.13-.21-.13-.33 0-.28.22-.5.5-.5H16c3.31 0 6-2.69 6-6 0-4.96-4.49-9-10-9m5.5 11c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5m-3-4c-.83 0-1.5-.67-1.5-1.5S13.67 6 14.5 6s1.5.67 1.5 1.5S15.33 9 14.5 9M5 11.5c0-.83.67-1.5 1.5-1.5s1.5.67 1.5 1.5S7.33 13 6.5 13 5 12.33 5 11.5m6-4c0 .83-.67 1.5-1.5 1.5S8 8.33 8 7.5 8.67 6 9.5 6s1.5.67 1.5 1.5"}),"Palette"),vc=$t(m.jsx("path",{d:"M6 19h4V5H6zm8-14v14h4V5z"}),"Pause"),Yg=$t(m.jsx("path",{d:"M8 5v14l11-7z"}),"PlayArrow"),$x=$t(m.jsx("path",{d:"M11 5v5.59H7.5l4.5 4.5 4.5-4.5H13V5zm-5 9c0 3.31 2.69 6 6 6s6-2.69 6-6h-2c0 2.21-1.79 4-4 4s-4-1.79-4-4z"}),"PlayForWork"),bx=$t(m.jsx("path",{d:"M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14"}),"Search"),vx=$t(m.jsx("path",{d:"M10.59 9.17 5.41 4 4 5.41l5.17 5.17zM14.5 4l2.04 2.04L4 18.59 5.41 20 17.96 7.46 20 9.5V4zm.33 9.41-1.41 1.41 3.13 3.13L14.5 20H20v-5.5l-2.04 2.04z"}),"Shuffle"),yx=$t(m.jsx("path",{d:"M2 20h20v-4H2zm2-3h2v2H4zM2 4v4h20V4zm4 3H4V5h2zm-4 7h20v-4H2zm2-3h2v2H4z"}),"Storage"),_x=$t(m.jsx("path",{d:"M14 17H4v2h10zm6-8H4v2h16zM4 15h16v-2H4zM4 5v2h16V5z"}),"Subject"),wx=$t(m.jsx("path",{d:"M16 17.01V10h-2v7.01h-3L15 21l4-3.99zM9 3 5 6.99h3V14h2V6.99h3z"}),"SwapVert"),kx=$t(m.jsx("path",{d:"M7.41 18.59 8.83 20 12 16.83 15.17 20l1.41-1.41L12 14zm9.18-13.18L15.17 4 12 7.17 8.83 4 7.41 5.41 12 10z"}),"UnfoldLess"),Cx=$t(m.jsx("path",{d:"M12 5.83 15.17 9l1.41-1.41L12 3 7.41 7.59 8.83 9zm0 12.34L8.83 15l-1.41 1.41L12 21l4.59-4.59L15.17 15z"}),"UnfoldMore"),Sc="data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20width='512'%20height='512'%20shape-rendering='geometricPrecision'%20image-rendering='optimizeQuality'%20fill-rule='evenodd'%20xmlns:v='https://vecta.io/nano'%3e%3cpath%20fill='%23efda4e'%20d='M-.5-.5h512v512H-.5V-.5z'/%3e%3cpath%20fill='%23020100'%20d='M308.5%20287.5c1.777-3.005%202.777-6.338%203-10%209.147-21.963%2025.48-35.463%2049-40.5%2021.999-4.173%2043.666-2.84%2065%204%2014.575%205.411%2025.575%2014.911%2033%2028.5l-1%202c-12.413%205.624-24.58%2011.624-36.5%2018-5.321-8.25-12.821-13.417-22.5-15.5-13.957-3.122-27.29-1.455-40%205-8.125%205.36-10.958%2012.86-8.5%2022.5%203.223%206.223%208.057%2010.723%2014.5%2013.5l64%2020c38.459%2016.085%2052.626%2044.585%2042.5%2085.5-7.572%2026.208-24.738%2042.041-51.5%2047.5-25.102%205.733-49.768%204.4-74-4-19.291-8.625-32.291-22.958-39-43%2011.266-8.887%2023.433-16.387%2036.5-22.5%203.117%206.896%206.784%2013.563%2011%2020%2012.705%2012.307%2027.872%2016.807%2045.5%2013.5%2022.189-3.504%2032.355-16.338%2030.5-38.5-2.833-6.833-7.667-11.667-14.5-14.5l-57-17c-36.004-11.84-52.67-36.673-50-74.5z'/%3e%3cpath%20fill='%23020200'%20d='M222.5%20238.5h43l-.5%20159c-2.688%2052.355-30.188%2076.855-82.5%2073.5-24.871-3.543-41.204-17.21-49-41l.5-2.5a12.14%2012.14%200%200%200%204.5-3.5c10.653-5.825%2021.32-11.325%2032-16.5%204.763%2021.72%2017.763%2028.887%2039%2021.5%204.616-2.618%207.783-6.451%209.5-11.5%201.163-5.968%202.163-11.968%203-18l.5-161z'/%3e%3cpath%20fill='%23615820'%20d='M311.5%20277.5c-.223%203.662-1.223%206.995-3%2010%20.223-3.662%201.223-6.995%203-10z'/%3e%3c/svg%3e",mk="data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20500%20500'%3e%3cpath%20fill='%234285f4'%20d='M44.271%2027.275l206.5%201v170l-58.5-36.5c-7.005-.916-12.505%201.584-16.5%207.5v147c4.625%204.412%2010.125%206.245%2016.5%205.5l57.5-35.5c.833%2054.003%201.356%20108.003.189%20162-1.272.546-45.599-.242-48.689%201.121-3.674%207.844-4.79%2011.207-13%2023.879-4.372%205.527-2.19%204.097-10.689%2012.258-5.166%202.748-4.191%203.45-14.311%206.242-17.67%201.983-35.336%201.983-53%200-9.535-3.774-10.879-4.163-18.526-11.22-5.562-4.39-11.131-11.803-11.974-15.28-4.068-7.881-3.42-9.116-5.5-13.5-3.672-1.503-35.798.203-40.746-1.335-5.823-2.314-2.946-.422-7.954-3.689-2.888-2.668-2.255-3.221-2.421-9.904L20.771%2050.275c.36-2.108-.41-5.806%202.522-11.615%204.343-5.852%205.374-7%2010.061-9.146%206.083-2.73%208.677-1.475%2010.917-2.239z'/%3e%3cpath%20d='M258.271%2030.275l154.63.407c5.654.559%2010.783%203.17%2014.37%207.093%204.907%204.408%206.204%208.723%207.5%2013.5v373c-.208%205.716-.297%207.982-4.848%2015.404-7.078%206.393-9.879%206.39-15.652%206.692-24.804%201.296-50.079%201.189-74.96%201.041-24.516-.014-68.46.89-81.5.391l-2.512-172.528c-20.083%2012.625-42.777%2025.125-63.028%2037.5-4.127%201.292-7.294.125-9.5-3.5l1-137c1.864-2.707%204.364-3.541%207.5-2.5%2020.366%2013.427%2064.35%2038.947%2065.581%2038.339l1.419-177.839z'%20fill='%23DDD'/%3e%3c/svg%3e",fk="data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20512%20512'%20width='32'%20height='32'%3e%3cpath%20fill='%23007acc'%20d='M-.5-.5h503l-1%20179h10v333h-421v-7h-91V-.5z'/%3e%3cpath%20fill='%230f81cf'%20d='M502.5-.5h9v179h-10l1-179z'/%3e%3cpath%20fill='%23fdfefe'%20d='M470.5%20227.5c.33%2017.508-.003%2034.841-1%2052-23.486-15.709-48.82-19.875-76-12.5-15.89%208.078-19.39%2019.911-10.5%2035.5%204.673%205.577%2010.173%2010.077%2016.5%2013.5l38%2019c17.945%209.278%2031.112%2023.112%2039.5%2041.5%201.352%203.22%202.186%206.553%202.5%2010a305.16%20305.16%200%200%201%201%2026c-3.553%2033.726-21.886%2054.559-55%2062.5-34.769%207.363-68.435%204.196-101-9.5-.167-19.003%200-38.003.5-57%2022.903%2021.314%2049.736%2029.147%2080.5%2023.5%2019.435-5.701%2025.268-17.868%2017.5-36.5-4.718-6.44-10.552-11.606-17.5-15.5a1552.42%201552.42%200%200%201-47-24c-27.679-19.331-38.846-45.831-33.5-79.5%206.43-26.433%2022.597-43.933%2048.5-52.5%2026.131-6.625%2052.464-7.292%2079-2a565.56%20565.56%200%200%201%2018%205.5z'/%3e%3cpath%20fill='%23fefefe'%20d='M122.5%20222.5h182v46h-65v206h-52v-206h-65v-46z'/%3e%3cpath%20fill='%2370b3e1'%20d='M470.5%20227.5c1.327%2017.505%201.327%2035.171%200%2053-.607-.124-.94-.457-1-1%20.997-17.159%201.33-34.492%201-52z'/%3e%3cpath%20fill='%236cafe0'%20d='M479.5%20386.5c1.465%205.09%202.132%2010.423%202%2016-.002%203.518-.335%206.851-1%2010a305.16%20305.16%200%200%200-1-26z'/%3e%3cpath%20fill='%231283cf'%20d='M-.5%20504.5h91v7h-91v-7z'/%3e%3c/svg%3e",$k="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI1MTIiIGhlaWdodD0iNTEyIj4KICAgIDxyYWRpYWxHcmFkaWVudCBpZD0ibXlHcmFkaWVudCI+CiAgICAgICAgPHN0b3Agb2Zmc2V0PSIxMCUiIHN0b3AtY29sb3I9IiMxQzJENUYiIC8+CiAgICAgICAgPHN0b3Agb2Zmc2V0PSI5NSUiIHN0b3AtY29sb3I9IiMwQjFENTMiIC8+CiAgICA8L3JhZGlhbEdyYWRpZW50PgogICAgPHBhdGggZmlsbD0idXJsKCcjbXlHcmFkaWVudCcpIiBkPSJNLS4xLS4xaDUxMnY1MTJILS4xVi0uMXoiLz4KICAgIDxwYXRoIGZpbGw9IiNmOGY4ZmEiCiAgICAgICAgICBkPSJNNDgyLjUgMjMxLjV2NmgtMjVjLS45NzItOC4xNy01LjYzOS0xMi4xNy0xNC0xMi05LjUzMS4wMjktMTMuMzY1IDQuNjk1LTExLjUgMTRsNC41IDQuNSAzMyA4YzE5LjM4OCA5LjYzNCAyMy4zODggMjMuODAxIDEyIDQyLjVhMzUuMDYgMzUuMDYgMCAwIDAtOCA2Yy0xMy45MjUgNC43NjEtMjguMjU4IDYuMjYxLTQzIDQuNS0xMC42MDEtMS4wMjQtMTguOTM1LTUuODU3LTI1LTE0LjUtMS4wNzctMi4yMjktMS43NDQtNC41NjMtMi03di04aDI1YzEuNDk1IDQuMjc5IDM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LjVjLjk3OC4zMTEgMS42NDUuOTc4IDIgMmwtMTYgMWMtNS43MTEtLjAwNS0xMS4wNDQtLjY3Mi0xNi0yYTEyOC4xOSAxMjguMTkgMCAwIDAgMTUuNSAxYzUuMjE2LS4wMDYgMTAuMDQ5LS42NzMgMTQuNS0yeiIvPgogICAgPHBhdGggZmlsbD0iI2E1YWNjMCIgZD0iTTIzMy41IDIwOS41djk0aDY5di0xN2MtMTMuNTEuMzI5LTI2Ljg0NC0uMDA0LTQwLTFoNDF2MTloLTcxYTIyNTYuNDEgMjI1Ni40MSAwIDAgMSAxLTk1eiIvPgogICAgPHBhdGggZmlsbD0iI2E2YWNjMCIKICAgICAgICAgIGQ9Ik0zMTYuNSAyMDkuNWMtLjk5OCAzMS4xNjItMS4zMzIgNjIuNDk2LTEgOTRoNzN2LTE3Yy0xNC44NDMuMzI5LTI5LjUxLS4wMDQtNDQtMWg0NXYxOWgtNzVhMjMwNC45NSAyMzA0Ljk1IDAgMCAxIDEtOTZjLjYwNy4xMjQuOTQuNDU3IDEgMXoiLz4KPC9zdmc+";class km extends _e.Component{isShowInstance;oldId;constructor(s){super(s),this.state={name:s.name,id:s.id,instance:s.instance||0,prefix:km.getPrefix(s.id)},this.isShowInstance=!s.folder&&!!s.instances&&(!!s.instance||!!s.instances[0]||s.instances.length>1),this.oldId=s.id}static getPrefix(s){const i=(s||"").split(".");return i.pop(),i.join(".")}getId(s){return s=(s||"").replace(/[\\/\][*,;'"`<>?\s]/g,"_"),`${this.state.prefix}.${s}`}handleCancel=()=>{this.props.onClose()};handleOk=()=>{this.props.onRename(this.oldId,this.state.id,this.state.name,this.state.instance===0?0:this.state.instance||void 0),this.props.onClose()};handleChange=s=>{this.setState({name:s,id:this.getId(s)})};render(){return m.jsxs(Pt,{onClose:()=>!1,maxWidth:"md",fullWidth:!0,open:!0,"aria-labelledby":"confirmation-dialog-title",children:[m.jsx(qt,{id:"confirmation-dialog-title",children:x.I18n.t("Rename")}),m.jsx(Wt,{children:m.jsxs("form",{noValidate:!0,autoComplete:"off",children:[m.jsx(Eo,{variant:"standard",style:{width:"100%"},id:"standard-name",autoFocus:!0,label:x.I18n.t("Name"),value:this.state.name,onKeyUp:s=>{s.key==="Enter"&&(s.preventDefault(),setTimeout(()=>this.handleOk(),200))},onChange:s=>this.handleChange(s.target.value),margin:"normal"}),m.jsx(Eo,{variant:"standard",id:"standard-name-id",style:{width:"100%"},label:x.I18n.t("ID"),value:this.state.id,disabled:!0,margin:"normal"}),this.isShowInstance&&m.jsxs(Di,{variant:"standard",children:[m.jsx(Rg,{htmlFor:"instance",children:x.I18n.t("Instance")}),m.jsx(Ai,{variant:"standard",value:this.state.instance,onChange:s=>this.setState({instance:parseInt(s.target.value,10)}),inputProps:{name:"instance",id:"instance"},children:this.props.instances.map(s=>m.jsx(tt,{value:s,children:s||"0"},s))})]})]})}),m.jsxs(Bt,{children:[m.jsx(Ue,{variant:"contained",onClick:this.handleOk,color:"primary",startIcon:m.jsx(Xo,{}),children:x.I18n.t("Ok")}),m.jsx(Ue,{color:"grey",variant:"contained",onClick:this.handleCancel,startIcon:m.jsx(so,{}),children:x.I18n.t("Cancel")})]})]})}}class Tx extends _e.Component{constructor(s){super(s),this.state={name:s.name,id:s.id}}handleCancel=()=>{this.props.onClose()};handleOk=()=>{this.props.onDelete(this.state.id),this.props.onClose()};render(){return m.jsxs(Pt,{onClose:()=>!1,maxWidth:"md",open:!0,"aria-labelledby":"confirmation-dialog-title",children:[m.jsx(qt,{id:"confirmation-dialog-title",children:x.I18n.t("Are you sure?")}),m.jsxs(Wt,{children:[m.jsx(fc,{}),m.jsx("span",{style:{fontSize:14,fontWeight:"bold"},children:x.I18n.t("Delete %s",this.state.name)})]}),m.jsxs(Bt,{children:[m.jsx(Ue,{variant:"contained",onClick:this.handleOk,color:"primary",startIcon:m.jsx(Xo,{}),children:x.I18n.t("Ok")}),m.jsx(Ue,{color:"grey",variant:"contained",onClick:this.handleCancel,startIcon:m.jsx(so,{}),children:x.I18n.t("Cancel")})]})]})}}const Sx=""+new URL("tileJS-C48gYbHw.png",import.meta.url).href,Ex=""+new URL("tileTS-CsXmgy4B.png",import.meta.url).href,Ix=""+new URL("tileBlockly-BMpdinN3.png",import.meta.url).href,xx=""+new URL("tileRules-BkbaFIhs.png",import.meta.url).href,Ut={card:{maxWidth:345,minWidth:250,display:"inline-block",margin:"0 10px 0 10px"},media:{height:122},text:{maxWidth:218,minHeight:30},complexity:{fontWeight:"bold",fontStyle:"italic",marginBottom:8}};class Dn extends _e.Component{handleCancel=()=>{this.props.onClose()};static openHtml(s){const i=x.I18n.getLanguage();!s.includes("javascript.md")&&(i==="de"||i==="ru")&&(s=s.replace(/\/en\//,`/${i}/`));const r=window.open(s,"_blank");r==null||r.focus()}getJSCard(){return m.jsxs(Zl,{style:Ut.card,children:[m.jsxs(Ql,{onClick:()=>this.props.onClose&&this.props.onClose("Javascript/js"),children:[m.jsx(ec,{style:Ut.media,image:Sx,title:"JavaScript"}),m.jsxs(tc,{children:[m.jsx("h2",{children:"JavaScript"}),m.jsx("div",{style:Ut.complexity,children:x.I18n.t("for programmers")}),m.jsx("div",{style:Ut.text,children:x.I18n.t("JS description")})]})]}),m.jsxs(sc,{children:[m.jsx(Ue,{size:"small",color:"primary",variant:"contained",onClick:()=>this.props.onClose&&this.props.onClose("Javascript/js"),children:x.I18n.t("Add")}),m.jsx(Ue,{size:"small",color:"secondary",onClick:()=>Dn.openHtml("https://github.com/ioBroker/ioBroker.javascript/blob/master/docs/en/javascript.md"),children:x.I18n.t("Learn More")})]})]})}getTSCard(){return m.jsxs(Zl,{style:Ut.card,children:[m.jsxs(Ql,{onClick:()=>this.props.onClose&&this.props.onClose("TypeScript/ts"),children:[m.jsx(ec,{style:Ut.media,image:Ex,title:"TypeScript"}),m.jsxs(tc,{children:[m.jsx("h2",{children:"TypeScript"}),m.jsx("div",{style:Ut.complexity,children:x.I18n.t("for professionals")}),m.jsx("div",{style:Ut.text,children:x.I18n.t("TS description")})]})]}),m.jsxs(sc,{children:[m.jsx(Ue,{size:"small",color:"primary",variant:"contained",onClick:()=>this.props.onClose&&this.props.onClose("TypeScript/ts"),children:x.I18n.t("Add")}),m.jsx(Ue,{size:"small",color:"secondary",onClick:()=>Dn.openHtml("https://github.com/ioBroker/ioBroker.javascript/blob/master/docs/en/javascript.md"),children:x.I18n.t("Learn More")})]})]})}getBlocklyCard(){return m.jsxs(Zl,{style:Ut.card,children:[m.jsxs(Ql,{onClick:()=>this.props.onClose&&this.props.onClose("Blockly"),children:[m.jsx(ec,{style:Ut.media,image:Ix,title:"Blockly"}),m.jsxs(tc,{children:[m.jsx("h2",{children:"Blockly"}),m.jsx("div",{style:Ut.complexity,children:x.I18n.t("normal")}),m.jsx("div",{style:Ut.text,children:x.I18n.t("Blockly description")})]})]}),m.jsxs(sc,{children:[m.jsx(Ue,{size:"small",color:"primary",variant:"contained",onClick:()=>this.props.onClose&&this.props.onClose("Blockly"),children:x.I18n.t("Add")}),m.jsx(Ue,{size:"small",color:"secondary",onClick:()=>Dn.openHtml("https://github.com/ioBroker/ioBroker.javascript/blob/master/docs/en/blockly.md"),children:x.I18n.t("Learn More")})]})]})}getRulesCard(){return m.jsxs(Zl,{style:Ut.card,children:[m.jsxs(Ql,{onClick:()=>this.props.onClose&&this.props.onClose("Rules"),children:[m.jsx(ec,{style:Ut.media,image:xx,title:"Rules"}),m.jsxs(tc,{children:[m.jsx("h2",{children:"Rules"}),m.jsx("div",{style:Ut.complexity,children:x.I18n.t("easy")}),m.jsx("div",{style:Ut.text,children:x.I18n.t("Rules description")})]})]}),m.jsxs(sc,{children:[m.jsx(Ue,{size:"small",color:"primary",variant:"contained",onClick:()=>this.props.onClose&&this.props.onClose("Rules"),children:x.I18n.t("Add")}),m.jsx(Ue,{size:"small",color:"secondary",onClick:()=>Dn.openHtml("https://github.com/ioBroker/ioBroker.javascript/blob/master/docs/en/javascript.md"),children:x.I18n.t("Learn More")})]})]})}render(){return m.jsxs(Pt,{onClose:()=>!1,maxWidth:"lg",fullWidth:!0,open:!0,"aria-labelledby":"confirmation-dialog-title",children:[m.jsx(qt,{id:"confirmation-dialog-title",children:x.I18n.t("Add new script")}),m.jsxs(Wt,{style:{textAlign:"center"},children:[this.getRulesCard(),this.getBlocklyCard(),this.getJSCard(),this.getTSCard()]}),m.jsx(Bt,{children:m.jsx(Ue,{color:"grey",onClick:this.handleCancel,startIcon:m.jsx(so,{}),children:x.I18n.t("Cancel")})})]})}}class ig extends _e.Component{isShowInstance;constructor(s){super(s),this.state={name:s.name||"Script",instance:s.instance||0,parent:s.parent,error:"",id:""},this.isShowInstance=!s.folder&&!!s.instances&&(!!s.instance||!!s.instances[0]||s.instances.length>1)}getId(s){return s=s||this.state.name||"",s=s.replace(/[\\/\][.*,;'"`<>?\s]/g,"_").trim().replace(/\.$/,"_"),`${this.state?this.state.parent:this.props.parent}.${s}`}handleOk=()=>{this.props.onAdd(this.getId(this.state.name),this.state.name,this.state.instance,this.props.type),this.props.onClose()};render(){var s;return m.jsxs(Pt,{onClose:()=>!1,maxWidth:"md",fullWidth:!0,open:!0,"aria-labelledby":"confirmation-dialog-title",children:[m.jsx(qt,{id:"confirmation-dialog-title",children:this.props.title||x.I18n.t("Create new")}),m.jsx(Wt,{children:m.jsxs("form",{noValidate:!0,autoComplete:"off",children:[m.jsx(Eo,{variant:"standard",style:{width:"100%"},id:"standard-name",autoFocus:!0,error:!!this.state.error,label:x.I18n.t("Name"),value:this.state.name||"",helperText:this.state.error,slotProps:{input:{endAdornment:this.state.name?m.jsx(qe,{size:"small",onClick:()=>this.setState({name:""}),children:m.jsx(QT,{})}):void 0}},onKeyUp:i=>{i.preventDefault(),i.key==="Enter"&&!this.state.error&&setTimeout(()=>this.handleOk(),200)},onChange:i=>{var c;const r=i.target.value,l=this.getId(r);r?(c=this.props.existingItems)!=null&&c.includes(l)?this.setState({name:r,id:l,error:x.I18n.t("Duplicate name")}):this.setState({name:r,id:l,error:""}):this.setState({name:r,id:l,error:x.I18n.t("Empty name is not allowed")})},margin:"normal"}),m.jsxs(Di,{variant:"standard",style:{width:"100%"},children:[m.jsx(Rg,{htmlFor:"parent",children:x.I18n.t("Folder")}),m.jsx(Ai,{variant:"standard",style:{width:"100%"},value:this.state.parent,onChange:i=>this.setState({parent:i.target.value}),inputProps:{name:"parent",id:"parent"},children:this.props.parents.map(i=>{const r=i.id.split(".");r.splice(0,2);const l=[];let c="script.js";return r.forEach(d=>{c+=`.${d}`;const h=this.props.parents.find(p=>p.id===c);h?l.push(h.name):l.push(d)}),l.length||l.push(i.name),m.jsx(tt,{value:i.id,children:l.join(" / ")},i.id)})})]}),m.jsx(Eo,{variant:"standard",id:"standard-name-id",style:{width:"100%"},label:x.I18n.t("ID"),value:this.getId(),disabled:!0,margin:"normal"}),this.isShowInstance&&m.jsxs(Di,{variant:"standard",children:[m.jsx(Rg,{htmlFor:"instance",children:x.I18n.t("Instance")}),m.jsx(Ai,{variant:"standard",value:this.state.instance,onChange:i=>this.setState({instance:parseInt(i.target.value,10)}),inputProps:{name:"instance",id:"instance"},children:(s=this.props.instances)==null?void 0:s.map(i=>m.jsx(tt,{value:i,children:i||"0"},`instance${i}`))})]})]})}),m.jsxs(Bt,{children:[m.jsx(Ue,{variant:"contained",onClick:this.handleOk,disabled:!!this.state.error,color:"primary",startIcon:m.jsx(Xo,{}),children:x.I18n.t("Ok")}),m.jsx(Ue,{color:"grey",variant:"contained",onClick:()=>this.props.onClose(),startIcon:m.jsx(so,{}),children:x.I18n.t("Cancel")})]})]})}}const Dx={title:a=>({background:a.palette.error.main,color:a.palette.error.contrastText,"&>h2":{color:a.palette.error.contrastText}})};class ou extends _e.Component{handleOk=()=>{this.props.onClose()};render(){return m.jsxs(Pt,{open:!0,maxWidth:"sm",fullWidth:!0,onClose:()=>this.handleOk(),"aria-labelledby":"alert-dialog-title","aria-describedby":"alert-dialog-description",children:[m.jsx(qt,{sx:Dx.title,id:"alert-dialog-title",children:this.props.title||x.I18n.t("Error")}),m.jsx(Wt,{children:m.jsx(Aw,{id:"alert-dialog-description",children:this.props.text||x.I18n.t("Unknown error!")})}),m.jsx(Bt,{children:m.jsx(Ue,{variant:"contained",onClick:()=>this.handleOk(),color:"primary",autoFocus:!0,startIcon:m.jsx(Xo,{}),children:x.I18n.t("Ok")})})]})}}const zr={icon:{width:24,height:24},filterWithButton:{width:"100%"},title:{fontWeight:"bold",marginTop:16}};class Ax extends _e.Component{constructor(s){super(s),this.state={instances:[],filter:window.localStorage.getItem("javascript.debug.filter")||"",showAskForStop:!1,jsInstance:window.localStorage.getItem("javascript.debug.instance")||"",jsInstanceHost:"",adapterToDebug:window.localStorage.getItem("javascript.debug.adapter")||""}}componentDidMount(){this.props.socket.getAdapterInstances().then(s=>{const i=s.filter(h=>{var p;return h&&!((p=h.common)!=null&&p.onlyWWW)}).map(h=>{var b,y,w;const p=h._id.replace(/^system\.adapter\./,""),[f]=p.split(".");return{id:p,enabled:(b=h.common)==null?void 0:b.enabled,host:(y=h.common)==null?void 0:y.host,icon:(w=h.common)!=null&&w.icon?`../../adapter/${f}/${h.common.icon}`:""}});i.sort((h,p)=>h.id>p.id?1:h.idh.id===this.state.jsInstance):null;let c;if(!this.state.jsInstance||!l){const h=i.find(p=>p.id.startsWith("javascript."));c=(h==null?void 0:h.host)||"",r=(h==null?void 0:h.id)||""}else c=(l==null?void 0:l.host)||"";let d=this.state.adapterToDebug||"";d&&!i.find(h=>h.id===d)&&(d=""),this.setState({instances:i,jsInstance:r,adapterToDebug:d,jsInstanceHost:c})})}handleOk=()=>{var s;if((s=this.state.instances.find(i=>i.id===this.state.adapterToDebug))!=null&&s.enabled){this.props.socket.getObject(`system.adapter.${this.state.adapterToDebug}`).then(i=>{i&&(i.common.enabled=!1,this.props.socket.setObject(i._id,i).then(()=>this.props.onDebug(this.state.jsInstance,this.state.adapterToDebug)))});return}this.props.onDebug(this.state.jsInstance,this.state.adapterToDebug)};renderJavascriptList(){const s=this.state.instances.filter(i=>i.id.startsWith("javascript."));return s.length<2?null:m.jsxs(Si,{children:[m.jsx("div",{style:zr.title,children:x.I18n.t("Host")}),m.jsx(Mg,{component:"nav",children:s.map(i=>m.jsxs(i_,{component:"div",selected:this.state.jsInstance===i.id,onClick:()=>this.setState({jsInstance:i.id,jsInstanceHost:i.host}),children:[m.jsx(Ng,{children:m.jsx("img",{src:i.icon,alt:i.id,style:zr.icon})}),m.jsx(Lg,{primary:i.id})]},i.id))})]})}renderInstances(){if(!this.state.jsInstance)return m.jsx(Si,{});const s=this.state.instances.filter(i=>i.id!==this.state.jsInstance&&i.host===this.state.jsInstanceHost&&(!this.state.filter||i.id.includes(this.state.filter.toLowerCase())));return m.jsxs(Si,{children:[m.jsx("div",{style:zr.title,children:x.I18n.t("Instances")}),m.jsx(Mg,{component:"nav",children:s.map(i=>m.jsxs(i_,{selected:this.state.adapterToDebug===i.id,onDoubleClick:()=>this.setState({adapterToDebug:i.id},()=>this.handleOk()),onClick:()=>this.setState({adapterToDebug:i.id}),children:[m.jsx(Ng,{children:m.jsx("img",{src:i.icon,alt:i.id,style:zr.icon})}),m.jsx(Lg,{primary:i.id})]},i.id))})]})}render(){return m.jsxs(Pt,{maxWidth:"md",fullWidth:!1,open:!0,onClose:()=>!1,"aria-labelledby":"confirmation-dialog-title",children:[m.jsx(qt,{id:"confirmation-dialog-title",children:this.props.title||x.I18n.t("Debug instance")}),m.jsx(Wt,{children:m.jsxs(Si,{container:!0,direction:"column",children:[m.jsx(Si,{children:m.jsx(Pn,{style:zr.filterWithButton,value:this.state.filter,placeholder:x.I18n.t("Filter"),onChange:s=>{this.setState({filter:s.target.value}),window.localStorage.setItem("javascript.debug.filter",s.target.value)},endAdornment:m.jsx(Ow,{position:"end",children:this.state.filter?m.jsx(qe,{size:"small","aria-label":"toggle password visibility",onClick:()=>this.setState({filter:""}),children:m.jsx(Lw,{})}):""})})}),m.jsx(Si,{children:m.jsxs(Si,{container:!0,children:[this.renderJavascriptList(),this.renderInstances()]})})]})}),m.jsxs(Bt,{children:[m.jsx(Ue,{variant:"contained",onClick:this.handleOk,disabled:!this.state.jsInstance||!this.state.adapterToDebug,color:"primary",startIcon:m.jsx(Xo,{}),children:x.I18n.t("Start")}),m.jsx(Ue,{color:"grey",variant:"contained",onClick:()=>this.props.onClose(),startIcon:m.jsx(so,{}),children:x.I18n.t("Close")})]})]})}}function bk(a){if(!a)throw new Error("Password must be a non-empty string.")}function Kg(a){return new TextEncoder().encode(a)}function Ox(a){return new TextDecoder().decode(a)}function Rx(a){let s="";for(let i=0;i({height:a.toolbar.height}),toolbarButtons:a=>({color:a.palette.mode==="dark"?"white !important":"black !important"}),iconButtonsDisabled:{filter:"grayscale(100%)",opacity:.5},toolbarSearch:{width:"calc(100% - 105px)",lineHeight:"34px",marginLeft:5},iconButtons:{width:32,height:32,padding:2},iconDropdownMenu:{paddingRight:5},menu:{width:"100%",height:"100%"},innerMenu:{width:"100%",height:"calc(100% - 76px)",overflowX:"hidden",overflowY:"auto"},listItemIcon:{minWidth:32},scriptIcon:{width:18,height:18,borderRadius:2,marginTop:4,marginBottom:4,marginLeft:8,marginRight:4},folder:{cursor:"pointer",padding:0,userSelect:"none"},folderReorder:{opacity:.3,transitionDuration:"0.5s",transitionProperty:"opacity"},folderIcon:{width:20,height:20},folderIconReorder:{paddingTop:4,paddingBottom:4,paddingLeft:8,paddingRight:4},folderIconNoReorder:{cursor:"pointer",paddingTop:4,paddingBottom:4,paddingLeft:8,paddingRight:4},script:{cursor:"pointer",padding:0,userSelect:"none"},scriptReorder:{opacity:1,transitionDuration:"0.5s",transitionProperty:"opacity"},reorder:{},selected:window.vendorPrefix?a=>({backgroundColor:a.palette.primary.main,color:a.palette.text.primary}):{backgroundColor:"#164477",color:"white"},instances:{fontSize:"smaller",fontWeight:"bold",marginRight:4},childrenCount:{fontSize:10,opacity:.4},footer:{height:24,display:"flex"},footerButtons:a=>({"& img":{color:a.palette.mode==="dark"?"#ffffff":"#111111",cursor:"pointer",mt:"1px",mr:"2px",height:22,width:22,"&:hover":{backgroundColor:"#dbdbdb"}},"& svg":{color:a.palette.mode==="dark"?"#ffffff":"#111111",cursor:"pointer",mt:"1px",mr:"2px",height:22,width:22,"&:hover":{backgroundColor:"#dbdbdb"}}}),footerButtonsRight:{float:"right"}},Tn={Blockly:mk,"Javascript/js":Sc,def:Sc,Rules:$k,"TypeScript/ts":fk};function Xg(a,s,i){var r;return i=i||x.I18n.getLanguage(),(r=s==null?void 0:s.common)!=null&&r.name?typeof s.common.name=="object"?(s.common.name[i]||s.common.name.en||a.replace(/^script\.js./,"")).toString():s.common.name.toString():a.replace(/^script\.js./,"")}function I_(a){var l;const s=[{id:Xt,depth:0,index:0,parent:null,title:"root",type:"folder",parentIndex:null}],i=Object.keys(a);for(let c=0;c1?h.join("."):null,instance:d.common.engine?parseInt(d.common.engine.split(".").pop(),10)||0:null,index:0,parentIndex:0}):s.push({id:i[c],title:Xg(i[c],d),depth:h.length-1,type:"folder",parent:h.length>1?h.join("."):null,index:0,parentIndex:null})}let r;do r=!1,s.forEach(c=>{if(c.parent&&!s.find(h=>h.id===c.parent)){const h=c.parent.split(".");h.pop(),s.push({id:c.parent,title:c.parent.split(".").pop()||"",depth:h.length-1,type:"folder",parent:h.length>1?h.join("."):null,index:0,parentIndex:null}),r=!0}});while(r);return s.sort((c,d)=>{const h=c.id.toLowerCase(),p=d.id.toLowerCase();return c.type==="folder"&&d.type!=="folder"?-1:d.type==="folder"&&c.type!=="folder"||h>p?1:hc.index=d),s.forEach(c=>{if(c.parent){const d=s.find(h=>h.id===c.parent);d&&(c.parentIndex=d.index)}}),s}function Px(a){const{onDrop:s}=a,[{isOver:i,isOverAny:r},l]=GI({accept:"script",drop:c=>i?s(c):void 0,collect:c=>({isOver:c.isOver({shallow:!0}),isOverAny:c.isOver()})});return m.jsx("div",{ref:l,style:{background:i?"#40adff":void 0,opacity:r?.7:void 0},children:a.children},a.folderName)}function x_(a){const{name:s}=a,[{opacity:i},r]=PI({type:"script",item:()=>({name:s}),collect:l=>({opacity:l.isDragging()?.3:1})});return m.jsx("div",{ref:r,style:{opacity:i,transform:"translate3d(0, 0, 0)"},children:a.children},s)}class So extends _e.Component{inputRef;filterTimer;problems;problemsTimer;onProblemUpdatedBound;parent=null;constructor(s){super(s);const i=window.localStorage?window.localStorage.getItem("SideMenu.expanded"):"[]";let r;try{r=JSON.parse(i||"[]")||[]}catch{r=[]}this.inputRef=_e.createRef(),this.state={listItems:I_(s.scripts||{}),expanded:r,problems:[],reorder:!1,themeName:this.props.themeName,selected:window.localStorage&&window.localStorage.getItem("SideMenu.selected")||null,creatingScript:null,creatingFolder:!1,copingScript:"",renaming:null,deleting:null,choosingType:!1,errorText:"",instances:s.instances||[],menuOpened:!1,menuAnchorEl:null,menuAnchorFilterEl:null,searchMode:!1,expertMode:this.props.expertMode,searchText:"",width:this.props.width||300,typeFilter:window.localStorage&&window.localStorage.getItem("SideMenu.typeFilter")||"",statusFilter:window.localStorage&&window.localStorage.getItem("SideMenu.statusFilter")||"",runningInstances:this.props.runningInstances||{},scriptsHash:s.scriptsHash,showAdapterDebug:!1,isAllZeroInstances:!1,showExportDialog:!1};const l=this.ensureSelectedIsVisible();l&&Object.assign(this.state,{expanded:l}),this.filterTimer=null,Object.assign(this.state,{isAllZeroInstances:this.getIsAllZeroInstances()}),this.problems=null,this.problemsTimer=null,this.onProblemUpdatedBound=this.onProblemUpdated.bind(this)}readProblems(s,i){var r,l;if(i||(i=Object.keys(this.props.scripts)),!i||!i.length)s&&s();else{const c=i.shift(),d=this.props.scripts[c];if(((r=this.props.scripts)==null?void 0:r[c].type)==="script"&&((l=d.common)!=null&&l.enabled)&&!c.match(/^script\.js\.global\./)){const h=d.common.engine.split(".").pop(),p=this,f=`javascript.${h}.scriptProblem.${c.substring(Xt.length+1)}`;this.props.socket.getState(f).then(b=>{p.onProblemUpdated(f,b),setTimeout(()=>p.readProblems(s,i),0)})}else setTimeout(()=>this.readProblems(s,i),0)}}componentDidMount(){this.readProblems(()=>{this.props.instances.forEach(s=>{this.props.socket.subscribeState(`javascript.${s}.scriptProblem.*`,this.onProblemUpdatedBound)})})}componentWillUnmount(){this.props.instances.forEach(s=>{this.props.socket.unsubscribeState(`javascript.${s}.scriptProblem.*`,this.onProblemUpdatedBound)})}onProblemUpdated(s,i){if(!i||!s)return;s=`${Xt}.${s.replace(/^javascript\.\d+\.scriptProblem\./,"")}`,this.problems||(this.problems=JSON.parse(JSON.stringify(this.state.problems))||[]);let r=!1;if(i.val)this.problems.includes(s)||(this.problems.push(s),r=!0);else{const l=this.problems.indexOf(s);l!==-1&&(this.problems.splice(l,1),r=!0)}r&&!this.problemsTimer&&(this.problemsTimer=setTimeout(()=>{this.problemsTimer=null,this.setState({problems:this.problems}),this.problems=null},300))}static filterListStatic(s,i,r,l,c){i=JSON.parse(JSON.stringify(i));let d=!1;const h={listItems:i};if(s&&r&&l){const p=l.toLowerCase();if(i.forEach(f=>{var v;const b=f.title.toLowerCase();f.filteredPartly=!1;let y=b.includes(p);const w=(v=c==null?void 0:c[f.id])==null?void 0:v.common;if(!y&&(w!=null&&w.source))if(w.engineType==="Blockly"){const _=w.source.lastIndexOf("//");y=w.source.substring(0,_).toLowerCase().includes(p)}else y=w.source.toLowerCase().includes(p);y?f.filtered&&(f.filtered=!1,d=!0):f.filtered||(f.filtered=!0,d=!0)}),d)for(let f=i.length-1;f>=0;f--){const b=i[f];if(!b.filtered||b.filteredPartly){let y=b;do y!=null&&y.parent&&i[y.parentIndex]&&(d=!0,i[y.parentIndex].filteredPartly=!0),y=y!=null&&y.parent&&i[y.parentIndex]?i[y.parentIndex]:null;while(y)}}}else i.forEach(p=>{(p.filtered||p.filteredPartly)&&(p.filtered=!1,p.filteredPartly=!1,d=!0)}),s||(h.searchText="",h.searchMode=!1,d=!0);return d?h:null}filterList(s,i){const r=So.filterListStatic(s,this.state.listItems,this.state.searchMode,this.state.searchText,this.props.scripts);r?this.setState(r,()=>i&&i()):i&&i()}static ensureSelectedIsVisibleStatic(s,i,r){i=JSON.parse(JSON.stringify(i));let l=!1,c=typeof s=="object"?s:r.find(d=>d.id===s);do{if(c!=null&&c.parent){const d=c.parent;c=r.find(h=>h.id===d)}else c=void 0;c&&(i.includes(c.id)||(i.push(c.id),l=!0))}while(c);return l?i:null}ensureSelectedIsVisible(s,i){return So.ensureSelectedIsVisibleStatic(s||this.state.selected,i||this.state.expanded,this.state.listItems)}static getDerivedStateFromProps(s,i){const r={};let l=!1;if(i.expertMode!==s.expertMode&&(l=!0,r.expertMode=s.expertMode),i.scriptsHash!==s.scriptsHash&&s.scripts){const c=I_(s.scripts||{});if(r.listItems=c,i.searchText){const p=So.filterListStatic(!0,c,i.searchMode,i.searchText,s.scripts);p&&Object.assign(r,p)}const d=So.getIsAllZeroInstancesStatic(c,s.instances||[]),h=So.ensureSelectedIsVisibleStatic(i.selected,i.expanded,i.listItems);r.isAllZeroInstances=d,h&&(r.expanded=h),l=!0}if(i.width!==s.width&&(l=!0,r.width=s.width),i.themeName!==s.themeName&&(l=!0,r.themeName=s.themeName),s.selectId&&i.selected!==s.selectId){const c=i.listItems.find(d=>d.id===s.selectId);if(!i.reorder&&c){const d=So.ensureSelectedIsVisibleStatic(c,i.expanded,i.listItems);r.selected=c.id,d&&(r.expanded=d),l=!0,window.localStorage&&window.localStorage.setItem("SideMenu.selected",c.id)}}return l?r:null}static getIsAllZeroInstancesStatic(s,i){let r=!i[0]&&i.length<=1;return r&&s.forEach(l=>{l.type!=="folder"&&l.instance!==0&&(r=!1)}),r}getIsAllZeroInstances(s,i){return s=s||this.state.listItems,i=i||this.state.instances,So.getIsAllZeroInstancesStatic(s||this.state.listItems,i||this.state.instances)}saveExpanded(s){window.localStorage.setItem("SideMenu.expanded",JSON.stringify(s||this.state.expanded))}showError(s){this.setState({errorText:s})}onToggle(s,i){if(i==null||i.stopPropagation(),s===Xt)return;const r=[...this.state.expanded],l=r.indexOf(s);l!==-1?(r.splice(l,1),this.state.selected&&this.state.selected.startsWith(`${s}.`)&&window.localStorage&&window.localStorage.setItem("SideMenu.selected",s)):(r.push(s),r.sort()),this.setState({expanded:r}),this.saveExpanded(r)}renderItemButtonsOnEnd(s,i){if(this.state.reorder)return null;if(s.type!=="folder"){let r=s.enabled?ng:rg;return s.enabled&&this.state.problems.includes(s.id)&&(r=E_),[m.jsx(qe,{onClick:l=>{l.stopPropagation(),this.props.onEnableDisable&&this.props.onEnableDisable(s.id,!s.enabled)},title:s.enabled?x.I18n.t("Pause script"):x.I18n.t("Run script"),disabled:this.props.debugMode,style:{...Pe.iconButtons,...this.props.debugMode?Pe.iconButtonsDisabled:void 0,color:r},size:"medium",children:s.enabled?m.jsx(vc,{}):m.jsx(Yg,{})},"startStop"),this.state.width>Ur?m.jsx(qe,{style:this.props.debugMode?Pe.iconButtonsDisabled:void 0,title:x.I18n.t("Delete script"),disabled:s.id===To||s.id===Cn||this.props.debugMode,onClick:l=>this.onDelete(s,l),size:"medium",children:m.jsx(fc,{})},"delete"):null,m.jsx(qe,{style:this.props.debugMode?Pe.iconButtonsDisabled:void 0,disabled:this.props.debugMode,title:x.I18n.t("Edit script or just double click"),onClick:l=>this.onEdit(s,l),size:"medium",children:m.jsx(gx,{})},"openInEdit")]}return this.state.width>Ur&&s.id!==Xt&&s.id!==Cn&&s.id!==To&&!(i!=null&&i.length)?m.jsx(qe,{style:this.props.debugMode?Pe.iconButtonsDisabled:void 0,title:x.I18n.t("Delete folder"),disabled:s.id===To||s.id===Cn||this.props.debugMode,onClick:r=>this.onDelete(s,r),size:"medium",children:m.jsx(fc,{})},"delete"):null}onDelete(s,i){return i==null||i.stopPropagation(),new Promise(r=>{if(!s){r();return}typeof s!="object"?this.setState({deleting:s},()=>r()):this.setState({deleting:s.id},()=>r())})}onEdit(s,i){this.onClick(s,i),this.props.onEdit&&this.props.onEdit(s.id)}getTextStyle(s){return!this.state.reorder&&s.type!=="folder"?{width:`calc(100% - ${this.state.width>Ur?185:137}px)`,overflow:"hidden",whiteSpace:"nowrap",flex:"none",padding:"0 16px 0 0"}:{whiteSpace:"nowrap",padding:"0 16px 0 0"}}onClick(s,i){if(i==null||i.stopPropagation(),!this.state.reorder&&s){const r=this.ensureSelectedIsVisible(s),l={selected:s.id};r&&(l.expanded=r),this.setState(l),window.localStorage&&window.localStorage.setItem("SideMenu.selected",s.id)}}onDblClick(s,i){i==null||i.stopPropagation(),!this.state.reorder&&(s.type==="folder"?this.onToggle(s.id):this.onEdit(s))}isFilteredOut(s){var i,r;return s.filtered&&!s.filteredPartly||this.state.typeFilter&&s.type!=="folder"&&s.type.toLowerCase()!==this.state.typeFilter.toLowerCase()||!this.state.expertMode&&((r=(i=this.props.scripts[s.id])==null?void 0:i.native)!=null&&r.protected)||this.state.statusFilter&&s.type!=="folder"&&(this.state.statusFilter==="running"&&!s.enabled||this.state.statusFilter==="paused"&&s.enabled||this.state.statusFilter==="problems"&&(!s.enabled||this.state.problems.indexOf(s.id)===-1))?!0:s.id===To&&!this.state.expertMode}renderListItem(s,i,r){var w,v;if(s.id===Xt&&!this.state.reorder)return null;const l=(this.state.reorder?s.depth:s.depth-1)*Lx;let c=s.title;if(this.state.searchText){const _=c.toLowerCase().indexOf(this.state.searchText.toLowerCase());_!==-1&&(c=[m.jsx("span",{children:c.substring(0,_)},"first"),m.jsx("span",{style:{color:"orange"},children:c.substring(_,_+this.state.searchText.length)},"second"),m.jsx("span",{children:c.substring(_+this.state.searchText.length)},"third")])}if(!this.state.isAllZeroInstances&&s.type!=="folder"){const _=this.state.runningInstances[`system.adapter.javascript.${s.instance}`];c=[m.jsxs("span",{title:`${x.I18n.t("Instance")} ${s.instance}${_?"":` (${x.I18n.t("not running")})`}`,style:{...Pe.instances,color:_?ng:rg},children:["[",s.instance,"]"]},"instance"),m.jsx("span",{children:c},"title")]}const d=this.state.reorder&&!this.props.debugMode,h={marginLeft:l,cursor:s.type==="folder"&&d?"default":"inherit",width:`calc(100% - ${l}px)`};d||(h.opacity=s.filteredPartly?.5:1),s.id===To&&s.id!==this.state.selected&&(h.color="#00a200");let p=s.id===Xt;!p&&i&&(p=this.state.expanded.includes(s.id));let f;s.type==="folder"?f={...Pe.folderIcon,...d?Pe.folderIconReorder:Pe.folderIconNoReorder}:f={...Pe.scriptIcon},s.id===To?f.color="#356956":s.id===Cn&&(f.color="#4899e1");let b=null;(r&&r.length||i&&i.length)&&(b=m.jsx("span",{style:Pe.childrenCount,children:r&&r.length!==i.length?`${r.length}(${i.length})`:i.length}));const y={...s.type==="folder"?Pe.folder:Pe.script,...d?Pe.reorder:void 0,...d&&s.type!=="folder"?Pe.scriptReorder:void 0,...d&&s.type==="folder"?Pe.folderReorder:void 0,...h};return m.jsxs(PT,{style:y,sx:s.id===this.state.selected&&!d?Pe.selected:void 0,className:x.Utils.clsx(d&&s.type==="folder"&&"folder-reorder",d&&s.type!=="folder"&&"script-reorder"),onClick:_=>this.onClick(s,_),onDoubleClick:_=>this.onDblClick(s,_),secondaryAction:this.renderItemButtonsOnEnd(s,i),children:[(v=(w=this.props.scripts[s.id])==null?void 0:w.native)!=null&&v.protected?m.jsx(S_,{style:{color:"orange",position:"absolute",right:5,width:10,height:10}}):null,m.jsx(Ng,{style:Pe.listItemIcon,children:s.type==="folder"?d||p?m.jsx(eS,{style:f,onClick:_=>!d&&this.onToggle(s.id,_)}):m.jsx(tS,{style:f,onClick:_=>!d&&this.onToggle(s.id,_)}):m.jsx("img",{style:f,alt:s.type,src:Tn[s.type]||Tn.def})}),m.jsx(Lg,{sx:{"& .MuiListItemText-primary":s.id===this.state.selected&&!d?Pe.selected:void 0},style:this.getTextStyle(s),primary:m.jsxs("span",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[c,b]})})]},s.id)}onDragFinish(s,i){let r=`${i}.${s.split(".").pop()}`;r!==s&&(this.state.listItems.find(l=>l.id===r)&&(r+=`_${x.I18n.t("copy")}`),this.props.onRename&&this.props.onRename(s,r))}renderOneItem(s,i){const r=this.state.statusFilter||this.state.typeFilter?s.filter(f=>f.parent===i.id?!this.isFilteredOut(f):!1):[],l=s.filter(f=>f.parent===i.id);if(this.isFilteredOut(i)||i.type==="folder"&&(this.state.statusFilter||this.state.typeFilter)&&!r.length)return null;const c=this.state.reorder&&!this.props.debugMode,d=this.renderListItem(i,l,r),h=[];let p;return l&&(c||this.state.expanded.includes(i.id)||i.id===Xt)&&(p=l.map(f=>this.renderOneItem(s,f))),c?i.type==="folder"?h.push(m.jsxs(Px,{onDrop:f=>this.onDragFinish(f.name,i.id),folderName:i.id,children:[m.jsx(x_,{name:i.id,children:d},`draggable_${i.id}`),p||null]},`droppable_${i.id}`)):h.push(m.jsxs(x_,{name:i.id,children:[d,p||null]},`draggable_${i.id}`)):(h.push(d),p==null||p.forEach(f=>h.push(f))),h}renderAllItems(s){const i=s.filter(r=>!r.parent).map(r=>this.renderOneItem(s,r));return m.jsx(Mg,{dense:!0,disablePadding:!0,sx:Pe.mainList,children:i})}onAddNew(s){s==null||s.stopPropagation();let i=this.state.listItems.find(l=>l.id===this.state.selected),r=Xt;for(;i&&i.type!=="folder";)i=this.state.listItems[i.parentIndex];i&&(r=i.id),this.parent=r,this.setState({choosingType:!0})}onCopy(s,i){s==null||s.stopPropagation();let r=this.state.listItems.find(c=>c.id===i),l=Xt;for(;r&&r.type!=="folder";)r=this.state.listItems[r.parentIndex];r&&(l=r.id),this.parent=l,this.setState({copingScript:i||""})}onAddNewFolder(s){s==null||s.stopPropagation();let i=this.state.listItems.find(l=>l.id===this.state.selected),r=Xt;for(;i&&i.type!=="folder";)i=this.state.listItems[i.parentIndex];i&&(r=i.id),this.parent=r,this.setState({creatingFolder:!0})}onRename(s){s==null||s.stopPropagation(),this.setState({renaming:this.state.selected})}getUniqueName(s){let i=1,r=`${x.I18n.t("Script")} `;if(s){const l=Xg(s,this.props.scripts[s]),c=l.match(/\d+$/);c?(r=l.replace(/\d+$/,""),i=parseInt(c[0],10)+1):r=l}for(;this.state.listItems.find(l=>l.id===`${this.parent}.${r.replace(/\.\s/g,"_")}${i}`);)i++;return r+i}getUniqueFolderName(){let s=1;for(;this.state.listItems.find(i=>i.id===`${this.parent}.${x.I18n.t("Folder")}_${s}`);)s++;return`${x.I18n.t("Folder")} ${s}`}onCloseMenu(s){this.setState({menuOpened:!1,menuAnchorEl:null,menuAnchorFilterEl:null},s)}getMainMenu(s,i){var l,c,d,h;const r=this.state.expertMode&&!!Object.keys(this.props.changedScripts).find(p=>{var f,b;return this.props.changedScripts[p]&&((b=(f=this.props.scripts[p])==null?void 0:f.native)==null?void 0:b.protected)});return m.jsxs(kc,{id:"long-menu",anchorEl:this.state.menuAnchorEl,open:this.state.menuOpened,onClose:()=>this.setState({menuOpened:!1,menuAnchorEl:null}),slotProps:{paper:{style:{maxHeight:Nx*7.5}}},children:[this.state.width<=Ur?m.jsxs(tt,{disabled:this.props.debugMode||!this.state.selected||this.state.selected===To||this.state.selected===Cn||!!(s!=null&&s.length),onClick:p=>{if(p.stopPropagation(),p.preventDefault(),this.state.listItems.find(f=>f.parent===this.state.selected)){this.showError(x.I18n.t("Cannot delete non empty item!"));return}this.setState({menuOpened:!1,menuAnchorEl:null},()=>this.onDelete(this.state.selected).then(()=>{}))},children:[m.jsx(fc,{style:{...Pe.iconDropdownMenu,color:"red"}}),x.I18n.t("Delete")]},"delete"):null,m.jsxs(tt,{disabled:this.props.debugMode||r,selected:this.state.expertMode,onClick:p=>{p.stopPropagation(),p.preventDefault(),this.onCloseMenu(()=>this.props.onExpertModeChange&&this.props.onExpertModeChange(!this.state.expertMode))},children:[m.jsx(x.IconExpert,{style:{...Pe.iconDropdownMenu,color:this.state.expertMode?"orange":"inherit"}}),x.I18n.t("Expert mode")]},"expertMode"),this.props.onExport&&m.jsxs(tt,{onClick:p=>{p.stopPropagation(),p.preventDefault(),this.onCloseMenu(()=>this.setState({showExportDialog:!0}))},children:[m.jsx(Cc,{style:Pe.iconDropdownMenu}),x.I18n.t("Export all scripts")]},"exportAll"),this.props.onImport&&m.jsxs(tt,{disabled:this.props.debugMode,onClick:p=>{p.stopPropagation(),p.preventDefault(),this.onCloseMenu(()=>this.props.onImport())},children:[m.jsx(jg,{style:Pe.iconDropdownMenu}),x.I18n.t("Import scripts")]},"import"),this.props.onThemeChange&&m.jsxs(tt,{onClick:()=>this.onCloseMenu(()=>{this.props.onThemeChange&&this.props.onThemeChange(x.Utils.toggleTheme(this.state.themeName))}),children:[m.jsx(fx,{style:Pe.iconDropdownMenu}),x.I18n.t('Change theme (actual "%s")',this.state.themeName)]},"dark"),this.props.onAddNew&&m.jsxs(tt,{disabled:!this.state.selected||!i||i.type==="folder",onClick:p=>{const f=this.state.selected;this.onCloseMenu(()=>this.onCopy(p,f))},children:[m.jsx(sS,{style:Pe.iconDropdownMenu}),x.I18n.t("Copy script")]},"copy"),this.state.expertMode&&m.jsxs(tt,{disabled:this.props.debugMode,onClick:p=>{p.stopPropagation(),p.preventDefault(),this.onCloseMenu(()=>this.setState({showAdapterDebug:!0}))},children:[m.jsx(cx,{style:Pe.iconDropdownMenu}),x.I18n.t("Debug instance")]},"debugInstance"),this.state.selected&&this.props.password&&this.props.scripts[this.state.selected].type==="script"?m.jsxs(tt,{disabled:this.props.debugMode||this.props.changedScripts[this.state.selected],onClick:p=>{p.stopPropagation(),p.preventDefault(),this.onCloseMenu(async()=>{var b;const f=await this.props.socket.getObject(this.state.selected);f&&((b=f.native)!=null&&b.protected?(delete f.native.protected,f.common.source=Jg(this.props.password,f.common.source||"")):(f.native||={},f.native.protected=!0,f.common.source=yc(this.props.password,f.common.source||"")),await this.props.socket.setObject(f._id,f))})},children:[m.jsx(S_,{style:{...Pe.iconDropdownMenu,color:"orange"}}),(c=(l=this.props.scripts[this.state.selected])==null?void 0:l.native)!=null&&c.protected?m.jsx("span",{style:{color:(h=(d=this.props.scripts[this.state.selected])==null?void 0:d.native)!=null&&h.protected?"orange":void 0},children:x.I18n.t("Unprotect script")}):x.I18n.t("Protect script")]},"encrypt"):null]},"menu")}getToolbarButtons(){const s=[],i=this.state.reorder&&!this.props.debugMode;if(this.state.searchMode&&!this.props.debugMode)s.push(m.jsx(Pn,{value:this.state.searchText,style:Pe.toolbarSearch,ref:this.inputRef,autoFocus:!0,placeholder:x.I18n.t("Search..."),onChange:r=>{this.setState({searchText:r.target.value}),this.filterTimer&&clearTimeout(this.filterTimer),this.filterTimer=setTimeout(()=>{this.filterTimer=null,this.filterList(!0),this.props.onSearch&&this.props.onSearch(this.state.searchText)},400)}},"searchInput")),s.push(m.jsx(qe,{sx:Pe.toolbarButtons,style:{float:"right"},title:x.I18n.t("End search mode"),onClick:r=>{r.stopPropagation(),this.filterList(!1,()=>this.props.onSearch&&this.props.onSearch(this.state.searchText))},size:"medium",children:m.jsx(hx,{})},"disableSearch")),this.state.searchText&&s.push(m.jsx(qe,{title:x.I18n.t("Clear search input"),sx:Pe.toolbarButtons,style:{marginTop:7,float:"right"},onClick:r=>{r.stopPropagation(),this.setState({searchText:""},()=>{this.filterList(!0),this.props.onSearch&&this.props.onSearch(this.state.searchText)})},size:"medium",children:m.jsx(Lw,{fontSize:"small"})},"cleanSearch"));else{if(!i){s.push(m.jsx(qe,{"aria-label":"More","aria-owns":this.state.menuOpened?"long-menu":void 0,title:x.I18n.t("Menu"),"aria-haspopup":"true",onClick:c=>{c.stopPropagation(),c.preventDefault(),this.setState({menuOpened:!0,menuAnchorEl:c.currentTarget})},size:"medium",children:m.jsx(mx,{})},"menuButton"));const r=this.state.listItems.find(c=>c.id===this.state.selected);let l;r&&this.state.width<=Ur&&r.type==="folder"&&(l=this.state.listItems.filter(c=>c.parent===this.state.selected)),s.push(this.getMainMenu(l,r)),s.push(m.jsx(qe,{disabled:this.props.debugMode,title:x.I18n.t("Create new script"),sx:{...Pe.toolbarButtons,...this.props.debugMode?Pe.iconButtonsDisabled:void 0},style:{color:i?"red":"inherit"},onClick:c=>this.onAddNew(c),size:"medium",children:m.jsx(oS,{})},"new-script")),s.push(m.jsx(qe,{disabled:this.props.debugMode,title:x.I18n.t("Create new folder"),sx:{...Pe.toolbarButtons,...this.props.debugMode?Pe.iconButtonsDisabled:void 0},style:{color:i?"red":"inherit"},onClick:c=>this.onAddNewFolder(c),size:"medium",children:m.jsx(iS,{})},"new-folder"))}s.push(m.jsx(qe,{disabled:i||this.props.debugMode,sx:{...Pe.toolbarButtons,...this.props.debugMode?Pe.iconButtonsDisabled:void 0},title:x.I18n.t("Search in scripts"),style:{float:"right",opacity:this.props.debugMode?.5:i?0:1},onClick:r=>{r.stopPropagation(),this.setState({searchMode:!0})},size:"medium",children:m.jsx(bx,{})},"search")),s.push(m.jsx(qe,{disabled:this.props.debugMode,title:x.I18n.t("Reorder scripts in folders"),sx:{...Pe.toolbarButtons,...this.props.debugMode?Pe.iconButtonsDisabled:void 0},style:{color:i?"red":"inherit",float:"right"},onClick:r=>{r.stopPropagation(),this.setState({reorder:!this.state.reorder})},size:"medium",children:m.jsx(wx,{})},"reorder")),!i&&this.state.selected&&this.state.selected!==To&&this.state.selected!==Cn&&s.push(m.jsx(qe,{sx:{...Pe.toolbarButtons,...this.props.debugMode?Pe.iconButtonsDisabled:void 0},disabled:this.props.debugMode,title:x.I18n.t("Rename"),onClick:r=>this.onRename(r),size:"medium",children:m.jsx(nS,{})},"rename")),s.push(m.jsxs("span",{style:{opacity:.5,fontSize:10},children:["v",this.props.version]},"version"))}return s}getFolders(){const s=[{id:Xt,name:x.I18n.t("Root folder")}];return this.state.listItems.forEach(i=>{i.type==="folder"&&i.id!==Xt&&(!i.id.startsWith(To)||this.state.expertMode)&&s.push({id:i.id,name:i.title})}),s}onCollapseAll(){this.setState({expanded:[]}),this.saveExpanded([])}onExpandAll(){const s=[];this.state.listItems.forEach(i=>this.state.listItems.find(r=>r.parent===i.id)&&s.push(i.id)),this.setState({expanded:s}),this.saveExpanded(s)}getBottomButtons(){return this.state.reorder||this.props.debugMode?null:[m.jsx(wt,{sx:Pe.footerButtons,title:x.I18n.t("Show only running scripts"),onClick:s=>{s.stopPropagation(),s.preventDefault();const i=this.state.statusFilter==="running"?"":"running";window.localStorage&&window.localStorage.setItem("SideMenu.statusFilter",i),this.setState({statusFilter:i})},children:m.jsx(vc,{style:{color:ng,opacity:this.state.statusFilter==="running"?1:.3,background:this.state.statusFilter==="running"?"gray":"inherit"}})},"filterByRunning"),m.jsx(wt,{sx:Pe.footerButtons,title:x.I18n.t("Show only paused scripts"),onClick:()=>{const s=this.state.statusFilter==="paused"?"":"paused";window.localStorage&&window.localStorage.setItem("SideMenu.statusFilter",s),this.setState({statusFilter:s})},children:m.jsx(Yg,{style:{color:rg,opacity:this.state.statusFilter==="paused"?1:.3,background:this.state.statusFilter==="paused"?"gray":"inherit"}})},"filterByPaused"),m.jsx(wt,{sx:Pe.footerButtons,style:{marginRight:16},title:x.I18n.t("Show only scripts with problems"),onClick:()=>{const s=this.state.statusFilter==="problems"?"":"problems";window.localStorage&&window.localStorage.setItem("SideMenu.statusFilter",s),this.setState({statusFilter:s})},children:m.jsx(vc,{style:{color:E_,opacity:this.state.statusFilter==="problems"?1:.3,background:this.state.statusFilter==="problems"?"gray":"inherit"}})},"filterByProblem"),m.jsx(wt,{sx:Pe.footerButtons,children:m.jsx("img",{alt:"Blockly",style:{opacity:this.state.typeFilter==="Blockly"?1:.3,background:this.state.typeFilter==="Blockly"?"gray":"inherit"},src:Tn.Blockly,onClick:()=>{const s=this.state.typeFilter==="Blockly"?"":"Blockly";window.localStorage&&window.localStorage.setItem("SideMenu.typeFilter",s),this.setState({typeFilter:s})}})},"filterBlockly"),m.jsx(wt,{sx:Pe.footerButtons,children:m.jsx("img",{alt:"Javascript",style:{opacity:this.state.typeFilter==="Javascript/js"?1:.3,background:this.state.typeFilter==="Javascript/js"?"gray":"inherit"},src:Tn["Javascript/js"],onClick:()=>{const s=this.state.typeFilter==="Javascript/js"?"":"Javascript/js";window.localStorage&&window.localStorage.setItem("SideMenu.typeFilter",s),this.setState({typeFilter:s})}})},"filterJS"),m.jsx(wt,{sx:Pe.footerButtons,children:m.jsx("img",{alt:"TypeScript",style:{opacity:this.state.typeFilter==="TypeScript/ts"?1:.3,background:this.state.typeFilter==="TypeScript/ts"?"gray":"inherit"},src:Tn["TypeScript/ts"],onClick:()=>{const s=this.state.typeFilter==="TypeScript/ts"?"":"TypeScript/ts";window.localStorage&&window.localStorage.setItem("SideMenu.typeFilter",s),this.setState({typeFilter:s})}})},"filterTS"),m.jsx(wt,{sx:Pe.footerButtons,children:m.jsx("img",{alt:"Rules",style:{opacity:this.state.typeFilter==="Rules"?1:.3,background:this.state.typeFilter==="Rules"?"gray":"inherit"},src:Tn.Rules,onClick:()=>{const s=this.state.typeFilter==="Rules"?"":"Rules";window.localStorage&&window.localStorage.setItem("SideMenu.typeFilter",s),this.setState({typeFilter:s})}})},"filterRules"),m.jsx("div",{style:{flexGrow:1}},"padding"),m.jsx(wt,{sx:Pe.footerButtons,onClick:()=>this.onExpandAll(),title:x.I18n.t("Expand all"),children:m.jsx(Cx,{style:Pe.footerButtonsRight})},"expandAll"),this.state.expanded.length?m.jsx(wt,{sx:Pe.footerButtons,onClick:()=>this.onCollapseAll(),title:x.I18n.t("Collapse all"),children:m.jsx(kx,{style:Pe.footerButtonsRight})},"collapseAll"):m.jsx("div",{style:{height:22,width:24}})]}getAdapterDebugDialog(){return this.state.showAdapterDebug?m.jsx(Ax,{socket:this.props.socket,onClose:()=>this.setState({showAdapterDebug:!1}),onDebug:(s,i)=>this.setState({showAdapterDebug:!1},()=>this.props.onDebugInstance({instance:s,adapter:i}))},"debug"):null}render(){var r,l,c;const s=this.state.renaming?this.state.listItems.find(d=>d.id===this.state.renaming):void 0,i=this.state.copingScript&&this.props.scripts[this.state.copingScript].type==="script"?this.props.scripts[this.state.copingScript]:void 0;return[m.jsxs(BT,{variant:"permanent",style:Pe.menu,sx:{"& .MuiDrawer-paper":Pe.drawerPaper},anchor:"left",onClick:()=>this.onClick({id:""}),children:[m.jsx(wt,{sx:Pe.toolbar,children:this.getToolbarButtons()}),m.jsx(Pg,{}),m.jsx(tk,{backend:pk,children:m.jsx("div",{style:Pe.innerMenu,children:this.renderAllItems(this.state.listItems)})}),m.jsx(Pg,{}),m.jsx("div",{style:Pe.footer,children:this.getBottomButtons()})]},"drawer"),s?m.jsx(km,{name:s.title,id:this.state.renaming||"",folder:s.type==="folder",instance:s.instance,instances:this.props.instances,onClose:()=>this.setState({renaming:null}),onRename:(d,h,p,f)=>this.props.onRename&&this.props.onRename(d,h,p,f)},"dialog-rename"):null,this.state.deleting?m.jsx(Tx,{name:this.state.listItems.find(d=>d.id===this.state.deleting).title,id:this.state.deleting,onClose:()=>this.setState({deleting:null}),onDelete:d=>this.props.onDelete&&this.props.onDelete(d)},"dialog-delete"):null,this.state.choosingType?m.jsx(Dn,{onClose:d=>{const h={choosingType:!1};d&&(h.creatingScript=d),this.setState(h)}},"dialog-script-type"):null,this.state.creatingScript?m.jsx(ig,{onClose:()=>this.setState({creatingScript:null}),title:x.I18n.t("Create new script"),name:this.getUniqueName(),parents:this.getFolders(),folder:!1,existingItems:this.state.listItems.map(d=>d.id),instance:this.props.instances[0]||0,instances:this.props.instances,type:this.state.creatingScript,parent:this.parent,onAdd:(d,h,p,f)=>this.props.onAddNew&&this.props.onAddNew(d,h,!1,p,f)},"dialog-new-script"):null,this.state.copingScript?m.jsx(ig,{onClose:()=>this.setState({copingScript:""}),title:x.I18n.t("Copy script"),name:this.getUniqueName(this.state.copingScript),parents:this.getFolders(),folder:!1,instance:parseInt((l=(r=i==null?void 0:i.common)==null?void 0:r.engine)==null?void 0:l.split(".").pop(),10)||0,instances:this.props.instances,type:((c=i==null?void 0:i.common)==null?void 0:c.engineType)||"Javascript/js",parent:this.parent,onAdd:(d,h,p,f)=>{var y;const b=this.state.copingScript&&this.props.scripts[this.state.copingScript].type==="script"?this.props.scripts[this.state.copingScript]:void 0;b!=null&&b.common&&(b.common.enabled=!1),this.props.onAddNew&&this.props.onAddNew(d,h,!1,p,f,(y=b==null?void 0:b.common)==null?void 0:y.source)}},"dialog-copy-script"):null,this.state.creatingFolder?m.jsx(ig,{onClose:()=>this.setState({creatingFolder:!1}),title:x.I18n.t("Create new folder"),parents:this.getFolders(),name:this.getUniqueFolderName(),parent:this.parent,onAdd:(d,h)=>this.props.onAddNew&&this.props.onAddNew(d,h,!0)},"dialog-new-folder"):null,this.state.errorText?m.jsx(ou,{onClose:()=>this.setState({errorText:""}),text:this.state.errorText},"error"):null,this.getAdapterDebugDialog(),this.state.showExportDialog?m.jsxs(Pt,{open:!0,onClose:()=>this.setState({showExportDialog:!1}),children:[m.jsx(qt,{children:x.I18n.t("Export all scripts")}),m.jsxs(Bt,{children:[m.jsx(Ue,{variant:"contained",onClick:()=>{this.setState({showExportDialog:!1}),this.props.onExport(!0)},color:"primary",children:x.I18n.t("as JSON")}),m.jsx(Ue,{variant:"contained",onClick:()=>{this.setState({showExportDialog:!1}),this.props.onExport(!1)},color:"grey",children:x.I18n.t("as plain text")}),m.jsx(Ue,{variant:"contained",onClick:()=>this.setState({showExportDialog:!1}),color:"primary",children:x.I18n.t("Cancel")})]})]},"dialog-export-format"):null]}}const Bx="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGAAAABgAQMAAADYVuV7AAAABlBMVEUAAAAzMzPI8eYgAAAAAXRSTlMAQObYZgAAACFJREFUeAFjAIJRwP////8PYIKWHCigNQdKj/pn1D+jAABTG16wVQqVpQAAAABJRU5ErkJggg==",jx="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGAAAABgAQMAAADYVuV7AAAABlBMVEUAAAAzMzPI8eYgAAAAAXRSTlMAQObYZgAAABtJREFUeAFjAIJRwP8fCj7QkENn/4z6Z5QzCgBjbWaoyx1PqQAAAABJRU5ErkJggg==";function Fx(a){let s,i=a.getHours();return i<10&&(i=`0${i.toString()}`),s=`${i}:`,i=a.getMinutes(),i<10&&(i=`0${i.toString()}`),s+=`${i}:`,i=a.getSeconds(),i<10&&(i=`0${i.toString()}`),s+=`${i}.`,i=a.getMilliseconds(),i<10?i=`00${i.toString()}`:i<100&&(i=`0${i.toString()}`),s+=i,s}const D_=34,Ht={logBox:{width:"100%",height:"100%",position:"relative",overflow:"hidden"},logBoxInner:a=>({display:"inline-block",color:a.palette.mode==="dark"?"white":"black",width:`calc(100% - ${D_}px)`,height:"100%",overflow:"auto",position:"relative",verticalAlign:"top"}),info:a=>({background:a.palette.mode==="dark"?"darkgrey":"lightgrey",color:(a.palette.mode==="dark","black")}),error:a=>({background:"#FF0000",color:a.palette.mode==="dark"?"black":"white"}),warn:a=>({background:"#FF8000",color:a.palette.mode==="dark"?"black":"white"}),debug:a=>({background:"gray",opacity:.8,color:a.palette.mode==="dark"?"black":"white"}),silly:a=>({background:"gray",opacity:.6,color:a.palette.mode==="dark"?"black":"white"}),table:{fontFamily:"monospace",width:"100%"},toolbox:{width:D_,height:"100%",boxShadow:"2px 0px 4px -1px rgba(0, 0, 0, 0.2), 4px 0px 5px 0px rgba(0, 0, 0, 0.14), 1px 0px 10px 0px rgba(0, 0, 0, 0.12)",display:"inline-block",verticalAlign:"top",overflow:"hidden"},trFrom:{width:90},trTime:{width:90},trSeverity:{width:40,fontWeight:"bold"},trPreMessage:{padding:0,margin:0},iconButtons:{width:32,height:32,padding:4},layoutIcon:a=>({"& img":{width:24,height:24,background:a.palette.mode==="dark"?"#9d9d9d":void 0,borderRadius:a.palette.mode==="dark"?"30px":void 0}})};function zx(a){return a<10?`00${a}`:a<100?`0${a}`:a.toString()}const Zs={};class Cm extends _e.Component{messagesEnd;constructor(s){super(s),this.state={lines:{},goBottom:!0,selected:null,editing:this.props.editing||[]},this.messagesEnd=_e.createRef()}static generateLine(s,i){let r=s.message||"";if(typeof r!="object"){const l=new RegExp(`${s.from.replace(".","\\.").replace(")","\\)").replace("(","\\(")} \\(\\d+\\) `,"g"),c=r.match(l);c?r=r.replace(c[0],""):r=r.replace(`${s.from} `,"")}return r.startsWith(`${i}: `)&&(r=r.substring(i.length+2)),m.jsxs(wt,{component:"tr",sx:Ht[s.severity],children:[m.jsx("td",{style:Ht.trFrom,children:s.from}),m.jsx("td",{style:Ht.trTime,children:Fx(new Date(s.ts))}),m.jsx("td",{style:Ht.trSeverity,children:s.severity}),m.jsx("td",{children:m.jsx("pre",{style:Ht.trPreMessage,children:r})})]},`tr_${s.ts}_${s.message.substring(s.message.length-10)}`)}scrollToBottom(){var s,i;(i=(s=this.messagesEnd)==null?void 0:s.current)==null||i.scrollIntoView({behavior:"smooth"})}logHandler=s=>{const i=this.state.lines,r=this.state.editing.filter(f=>s.message.includes(f));let l=null;if(!r.length||(r.length===1?l=r[0]:(r.sort(),l=r[r.length-1]),!l))return;const c=i[l]||[],d=Zs[l]||[];c.push(Cm.generateLine(s,l));let h=s.severity;(h==="info"||h==="warn")&&(h+=" ");const p=new Date(s.ts);d.push(`${p.toLocaleString()}.${zx(p.getMilliseconds())} [${h}]: ${s.message}`),c.length>300&&(c.splice(0,c.length-300),d.splice(0,c.length-300)),Zs[l]=d,i[l]=c,this.setState({lines:i})};componentDidMount(){this.props.socket.registerLogHandler(this.logHandler)}componentWillUnmount(){this.props.socket.unregisterLogHandler(this.logHandler)}componentDidUpdate(){this.state.goBottom&&this.scrollToBottom()}static getDerivedStateFromProps(s,i){let r=!1;const l={};if(s.selected!==i.selected){const c=s.selected,d=i.lines;c&&(d[c]=d[c]||[],Zs[c]=Zs[c]||[]),l.selected=c,r=!0}if(JSON.stringify(s.editing)!==JSON.stringify(i.editing)){const c=JSON.parse(JSON.stringify(s.editing));r=!0;const d=i.lines;for(const h in Zs)Object.prototype.hasOwnProperty.call(Zs,h)&&(c.includes(h)||(delete Zs[h],delete d[h]));l.editing=c}return r?l:null}onCopy(){x.Utils.copyToClipboard((Zs[this.state.selected]||[]).join(` +`))}clearLog(){const s=this.state.lines;s[this.state.selected]&&(s[this.state.selected]=[]),Zs[this.state.selected]&&(Zs[this.state.selected]=[]),this.setState({lines:s})}renderLogList(s){return this.state.selected&&(s!=null&&s.length)?m.jsxs(wt,{sx:Ht.logBoxInner,children:[m.jsx("table",{style:Ht.table,children:m.jsx("tbody",{children:s})},"logTable"),m.jsx("div",{ref:this.messagesEnd,style:{float:"left",clear:"both"}},"logScrollPoint")]},"logList"):m.jsx(wt,{sx:Ht.logBoxInner,style:{paddingLeft:10},children:x.I18n.t("Log outputs")},"logList")}render(){const s=this.state.selected?this.state.lines[this.state.selected]:null;return m.jsxs("div",{style:Ht.logBox,children:[m.jsxs("div",{style:Ht.toolbox,children:[m.jsx(qe,{style:Ht.iconButtons,onClick:()=>this.setState({goBottom:!this.state.goBottom}),color:this.state.goBottom?"secondary":void 0,size:"medium",children:m.jsx(rS,{})}),s!=null&&s.length?m.jsx(qe,{style:Ht.iconButtons,onClick:()=>this.clearLog(),size:"medium",children:m.jsx(aS,{})}):null,s!=null&&s.length?m.jsx(qe,{style:Ht.iconButtons,onClick:()=>this.onCopy(),size:"medium",children:m.jsx(lS,{})}):null,this.props.onLayoutChange?m.jsx(qe,{style:Ht.iconButtons,onClick:()=>this.props.onLayoutChange&&this.props.onLayoutChange(),title:x.I18n.t("Change layout"),size:"medium",sx:Ht.layoutIcon,children:m.jsx("img",{alt:"split",src:this.props.verticalLayout?Bx:jx})}):null,m.jsx(qe,{style:Ht.iconButtons,onClick:()=>this.props.onHideLog(),title:x.I18n.t("Hide logs"),size:"medium",children:m.jsx(cS,{})})]},"toolbox"),this.renderLogList(s)]})}}var A_="focus-outline-hidden";function yk(){var a=this;document.addEventListener("keydown",function(s){a.focusByKeyboard=!0},!0),document.addEventListener("mousedown",function(s){a.focusByKeyboard=!1},!0),document.addEventListener("focus",function(s){a.updateVisibility()},!0),document.addEventListener("focusout",function(s){window.setTimeout(function(){document.hasFocus()||(a.focusByKeyboard=!0,a.updateVisibility())},0)}),this.updateVisibility()}yk.prototype={focusByKeyboard:!0,updateVisibility:function(){this.hidden=!this.focusByKeyboard},set hidden(a){document.documentElement.classList.toggle(A_,a)},get hidden(){return document.documentElement.classList.contains(A_)}};new yk;var _k={exports:{}};(function(a){(function(){var s={}.hasOwnProperty;function i(){for(var r=[],l=0;l4&&arguments[4]!==void 0?arguments[4]:"easeInOutCubic";return r>l?i:s+(i-s)*Hx[c](r/l)};Ni.calcEndPoint=function(s){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:window,r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0;if(Wx(s))return parseInt(s)+r;var l=i===window||i===document.documentElement?window.pageYOffset:i.scrollTop-i.getBoundingClientRect().top,c=s.nodeName.toLowerCase()==="html"?-l:s.getBoundingClientRect().top+l;return c+r};(function(a,s){Object.defineProperty(s,"__esModule",{value:!0});var i=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(l){return typeof l}:function(l){return l&&typeof Symbol=="function"&&l.constructor===Symbol&&l!==Symbol.prototype?"symbol":typeof l},r=Ni;s.default=function(l){var c=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},d=c.duration,h=d===void 0?500:d,p=c.context,f=p===void 0?window:p,b=c.offset,y=b===void 0?0:b,w=c.ease,v=w===void 0?"easeInOutCubic":w,_=c.callback;if((typeof window>"u"?"undefined":i(window))==="object"){var $=f.scrollTop!==null&&f.scrollTop!==void 0?f.scrollTop:window.pageYOffset,T=(0,r.calcEndPoint)(l,f,y),S=performance.now(),E=window.requestAnimationFrame,D=function R(){var L=performance.now()-S,H=(0,r.setPosition)($,T,L,h,v);f!==window?f.scrollTop=H:window.scroll(0,H),L>h?typeof _=="function"&&_(l):E(R)};D()}},a.exports=s.default})(Zg,Zg.exports);var wk=Zg.exports,Qg={exports:{}};(function(a,s){Object.defineProperty(s,"__esModule",{value:!0});var i=Object.assign||function(d){for(var h=1;h0&&arguments[0]!==void 0?arguments[0]:{},h=d.query,p=h===void 0?'[href^="#"]:not([href="#"]':h,f=d.match,b=f===void 0?function(T){return document.getElementById(T.hash.substring(1))}:f,y=d.hashChange,w=y===void 0?!0:y,v=d.scrollSmoothConfig,_=document.querySelectorAll(p),$=function(S){S.preventDefault();var E=b(S.target);E&&(w&&history.replaceState(null,null,"#"+E.id),(0,l.default)(E,i({},v)))};Array.from(_).map(function(T){T.addEventListener("click",$,!1)})},a.exports=s.default})(Qg,Qg.exports);var Gx=Qg.exports,em={exports:{}};(function(a,s){Object.defineProperty(s,"__esModule",{value:!0});function i(r){if(Array.isArray(r)){for(var l=0,c=Array(r.length);l0&&arguments[0]!==void 0?arguments[0]:{},l=r.activeClass,c=l===void 0?"active":l,d=r.query,h=d===void 0?'[href^="#"]:not([href="#"]):not([href="#0"])':d,p=r.threshold,f=p===void 0?[.25,.5,.75]:p,b=r.detectType,y=b===void 0?"max":b,w={threshold:f},v=function(H){return H.classList.remove(c)},_=function(H){return H.classList.add(c)},$=function(){document.querySelectorAll("."+c).forEach(v)},T=function(H){$(),_(document.querySelector('a[href="#'+H.id+'"]'))},S=function(H){H.forEach(function(G){G.intersectionRatio>=Math[y].apply(Math,i(f))&&T(G.target)})},E=document.querySelectorAll(h),D=new IntersectionObserver(S,w),R=function(H){var G=document.querySelector("#"+H.hash.slice(1));D.observe(G)};E.forEach(R)},a.exports=s.default})(em,em.exports);var Vx=em.exports;(function(a,s){Object.defineProperty(s,"__esModule",{value:!0});var i=wk,r=f(i),l=Ni,c=Gx,d=f(c),h=Vx,p=f(h);function f(b){return b&&b.__esModule?b:{default:b}}s.default={to:r.default,calcEndPoint:l.calcEndPoint,anchorScroll:d.default,observe:p.default},a.exports=s.default})(qg,qg.exports);var Yx=qg.exports;const Kx=qo(Yx);var Tm={exports:{}},Jx=Tm.exports;(function(a){(function(s,i){a.exports?a.exports=i():s.Scrollparent=i()})(Jx,function(){var s=/(auto|scroll)/,i=function(h,p){return h.parentNode===null?p:i(h.parentNode,p.concat([h]))},r=function(h,p){return getComputedStyle(h,null).getPropertyValue(p)},l=function(h){return r(h,"overflow")+r(h,"overflow-y")+r(h,"overflow-x")},c=function(h){return s.test(l(h))},d=function(h){if(h instanceof HTMLElement||h instanceof SVGElement){for(var p=i(h.parentNode,[]),f=0;f=s||G<0||y&&z>=c}function S(){var H=ag();if(T(H))return E(H);h=setTimeout(S,$(H))}function E(H){return h=void 0,w&&r?v(H):(r=l=void 0,d)}function D(){h!==void 0&&clearTimeout(h),f=0,r=p=l=h=void 0}function R(){return h===void 0?d:E(ag())}function L(){var H=ag(),G=T(H);if(r=arguments,l=this,p=H,G){if(h===void 0)return _(p);if(y)return h=setTimeout(S,s),v(p)}return h===void 0&&(h=setTimeout(S,s)),d}return L.cancel=D,L.flush=R,L}function tm(a){var s=typeof a;return!!a&&(s=="object"||s=="function")}function p0(a){return!!a&&typeof a=="object"}function g0(a){return typeof a=="symbol"||p0(a)&&c0.call(a)==Qx}function M_(a){if(typeof a=="number")return a;if(g0(a))return R_;if(tm(a)){var s=typeof a.valueOf=="function"?a.valueOf():a;a=tm(s)?s+"":s}if(typeof a!="string")return a===0?a:+a;a=a.replace(e0,"");var i=s0.test(a);return i||o0.test(a)?i0(a.slice(2),i?2:8):t0.test(a)?R_:+a}var m0=h0;const f0=qo(m0);var sm="data-focus-lock",kk="data-focus-lock-disabled",$0="data-no-focus-lock",b0="data-autofocus-inside",v0="data-no-autofocus";function lg(a,s){return typeof a=="function"?a(s):a&&(a.current=s),a}function y0(a,s){var i=kt(function(){return{value:a,callback:s,facade:{get current(){return i.value},set current(r){var l=i.value;l!==r&&(i.value=r,i.callback(r,l))}}}})[0];return i.callback=s,i.facade}var _0=typeof window<"u"?mm:Lt,N_=new WeakMap;function w0(a,s){var i=y0(null,function(r){return a.forEach(function(l){return lg(l,r)})});return _0(function(){var r=N_.get(i);if(r){var l=new Set(r),c=new Set(a),d=i.current;l.forEach(function(h){c.has(h)||lg(h,null)}),c.forEach(function(h){l.has(h)||lg(h,d)})}N_.set(i,a)},[a]),i}var cg={width:"1px",height:"0px",padding:0,overflow:"hidden",position:"fixed",top:"1px",left:"1px"};function Ck(a){return a}function Tk(a,s){s===void 0&&(s=Ck);var i=[],r=!1,l={read:function(){if(r)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return i.length?i[i.length-1]:a},useMedium:function(c){var d=s(c,r);return i.push(d),function(){i=i.filter(function(h){return h!==d})}},assignSyncMedium:function(c){for(r=!0;i.length;){var d=i;i=[],d.forEach(c)}i={push:function(h){return c(h)},filter:function(){return i}}},assignMedium:function(c){r=!0;var d=[];if(i.length){var h=i;i=[],h.forEach(c),d=i}var p=function(){var b=d;d=[],b.forEach(c)},f=function(){return Promise.resolve().then(p)};f(),i={push:function(b){d.push(b),f()},filter:function(b){return d=d.filter(b),i}}}};return l}function Sm(a,s){return s===void 0&&(s=Ck),Tk(a,s)}function k0(a){a===void 0&&(a={});var s=Tk(null);return s.options=uS({async:!0,ssr:!1},a),s}var Sk=Sm({},function(a){var s=a.target,i=a.currentTarget;return{target:s,currentTarget:i}}),Ek=Sm(),C0=Sm(),T0=k0({async:!0,ssr:typeof document<"u"}),S0=pm(void 0),E0=[],Em=xw(function(s,i){var r,l=kt(),c=l[0],d=l[1],h=Yo(),p=Yo(!1),f=Yo(null),b=kt({}),y=b[1],w=s.children,v=s.disabled,_=v===void 0?!1:v,$=s.noFocusGuards,T=$===void 0?!1:$,S=s.persistentFocus,E=S===void 0?!1:S,D=s.crossFrame,R=D===void 0?!0:D,L=s.autoFocus,H=L===void 0?!0:L;s.allowTextSelection;var G=s.group,z=s.className,Z=s.whiteList,he=s.hasPositiveIndices,Ce=s.shards,M=Ce===void 0?E0:Ce,Y=s.as,C=Y===void 0?"div":Y,Q=s.lockProps,ve=Q===void 0?{}:Q,ce=s.sideCar,ne=s.returnFocus,me=ne===void 0?!1:ne,re=s.focusOptions,B=s.onActivation,N=s.onDeactivation,te=kt({}),X=te[0],se=xn(function(K){var O=K.captureFocusRestore;if(!f.current){var A,U=(A=document)==null?void 0:A.activeElement;f.current=U,U!==document.body&&(f.current=O(U))}h.current&&B&&B(h.current),p.current=!0,y()},[B]),F=xn(function(){p.current=!1,N&&N(h.current),y()},[N]),Te=xn(function(K){var O=f.current;if(O){var A=(typeof O=="function"?O():O)||document.body,U=typeof me=="function"?me(A):me;if(U){var W=typeof U=="object"?U:void 0;f.current=null,K?Promise.resolve().then(function(){return A.focus(W)}):A.focus(W)}}},[me]),ae=xn(function(K){p.current&&Sk.useMedium(K)},[]),we=Ek.useMedium,Ie=xn(function(K){h.current!==K&&(h.current=K,d(K))},[]),Me=Dg((r={},r[kk]=_&&"disabled",r[sm]=G,r),ve),Ae=T!==!0,We=Ae&&T!=="tail",k=w0([i,Ie]),q=us(function(){return{observed:h,shards:M,enabled:!_,active:p.current}},[_,p.current,M,c]);return _e.createElement(Og,null,Ae&&[_e.createElement("div",{key:"guard-first","data-focus-guard":!0,tabIndex:_?-1:0,style:cg}),he?_e.createElement("div",{key:"guard-nearest","data-focus-guard":!0,tabIndex:_?-1:1,style:cg}):null],!_&&_e.createElement(ce,{id:X,sideCar:T0,observed:c,disabled:_,persistentFocus:E,crossFrame:R,autoFocus:H,whiteList:Z,shards:M,onActivation:se,onDeactivation:F,returnFocus:Te,focusOptions:re,noFocusGuards:T}),_e.createElement(C,Dg({ref:k},Me,{className:z,onBlur:we,onFocus:ae}),_e.createElement(S0.Provider,{value:q},w)),We&&_e.createElement("div",{"data-focus-guard":!0,tabIndex:_?-1:0,style:cg}))});Em.propTypes={};function I0(a,s){function i(r){return r.displayName||r.name||"Component"}return function(l){var c=[],d;function h(){d=a(c.map(function(f){return f.props})),s(d)}var p=(function(f){AS(b,f);function b(){return f.apply(this,arguments)||this}b.peek=function(){return d};var y=b.prototype;return y.componentDidMount=function(){c.push(this),h()},y.componentDidUpdate=function(){h()},y.componentWillUnmount=function(){var v=c.indexOf(this);c.splice(v,1),h()},y.render=function(){return _e.createElement(l,this.props)},b})(MT);return qS(p,"displayName","SideEffect("+i(l)+")"),p}}var oo=function(a){for(var s=Array(a.length),i=0;i=0}).sort(P0)},j0=["button:enabled","select:enabled","textarea:enabled","input:enabled","a[href]","area[href]","summary","iframe","object","embed","audio[controls]","video[controls]","[tabindex]","[contenteditable]","[autofocus]"],Dm=j0.join(","),F0="".concat(Dm,", [data-focus-guard]"),Lk=function(a,s){return oo((a.shadowRoot||a).children).reduce(function(i,r){return i.concat(r.matches(s?F0:Dm)?[r]:[],Lk(r))},[])},z0=function(a,s){var i;return a instanceof HTMLIFrameElement&&(!((i=a.contentDocument)===null||i===void 0)&&i.body)?Bn([a.contentDocument.body],s):[a]},Bn=function(a,s){return a.reduce(function(i,r){var l,c=Lk(r,s),d=(l=[]).concat.apply(l,c.map(function(h){return z0(h,s)}));return i.concat(d,r.parentNode?oo(r.parentNode.querySelectorAll(Dm)).filter(function(h){return h===r}):[])},[])},U0=function(a){var s=a.querySelectorAll("[".concat(b0,"]"));return oo(s).map(function(i){return Bn([i])}).reduce(function(i,r){return i.concat(r)},[])},Am=function(a,s){return oo(a).filter(function(i){return Ak(s,i)}).filter(function(i){return M0(i)})},L_=function(a,s){return s===void 0&&(s=new Map),oo(a).filter(function(i){return Ok(s,i)})},Om=function(a,s,i){return xm(Am(Bn(a,i),s),!0,i)},ta=function(a,s){return xm(Am(Bn(a),s),!1)},H0=function(a,s){return Am(U0(a),s)},xi=function(a,s){return a.shadowRoot?xi(a.shadowRoot,s):Object.getPrototypeOf(a).contains!==void 0&&Object.getPrototypeOf(a).contains.call(a,s)?!0:oo(a.children).some(function(i){var r;if(i instanceof HTMLIFrameElement){var l=(r=i.contentDocument)===null||r===void 0?void 0:r.body;return l?xi(l,s):!1}return xi(i,s)})},W0=function(a){for(var s=new Set,i=a.length,r=0;r0&&s.add(l),(c&Node.DOCUMENT_POSITION_CONTAINS)>0&&s.add(r)}return a.filter(function(d,h){return!s.has(h)})},Pk=function(a){return a.parentNode?Pk(a.parentNode):a},Rm=function(a){var s=Ri(a);return s.filter(Boolean).reduce(function(i,r){var l=r.getAttribute(sm);return i.push.apply(i,l?W0(oo(Pk(r).querySelectorAll("[".concat(sm,'="').concat(l,'"]:not([').concat(kk,'="disabled"])')))):[r]),i},[])},G0=function(a){try{return a()}catch{return}},sa=function(a){if(a===void 0&&(a=document),!(!a||!a.activeElement)){var s=a.activeElement;return s.shadowRoot?sa(s.shadowRoot):s instanceof HTMLIFrameElement&&G0(function(){return s.contentWindow.document})?sa(s.contentWindow.document):s}},V0=function(a,s){return a===s},Y0=function(a,s){return!!oo(a.querySelectorAll("iframe")).some(function(i){return V0(i,s)})},Bk=function(a,s){return s===void 0&&(s=sa(Ik(a).ownerDocument)),!s||s.dataset&&s.dataset.focusGuard?!1:Rm(a).some(function(i){return xi(i,s)||Y0(i,s)})},K0=function(a){a===void 0&&(a=document);var s=sa(a);return s?oo(a.querySelectorAll("[".concat($0,"]"))).some(function(i){return xi(i,s)}):!1},J0=function(a,s){return s.filter(Nk).filter(function(i){return i.name===a.name}).filter(function(i){return i.checked})[0]||a},Mm=function(a,s){return Nk(a)&&a.name?J0(a,s):a},X0=function(a){var s=new Set;return a.forEach(function(i){return s.add(Mm(i,a))}),a.filter(function(i){return s.has(i)})},P_=function(a){return a[0]&&a.length>1?Mm(a[0],a):a[0]},B_=function(a,s){return a.indexOf(Mm(s,a))},im="NEW_FOCUS",q0=function(a,s,i,r,l){var c=a.length,d=a[0],h=a[c-1],p=Im(r);if(!(r&&a.indexOf(r)>=0)){var f=r!==void 0?i.indexOf(r):-1,b=l?i.indexOf(l):f,y=l?a.indexOf(l):-1;if(f===-1)return y!==-1?y:im;if(y===-1)return im;var w=f-b,v=i.indexOf(d),_=i.indexOf(h),$=X0(i),T=r!==void 0?$.indexOf(r):-1,S=l?$.indexOf(l):T,E=$.filter(function(z){return z.tabIndex>=0}),D=r!==void 0?E.indexOf(r):-1,R=l?E.indexOf(l):D,L=D>=0&&R>=0?R-D:S-T;if(!w&&y>=0||s.length===0)return y;var H=B_(a,s[0]),G=B_(a,s[s.length-1]);if(f<=v&&p&&Math.abs(w)>1)return G;if(f>=_&&p&&Math.abs(w)>1)return H;if(w&&Math.abs(L)>1)return y;if(f<=v)return G;if(f>_)return H;if(w)return Math.abs(w)>1?y:(c+y+w)%c}},Z0=function(a){return function(s){var i,r=(i=Rk(s))===null||i===void 0?void 0:i.autofocus;return s.autofocus||r!==void 0&&r!=="false"||a.indexOf(s)>=0}},j_=function(a,s,i){var r=a.map(function(c){var d=c.node;return d}),l=L_(r.filter(Z0(i)));return l&&l.length?P_(l):P_(L_(s))},nm=function(a,s){return s===void 0&&(s=[]),s.push(a),a.parentNode&&nm(a.parentNode.host||a.parentNode,s),s},ug=function(a,s){for(var i=nm(a),r=nm(s),l=0;l=0)return c}return!1},jk=function(a,s,i){var r=Ri(a),l=Ri(s),c=r[0],d=!1;return l.filter(Boolean).forEach(function(h){d=ug(d||h,h)||d,i.filter(Boolean).forEach(function(p){var f=ug(c,p);f&&(!d||xi(f,d)?d=f:d=ug(f,d))})}),d},F_=function(a,s){return a.reduce(function(i,r){return i.concat(H0(r,s))},[])},Q0=function(a,s){var i=new Map;return s.forEach(function(r){return i.set(r.node,r)}),a.map(function(r){return i.get(r)}).filter(L0)},eD=function(a,s){var i=sa(Ri(a).length>0?document:Ik(a).ownerDocument),r=Rm(a).filter(om),l=jk(i||a,a,r),c=new Map,d=ta(r,c),h=d.filter(function(_){var $=_.node;return om($)});if(h[0]){var p=ta([l],c).map(function(_){var $=_.node;return $}),f=Q0(p,h),b=f.map(function(_){var $=_.node;return $}),y=f.filter(function(_){var $=_.tabIndex;return $>=0}).map(function(_){var $=_.node;return $}),w=q0(b,y,p,i,s);if(w===im){var v=j_(d,y,F_(r,c))||j_(d,b,F_(r,c));if(v)return{node:v};console.warn("focus-lock: cannot find any node to move focus into");return}return w===void 0?w:f[w]}},tD=function(a){var s=Rm(a).filter(om),i=jk(a,a,s),r=xm(Bn([i],!0),!0,!0),l=Bn(s,!1);return r.map(function(c){var d=c.node,h=c.index;return{node:d,index:h,lockItem:l.indexOf(d)>=0,guard:Im(d)}})},Nm=function(a,s){a&&("focus"in a&&a.focus(s),"contentWindow"in a&&a.contentWindow&&a.contentWindow.focus())},dg=0,hg=!1,Fk=function(a,s,i){i===void 0&&(i={});var r=eD(a,s);if(!hg&&r){if(dg>2){console.error("FocusLock: focus-fighting detected. Only one focus management system could be active. See https://github.com/theKashey/focus-lock/#focus-fighting"),hg=!0,setTimeout(function(){hg=!1},1);return}dg++,Nm(r.node,i.focusOptions),dg--}};function Hr(a){if(!a)return null;if(typeof WeakRef>"u")return function(){return a||null};var s=a?new WeakRef(a):null;return function(){return(s==null?void 0:s.deref())||null}}var sD=function(a){if(!a)return null;for(var s=[],i=a;i&&i!==document.body;)s.push({current:Hr(i),parent:Hr(i.parentElement),left:Hr(i.previousElementSibling),right:Hr(i.nextElementSibling)}),i=i.parentElement;return{element:Hr(a),stack:s,ownerDocument:a.ownerDocument}},oD=function(a){var s,i,r,l,c;if(a)for(var d=a.stack,h=a.ownerDocument,p=new Map,f=0,b=d;f-1&&(T.filter(function(E){var D=E.guard,R=E.node;return D&&R.dataset.focusAutoGuard}).forEach(function(E){var D=E.node;return D.removeAttribute("tabIndex")}),U_(S,T.length,1,T),U_(S,-1,-1,T))}}}return s},Vk=function(s){Ec()&&s&&(s.stopPropagation(),s.preventDefault())},Bm=function(){return Lm(Ec)},_D=function(s){var i=s.target,r=s.currentTarget;r.contains(i)||mD(r,i)},wD=function(){return null},Yk=function(){Pm=!0},Kk=function(){Pm=!1,oa="just",Lm(function(){oa="meanwhile"})},kD=function(){document.addEventListener("focusin",Vk),document.addEventListener("focusout",Bm),window.addEventListener("focus",Yk),window.addEventListener("blur",Kk)},CD=function(){document.removeEventListener("focusin",Vk),document.removeEventListener("focusout",Bm),window.removeEventListener("focus",Yk),window.removeEventListener("blur",Kk)};function TD(a){return a.filter(function(s){var i=s.disabled;return!i})}var Jk={moveFocusInside:Fk,focusInside:Bk,focusNextElement:aD,focusPrevElement:lD,focusFirstElement:cD,focusLastElement:uD,captureFocusRestore:zk};function SD(a){var s=a.slice(-1)[0];s&&!Rn&&kD();var i=Rn,r=i&&s&&s.id===i.id;Rn=s,i&&!r&&(i.onDeactivation(),a.filter(function(l){var c=l.id;return c===i.id}).length||i.returnFocus(!s)),s?(ss=null,(!r||i.observed!==s.observed)&&s.onActivation(Jk),Ec(),Lm(Ec)):(CD(),ss=null)}Sk.assignSyncMedium(_D);Ek.assignMedium(Bm);C0.assignMedium(function(a){return a(Jk)});const ED=I0(TD,SD)(wD);var Xk=xw(function(s,i){return _e.createElement(Em,Dg({sideCar:ED,ref:i},s))}),qk=Em.propTypes||{};qk.sideCar;OS(qk,["sideCar"]);Xk.propTypes={};var Zk={exports:{}},ct={};var jm=Symbol.for("react.element"),Fm=Symbol.for("react.portal"),iu=Symbol.for("react.fragment"),nu=Symbol.for("react.strict_mode"),ru=Symbol.for("react.profiler"),au=Symbol.for("react.provider"),lu=Symbol.for("react.context"),ID=Symbol.for("react.server_context"),cu=Symbol.for("react.forward_ref"),uu=Symbol.for("react.suspense"),du=Symbol.for("react.suspense_list"),hu=Symbol.for("react.memo"),pu=Symbol.for("react.lazy"),xD=Symbol.for("react.offscreen"),Qk;Qk=Symbol.for("react.module.reference");function Cs(a){if(typeof a=="object"&&a!==null){var s=a.$$typeof;switch(s){case jm:switch(a=a.type,a){case iu:case ru:case nu:case uu:case du:return a;default:switch(a=a&&a.$$typeof,a){case ID:case lu:case cu:case pu:case hu:case au:return a;default:return s}}case Fm:return s}}}ct.ContextConsumer=lu;ct.ContextProvider=au;ct.Element=jm;ct.ForwardRef=cu;ct.Fragment=iu;ct.Lazy=pu;ct.Memo=hu;ct.Portal=Fm;ct.Profiler=ru;ct.StrictMode=nu;ct.Suspense=uu;ct.SuspenseList=du;ct.isAsyncMode=function(){return!1};ct.isConcurrentMode=function(){return!1};ct.isContextConsumer=function(a){return Cs(a)===lu};ct.isContextProvider=function(a){return Cs(a)===au};ct.isElement=function(a){return typeof a=="object"&&a!==null&&a.$$typeof===jm};ct.isForwardRef=function(a){return Cs(a)===cu};ct.isFragment=function(a){return Cs(a)===iu};ct.isLazy=function(a){return Cs(a)===pu};ct.isMemo=function(a){return Cs(a)===hu};ct.isPortal=function(a){return Cs(a)===Fm};ct.isProfiler=function(a){return Cs(a)===ru};ct.isStrictMode=function(a){return Cs(a)===nu};ct.isSuspense=function(a){return Cs(a)===uu};ct.isSuspenseList=function(a){return Cs(a)===du};ct.isValidElementType=function(a){return typeof a=="string"||typeof a=="function"||a===iu||a===ru||a===nu||a===uu||a===du||a===xD||typeof a=="object"&&a!==null&&(a.$$typeof===pu||a.$$typeof===hu||a.$$typeof===au||a.$$typeof===lu||a.$$typeof===cu||a.$$typeof===Qk||a.getModuleId!==void 0)};ct.typeOf=Cs;Zk.exports=ct;var eC=Zk.exports;function DD(a){function s(N,te,X,se,F){for(var Te=0,ae=0,we=0,Ie=0,Me,Ae,We=0,k=0,q,K=q=Me=0,O=0,A=0,U=0,W=0,ue=X.length,V=ue-1,be,pe="",fe="",Le="",He="",Be;OMe)&&(W=(pe=pe.replace(" ",":")).length),0se&&(se=(te=te.trim()).charCodeAt(0)),se){case 38:return te.replace(S,"$1"+N.trim());case 58:return N.trim()+te.replace(S,"$1"+N.trim());default:if(0<1*X&&0ae.charCodeAt(8))break;case 115:F=F.replace(ae,"-webkit-"+ae)+";"+F;break;case 207:case 102:F=F.replace(ae,"-webkit-"+(102X.charCodeAt(0)&&(X=X.trim()),B=X,X=[B],01?s-1:0),r=1;r0?" Args: "+i.join(", "):""))}var MD=(function(){function a(i){this.groupSizes=new Uint32Array(512),this.length=512,this.tag=i}var s=a.prototype;return s.indexOfGroup=function(i){for(var r=0,l=0;l=this.groupSizes.length){for(var l=this.groupSizes,c=l.length,d=c;i>=d;)(d<<=1)<0&&ma(16,""+i);this.groupSizes=new Uint32Array(d),this.groupSizes.set(l),this.length=d;for(var h=c;h=this.length||this.groupSizes[i]===0)return r;for(var l=this.groupSizes[i],c=this.indexOfGroup(i),d=c+l,h=c;h=Jr&&(Jr=s+1),_c.set(a,s),xc.set(s,a)},PD="style["+jn+'][data-styled-version="5.3.11"]',BD=new RegExp("^"+jn+'\\.g(\\d+)\\[id="([\\w\\d-]+)"\\].*?"([^"]*)'),jD=function(a,s,i){for(var r,l=i.split(","),c=0,d=l.length;c=0;f--){var b=p[f];if(b&&b.nodeType===1&&b.hasAttribute(jn))return b}})(i),c=l!==void 0?l.nextSibling:null;r.setAttribute(jn,"active"),r.setAttribute("data-styled-version","5.3.11");var d=zD();return d&&r.setAttribute("nonce",d),i.insertBefore(r,c),r},UD=(function(){function a(i){var r=this.element=tC(i);r.appendChild(document.createTextNode("")),this.sheet=(function(l){if(l.sheet)return l.sheet;for(var c=document.styleSheets,d=0,h=c.length;d=0){var l=document.createTextNode(r),c=this.nodes[i];return this.element.insertBefore(l,c||null),this.length++,!0}return!1},s.deleteRule=function(i){this.element.removeChild(this.nodes[i]),this.length--},s.getRule=function(i){return i0&&(y+=w+",")})),c+=""+f+b+'{content:"'+y+`"}/*!sc*/ +`}}}return c})(this)},a})(),VD=/(a)(d)/gi,V_=function(a){return String.fromCharCode(a+(a>25?39:97))};function am(a){var s,i="";for(s=Math.abs(a);s>52;s=s/52|0)i=V_(s%52)+i;return(V_(s%52)+i).replace(VD,"$1-$2")}var An=function(a,s){for(var i=s.length;i;)a=33*a^s.charCodeAt(--i);return a},sC=function(a){return An(5381,a)};function oC(a){for(var s=0;s>>0);if(!i.hasNameForId(l,h)){var p=r(d,"."+h,void 0,l);i.insertRules(l,h,p)}c.push(h),this.staticRulesId=h}else{for(var f=this.rules.length,b=An(this.baseHash,r.hash),y="",w=0;w>>0);if(!i.hasNameForId(l,T)){var S=r(y,"."+T,void 0,l);i.insertRules(l,T,S)}c.push(T)}}return c.join(" ")},a})(),JD=/^\s*\/\/.*$/gm,XD=[":","[",".","#"];function qD(a){var s,i,r,l,c=Ko,d=c.options,h=d===void 0?Ko:d,p=c.plugins,f=p===void 0?Ic:p,b=new DD(h),y=[],w=(function($){function T(S){if(S)try{$(S+"}")}catch{}}return function(S,E,D,R,L,H,G,z,Z,he){switch(S){case 1:if(Z===0&&E.charCodeAt(0)===64)return $(E+";"),"";break;case 2:if(z===0)return E+"/*|*/";break;case 3:switch(z){case 102:case 112:return $(D[0]+E),"";default:return E+(he===0?"/*|*/":"")}case-2:E.split("/*|*/}").forEach(T)}}})((function($){y.push($)})),v=function($,T,S){return T===0&&XD.indexOf(S[i.length])!==-1||S.match(l)?$:"."+s};function _($,T,S,E){E===void 0&&(E="&");var D=$.replace(JD,""),R=T&&S?S+" "+T+" { "+D+" }":D;return s=E,i=T,r=new RegExp("\\"+i+"\\b","g"),l=new RegExp("(\\"+i+"\\b){2,}"),b(S||!T?"":T,R)}return b.use([].concat(f,[function($,T,S){$===2&&S.length&&S[0].lastIndexOf(i)>0&&(S[0]=S[0].replace(r,v))},w,function($){if($===-2){var T=y;return y=[],T}}])),_.hash=f.length?f.reduce((function($,T){return T.name||ma(15),An($,T.name)}),5381).toString():"",_}var iC=_e.createContext();iC.Consumer;var nC=_e.createContext(),ZD=(nC.Consumer,new Dc),lm=qD();function rC(){return na(iC)||ZD}function aC(){return na(nC)||lm}var QD=(function(){function a(s,i){var r=this;this.inject=function(l,c){c===void 0&&(c=lm);var d=r.name+c.hash;l.hasNameForId(r.id,d)||l.insertRules(r.id,d,c(r.rules,d,"@keyframes"))},this.toString=function(){return ma(12,String(r.name))},this.name=s,this.id="sc-keyframes-"+s,this.rules=i}return a.prototype.getName=function(s){return s===void 0&&(s=lm),this.name+s.hash},a})(),eA=/([A-Z])/,tA=/([A-Z])/g,sA=/^ms-/,oA=function(a){return"-"+a.toLowerCase()};function Y_(a){return eA.test(a)?a.replace(tA,oA).replace(sA,"-ms-"):a}var K_=function(a){return a==null||a===!1||a===""};function Mi(a,s,i,r){if(Array.isArray(a)){for(var l,c=[],d=0,h=a.length;d1?s-1:0),r=1;r?@[\\\]^`{|}~-]+/g,nA=/(^-|-$)/g;function pg(a){return a.replace(iA,"-").replace(nA,"")}var uC=function(a){return am(sC(a)>>>0)};function lc(a){return typeof a=="string"&&!0}var cm=function(a){return typeof a=="function"||typeof a=="object"&&a!==null&&!Array.isArray(a)},rA=function(a){return a!=="__proto__"&&a!=="constructor"&&a!=="prototype"};function aA(a,s,i){var r=a[i];cm(s)&&cm(r)?dC(r,s):a[i]=s}function dC(a){for(var s=arguments.length,i=new Array(s>1?s-1:0),r=1;r=0||(he[z]=H[z]);return he})(s,["componentId"]),L=D&&D+"-"+(lc(E)?E:pg(W_(E)));return hC(E,to({},R,{attrs:w,componentId:L}),i)},Object.defineProperty(_,"defaultProps",{get:function(){return this._foldedDefaultProps},set:function(E){this._foldedDefaultProps=r?dC({},a.defaultProps,E):E}}),Object.defineProperty(_,"toString",{value:function(){return"."+_.styledComponentId}}),l&&RS(_,a,{attrs:!0,componentStyle:!0,displayName:!0,foldedComponentIds:!0,shouldForwardProp:!0,styledComponentId:!0,target:!0,withComponent:!0}),_}var ks=function(a){return(function s(i,r,l){if(l===void 0&&(l=Ko),!eC.isValidElementType(r))return ma(1,String(r));var c=function(){return i(r,l,lC.apply(void 0,arguments))};return c.withConfig=function(d){return s(i,r,to({},l,{},d))},c.attrs=function(d){return s(i,r,to({},l,{attrs:Array.prototype.concat(l.attrs,d).filter(Boolean)}))},c})(hC,a)};["a","abbr","address","area","article","aside","audio","b","base","bdi","bdo","big","blockquote","body","br","button","canvas","caption","cite","code","col","colgroup","data","datalist","dd","del","details","dfn","dialog","div","dl","dt","em","embed","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","iframe","img","input","ins","kbd","keygen","label","legend","li","link","main","map","mark","marquee","menu","menuitem","meta","meter","nav","noscript","object","ol","optgroup","option","output","p","param","picture","pre","progress","q","rp","rt","ruby","s","samp","script","section","select","small","source","span","strong","style","sub","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","title","tr","track","u","ul","var","video","wbr","circle","clipPath","defs","ellipse","foreignObject","g","image","line","linearGradient","marker","mask","path","pattern","polygon","polyline","radialGradient","rect","stop","svg","text","textPath","tspan"].forEach((function(a){ks[a]=ks(a)}));var lA=(function(){function a(i,r){this.rules=i,this.componentId=r,this.isStatic=oC(i),Dc.registerId(this.componentId+1)}var s=a.prototype;return s.createStyles=function(i,r,l,c){var d=c(Mi(this.rules,r,l,c).join(""),""),h=this.componentId+i;l.insertRules(h,h,d)},s.removeStyles=function(i,r){r.clearRules(this.componentId+i)},s.renderStyles=function(i,r,l,c){i>2&&Dc.registerId(this.componentId+i),this.removeStyles(i,l),this.createStyles(i,r,l,c)},a})();function cA(a){for(var s=arguments.length,i=new Array(s>1?s-1:0),r=1;ra.length)&&(s=a.length);for(var i=0,r=Array(s);i=a.length?{done:!0}:{done:!1,value:a[r++]}},e:function(p){throw p},f:l}}throw new TypeError(`Invalid attempt to iterate non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var c,d=!0,h=!1;return{s:function(){i=i.call(a)},n:function(){var p=i.next();return d=p.done,p},e:function(p){h=!0,c=p},f:function(){try{d||i.return==null||i.return()}finally{if(h)throw c}}}}function vs(a,s,i){return(s=gC(s))in a?Object.defineProperty(a,s,{value:i,enumerable:!0,configurable:!0,writable:!0}):a[s]=i,a}function Ac(a){return Ac=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(s){return s.__proto__||Object.getPrototypeOf(s)},Ac(a)}function fA(a,s){if(typeof s!="function"&&s!==null)throw new TypeError("Super expression must either be null or a function");a.prototype=Object.create(s&&s.prototype,{constructor:{value:a,writable:!0,configurable:!0}}),Object.defineProperty(a,"prototype",{writable:!1}),s&&um(a,s)}function pC(){try{var a=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(pC=function(){return!!a})()}function $A(a,s){var i=a==null?null:typeof Symbol<"u"&&a[Symbol.iterator]||a["@@iterator"];if(i!=null){var r,l,c,d,h=[],p=!0,f=!1;try{if(c=(i=i.call(a)).next,s!==0)for(;!(p=(r=c.call(i)).done)&&(h.push(r.value),h.length!==s);p=!0);}catch(b){f=!0,l=b}finally{try{if(!p&&i.return!=null&&(d=i.return(),Object(d)!==d))return}finally{if(f)throw l}}return h}}function bA(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function q_(a,s){var i=Object.keys(a);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(a);s&&(r=r.filter(function(l){return Object.getOwnPropertyDescriptor(a,l).enumerable})),i.push.apply(i,r)}return i}function Oc(a){for(var s=1;si.right&&(i.right=h.right),h.bottom>i.bottom&&(i.bottom=h.bottom),h.left=0+p&&l>=0+p&&r<=d-p&&i<=c-p}function TA(a){return a===document.querySelector("body")||a===document.querySelector("html")}var SA=function(s){return/(left|right)/.test(s)},gg=function(s,i){return s>i},mg=function(s,i){return s>i},Qs=function(s){return s<0?0:s};function EA(a){return Object.keys(a).map(function(s){return{position:s,value:a[s]}}).sort(function(s,i){return i.value-s.value}).map(function(s){return s.position})}var ow,IA=ks.div(ow||(ow=Ls([` +`])));function wc(a){var s=a.getBoundingClientRect(),i=s.top,r=s.right,l=s.bottom,c=s.left,d=s.width,h=s.height;return{top:i,right:r,bottom:l,left:c,width:d,height:h}}function vC(a,s){if(!s.highlightedSelectors)return wc(a);var i=wc(a),r=Nn(s.highlightedSelectors),l;try{for(r.s();!(l=r.n()).done;){var c=l.value,d=document.querySelector(c);if(!(!d||d.style.display==="none"||d.style.visibility==="hidden")){var h=wc(d);h.topi.right&&(i.right=h.right),h.bottom>i.bottom&&(i.bottom=h.bottom),h.left=0+p&&l>=0+p&&r<=d-p&&i<=c-p}function SA(a){return a===document.querySelector("body")||a===document.querySelector("html")}var EA=function(s){return/(left|right)/.test(s)},mg=function(s,i){return s>i},fg=function(s,i){return s>i},Qs=function(s){return s<0?0:s};function IA(a){return Object.keys(a).map(function(s){return{position:s,value:a[s]}}).sort(function(s,i){return i.value-s.value}).map(function(s){return s.position})}var iw,xA=ks.div(iw||(iw=Ls([` --reactour-accent: `,`; `,` position: fixed; @@ -151,7 +151,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho padding: 24px 30px; box-shadow: 0 0.5em 3em rgba(0, 0, 0, 0.3); color: inherit; - `):""},function(a){var s=a.targetTop,i=a.targetRight,r=a.targetBottom,l=a.targetLeft,c=a.windowWidth,d=a.windowHeight,h=a.helperWidth,p=a.helperHeight,f=a.helperPosition,b=a.padding,y={left:l,right:c-i,top:s,bottom:d-r},w=function(T){return y[T]>(SA(T)?h+b*2:p+b*2)},v=function(T){for(var E=EA(y),D=0;Db?P:b,G=mg(s+p,d)?mg(r+b,d)?r-p:r-p+b:s-b,z=G>b?G:b,Z={top:[W,s-p-b*2],right:[i+b*2,z],bottom:[W,r+b*2],left:[l-h-b*2,z],center:[c/2-h/2,d/2-p/2]};return T==="center"||w(T)?Z[T]:v(Z)},$=_(f);return"translate(".concat(Math.round($[0]),"px, ").concat(Math.round($[1]),"px)")}),iw,xA=ks.span(iw||(iw=Ls([` + `):""},function(a){var s=a.targetTop,i=a.targetRight,r=a.targetBottom,l=a.targetLeft,c=a.windowWidth,d=a.windowHeight,h=a.helperWidth,p=a.helperHeight,f=a.helperPosition,b=a.padding,y={left:l,right:c-i,top:s,bottom:d-r},w=function(S){return y[S]>(EA(S)?h+b*2:p+b*2)},v=function(S){for(var E=IA(y),D=0;Db?L:b,G=fg(s+p,d)?fg(r+b,d)?r-p:r-p+b:s-b,z=G>b?G:b,Z={top:[H,s-p-b*2],right:[i+b*2,z],bottom:[H,r+b*2],left:[l-h-b*2,z],center:[c/2-h/2,d/2-p/2]};return S==="center"||w(S)?Z[S]:v(Z)},$=_(f);return"translate(".concat(Math.round($[0]),"px, ").concat(Math.round($[1]),"px)")}),nw,DA=ks.span(nw||(nw=Ls([` position: absolute; font-family: monospace; background: var(--reactour-accent); @@ -167,18 +167,18 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho box-shadow: 0 0.25em 0.5em rgba(0, 0, 0, 0.3); top: -0.8125em; left: -0.8125em; -`])),function(a){return a.accentColor}),nw,DA=ks.div(nw||(nw=Ls([` +`])),function(a){return a.accentColor}),rw,AA=ks.div(rw||(rw=Ls([` display: flex; margin-top: 24px; align-items: center; justify-content: center; -`]))),rw,AA=ks.nav(rw||(rw=Ls([` +`]))),aw,OA=ks.nav(aw||(aw=Ls([` counter-reset: dot; display: flex; justify-content: center; align-items: center; flex-wrap: wrap; -`]))),aw,RA=ks.button(aw||(aw=Ls([` +`]))),lw,RA=ks.button(lw||(lw=Ls([` counter-increment: dot; width: 8px; height: 8px; @@ -217,7 +217,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho transform: translate(-50%, -2px); } } -`])),function(a){return a.current===a.index?"0":"1px solid #caccce"},function(a){return a.disabled?"not-allowed":"pointer"},function(a){return a.current===a.index?1.25:1},function(a){return a.current===a.index?"var(--reactour-accent)":"#caccce"},function(a){return a.current===a.index?"var(--reactour-accent)":"none"},function(a){return a.current===a.index?a.accentColor:"#caccce"},function(a){return a.current===a.index?a.accentColor:"none"},function(a){return a.showNumber?"block":"none"}),lw,OA=ks.div(lw||(lw=Ls([` +`])),function(a){return a.current===a.index?"0":"1px solid #caccce"},function(a){return a.disabled?"not-allowed":"pointer"},function(a){return a.current===a.index?1.25:1},function(a){return a.current===a.index?"var(--reactour-accent)":"#caccce"},function(a){return a.current===a.index?"var(--reactour-accent)":"none"},function(a){return a.current===a.index?a.accentColor:"#caccce"},function(a){return a.current===a.index?a.accentColor:"none"},function(a){return a.showNumber?"block":"none"}),cw,MA=ks.div(cw||(cw=Ls([` opacity: `,`; color: `,`; width: 100%; @@ -227,7 +227,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho position: fixed; z-index: 99999; pointer-events: none; -`])),function(a){return!a.maskClassName&&.7},function(a){return!a.maskClassName&&"#000"});function vC(a){var s=a.windowWidth,i=a.windowHeight,r=a.targetWidth,l=a.targetHeight,c=a.targetTop,d=a.targetLeft,h=a.padding,p=a.rounded,f=a.roundedStep,b=a.disableInteraction,y=a.disableInteractionClassName,w=a.className,v=a.onClick,_=a.highlightedBorder,$=Qs(r+h*2),S=Qs(l+h*2),T=Qs(c-h),E=Qs(d-h),D=f?Math.min($/2,S/2):p;return _e.createElement(OA,{onClick:v,maskClassName:w},_e.createElement("svg",{width:s,height:i,xmlns:"http://www.w3.org/2000/svg",className:w},_e.createElement("defs",null,_e.createElement("mask",{id:"mask-main"},_e.createElement("rect",{x:0,y:0,width:s,height:i,fill:"white"}),_e.createElement("rect",{x:E,y:T,width:$,height:S,fill:"black"}),_e.createElement("rect",{x:E-1,y:T-1,width:D,height:D,fill:"white"}),_e.createElement("circle",{cx:E+D,cy:T+D,r:D,fill:"black"}),_e.createElement("rect",{x:E+$-D+1,y:T-1,width:D,height:D,fill:"white"}),_e.createElement("circle",{cx:E+$-D,cy:T+D,r:D,fill:"black"}),_e.createElement("rect",{x:E-1,y:T+S-D+1,width:D,height:D,fill:"white"}),_e.createElement("circle",{cx:E+D,cy:T+S-D,r:D,fill:"black"}),_e.createElement("rect",{x:E+$-D+1,y:T+S-D+1,width:D,height:D,fill:"white"}),_e.createElement("circle",{cx:E+$-D,cy:T+S-D,r:D,fill:"black "})),_e.createElement("clipPath",{id:"clip-path"},_e.createElement("rect",{x:0,y:0,width:s,height:T}),_e.createElement("rect",{x:0,y:T,width:E,height:S}),_e.createElement("rect",{x:d+r+h,y:T,width:Qs(s-r-E),height:S}),_e.createElement("rect",{x:0,y:c+l+h,width:s,height:Qs(i-l-T)}))),_e.createElement("rect",{x:0,y:0,width:s,height:i,fill:"currentColor",mask:"url(#mask-main)"}),_e.createElement("rect",{x:0,y:0,width:s,height:i,fill:"currentColor",clipPath:"url(#clip-path)",pointerEvents:"auto"}),_e.createElement("rect",{x:E,y:T,width:$,height:S,pointerEvents:"auto",fill:"transparent",display:b?"block":"none",className:y}),_&&_e.createElement("rect",{x:Qs(E+_.width/2),y:Qs(T+_.width/2),width:Qs($-_.width),height:Qs(S-_.width),pointerEvents:"auto",fill:"none",strokeWidth:_.width,stroke:_.color,rx:D-2})))}vC.propTypes={windowWidth:ke.number.isRequired,windowHeight:ke.number.isRequired,targetWidth:ke.number.isRequired,targetHeight:ke.number.isRequired,targetTop:ke.number.isRequired,targetLeft:ke.number.isRequired,padding:ke.number.isRequired,rounded:ke.number.isRequired,roundedStep:ke.bool,disableInteraction:ke.bool.isRequired,disableInteractionClassName:ke.string.isRequired,highlightedBorder:ke.shape({color:ke.string.isRequired,width:ke.number.isRequired})};var NA=(function(a){var s=a.step,i=a.refresh,r=kt(0),l=vA(r,2),c=l[0],d=l[1];return Lt(function(){if(s.resizeObservables){var h=function(w){var v=Mn(w),_;try{var $=function(){var T=_.value;if(!T.attributes)return 1;var E=s.resizeObservables.find(function(D){return T.matches(D)||T.querySelector(D)!=null});E&&d(c+1)};for(v.s();!(_=v.n()).done;)$()}catch(S){v.e(S)}finally{v.f()}},p=new MutationObserver(function(y){var w=Mn(y),v;try{for(w.s();!(v=w.n()).done;){var _=v.value;_.addedNodes.length!==0&&h(_.addedNodes),_.removedNodes.length!==0&&h(_.removedNodes)}}catch($){w.e($)}finally{w.f()}}),f=document.documentElement||document.body,b={childList:!0,subtree:!0};return p.observe(f,b),function(){p.disconnect()}}},[s,c]),Lt(function(){if(s.resizeObservables){var h=new ResizeObserver(function(w){i()}),p=Mn(s.resizeObservables),f;try{for(p.s();!(f=p.n()).done;){var b=f.value,y=document.querySelector(b);y&&h.observe(y)}}catch(w){p.e(w)}finally{p.f()}return function(){h.disconnect()}}},[s,c]),null}),MA=(function(a){var s=a.step,i=a.refresh;return Lt(function(){if(s.mutationObservables){var r=function(p){var f=Mn(p),b;try{var y=function(){var v=b.value;if(!v.attributes)return 1;var _=s.mutationObservables.find(function($){return v.matches($)||v.querySelector($)!=null});_&&i()};for(f.s();!(b=f.n()).done;)y()}catch(w){f.e(w)}finally{f.f()}},l=new MutationObserver(function(h){var p=Mn(h),f;try{for(p.s();!(f=p.n()).done;){var b=f.value;b.addedNodes.length!==0&&r(b.addedNodes),b.removedNodes.length!==0&&r(b.removedNodes)}}catch(y){p.e(y)}finally{p.f()}}),c=document.documentElement||document.body,d={childList:!0,subtree:!0};return l.observe(c,d),function(){l.disconnect()}}},[s]),null});function LA(a){var s=a.children,i=Ko(null);return i.current===null&&(i.current=document.createElement("div"),i.current.setAttribute("id","___reactour")),Lt(function(){return document.body.appendChild(i.current),function(){document.body.removeChild(i.current)}},[i]),OS(s,i.current)}var PA={disableFocusLock:ke.bool,badgeContent:ke.func,highlightedMaskClassName:ke.string,children:ke.oneOfType([ke.node,ke.element]),className:ke.string,closeButtonAriaLabel:ke.string,closeWithMask:ke.bool,inViewThreshold:ke.number,isOpen:ke.bool.isRequired,lastStepNextButton:ke.node,maskClassName:ke.string,maskSpace:ke.number,nextButton:ke.node,onAfterOpen:ke.func,onBeforeClose:ke.func,onRequestClose:ke.func,prevButton:ke.node,scrollDuration:ke.number,scrollOffset:ke.number,showButtons:ke.bool,showCloseButton:ke.bool,showNavigation:ke.bool,showNavigationNumber:ke.bool,showNumber:ke.bool,startAt:ke.number,goToStep:ke.number,getCurrentStep:ke.func,nextStep:ke.func,prevStep:ke.func,steps:ke.arrayOf(ke.shape({selector:ke.string,content:ke.oneOfType([ke.node,ke.element,ke.func]).isRequired,position:ke.oneOfType([ke.arrayOf(ke.number),ke.oneOf(["top","right","bottom","left","center"])]),action:ke.func,style:ke.object,stepInteraction:ke.bool,navDotAriaLabel:ke.string,roundedStep:ke.bool})),update:ke.string,updateDelay:ke.number,disableInteraction:ke.bool,disableDotsNavigation:ke.bool,disableKeyboardNavigation:ke.oneOfType([ke.arrayOf(ke.oneOf(["esc","right","left"])),ke.bool]),rounded:ke.number,accentColor:ke.string,highlightedBorder:ke.shape({color:ke.string.isRequired,width:ke.number.isRequired})},BA={disableFocusLock:!1,showNavigation:!0,showNavigationNumber:!0,showButtons:!0,showCloseButton:!0,closeButtonAriaLabel:"Close",showNumber:!0,scrollDuration:1,maskSpace:10,updateDelay:1,disableInteraction:!1,rounded:0,accentColor:"#007aff",closeWithMask:!0},Sn={mask:{disableInteraction:"reactour__mask--disable-interaction"},helper:{base:"reactour__helper",isOpen:"reactour__helper--is-open"},dot:{base:"reactour__dot",active:"reactour__dot--is-active"}},Um=(function(a){function s(){var i;return hA(this,s),i=dA(this,s),vs(i,"unlockFocus",function(r){i.setState({focusUnlocked:!0},r())}),vs(i,"showStep",function(){if(!(!i.helper||!i.helper.current)){var r=i.props.steps,l=i.state,c=l.current,d=l.focusUnlocked;d&&i.setState({focusUnlocked:!1});var h=r[c],p=h.selector?document.querySelector(h.selector):null,f=function(_){h.action&&typeof h.action=="function"&&i.unlockFocus(function(){return h.action(_)})};if(h.observe){var b=document.querySelector(h.observe),y={attributes:!0,childList:!0,characterData:!0};i.setState(function(v){return v.observer&&setTimeout(function(){v.observer.disconnect()},0),{observer:new MutationObserver(function(_){_.forEach(function($){if($.type==="childList"&&$.addedNodes.length>0){var S=function(){return f($.addedNodes[0])};setTimeout(function(){return i.calculateNode($.addedNodes[0],h,S)},100)}else if($.type==="childList"&&$.removedNodes.length>0){var T=function(){return f(p)};i.calculateNode(p,h,T)}})})}},function(){return i.state.observer.observe(b,y)})}else i.state.observer&&(i.state.observer.disconnect(),i.setState({observer:null}));if(p){var w=function(){return f(p)};i.calculateNode(p,h,w)}else i.setState(fg(null,h,i.helper.current),f),h.selector&&console.warn("Doesn't find a DOM node '".concat(h.selector,"'. Please check the 'steps' Tour prop Array at position ").concat(c,"."))}}),vs(i,"calculateNode",function(r,l,c){var d=i.props,h=d.scrollDuration,p=d.inViewThreshold,f=d.scrollOffset,b=bC(r,l),y=Math.max(document.documentElement.clientWidth,window.innerWidth||0),w=Math.max(document.documentElement.clientHeight,window.innerHeight||0);if(CA(Ac(Ac({},b),{},{w:y,h:w,threshold:p})))i.setState(fg(r,l,i.helper.current),c);else{var v=qx(r),_=f||(b.height>w?-25:-(w/2)+b.height/2);Kx.to(r,{context:TA(v)?window:v,duration:h,offset:_,callback:function(S){i.setState(fg(S,l,i.helper.current),c)}})}}),vs(i,"recalculateNode",function(r){var l=document.querySelector(r.selector),c=function(h){r.action&&typeof r.action=="function"&&i.unlockFocus(function(){return r.action(h)})};i.calculateNode(l,r,function(){return c(l)})}),vs(i,"maskClickHandler",function(r){var l=i.props,c=l.closeWithMask,d=l.onRequestClose;c&&!r.target.classList.contains(Sn.mask.disableInteraction)&&d(r)}),vs(i,"nextStep",function(){var r=i.props,l=r.steps,c=r.getCurrentStep;i.setState(function(d){var h=d.current0?l.current-1:l.current;return typeof r=="function"&&r(c),{current:c}},i.showStep)}),vs(i,"gotoStep",function(r){var l=i.props,c=l.steps,d=l.getCurrentStep;i.setState(function(h){var p=c[r]?r:h.current;return typeof d=="function"&&d(p),{current:p}},i.showStep)}),vs(i,"keyDownHandler",function(r){var l=i.props,c=l.onRequestClose,d=l.nextStep,h=l.prevStep,p=l.disableKeyboardNavigation;if(r.stopPropagation(),p!==!0){var f,b,y;p&&(f=p.includes("esc"),b=p.includes("right"),y=p.includes("left")),r.keyCode===27&&!f&&(r.preventDefault(),c()),r.keyCode===39&&!b&&(r.preventDefault(),typeof d=="function"?d():i.nextStep()),r.keyCode===37&&!y&&(r.preventDefault(),typeof h=="function"?h():i.prevStep())}}),i.state={isOpen:!1,current:0,top:0,right:0,bottom:0,left:0,width:0,height:0,w:0,h:0,inDOM:!1,observer:null,focusUnlocked:!1},i.helper=MT(),i.helperElement=null,i.debouncedShowStep=m0(i.showStep,70),i}return mA(s,a),gA(s,[{key:"componentDidMount",value:function(){var r=this.props,l=r.isOpen,c=r.startAt;l&&this.open(c)}},{key:"UNSAFE_componentWillReceiveProps",value:function(r){var l=this.props,c=l.isOpen,d=l.update,h=l.updateDelay;!c&&r.isOpen?this.open(r.startAt):c&&!r.isOpen&&this.close(),c&&d!==r.update&&(r.steps[this.state.current]?setTimeout(this.showStep,h):this.props.onRequestClose()),c&&r.isOpen&&this.state.current!==r.goToStep&&this.gotoStep(r.goToStep)}},{key:"componentWillUnmount",value:function(){var r=this.props.isOpen;r&&this.close(),this.state.observer&&this.state.observer.disconnect()}},{key:"open",value:function(r){var l=this,c=this.props.onAfterOpen;this.setState(function(d){return{isOpen:!0,current:r!==void 0?r:d.current}},function(){setTimeout(l.showStep,1),l.helperElement=l.helper.current,l.props.disableFocusLock||l.helper.current.focus(),c&&c(l.helperElement)}),window.addEventListener("resize",this.debouncedShowStep,!1),window.addEventListener("keydown",this.keyDownHandler,!1)}},{key:"close",value:function(){this.setState(function(r){return r.observer&&r.observer.disconnect(),{isOpen:!1,observer:null}},this.onBeforeClose),window.removeEventListener("resize",this.debouncedShowStep),window.removeEventListener("keydown",this.keyDownHandler)}},{key:"onBeforeClose",value:function(){var r=this.props.onBeforeClose;r&&r(this.helperElement)}},{key:"render",value:function(){var r=this,l=this.props,c=l.className,d=l.steps,h=l.maskClassName,p=l.showButtons,f=l.showCloseButton,b=l.closeButtonAriaLabel,y=l.showNavigation,w=l.showNavigationNumber,v=l.showNumber,_=l.onRequestClose,$=l.maskSpace,S=l.lastStepNextButton,T=l.nextButton,E=l.prevButton,D=l.badgeContent,M=l.highlightedMaskClassName,P=l.disableInteraction,W=l.disableDotsNavigation,G=l.nextStep,z=l.prevStep,Z=l.rounded,he=l.accentColor,Ce=l.CustomHelper,O=l.disableFocusLock,K=l.highlightedBorder,C=this.state,Q=C.isOpen,ve=C.current,ce=C.inDOM,ne=C.top,me=C.right,re=C.bottom,B=C.left,N=C.width,te=C.height,q=C.w,se=C.h,F=C.helperWidth,Te=C.helperHeight,ae=C.helperPosition;return Q?_e.createElement(LA,null,_e.createElement(_A,null),_e.createElement(NA,{step:d[ve],refresh:function(){return r.recalculateNode(d[ve])}}),_e.createElement(MA,{step:d[ve],refresh:function(){return r.recalculateNode(d[ve])}}),_e.createElement(vC,{onClick:this.maskClickHandler,forwardRef:function(Ie){return r.mask=Ie},windowWidth:q,windowHeight:se,targetWidth:N,targetHeight:te,targetTop:ne,targetLeft:B,padding:$,rounded:Z,roundedStep:d[ve].roundedStep,className:h,disableInteraction:d[ve].stepInteraction===!1||P?!d[ve].stepInteraction:P,disableInteractionClassName:"".concat(Sn.mask.disableInteraction," ").concat(M),highlightedBorder:K}),_e.createElement(Jk,{disabled:O,autoFocus:!1},_e.createElement(IA,{ref:this.helper,targetHeight:te,targetWidth:N,targetTop:ne,targetRight:me,targetBottom:re,targetLeft:B,windowWidth:q,windowHeight:se,helperWidth:F,helperHeight:Te,helperPosition:ae,padding:$,tabIndex:-1,current:ve,style:d[ve].style?d[ve].style:{},rounded:Z,className:A_(Sn.helper.base,c,vs({},Sn.helper.isOpen,Q)),accentColor:he,defaultStyles:!Ce,role:"dialog"},Ce?_e.createElement(Ce,{current:ve,totalSteps:d.length,gotoStep:this.gotoStep,close:_,content:d[ve]&&(typeof d[ve].content=="function"?d[ve].content({close:_,goTo:this.gotoStep,inDOM:ce,step:ve+1}):d[ve].content)},this.props.children):_e.createElement(_e.Fragment,null,this.props.children,d[ve]&&(typeof d[ve].content=="function"?d[ve].content({close:_,goTo:this.gotoStep,inDOM:ce,step:ve+1}):d[ve].content),v&&_e.createElement(xA,{"data-tour-elem":"badge",accentColor:he},typeof D=="function"?D(ve+1,d.length):ve+1),(p||y)&&_e.createElement(DA,{"data-tour-elem":"controls"},p&&_e.createElement(tw,{onClick:typeof z=="function"?z:this.prevStep,disabled:ve===0,label:E||null}),y&&_e.createElement(AA,{"data-tour-elem":"navigation"},d.map(function(we,Ie){return _e.createElement(RA,{key:"".concat(we.selector?we.selector:"undef","_").concat(Ie),onClick:function(){return r.gotoStep(Ie)},current:ve,index:Ie,accentColor:he,disabled:ve===Ie||W,showNumber:w,"data-tour-elem":"dot",className:A_(Sn.dot.base,vs({},Sn.dot.active,ve===Ie)),"aria-label":we.navDotAriaLabel})})),p&&_e.createElement(tw,{onClick:ve===d.length-1?S?_:function(){}:typeof G=="function"?G:this.nextStep,disabled:!S&&ve===d.length-1,inverted:!0,label:S&&ve===d.length-1?S:T||null})),f&&_e.createElement(kA,{onClick:_,className:"reactour__close",ariaLabel:b}))))):null}}])})(xw),fg=function(s,i,r){if(r){var l=Math.max(document.documentElement.clientWidth,window.innerWidth||0),c=Math.max(document.documentElement.clientHeight,window.innerHeight||0),d=_c(r),h=d.width,p=d.height,f={top:c+10,right:l/2+9,bottom:c/2+9,left:l/2-h/2,width:0,height:0,w:l,h:c,helperPosition:"center"};return s&&(f=bC(s,i)),function(){return Ac(Ac({w:l,h:c,helperWidth:h,helperHeight:p,helperPosition:i.position},f),{},{inDOM:!!s})}}};Um.propTypes=PA;Um.defaultProps=BA;const jA=""+new URL("blockly2js-B3Jxf2e-.svg",import.meta.url).href,FA=""+new URL("rules2js-DnYyR8mI.svg",import.meta.url).href,Ns={selectTriggers:0,addScheduleByDoubleClick:1,openTagsMenu:2,selectIntervalTag:3,selectActions:4,addActionPrintText:5,showJavascript:6,switchBackToRules:7,saveTheScript:8},zA=[{selector:".blocks-triggers",content:"Select triggers"},{selector:".block-TriggerScheduleBlock",content:"Double click to add the block"},{selector:".tag-card",content:"Open drop down menu"},{selector:".tag-card-interval",content:"Select interval"},{selector:".blocks-actions",content:"Select action blocks"},{selector:".block-ActionPrintText",content:"Double click to add the block"},{selector:".button-js-code",content:"Check the script"},{selector:".button-js-code",content:"Switch back to rules"},{selector:".button-save",content:"Save the script"}],$g=187,lc={root:{left:0,top:0,width:"100%",height:"100%",position:"fixed",background:"rgba(0, 0, 0, .3)",zIndex:2e4},connecting:{left:"40%",top:"40%",width:"20%",height:"20%",position:"absolute"},spinner:{animation:"admin-connecting-rotator 1.4s linear infinite"},path:{strokeDasharray:187,strokeDashoffset:0,transformOrigin:"center",animation:"admin-connecting-dash 1.4s ease-in-out infinite, $colors 5.6s ease-in-out infinite"}};function En(){return m.jsxs("div",{style:lc.root,children:[m.jsx("style",{children:` +`])),function(a){return!a.maskClassName&&.7},function(a){return!a.maskClassName&&"#000"});function yC(a){var s=a.windowWidth,i=a.windowHeight,r=a.targetWidth,l=a.targetHeight,c=a.targetTop,d=a.targetLeft,h=a.padding,p=a.rounded,f=a.roundedStep,b=a.disableInteraction,y=a.disableInteractionClassName,w=a.className,v=a.onClick,_=a.highlightedBorder,$=Qs(r+h*2),T=Qs(l+h*2),S=Qs(c-h),E=Qs(d-h),D=f?Math.min($/2,T/2):p;return _e.createElement(MA,{onClick:v,maskClassName:w},_e.createElement("svg",{width:s,height:i,xmlns:"http://www.w3.org/2000/svg",className:w},_e.createElement("defs",null,_e.createElement("mask",{id:"mask-main"},_e.createElement("rect",{x:0,y:0,width:s,height:i,fill:"white"}),_e.createElement("rect",{x:E,y:S,width:$,height:T,fill:"black"}),_e.createElement("rect",{x:E-1,y:S-1,width:D,height:D,fill:"white"}),_e.createElement("circle",{cx:E+D,cy:S+D,r:D,fill:"black"}),_e.createElement("rect",{x:E+$-D+1,y:S-1,width:D,height:D,fill:"white"}),_e.createElement("circle",{cx:E+$-D,cy:S+D,r:D,fill:"black"}),_e.createElement("rect",{x:E-1,y:S+T-D+1,width:D,height:D,fill:"white"}),_e.createElement("circle",{cx:E+D,cy:S+T-D,r:D,fill:"black"}),_e.createElement("rect",{x:E+$-D+1,y:S+T-D+1,width:D,height:D,fill:"white"}),_e.createElement("circle",{cx:E+$-D,cy:S+T-D,r:D,fill:"black "})),_e.createElement("clipPath",{id:"clip-path"},_e.createElement("rect",{x:0,y:0,width:s,height:S}),_e.createElement("rect",{x:0,y:S,width:E,height:T}),_e.createElement("rect",{x:d+r+h,y:S,width:Qs(s-r-E),height:T}),_e.createElement("rect",{x:0,y:c+l+h,width:s,height:Qs(i-l-S)}))),_e.createElement("rect",{x:0,y:0,width:s,height:i,fill:"currentColor",mask:"url(#mask-main)"}),_e.createElement("rect",{x:0,y:0,width:s,height:i,fill:"currentColor",clipPath:"url(#clip-path)",pointerEvents:"auto"}),_e.createElement("rect",{x:E,y:S,width:$,height:T,pointerEvents:"auto",fill:"transparent",display:b?"block":"none",className:y}),_&&_e.createElement("rect",{x:Qs(E+_.width/2),y:Qs(S+_.width/2),width:Qs($-_.width),height:Qs(T-_.width),pointerEvents:"auto",fill:"none",strokeWidth:_.width,stroke:_.color,rx:D-2})))}yC.propTypes={windowWidth:ke.number.isRequired,windowHeight:ke.number.isRequired,targetWidth:ke.number.isRequired,targetHeight:ke.number.isRequired,targetTop:ke.number.isRequired,targetLeft:ke.number.isRequired,padding:ke.number.isRequired,rounded:ke.number.isRequired,roundedStep:ke.bool,disableInteraction:ke.bool.isRequired,disableInteractionClassName:ke.string.isRequired,highlightedBorder:ke.shape({color:ke.string.isRequired,width:ke.number.isRequired})};var NA=(function(a){var s=a.step,i=a.refresh,r=kt(0),l=yA(r,2),c=l[0],d=l[1];return Lt(function(){if(s.resizeObservables){var h=function(w){var v=Nn(w),_;try{var $=function(){var S=_.value;if(!S.attributes)return 1;var E=s.resizeObservables.find(function(D){return S.matches(D)||S.querySelector(D)!=null});E&&d(c+1)};for(v.s();!(_=v.n()).done;)$()}catch(T){v.e(T)}finally{v.f()}},p=new MutationObserver(function(y){var w=Nn(y),v;try{for(w.s();!(v=w.n()).done;){var _=v.value;_.addedNodes.length!==0&&h(_.addedNodes),_.removedNodes.length!==0&&h(_.removedNodes)}}catch($){w.e($)}finally{w.f()}}),f=document.documentElement||document.body,b={childList:!0,subtree:!0};return p.observe(f,b),function(){p.disconnect()}}},[s,c]),Lt(function(){if(s.resizeObservables){var h=new ResizeObserver(function(w){i()}),p=Nn(s.resizeObservables),f;try{for(p.s();!(f=p.n()).done;){var b=f.value,y=document.querySelector(b);y&&h.observe(y)}}catch(w){p.e(w)}finally{p.f()}return function(){h.disconnect()}}},[s,c]),null}),LA=(function(a){var s=a.step,i=a.refresh;return Lt(function(){if(s.mutationObservables){var r=function(p){var f=Nn(p),b;try{var y=function(){var v=b.value;if(!v.attributes)return 1;var _=s.mutationObservables.find(function($){return v.matches($)||v.querySelector($)!=null});_&&i()};for(f.s();!(b=f.n()).done;)y()}catch(w){f.e(w)}finally{f.f()}},l=new MutationObserver(function(h){var p=Nn(h),f;try{for(p.s();!(f=p.n()).done;){var b=f.value;b.addedNodes.length!==0&&r(b.addedNodes),b.removedNodes.length!==0&&r(b.removedNodes)}}catch(y){p.e(y)}finally{p.f()}}),c=document.documentElement||document.body,d={childList:!0,subtree:!0};return l.observe(c,d),function(){l.disconnect()}}},[s]),null});function PA(a){var s=a.children,i=Yo(null);return i.current===null&&(i.current=document.createElement("div"),i.current.setAttribute("id","___reactour")),Lt(function(){return document.body.appendChild(i.current),function(){document.body.removeChild(i.current)}},[i]),MS(s,i.current)}var BA={disableFocusLock:ke.bool,badgeContent:ke.func,highlightedMaskClassName:ke.string,children:ke.oneOfType([ke.node,ke.element]),className:ke.string,closeButtonAriaLabel:ke.string,closeWithMask:ke.bool,inViewThreshold:ke.number,isOpen:ke.bool.isRequired,lastStepNextButton:ke.node,maskClassName:ke.string,maskSpace:ke.number,nextButton:ke.node,onAfterOpen:ke.func,onBeforeClose:ke.func,onRequestClose:ke.func,prevButton:ke.node,scrollDuration:ke.number,scrollOffset:ke.number,showButtons:ke.bool,showCloseButton:ke.bool,showNavigation:ke.bool,showNavigationNumber:ke.bool,showNumber:ke.bool,startAt:ke.number,goToStep:ke.number,getCurrentStep:ke.func,nextStep:ke.func,prevStep:ke.func,steps:ke.arrayOf(ke.shape({selector:ke.string,content:ke.oneOfType([ke.node,ke.element,ke.func]).isRequired,position:ke.oneOfType([ke.arrayOf(ke.number),ke.oneOf(["top","right","bottom","left","center"])]),action:ke.func,style:ke.object,stepInteraction:ke.bool,navDotAriaLabel:ke.string,roundedStep:ke.bool})),update:ke.string,updateDelay:ke.number,disableInteraction:ke.bool,disableDotsNavigation:ke.bool,disableKeyboardNavigation:ke.oneOfType([ke.arrayOf(ke.oneOf(["esc","right","left"])),ke.bool]),rounded:ke.number,accentColor:ke.string,highlightedBorder:ke.shape({color:ke.string.isRequired,width:ke.number.isRequired})},jA={disableFocusLock:!1,showNavigation:!0,showNavigationNumber:!0,showButtons:!0,showCloseButton:!0,closeButtonAriaLabel:"Close",showNumber:!0,scrollDuration:1,maskSpace:10,updateDelay:1,disableInteraction:!1,rounded:0,accentColor:"#007aff",closeWithMask:!0},Sn={mask:{disableInteraction:"reactour__mask--disable-interaction"},helper:{base:"reactour__helper",isOpen:"reactour__helper--is-open"},dot:{base:"reactour__dot",active:"reactour__dot--is-active"}},Wm=(function(a){function s(){var i;return pA(this,s),i=hA(this,s),vs(i,"unlockFocus",function(r){i.setState({focusUnlocked:!0},r())}),vs(i,"showStep",function(){if(!(!i.helper||!i.helper.current)){var r=i.props.steps,l=i.state,c=l.current,d=l.focusUnlocked;d&&i.setState({focusUnlocked:!1});var h=r[c],p=h.selector?document.querySelector(h.selector):null,f=function(_){h.action&&typeof h.action=="function"&&i.unlockFocus(function(){return h.action(_)})};if(h.observe){var b=document.querySelector(h.observe),y={attributes:!0,childList:!0,characterData:!0};i.setState(function(v){return v.observer&&setTimeout(function(){v.observer.disconnect()},0),{observer:new MutationObserver(function(_){_.forEach(function($){if($.type==="childList"&&$.addedNodes.length>0){var T=function(){return f($.addedNodes[0])};setTimeout(function(){return i.calculateNode($.addedNodes[0],h,T)},100)}else if($.type==="childList"&&$.removedNodes.length>0){var S=function(){return f(p)};i.calculateNode(p,h,S)}})})}},function(){return i.state.observer.observe(b,y)})}else i.state.observer&&(i.state.observer.disconnect(),i.setState({observer:null}));if(p){var w=function(){return f(p)};i.calculateNode(p,h,w)}else i.setState($g(null,h,i.helper.current),f),h.selector&&console.warn("Doesn't find a DOM node '".concat(h.selector,"'. Please check the 'steps' Tour prop Array at position ").concat(c,"."))}}),vs(i,"calculateNode",function(r,l,c){var d=i.props,h=d.scrollDuration,p=d.inViewThreshold,f=d.scrollOffset,b=vC(r,l),y=Math.max(document.documentElement.clientWidth,window.innerWidth||0),w=Math.max(document.documentElement.clientHeight,window.innerHeight||0);if(TA(Oc(Oc({},b),{},{w:y,h:w,threshold:p})))i.setState($g(r,l,i.helper.current),c);else{var v=qx(r),_=f||(b.height>w?-25:-(w/2)+b.height/2);Kx.to(r,{context:SA(v)?window:v,duration:h,offset:_,callback:function(T){i.setState($g(T,l,i.helper.current),c)}})}}),vs(i,"recalculateNode",function(r){var l=document.querySelector(r.selector),c=function(h){r.action&&typeof r.action=="function"&&i.unlockFocus(function(){return r.action(h)})};i.calculateNode(l,r,function(){return c(l)})}),vs(i,"maskClickHandler",function(r){var l=i.props,c=l.closeWithMask,d=l.onRequestClose;c&&!r.target.classList.contains(Sn.mask.disableInteraction)&&d(r)}),vs(i,"nextStep",function(){var r=i.props,l=r.steps,c=r.getCurrentStep;i.setState(function(d){var h=d.current0?l.current-1:l.current;return typeof r=="function"&&r(c),{current:c}},i.showStep)}),vs(i,"gotoStep",function(r){var l=i.props,c=l.steps,d=l.getCurrentStep;i.setState(function(h){var p=c[r]?r:h.current;return typeof d=="function"&&d(p),{current:p}},i.showStep)}),vs(i,"keyDownHandler",function(r){var l=i.props,c=l.onRequestClose,d=l.nextStep,h=l.prevStep,p=l.disableKeyboardNavigation;if(r.stopPropagation(),p!==!0){var f,b,y;p&&(f=p.includes("esc"),b=p.includes("right"),y=p.includes("left")),r.keyCode===27&&!f&&(r.preventDefault(),c()),r.keyCode===39&&!b&&(r.preventDefault(),typeof d=="function"?d():i.nextStep()),r.keyCode===37&&!y&&(r.preventDefault(),typeof h=="function"?h():i.prevStep())}}),i.state={isOpen:!1,current:0,top:0,right:0,bottom:0,left:0,width:0,height:0,w:0,h:0,inDOM:!1,observer:null,focusUnlocked:!1},i.helper=LT(),i.helperElement=null,i.debouncedShowStep=f0(i.showStep,70),i}return fA(s,a),mA(s,[{key:"componentDidMount",value:function(){var r=this.props,l=r.isOpen,c=r.startAt;l&&this.open(c)}},{key:"UNSAFE_componentWillReceiveProps",value:function(r){var l=this.props,c=l.isOpen,d=l.update,h=l.updateDelay;!c&&r.isOpen?this.open(r.startAt):c&&!r.isOpen&&this.close(),c&&d!==r.update&&(r.steps[this.state.current]?setTimeout(this.showStep,h):this.props.onRequestClose()),c&&r.isOpen&&this.state.current!==r.goToStep&&this.gotoStep(r.goToStep)}},{key:"componentWillUnmount",value:function(){var r=this.props.isOpen;r&&this.close(),this.state.observer&&this.state.observer.disconnect()}},{key:"open",value:function(r){var l=this,c=this.props.onAfterOpen;this.setState(function(d){return{isOpen:!0,current:r!==void 0?r:d.current}},function(){setTimeout(l.showStep,1),l.helperElement=l.helper.current,l.props.disableFocusLock||l.helper.current.focus(),c&&c(l.helperElement)}),window.addEventListener("resize",this.debouncedShowStep,!1),window.addEventListener("keydown",this.keyDownHandler,!1)}},{key:"close",value:function(){this.setState(function(r){return r.observer&&r.observer.disconnect(),{isOpen:!1,observer:null}},this.onBeforeClose),window.removeEventListener("resize",this.debouncedShowStep),window.removeEventListener("keydown",this.keyDownHandler)}},{key:"onBeforeClose",value:function(){var r=this.props.onBeforeClose;r&&r(this.helperElement)}},{key:"render",value:function(){var r=this,l=this.props,c=l.className,d=l.steps,h=l.maskClassName,p=l.showButtons,f=l.showCloseButton,b=l.closeButtonAriaLabel,y=l.showNavigation,w=l.showNavigationNumber,v=l.showNumber,_=l.onRequestClose,$=l.maskSpace,T=l.lastStepNextButton,S=l.nextButton,E=l.prevButton,D=l.badgeContent,R=l.highlightedMaskClassName,L=l.disableInteraction,H=l.disableDotsNavigation,G=l.nextStep,z=l.prevStep,Z=l.rounded,he=l.accentColor,Ce=l.CustomHelper,M=l.disableFocusLock,Y=l.highlightedBorder,C=this.state,Q=C.isOpen,ve=C.current,ce=C.inDOM,ne=C.top,me=C.right,re=C.bottom,B=C.left,N=C.width,te=C.height,X=C.w,se=C.h,F=C.helperWidth,Te=C.helperHeight,ae=C.helperPosition;return Q?_e.createElement(PA,null,_e.createElement(wA,null),_e.createElement(NA,{step:d[ve],refresh:function(){return r.recalculateNode(d[ve])}}),_e.createElement(LA,{step:d[ve],refresh:function(){return r.recalculateNode(d[ve])}}),_e.createElement(yC,{onClick:this.maskClickHandler,forwardRef:function(Ie){return r.mask=Ie},windowWidth:X,windowHeight:se,targetWidth:N,targetHeight:te,targetTop:ne,targetLeft:B,padding:$,rounded:Z,roundedStep:d[ve].roundedStep,className:h,disableInteraction:d[ve].stepInteraction===!1||L?!d[ve].stepInteraction:L,disableInteractionClassName:"".concat(Sn.mask.disableInteraction," ").concat(R),highlightedBorder:Y}),_e.createElement(Xk,{disabled:M,autoFocus:!1},_e.createElement(xA,{ref:this.helper,targetHeight:te,targetWidth:N,targetTop:ne,targetRight:me,targetBottom:re,targetLeft:B,windowWidth:X,windowHeight:se,helperWidth:F,helperHeight:Te,helperPosition:ae,padding:$,tabIndex:-1,current:ve,style:d[ve].style?d[ve].style:{},rounded:Z,className:O_(Sn.helper.base,c,vs({},Sn.helper.isOpen,Q)),accentColor:he,defaultStyles:!Ce,role:"dialog"},Ce?_e.createElement(Ce,{current:ve,totalSteps:d.length,gotoStep:this.gotoStep,close:_,content:d[ve]&&(typeof d[ve].content=="function"?d[ve].content({close:_,goTo:this.gotoStep,inDOM:ce,step:ve+1}):d[ve].content)},this.props.children):_e.createElement(_e.Fragment,null,this.props.children,d[ve]&&(typeof d[ve].content=="function"?d[ve].content({close:_,goTo:this.gotoStep,inDOM:ce,step:ve+1}):d[ve].content),v&&_e.createElement(DA,{"data-tour-elem":"badge",accentColor:he},typeof D=="function"?D(ve+1,d.length):ve+1),(p||y)&&_e.createElement(AA,{"data-tour-elem":"controls"},p&&_e.createElement(sw,{onClick:typeof z=="function"?z:this.prevStep,disabled:ve===0,label:E||null}),y&&_e.createElement(OA,{"data-tour-elem":"navigation"},d.map(function(we,Ie){return _e.createElement(RA,{key:"".concat(we.selector?we.selector:"undef","_").concat(Ie),onClick:function(){return r.gotoStep(Ie)},current:ve,index:Ie,accentColor:he,disabled:ve===Ie||H,showNumber:w,"data-tour-elem":"dot",className:O_(Sn.dot.base,vs({},Sn.dot.active,ve===Ie)),"aria-label":we.navDotAriaLabel})})),p&&_e.createElement(sw,{onClick:ve===d.length-1?T?_:function(){}:typeof G=="function"?G:this.nextStep,disabled:!T&&ve===d.length-1,inverted:!0,label:T&&ve===d.length-1?T:S||null})),f&&_e.createElement(CA,{onClick:_,className:"reactour__close",ariaLabel:b}))))):null}}])})(Dw),$g=function(s,i,r){if(r){var l=Math.max(document.documentElement.clientWidth,window.innerWidth||0),c=Math.max(document.documentElement.clientHeight,window.innerHeight||0),d=wc(r),h=d.width,p=d.height,f={top:c+10,right:l/2+9,bottom:c/2+9,left:l/2-h/2,width:0,height:0,w:l,h:c,helperPosition:"center"};return s&&(f=vC(s,i)),function(){return Oc(Oc({w:l,h:c,helperWidth:h,helperHeight:p,helperPosition:i.position},f),{},{inDOM:!!s})}}};Wm.propTypes=BA;Wm.defaultProps=jA;const FA=""+new URL("blockly2js-B3Jxf2e-.svg",import.meta.url).href,zA=""+new URL("rules2js-DnYyR8mI.svg",import.meta.url).href,UA="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA2NCAzMiIgd2lkdGg9IjY0IiBoZWlnaHQ9IjMyIj4KICA8cG9seWdvbiBwb2ludHM9IjgsMSA2MywxIDYzLDMxIDgsMzEgMSwxNiIgZmlsbD0iIzRhOTBkOSIgZmlsbC1vcGFjaXR5PSIwLjE1IiBzdHJva2U9IiM0YTkwZDkiIHN0cm9rZS13aWR0aD0iMS41IiBzdHJva2UtbGluZWpvaW49InJvdW5kIi8+CiAgPGNpcmNsZSBjeD0iMTAuNSIgY3k9IjE2IiByPSIyIiBmaWxsPSJub25lIiBzdHJva2U9IiM0YTkwZDkiIHN0cm9rZS13aWR0aD0iMS4yIi8+CiAgPHRleHQgeD0iMzciIHk9IjIxIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIiBmb250LWZhbWlseT0iQXJpYWwsc2Fucy1zZXJpZiIgZm9udC1zaXplPSIxNCIgZm9udC13ZWlnaHQ9ImJvbGQiIGZpbGw9IiM0YTkwZDkiPk5hbWU8L3RleHQ+Cjwvc3ZnPgo=",HA="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA2NCAzMiIgd2lkdGg9IjY0IiBoZWlnaHQ9IjMyIj4KICA8cG9seWdvbiBwb2ludHM9IjgsMSA2M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:2,selectIntervalTag:3,selectActions:4,addActionPrintText:5,showJavascript:6,switchBackToRules:7,saveTheScript:8},VA=[{selector:".blocks-triggers",content:"Select triggers"},{selector:".block-TriggerScheduleBlock",content:"Double click to add the block"},{selector:".tag-card",content:"Open drop down menu"},{selector:".tag-card-interval",content:"Select interval"},{selector:".blocks-actions",content:"Select action blocks"},{selector:".block-ActionPrintText",content:"Double click to add the block"},{selector:".button-js-code",content:"Check the script"},{selector:".button-js-code",content:"Switch back to rules"},{selector:".button-save",content:"Save the script"}],bg=187,cc={root:{left:0,top:0,width:"100%",height:"100%",position:"fixed",background:"rgba(0, 0, 0, .3)",zIndex:2e4},connecting:{left:"40%",top:"40%",width:"20%",height:"20%",position:"absolute"},spinner:{animation:"admin-connecting-rotator 1.4s linear infinite"},path:{strokeDasharray:187,strokeDashoffset:0,transformOrigin:"center",animation:"admin-connecting-dash 1.4s ease-in-out infinite, $colors 5.6s ease-in-out infinite"}};function En(){return m.jsxs("div",{style:cc.root,children:[m.jsx("style",{children:` ' @keyframes admin-connecting-colors { 0% { stroke: #4285F4; @@ -247,14 +247,14 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho } @keyframes admin-connecting-dash { 0% { - stroke-dashoffset: ${$g}; + stroke-dashoffset: ${bg}; } 50% { - stroke-dashoffset: ${$g/4}; + stroke-dashoffset: ${bg/4}; transform: rotate(135deg); } 100% { - stroke-dashoffset: ${$g}; + stroke-dashoffset: ${bg}; transform: 'rotate(450deg); } } @@ -266,20 +266,20 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho transform: rotate(270deg); } } -`}),m.jsx("div",{style:lc.connecting,children:m.jsx("svg",{style:lc.spinner,width:"100%",height:"100%",viewBox:"0 0 66 66",xmlns:"http://www.w3.org/2000/svg",children:m.jsx("circle",{style:lc.path,fill:"none",strokeWidth:"6",strokeLinecap:"round",cx:"33",cy:"33",r:"30"})})})]})}const UA=_e.lazy(()=>Fn(()=>Promise.resolve().then(()=>vR),void 0,import.meta.url)),HA=_e.lazy(()=>Fn(()=>import("./index-B0ByV4SK.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13]),import.meta.url)),WA=_e.lazy(()=>Fn(()=>import("./index-ns4mNOlq.js"),__vite__mapDeps([14,1,2,3,4,6,7,5,15,8,9,10,11,12]),import.meta.url)),GA=_e.lazy(()=>Fn(()=>import("./ScriptEditorVanillaMonaco-DSYvOslZ.js"),__vite__mapDeps([15,1,2,3,4,6,7,5]),import.meta.url)),VA=_e.lazy(()=>Fn(()=>import("./ScriptEditor-C-fO5h68.js"),__vite__mapDeps([16,1,2,3,4,6,5,15,7,17]),import.meta.url)),KA=_e.lazy(()=>Fn(()=>import("./OpenAiDialog-CANTLp4d.js"),__vite__mapDeps([18,1,2,3,4,6,5,9,19,15,7,8,10,11,12]),import.meta.url)),cw={Blockly:gk,"Javascript/js":Tc,Rules:fk,def:Tc,"TypeScript/ts":mk},YA=48,uw="#02a102",bg="#70aae9",JA=Tw[400],qA=Sw[400],Fe={toolbar:a=>({minHeight:38,boxShadow:"0px 2px 4px -1px rgba(0, 0, 0, 0.2), 0px 4px 5px 0px rgba(0, 0, 0, 0.14), 0px 1px 10px 0px rgba(0, 0, 0, 0.12)",backgroundColor:a.palette.mode==="dark"?"#1e1e1e":"#E2E2E2"}),toolbarButtons:{padding:4,marginLeft:4},toolbarButtonsDisabled:{filter:"grayscale(100%)",opacity:.5},editorDiv:a=>({height:`calc(100% - ${(parseInt(a.toolbar.height,10)||48)+38+10}px)`,width:"100%",overflow:"hidden",position:"relative"}),textButton:{marginRight:10,minHeight:24,padding:"6px 16px",height:32},saveButton:{background:"#ff9900"},tabIcon:{width:24,height:24,verticalAlign:"middle",marginBottom:2,marginRight:2,borderRadius:3},hintIcon:{padding:"0 8px 0 8px"},hintButton:{marginTop:8,marginLeft:20},tabMenuButton:{position:"absolute",top:0,right:0},tabChanged:a=>({color:a.palette.secondary.main}),tabText:{maxWidth:130,textOverflow:"ellipsis",whiteSpace:"nowrap",overflow:"hidden",display:"inline-block",verticalAlign:"middle"},tabChangedIcon:{color:"#FF0000",fontSize:16,marginLeft:5},closeButton:{marginLeft:5},notRunning:{color:"#ffbc00",marginRight:8,marginLeft:8},tabButton:{minHeight:48},tabButtonWrapper:{display:"inline-block"},menuIcon:{width:18,height:18,borderRadius:2,marginRight:5}};class Rn extends _e.Component{getSelect=null;changedMirror={};cron={initValue:null,callback:null};scriptDialog={initValue:null,callback:null,args:null,isReturn:!1};objects;scripts;selectId={initValue:null,callback:null};confirmCallback=null;lastKnownTs={};constructor(s){var c,d;super(s);let i=window.localStorage.getItem("Editor.selected")||"";const r=window.localStorage.getItem("Editor.editing")||"[]";let l;try{l=JSON.parse(r)}catch{l=[]}i&&!l.includes(i)&&l.push(i),i&&!this.props.password&&((d=(c=this.props.objects[i])==null?void 0:c.native)!=null&&d.protected)&&(i=l.find(h=>{var p,f;return!((f=(p=this.props.objects[h])==null?void 0:p.native)!=null&&f.protected)})||""),!i&&l.length&&(this.props.password?i=l[0]:i=l.find(h=>{var p,f;return!((f=(p=this.props.objects[h])==null?void 0:p.native)!=null&&f.protected)})||""),this.state={askAboutDebug:!1,astroEvents:null,blockly:null,changed:{},cmdToBlockly:"",cmdToRules:"",confirm:"",debugEnabled:!1,editing:l,insert:"",instancesLoaded:!1,isTourOpen:window.localStorage.getItem("tour")!=="true",menuDebugAnchorEl:null,menuOpened:!!this.props.menuOpened,menuTabsOpened:!1,openAiDialog:!1,triggerPrettier:1,scriptConflict:"",rules:null,runningInstances:this.props.runningInstances||{},searchText:"",selected:i,showAdapterDebug:!1,showAstro:!1,showCompiledCode:!1,showCron:!1,showDebugMenu:!1,showScript:!1,showSelectId:!1,themeType:this.props.themeType,toast:"",tourStep:Ns.selectTriggers,verboseEnabled:!1,visible:s.visible},this.setChangedInAdmin(),window.systemLang=x.I18n.getLanguage(),window.main={objects:{},getObject:(h,p)=>this.props.socket.getObject(h).then(f=>p==null?void 0:p(null,f)).catch(f=>p==null?void 0:p(f)),instances:[],selectIdDialog:(h,p,f)=>{typeof p=="function"&&(f=p,p=null),this.selectId.callback=f,this.selectId.initValue=h,this.selectId.type=p,this.setState({showSelectId:!0})},cronDialog:(h,p)=>{this.cron.callback=p,this.cron.initValue=h,this.setState({showCron:!0})},showScriptDialog:(h,p,f,b)=>{this.scriptDialog.callback=b,this.scriptDialog.initValue=h,this.scriptDialog.args=p,this.scriptDialog.isReturn=f||!1,this.setState({showScript:!0})}},this.objects=s.objects,this.scripts={},this.getAllAdapterInstances().then(()=>{this.props.onSelectedChange&&this.state.selected&&setTimeout(()=>this.props.onSelectedChange(this.state.selected,this.state.editing),100)})}async getAllAdapterInstances(){const s=await this.props.socket.getAdapterInstances(!0),i={},r=s.map(l=>(i[l._id]=l,l._id));window.main.objects=i,window.main.instances=r,this.setState({instancesLoaded:!0})}static onInstanceChanged(s,i){if(s)if(!i&&window.main.instances.includes(s)){delete window.main.objects[s];const r=window.main.instances.indexOf(s);window.main.instances.splice(r,1)}else(i==null?void 0:i.type)==="instance"&&(window.main.instances.includes(s)||(window.main.instances.push(s),window.main.instances.sort()),window.main.objects[s]=i)}setChangedInAdmin(){const s=Object.keys(this.state.changed).find(i=>this.state.changed[i]);Object.keys(this.state.changed).forEach(i=>{this.changedMirror[i]=this.state.changed[i]}),Object.keys(this.changedMirror).forEach(i=>{this.state.changed[i]===void 0&&delete this.changedMirror[i]}),this.props.onChangedChanged(this.changedMirror),typeof window.parent<"u"&&window.parent&&(window.parent.configNotSaved=!!s)}componentDidMount(){window.addEventListener("beforeunload",this.onBrowserClose,!1),this.props.socket.subscribeObject("system.adapter.*",Rn.onInstanceChanged)}componentWillUnmount(){window.removeEventListener("beforeunload",this.onBrowserClose),this.props.socket.unsubscribeObject("system.adapter.*",Rn.onInstanceChanged)}componentDidUpdate(s){if(s.scriptsHash!==this.props.scriptsHash)for(const i of this.state.editing){const r=this.props.objects[i];if(!r||r.type!=="script")continue;const l=r.ts||0,c=this.lastKnownTs[i];c!==void 0&&l!==c&&(this.state.changed[i]?this.state.scriptConflict||this.setState({scriptConflict:i}):(this.scripts[i]=this.getScriptFromObject(i),this.lastKnownTs[i]=l))}}onBrowserClose=s=>{const i=Object.keys(this.scripts).find(r=>JSON.stringify(this.scripts[r])!==JSON.stringify(this.getScriptFromObject(r)));if(i){console.log(`Script ${JSON.stringify(this.scripts[i])}`);const r=x.I18n.t("Configuration not saved.");return s=s||window.event,s&&(s.returnValue=r),r}};removeNonExistingScripts(s,i){s=s||this.props,i=i||{};let r=!1;if(this.state.editing&&this.state.editing.find(c=>s&&!s.objects[c])){const c=[...this.state.editing];for(let d=c.length-1;d>=0;d--)this.objects[c[d]]||(r=!0,c.splice(d,1));r&&(i.editing=c),this.state.selected&&!this.objects[this.state.selected]&&(r=!0,i.selected=c[0]||"",i.selected&&this.scripts[i.selected]&&(this.state.blockly!==(this.scripts[i.selected].engineType==="Blockly")&&(i.blockly=this.scripts[i.selected].engineType==="Blockly",r=!0),this.state.rules!==(this.scripts[i.selected].engineType==="Rules")&&(i.rules=this.scripts[i.selected].engineType==="Rules",r=!0),this.state.verboseEnabled!==this.scripts[i.selected].verbose&&(i.verboseEnabled=this.scripts[i.selected].verbose,r=!0),this.state.debugEnabled!==this.scripts[i.selected].debug&&(i.debugEnabled=this.scripts[i.selected].debug,r=!0)))}return r}UNSAFE_componentWillReceiveProps(s){var l,c,d;const i={};let r=!1;if(JSON.stringify(s.runningInstances)!==JSON.stringify(this.state.runningInstances)&&(r=!0,i.runningInstances=s.runningInstances),this.state.menuOpened!==s.menuOpened&&(i.menuOpened=s.menuOpened,r=!0),this.state.themeType!==s.themeType&&(i.themeType=s.themeType,r=!0),this.removeNonExistingScripts(s,i)&&(r=!0),this.state.searchText!==s.searchText&&(i.searchText=s.searchText,r=!0),this.objects!==s.objects){this.objects=s.objects,window.main.objects=s.objects,Object.keys(this.scripts).forEach(p=>{const f=this.scripts[p].source;this.scripts[p]=JSON.parse(JSON.stringify(this.objects[p].common)),this.scripts[p].source=f}),this.state.selected&&this.objects[this.state.selected]&&(this.scripts[this.state.selected]||=JSON.parse(JSON.stringify(this.objects[this.state.selected].common)),this.state.blockly!==(this.scripts[this.state.selected].engineType==="Blockly")&&(i.blockly=this.scripts[this.state.selected].engineType==="Blockly",r=!0),this.state.rules!==(this.scripts[this.state.selected].engineType==="Rules")&&(i.rules=this.scripts[this.state.selected].engineType==="Rules",r=!0),this.state.verboseEnabled!==this.scripts[this.state.selected].verbose&&(i.verboseEnabled=this.scripts[this.state.selected].verbose,r=!0),this.state.debugEnabled!==this.scripts[this.state.selected].debug&&(i.debugEnabled=this.scripts[this.state.selected].debug,r=!0));const h=[...this.state.editing];for(let p=h.length-1;p>=0;p--)this.objects[h[p]]||(r=!0,h.splice(p,1),this.state.changed[h[p]]!==void 0&&(i.changed||={...this.state.changed},i.changed&&delete i.changed[h[p]]));this.state.selected&&!this.objects[this.state.selected]&&(i.selected=h[0]||""),r&&(i.editing=h)}else for(const h in this.scripts)if(Object.prototype.hasOwnProperty.call(this.scripts,h)){if((l=this.objects[h])!=null&&l.common){if(this.objects[h].type==="script"){const p=this.scripts[h].source,f=JSON.parse(JSON.stringify(this.scripts[h]));f.source=this.objects[h].common.source,JSON.stringify(f)!==JSON.stringify(this.objects[h].common)&&(this.scripts[h]=JSON.parse(JSON.stringify(this.objects[h].common)),this.scripts[h].source=p),p!==this.objects[h].common.source?this.state.changed[h]?(d=this.objects[h].from)!=null&&d.startsWith("system.adapter.javascript.")&&(this.objects[h].from="system.adapter.admin.0",this.setState({toast:x.I18n.t("Script %s was modified on disk.",h.split(".").pop())})):this.props.password&&((c=this.objects[h].native)!=null&&c.protected)?this.scripts[h].source=Vg(this.props.password,this.objects[h].common.source):this.scripts[h].source=this.objects[h].common.source:this.state.changed[h]&&(i.changed||={...this.state.changed},i.changed&&(i.changed[h]=!1),r=!0)}}else if(this.scripts[h]&&(delete this.scripts[h],this.state.selected===h)){if(this.state.editing.indexOf(h)!==-1){const p=[...this.state.editing],f=p.indexOf(h);f!==-1&&(p.splice(f,1),i.editing=p,r=!0)}i.selected=this.state.editing[0]||"",r=!0}}if(s.selected&&this.state.selected!==s.selected){const h=this.getScriptFromObject(s.selected);this.scripts[s.selected]||=h;const p=h&&JSON.stringify(this.scripts[s.selected])!==JSON.stringify(h),f=[...this.state.editing];s.selected&&!f.includes(s.selected)&&(f.push(s.selected),this.props.onSelectedChange(s.selected,f),window.localStorage.setItem("Editor.editing",JSON.stringify(f))),r=!0,i.changed||={...this.state.changed},i.changed[s.selected]=!!p,i.editing=f,i.selected=s.selected,i.blockly=this.scripts[s.selected].engineType==="Blockly",i.rules=this.scripts[s.selected].engineType==="Rules",i.verboseEnabled=this.scripts[s.selected].verbose,i.debugEnabled=this.scripts[s.selected].debug,i.showCompiledCode=!1}this.state.visible!==s.visible&&(r=!0,i.visible=s.visible),r&&this.setState(i,()=>this.setChangedInAdmin())}onRestart(){var s,i;(i=(s=this.props).onRestart)==null||i.call(s,this.state.selected)}onStartStop(){var i,r,l;const s=JSON.parse(JSON.stringify(this.scripts[this.state.selected]));s.enabled=!s.enabled,this.props.password&&((i=this.props.objects[this.state.selected].native)!=null&&i.protected)&&(s.source=vc(this.props.password,s.source)),(l=(r=this.props).onChange)==null||l.call(r,this.state.selected,s)}onSave(){if(this.state.isTourOpen&&this.state.tourStep===Ns.saveTheScript&&(this.setState({isTourOpen:!1}),window.localStorage.setItem("tour","true")),this.state.changed[this.state.selected]){const s={...this.state.changed};s[this.state.selected]=!1,this.setState({changed:s},()=>{var r,l,c;this.setChangedInAdmin();const i=JSON.parse(JSON.stringify(this.scripts[this.state.selected]));this.props.password&&((r=this.props.objects[this.state.selected].native)!=null&&r.protected)&&(i.source=vc(this.props.password,i.source)),(c=(l=this.props).onChange)==null||c.call(l,this.state.selected,i)})}}onSaveAll(){const s={...this.state.changed};Object.keys(s).forEach(i=>{var r,l,c;if(s[i]){s[i]=!1;const d=JSON.parse(JSON.stringify(this.scripts[i]));this.props.password&&((r=this.props.objects[i].native)!=null&&r.protected)&&(d.source=vc(this.props.password,d.source)),(c=(l=this.props).onChange)==null||c.call(l,i,d)}}),this.setState({changed:s},()=>this.setChangedInAdmin())}onCancel(){var i;this.scripts[this.state.selected]=this.getScriptFromObject(this.state.selected),this.lastKnownTs[this.state.selected]=((i=this.props.objects[this.state.selected])==null?void 0:i.ts)||0;const s={...this.state.changed};s[this.state.selected]=!1,this.setState({changed:s},()=>this.setChangedInAdmin())}onRegisterSelect(s){this.getSelect=s}onConvertBlockly2JS(){this.showConfirmDialog(x.I18n.t("It will not be possible to revert this operation."),s=>{if(s){this.scripts[this.state.selected].engineType="Javascript/js";const r=this.scripts[this.state.selected].source.split(` +`}),m.jsx("div",{style:cc.connecting,children:m.jsx("svg",{style:cc.spinner,width:"100%",height:"100%",viewBox:"0 0 66 66",xmlns:"http://www.w3.org/2000/svg",children:m.jsx("circle",{style:cc.path,fill:"none",strokeWidth:"6",strokeLinecap:"round",cx:"33",cy:"33",r:"30"})})})]})}const vg=[UA,HA,WA,GA],YA=_e.lazy(()=>Fn(()=>Promise.resolve().then(()=>CO),void 0,import.meta.url)),KA=_e.lazy(()=>Fn(()=>import("./index-DqPwE1_T.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13]),import.meta.url)),JA=_e.lazy(()=>Fn(()=>import("./index-Dl-EtX3d.js"),__vite__mapDeps([14,1,2,3,4,6,7,5,15,8,9,10,11,12]),import.meta.url)),XA=_e.lazy(()=>Fn(()=>import("./ScriptEditorVanillaMonaco-DSYvOslZ.js"),__vite__mapDeps([15,1,2,3,4,6,7,5]),import.meta.url)),qA=_e.lazy(()=>Fn(()=>import("./ScriptEditor-C-fO5h68.js"),__vite__mapDeps([16,1,2,3,4,6,5,15,7,17]),import.meta.url)),ZA=_e.lazy(()=>Fn(()=>import("./OpenAiDialog-CdW_zvS-.js"),__vite__mapDeps([18,1,2,3,4,6,5,9,19,15,7,8,10,11,12]),import.meta.url)),uw={Blockly:mk,"Javascript/js":Sc,Rules:$k,def:Sc,"TypeScript/ts":fk},QA=48,dw="#02a102",yg="#70aae9",eO=Sw[400],tO=Ew[400],Fe={toolbar:a=>({minHeight:38,boxShadow:"0px 2px 4px -1px rgba(0, 0, 0, 0.2), 0px 4px 5px 0px rgba(0, 0, 0, 0.14), 0px 1px 10px 0px rgba(0, 0, 0, 0.12)",backgroundColor:a.palette.mode==="dark"?"#1e1e1e":"#E2E2E2"}),toolbarButtons:{padding:4,marginLeft:4},toolbarButtonsDisabled:{filter:"grayscale(100%)",opacity:.5},editorDiv:a=>({height:`calc(100% - ${(parseInt(a.toolbar.height,10)||48)+38+10}px)`,width:"100%",overflow:"hidden",position:"relative"}),textButton:{marginRight:10,minHeight:24,padding:"6px 16px",height:32},saveButton:{background:"#ff9900"},tabIcon:{width:24,height:24,verticalAlign:"middle",marginBottom:2,marginRight:2,borderRadius:3},hintIcon:{padding:"0 8px 0 8px"},hintButton:{marginTop:8,marginLeft:20},tabMenuButton:{position:"absolute",top:0,right:0},tabChanged:a=>({color:a.palette.secondary.main}),tabText:{maxWidth:130,textOverflow:"ellipsis",whiteSpace:"nowrap",overflow:"hidden",display:"inline-block",verticalAlign:"middle"},tabChangedIcon:{color:"#FF0000",fontSize:16,marginLeft:5},closeButton:{marginLeft:5},notRunning:{color:"#ffbc00",marginRight:8,marginLeft:8},tabButton:{minHeight:48},tabButtonWrapper:{display:"inline-block"},menuIcon:{width:18,height:18,borderRadius:2,marginRight:5}};class On extends _e.Component{getSelect=null;changedMirror={};cron={initValue:null,callback:null};scriptDialog={initValue:null,callback:null,args:null,isReturn:!1};objects;scripts;selectId={initValue:null,callback:null};confirmCallback=null;lastKnownTs={};constructor(s){var c,d;super(s);let i=window.localStorage.getItem("Editor.selected")||"";const r=window.localStorage.getItem("Editor.editing")||"[]";let l;try{l=JSON.parse(r)}catch{l=[]}i&&!l.includes(i)&&l.push(i),i&&!this.props.password&&((d=(c=this.props.objects[i])==null?void 0:c.native)!=null&&d.protected)&&(i=l.find(h=>{var p,f;return!((f=(p=this.props.objects[h])==null?void 0:p.native)!=null&&f.protected)})||""),!i&&l.length&&(this.props.password?i=l[0]:i=l.find(h=>{var p,f;return!((f=(p=this.props.objects[h])==null?void 0:p.native)!=null&&f.protected)})||""),this.state={askAboutDebug:!1,astroEvents:null,blockly:null,changed:{},cmdToBlockly:"",cmdToRules:"",confirm:"",debugEnabled:!1,editing:l,insert:"",instancesLoaded:!1,isTourOpen:window.localStorage.getItem("tour")!=="true",menuDebugAnchorEl:null,menuOidDisplayAnchorEl:null,oidDisplayMode:parseInt(window.localStorage.getItem("Blockly.FieldOID.displayMode")||"0",10)||0,oidShowIcon:window.localStorage.getItem("Blockly.FieldOID.showIcon")==="true",menuOpened:!!this.props.menuOpened,menuTabsOpened:!1,openAiDialog:!1,triggerPrettier:1,scriptConflict:"",rules:null,runningInstances:this.props.runningInstances||{},searchText:"",selected:i,showAdapterDebug:!1,showAstro:!1,showCompiledCode:!1,showCron:!1,showDebugMenu:!1,showScript:!1,showSelectId:!1,themeType:this.props.themeType,toast:"",tourStep:Ms.selectTriggers,verboseEnabled:!1,visible:s.visible},this.setChangedInAdmin(),window.systemLang=x.I18n.getLanguage(),window.main={objects:{},getObject:(h,p)=>this.props.socket.getObject(h).then(f=>p==null?void 0:p(null,f)).catch(f=>p==null?void 0:p(f)),instances:[],selectIdDialog:(h,p,f)=>{typeof p=="function"&&(f=p,p=null),this.selectId.callback=f,this.selectId.initValue=h,this.selectId.type=p,this.setState({showSelectId:!0})},cronDialog:(h,p)=>{this.cron.callback=p,this.cron.initValue=h,this.setState({showCron:!0})},showScriptDialog:(h,p,f,b)=>{this.scriptDialog.callback=b,this.scriptDialog.initValue=h,this.scriptDialog.args=p,this.scriptDialog.isReturn=f||!1,this.setState({showScript:!0})}},this.objects=s.objects,this.scripts={},this.getAllAdapterInstances().then(()=>{this.props.onSelectedChange&&this.state.selected&&setTimeout(()=>this.props.onSelectedChange(this.state.selected,this.state.editing),100)})}async getAllAdapterInstances(){const s=await this.props.socket.getAdapterInstances(!0),i={},r=s.map(l=>(i[l._id]=l,l._id));window.main.objects=i,window.main.instances=r,this.setState({instancesLoaded:!0})}static onInstanceChanged(s,i){if(s)if(!i&&window.main.instances.includes(s)){delete window.main.objects[s];const r=window.main.instances.indexOf(s);window.main.instances.splice(r,1)}else(i==null?void 0:i.type)==="instance"&&(window.main.instances.includes(s)||(window.main.instances.push(s),window.main.instances.sort()),window.main.objects[s]=i)}setChangedInAdmin(){const s=Object.keys(this.state.changed).find(i=>this.state.changed[i]);Object.keys(this.state.changed).forEach(i=>{this.changedMirror[i]=this.state.changed[i]}),Object.keys(this.changedMirror).forEach(i=>{this.state.changed[i]===void 0&&delete this.changedMirror[i]}),this.props.onChangedChanged(this.changedMirror),typeof window.parent<"u"&&window.parent&&(window.parent.configNotSaved=!!s)}componentDidMount(){window.addEventListener("beforeunload",this.onBrowserClose,!1),this.props.socket.subscribeObject("system.adapter.*",On.onInstanceChanged)}componentWillUnmount(){window.removeEventListener("beforeunload",this.onBrowserClose),this.props.socket.unsubscribeObject("system.adapter.*",On.onInstanceChanged)}componentDidUpdate(s){if(s.scriptsHash!==this.props.scriptsHash)for(const i of this.state.editing){const r=this.props.objects[i];if(!r||r.type!=="script")continue;const l=r.ts||0,c=this.lastKnownTs[i];c!==void 0&&l!==c&&(this.state.changed[i]?this.state.scriptConflict||this.setState({scriptConflict:i}):(this.scripts[i]=this.getScriptFromObject(i),this.lastKnownTs[i]=l))}}onBrowserClose=s=>{const i=Object.keys(this.scripts).find(r=>JSON.stringify(this.scripts[r])!==JSON.stringify(this.getScriptFromObject(r)));if(i){console.log(`Script ${JSON.stringify(this.scripts[i])}`);const r=x.I18n.t("Configuration not saved.");return s=s||window.event,s&&(s.returnValue=r),r}};removeNonExistingScripts(s,i){s=s||this.props,i=i||{};let r=!1;if(this.state.editing&&this.state.editing.find(c=>s&&!s.objects[c])){const c=[...this.state.editing];for(let d=c.length-1;d>=0;d--)this.objects[c[d]]||(r=!0,c.splice(d,1));r&&(i.editing=c),this.state.selected&&!this.objects[this.state.selected]&&(r=!0,i.selected=c[0]||"",i.selected&&this.scripts[i.selected]&&(this.state.blockly!==(this.scripts[i.selected].engineType==="Blockly")&&(i.blockly=this.scripts[i.selected].engineType==="Blockly",r=!0),this.state.rules!==(this.scripts[i.selected].engineType==="Rules")&&(i.rules=this.scripts[i.selected].engineType==="Rules",r=!0),this.state.verboseEnabled!==this.scripts[i.selected].verbose&&(i.verboseEnabled=this.scripts[i.selected].verbose,r=!0),this.state.debugEnabled!==this.scripts[i.selected].debug&&(i.debugEnabled=this.scripts[i.selected].debug,r=!0)))}return r}UNSAFE_componentWillReceiveProps(s){var l,c,d;const i={};let r=!1;if(JSON.stringify(s.runningInstances)!==JSON.stringify(this.state.runningInstances)&&(r=!0,i.runningInstances=s.runningInstances),this.state.menuOpened!==s.menuOpened&&(i.menuOpened=s.menuOpened,r=!0),this.state.themeType!==s.themeType&&(i.themeType=s.themeType,r=!0),this.removeNonExistingScripts(s,i)&&(r=!0),this.state.searchText!==s.searchText&&(i.searchText=s.searchText,r=!0),this.objects!==s.objects){this.objects=s.objects,window.main.objects=s.objects,Object.keys(this.scripts).forEach(p=>{const f=this.scripts[p].source;this.scripts[p]=JSON.parse(JSON.stringify(this.objects[p].common)),this.scripts[p].source=f}),this.state.selected&&this.objects[this.state.selected]&&(this.scripts[this.state.selected]||=JSON.parse(JSON.stringify(this.objects[this.state.selected].common)),this.state.blockly!==(this.scripts[this.state.selected].engineType==="Blockly")&&(i.blockly=this.scripts[this.state.selected].engineType==="Blockly",r=!0),this.state.rules!==(this.scripts[this.state.selected].engineType==="Rules")&&(i.rules=this.scripts[this.state.selected].engineType==="Rules",r=!0),this.state.verboseEnabled!==this.scripts[this.state.selected].verbose&&(i.verboseEnabled=this.scripts[this.state.selected].verbose,r=!0),this.state.debugEnabled!==this.scripts[this.state.selected].debug&&(i.debugEnabled=this.scripts[this.state.selected].debug,r=!0));const h=[...this.state.editing];for(let p=h.length-1;p>=0;p--)this.objects[h[p]]||(r=!0,h.splice(p,1),this.state.changed[h[p]]!==void 0&&(i.changed||={...this.state.changed},i.changed&&delete i.changed[h[p]]));this.state.selected&&!this.objects[this.state.selected]&&(i.selected=h[0]||""),r&&(i.editing=h)}else for(const h in this.scripts)if(Object.prototype.hasOwnProperty.call(this.scripts,h)){if((l=this.objects[h])!=null&&l.common){if(this.objects[h].type==="script"){const p=this.scripts[h].source,f=JSON.parse(JSON.stringify(this.scripts[h]));f.source=this.objects[h].common.source,JSON.stringify(f)!==JSON.stringify(this.objects[h].common)&&(this.scripts[h]=JSON.parse(JSON.stringify(this.objects[h].common)),this.scripts[h].source=p),p!==this.objects[h].common.source?this.state.changed[h]?(d=this.objects[h].from)!=null&&d.startsWith("system.adapter.javascript.")&&(this.objects[h].from="system.adapter.admin.0",this.setState({toast:x.I18n.t("Script %s was modified on disk.",h.split(".").pop())})):this.props.password&&((c=this.objects[h].native)!=null&&c.protected)?this.scripts[h].source=Jg(this.props.password,this.objects[h].common.source):this.scripts[h].source=this.objects[h].common.source:this.state.changed[h]&&(i.changed||={...this.state.changed},i.changed&&(i.changed[h]=!1),r=!0)}}else if(this.scripts[h]&&(delete this.scripts[h],this.state.selected===h)){if(this.state.editing.indexOf(h)!==-1){const p=[...this.state.editing],f=p.indexOf(h);f!==-1&&(p.splice(f,1),i.editing=p,r=!0)}i.selected=this.state.editing[0]||"",r=!0}}if(s.selected&&this.state.selected!==s.selected){const h=this.getScriptFromObject(s.selected);this.scripts[s.selected]||=h;const p=h&&JSON.stringify(this.scripts[s.selected])!==JSON.stringify(h),f=[...this.state.editing];s.selected&&!f.includes(s.selected)&&(f.push(s.selected),this.props.onSelectedChange(s.selected,f),window.localStorage.setItem("Editor.editing",JSON.stringify(f))),r=!0,i.changed||={...this.state.changed},i.changed[s.selected]=!!p,i.editing=f,i.selected=s.selected,i.blockly=this.scripts[s.selected].engineType==="Blockly",i.rules=this.scripts[s.selected].engineType==="Rules",i.verboseEnabled=this.scripts[s.selected].verbose,i.debugEnabled=this.scripts[s.selected].debug,i.showCompiledCode=!1}this.state.visible!==s.visible&&(r=!0,i.visible=s.visible),r&&this.setState(i,()=>this.setChangedInAdmin())}onRestart(){var s,i;(i=(s=this.props).onRestart)==null||i.call(s,this.state.selected)}onStartStop(){var i,r,l;const s=JSON.parse(JSON.stringify(this.scripts[this.state.selected]));s.enabled=!s.enabled,this.props.password&&((i=this.props.objects[this.state.selected].native)!=null&&i.protected)&&(s.source=yc(this.props.password,s.source)),(l=(r=this.props).onChange)==null||l.call(r,this.state.selected,s)}onSave(){if(this.state.isTourOpen&&this.state.tourStep===Ms.saveTheScript&&(this.setState({isTourOpen:!1}),window.localStorage.setItem("tour","true")),this.state.changed[this.state.selected]){const s={...this.state.changed};s[this.state.selected]=!1,this.setState({changed:s},()=>{var r,l,c;this.setChangedInAdmin();const i=JSON.parse(JSON.stringify(this.scripts[this.state.selected]));this.props.password&&((r=this.props.objects[this.state.selected].native)!=null&&r.protected)&&(i.source=yc(this.props.password,i.source)),(c=(l=this.props).onChange)==null||c.call(l,this.state.selected,i)})}}onSaveAll(){const s={...this.state.changed};Object.keys(s).forEach(i=>{var r,l,c;if(s[i]){s[i]=!1;const d=JSON.parse(JSON.stringify(this.scripts[i]));this.props.password&&((r=this.props.objects[i].native)!=null&&r.protected)&&(d.source=yc(this.props.password,d.source)),(c=(l=this.props).onChange)==null||c.call(l,i,d)}}),this.setState({changed:s},()=>this.setChangedInAdmin())}onCancel(){var i;this.scripts[this.state.selected]=this.getScriptFromObject(this.state.selected),this.lastKnownTs[this.state.selected]=((i=this.props.objects[this.state.selected])==null?void 0:i.ts)||0;const s={...this.state.changed};s[this.state.selected]=!1,this.setState({changed:s},()=>this.setChangedInAdmin())}onRegisterSelect(s){this.getSelect=s}onConvertBlockly2JS(){this.showConfirmDialog(x.I18n.t("It will not be possible to revert this operation."),s=>{if(s){this.scripts[this.state.selected].engineType="Javascript/js";const r=this.scripts[this.state.selected].source.split(` `);r.pop(),this.scripts[this.state.selected].source=r.join(` -`);const l=this.state.selected,c={...this.state.changed};c[this.state.selected]=!0,this.setState({changed:c,blockly:!1,selected:""},()=>{this.setChangedInAdmin(),setTimeout(()=>this.setState({selected:l}),100)})}})}onChange(s){if(s.script!==void 0){if(s.script===this.scripts[this.state.selected].source)return;this.scripts[this.state.selected].source=s.script}s.debug!==void 0&&(this.scripts[this.state.selected].debug=s.debug),s.verbose!==void 0&&(this.scripts[this.state.selected].verbose=s.verbose);const i=JSON.stringify(this.scripts[this.state.selected])!==JSON.stringify(this.getScriptFromObject(this.state.selected));if(i!==!!this.state.changed[this.state.selected]){const r={...this.state.changed};r[this.state.selected]=i,this.objects[this.state.selected].from="system.adapter.admin.0",this.setState({changed:r},()=>this.setChangedInAdmin())}}onTabChange(s){var r,l;if(this.props.debugMode)return;window.localStorage.setItem("Editor.selected",s);const i=this.scripts[s]||this.getScriptFromObject(s);this.scripts[s]||(this.scripts[s]=i),this.lastKnownTs[s]===void 0&&this.props.objects[s]&&(this.lastKnownTs[s]=this.props.objects[s].ts||0),this.setState({selected:s,rules:i.engineType==="Rules",blockly:i.engineType==="Blockly",showCompiledCode:!1,verboseEnabled:i.verbose,debugEnabled:i.debug}),(l=(r=this.props).onSelectedChange)==null||l.call(r,s,this.state.editing)}isScriptChanged(s){return!!(this.scripts[s]&&this.props.objects[s]&&JSON.stringify(this.scripts[s])!==JSON.stringify(this.getScriptFromObject(s)))}onTabClose(s,i){i==null||i.stopPropagation();const r=this.state.editing.indexOf(s);if(this.state.editing.includes(s))if(this.isScriptChanged(s))this.showConfirmDialog(x.I18n.t("Discard changes for %s",this.props.objects[s].common.name),l=>{l&&(delete this.scripts[s],delete this.lastKnownTs[s],this.onTabClose(s))});else{const l=[...this.state.editing];l.splice(r,1);const c={editing:l};if(s===this.state.selected?l.length?r===0||l.length===1?c.selected=l[0]:c.selected=l[r-1]:c.selected="":this.state.selected&&!l.length&&(c.selected=""),window.localStorage.setItem("Editor.editing",JSON.stringify(l)),c.selected!==void 0){c.changed||={...this.state.changed},c.changed[c.selected]=this.isScriptChanged(c.selected);const d=c.selected?this.scripts[c.selected]||this.getScriptFromObject(c.selected):void 0;c.blockly=(d==null?void 0:d.engineType)==="Blockly",c.rules=(d==null?void 0:d.engineType)==="Rules",c.verboseEnabled=!!(d!=null&&d.verbose),c.debugEnabled=!!(d!=null&&d.debug),c.showCompiledCode=!1}this.setState(c,()=>{var d,h,p,f;this.setChangedInAdmin(),c.selected!==void 0?((h=(d=this.props).onSelectedChange)==null||h.call(d,c.selected,this.state.editing),window.localStorage.setItem("Editor.selected",c.selected)):(f=(p=this.props).onSelectedChange)==null||f.call(p,this.state.selected,this.state.editing)})}}showConfirmDialog(s,i){this.confirmCallback=i,this.setState({confirm:s})}sendCommandToBlockly(s){this.setState({cmdToBlockly:s},()=>setTimeout(()=>this.setState({cmdToBlockly:""}),200))}sendCommandToRules(s){this.setState({cmdToRules:s},()=>setTimeout(()=>this.setState({cmdToRules:""}),200))}static getText(s){return typeof s=="object"?s[x.I18n.getLanguage()]||s.en:s}getScriptFullName(s){var c;const i=s.split(".");i.shift(),i.shift();const r=[];let l="script.js";for(let d=0;dthis.onTabChange(i),indicatorColor:"primary",style:{position:"relative",marginLeft:10,width:this.state.editing.length>1?"calc(100% - 50px)":"100%",display:"inline-block"},textColor:"primary",variant:"scrollable",scrollButtons:"auto",allowScrollButtonsMobile:!0,children:[this.state.editing.map(s=>{var h,p;if(!this.props.objects[s]){const f=[m.jsx(wt,{sx:this.isScriptChanged(s)?Fe.tabChanged:void 0,style:Fe.tabText,children:s.split(".").pop()},"text"),m.jsx(qe,{onClick:b=>this.onTabClose(s,b),style:Fe.closeButton,size:"small",component:"span",children:m.jsx(sc,{})},"icon")];return m.jsx(qp,{wrapped:!0,href:`#${s}`,label:f,value:s,sx:{"& .MuiTab-wrapper":Fe.tabButtonWrapper}},s)}if(!this.props.password&&((h=this.props.objects[s].native)!=null&&h.protected))return null;let i=Rn.getText(this.props.objects[s].common.name)||"";const r=this.getScriptFullName(s);i.length>18&&(i=`${i.substring(0,15)}...`);const l=(p=this.getScriptFromObject(s))==null?void 0:p.source,c=this.scripts[s]&&l!==this.scripts[s].source,d=[m.jsx(wt,{sx:this.isScriptChanged(s)?Fe.tabChanged:void 0,style:Fe.tabText,children:i},"text"),c?m.jsx("span",{style:Fe.tabChangedIcon,children:"▣"},"changedSign"):null,!this.props.debugInstance&&(!this.props.debugMode||this.state.selected!==s)&&m.jsx(qe,{onClick:f=>this.onTabClose(s,f),style:Fe.closeButton,size:"small",component:"span",children:m.jsx(sc,{})},"icon")];return m.jsx(qp,{disabled:!!this.props.debugInstance||this.state.selected!==s&&this.props.debugMode,wrapped:!0,iconPosition:"start",icon:m.jsx("img",{alt:"",src:cw[this.props.objects[s].common.engineType]||cw.def,style:Fe.tabIcon},"icon"),href:`#${s}`,label:d,style:Fe.tabButton,value:s,title:r,sx:{"& .MuiTab-wrapper":Fe.tabButtonWrapper}},s)}),this.props.debugInstance?m.jsx(qp,{disabled:!1,wrapped:!0,href:`#${this.props.debugInstance.adapter}`,label:this.props.debugInstance.adapter,style:Fe.tabButton,value:this.props.debugInstance.adapter,title:this.props.debugInstance.adapter,sx:{"& .MuiTab-wrapper":Fe.tabButtonWrapper}},this.props.debugInstance.adapter):""]},"tabs1"),this.state.editing.length>1?m.jsx(qe,{href:"#","aria-label":"Close all but current",style:Fe.tabMenuButton,title:x.I18n.t("Close all but current"),"aria-haspopup":"false",onClick:s=>{const i=[this.state.selected];Object.keys(this.scripts).forEach(r=>r!==this.state.selected&&JSON.stringify(this.scripts[r])!==JSON.stringify(this.getScriptFromObject(r))&&i.push(r)),window.localStorage.setItem("Editor.editing",JSON.stringify(i)),this.setState({menuTabsOpened:!1,editing:i})},size:"medium",children:m.jsx(uS,{})},"menuButton"):null]:m.jsx(wt,{sx:Fe.toolbar,children:m.jsxs(Ue,{color:"grey",disabled:!0,style:Fe.hintButton,href:"",children:[m.jsx("span",{children:x.I18n.t("Click on this icon")},"select2"),m.jsx(dS,{style:Fe.hintIcon},"select3"),m.jsx("span",{children:x.I18n.t("for edit or create script")},"select4")]},"select1")},"tabs2")}getDebugMenu(){return this.state.showDebugMenu?m.jsxs(pm,{id:"menu-debug",anchorEl:this.state.menuDebugAnchorEl,open:this.state.showDebugMenu,onClose:()=>this.setState({showDebugMenu:!1,menuDebugAnchorEl:null}),slotProps:{root:{style:{maxHeight:YA*7.5}}},children:[m.jsxs(it,{title:x.I18n.t("debug_help"),onClick:s=>{s.stopPropagation(),s.preventDefault(),this.setState({showDebugMenu:!1,menuDebugAnchorEl:null,debugEnabled:!this.state.debugEnabled},()=>this.onChange({debug:this.state.debugEnabled}))},children:[m.jsx(wc,{checked:this.state.debugEnabled}),m.jsx(oc,{style:{...Fe.menuIcon,color:uw}}),x.I18n.t("debug_label")]},"debugEnabled"),m.jsxs(it,{title:x.I18n.t("verbose_help"),onClick:s=>{s.stopPropagation(),s.preventDefault(),this.setState({showDebugMenu:!1,menuDebugAnchorEl:null,verboseEnabled:!this.state.verboseEnabled},()=>this.onChange({verbose:this.state.verboseEnabled}))},children:[m.jsx(wc,{checked:this.state.verboseEnabled}),m.jsx(n_,{style:{...Fe.menuIcon,color:bg}}),x.I18n.t("verbose_label")]},"verboseEnabled")]},"menuDebug"):null}getDebugBadge(){return[this.state.debugEnabled&&this.state.verboseEnabled?m.jsx(oc,{style:{...Fe.menuIcon,color:bg}},"DebugVerbose"):null,this.state.debugEnabled&&!this.state.verboseEnabled?m.jsx(oc,{style:{...Fe.menuIcon,color:uw}},"DebugNoVerbose"):null,!this.state.debugEnabled&&this.state.verboseEnabled?m.jsx(n_,{style:{...Fe.menuIcon,color:bg}},"noDebugVerbose"):null]}getAskAboutDebug(){return this.state.askAboutDebug?m.jsx(x.DialogConfirm,{onClose:()=>{this.setState({askAboutDebug:!1},()=>this.props.onDebugModeChange(!0))},ok:x.I18n.t("Yes"),cancel:x.I18n.t("Cancel"),text:x.I18n.t("The script will be stopped and must be activated manually after debugging. Continue?")}):null}renderOpenAiDialog(){return this.state.openAiDialog?m.jsx(_n,{fallback:m.jsx(En,{}),children:m.jsx(KA,{adapterName:this.props.adapterName,socket:this.props.socket,runningInstances:this.state.runningInstances,themeType:this.state.themeType,onClose:()=>this.setState({openAiDialog:!1}),language:this.scripts[this.state.selected].engineType==="TypeScript/ts"?"typescript":"javascript",onAddCode:s=>this.setState({insert:s})})}):null}getToolbar(){var r,l;const s=!!(this.state.selected&&((r=this.scripts[this.state.selected])!=null&&r.engine)&&this.state.runningInstances[this.scripts[this.state.selected].engine]),i=!!(this.state.selected&&((l=this.scripts[this.state.selected])!=null&&l.enabled));if(this.state.selected){const c=Object.keys(this.state.changed).filter(h=>this.state.changed[h]).length,d=this.state.changed[this.state.selected];return m.jsxs(jT,{variant:"dense",sx:Fe.toolbar,children:[!this.props.debugInstance&&this.state.menuOpened&&this.props.onLocate&&m.jsx(qe,{style:Fe.toolbarButtons,title:x.I18n.t("Locate file"),onClick:()=>this.props.onLocate(this.state.selected),size:"medium",children:m.jsx(hS,{})},"locate"),!this.props.debugInstance&&!d&&s?m.jsx(qe,{disabled:this.props.debugMode,style:Fe.toolbarButtons,onClick:()=>this.onRestart(),title:x.I18n.t("Restart"),size:"medium",children:m.jsx(pS,{})},"restart"):null,!this.props.debugInstance&&!d?m.jsx(qe,{disabled:this.props.debugMode,onClick:()=>this.onStartStop(),title:i?x.I18n.t("Pause script"):x.I18n.t("Run script"),size:"medium",style:{...Fe.toolbarButtons,color:i?JA:qA},children:i?m.jsx(gS,{}):m.jsx(mS,{})},"start-stop"):null,!this.props.debugInstance&&!d&&!i?m.jsx("span",{style:Fe.notRunning,children:x.I18n.t("Script is not running")}):null,!d&&i&&!s?m.jsx("span",{style:Fe.notRunning,children:x.I18n.t("Instance is disabled")}):null,d?m.jsx(Ue,{color:"grey",variant:"contained",style:{...Fe.textButton,...Fe.saveButton},className:"button-save",onClick:()=>this.onSave(),endIcon:m.jsx(r_,{}),children:x.I18n.t("Save")},"save"):null,c>1||c===1&&!d?m.jsx(Ue,{color:"grey",variant:"contained",style:Fe.textButton,onClick:()=>this.onSaveAll(),endIcon:m.jsx(r_,{}),children:x.I18n.t("Save all")},"saveall"):null,d?m.jsx(Ue,{color:"grey",variant:"contained",style:Fe.textButton,onClick:()=>this.onCancel(),endIcon:m.jsx(Yc,{}),children:x.I18n.t("Cancel")},"cancel"):null,m.jsx("div",{style:{flex:2}}),!this.props.debugInstance&&!this.state.showCompiledCode&&m.jsx(qe,{style:Fe.toolbarButtons,title:x.I18n.t("Prettify the script"),onClick:()=>this.setState({triggerPrettier:this.state.triggerPrettier+1}),size:"medium",children:m.jsx(fS,{})},"prettier"),this.state.blockly&&!this.state.showCompiledCode?m.jsx(qe,{"aria-label":"Export Blocks",title:x.I18n.t("Export blocks"),style:Fe.toolbarButtons,onClick:()=>this.sendCommandToBlockly("export"),size:"medium",children:m.jsx(kc,{})},"export"):null,this.state.blockly&&!this.state.showCompiledCode&&m.jsx(qe,{"aria-label":"Import Blocks",title:x.I18n.t("Import blocks"),style:Fe.toolbarButtons,onClick:()=>this.sendCommandToBlockly("import"),size:"medium",children:m.jsx(Lg,{})},"import"),this.state.blockly&&!this.state.showCompiledCode&&m.jsx(qe,{"aria-label":"Check code",title:x.I18n.t("Check blocks"),style:Fe.toolbarButtons,onClick:()=>this.sendCommandToBlockly("check"),size:"medium",children:m.jsx($S,{})},"check"),!this.props.debugMode&&!this.state.blockly&&!this.state.rules&&!this.state.showCompiledCode?m.jsx(qe,{"aria-label":"create CRON",title:x.I18n.t("Create or edit CRON or time wizard"),style:Fe.toolbarButtons,onClick:()=>this.setState({showCron:!0}),size:"medium",children:m.jsx(bS,{})},"select-cron"):null,this.scripts[this.state.selected]&&this.scripts[this.state.selected].engineType!=="Blockly"&&this.scripts[this.state.selected].engineType!=="Rules"?m.jsx(qe,{"aria-label":"AI",title:x.I18n.t("AI code generator"),style:Fe.toolbarButtons,size:"medium",onClick:()=>this.setState({openAiDialog:!0}),children:m.jsx(vS,{})},"ai"):null,m.jsx(qe,{"aria-label":"Show astronomical events",title:x.I18n.t("Show astronomical events"),style:Fe.toolbarButtons,disabled:!s,onClick:()=>{this.setState({showAstro:!0,astroEvents:null}),this.props.socket.sendTo(this.scripts[this.state.selected].engine.replace("system.adapter.",""),"calcAstroAll",{}).then(h=>this.setState({astroEvents:h}))},size:"medium",children:m.jsx(yS,{})},"show-astro"),!this.props.debugMode&&!this.state.blockly&&!this.state.rules&&!this.state.showCompiledCode&&m.jsx(qe,{"aria-label":"select ID",title:x.I18n.t("Insert object ID"),style:Fe.toolbarButtons,onClick:()=>this.setState({showSelectId:!0}),size:"medium",children:m.jsx(_S,{})},"select-id"),this.state.blockly&&!this.state.rules&&this.state.showCompiledCode&&m.jsx(Ue,{color:"grey","aria-label":"convert to javascript",title:x.I18n.t("Convert blockly to javascript for ever."),onClick:()=>this.onConvertBlockly2JS(),children:"Blockly=>JS"},"convert2js"),this.state.rules&&!this.state.showCompiledCode&&m.jsx(qe,{"aria-label":"Export Blocks",title:x.I18n.t("Export blocks"),style:Fe.toolbarButtons,onClick:()=>this.sendCommandToRules("export"),size:"medium",children:m.jsx(kc,{})},"export"),this.state.rules&&!this.state.showCompiledCode&&m.jsx(qe,{"aria-label":"Import Blocks",title:x.I18n.t("Import blocks"),style:Fe.toolbarButtons,onClick:()=>this.sendCommandToRules("import"),size:"medium",children:m.jsx(Lg,{})},"import"),this.props.expertMode&&!d&&(this.props.debugMode||!this.state.blockly&&!this.state.rules||(this.state.blockly||this.state.rules)&&this.state.showCompiledCode)&&m.jsx(qe,{style:Fe.toolbarButtons,color:this.props.debugMode?"primary":"default",disabled:!this.props.debugMode&&!s,onClick:()=>{!this.props.debugMode&&i?this.setState({askAboutDebug:!0}):this.props.onDebugModeChange(!this.props.debugMode)},size:"medium",children:m.jsx(oc,{style:{fontSize:32}})}),(this.state.blockly||this.state.rules)&&m.jsx(Ue,{"aria-label":"blockly",title:x.I18n.t("Show javascript code"),className:"button-js-code",color:this.state.showCompiledCode?"secondary":"inherit",disabled:this.props.debugMode,style:{...Fe.toolbarButtons,...this.props.debugMode?Fe.toolbarButtonsDisabled:void 0,padding:"0 5px"},onClick:()=>{this.props.debugMode||(this.setState({showCompiledCode:!this.state.showCompiledCode}),this.state.isTourOpen&&this.state.tourStep===Ns.showJavascript&&this.setState({tourStep:Ns.switchBackToRules}),this.state.isTourOpen&&this.state.tourStep===Ns.switchBackToRules&&this.setState({tourStep:Ns.saveTheScript}))},children:m.jsx("img",{alt:this.state.blockly?"blockly2js":"rules2js",src:this.state.blockly?jA:FA})},"blockly-code"),m.jsx(qe,{disabled:this.props.debugMode,"aria-label":"Debug menu",title:x.I18n.t("Debug options"),style:Fe.toolbarButtons,onClick:h=>this.setState({showDebugMenu:!0,menuDebugAnchorEl:h.currentTarget}),size:"medium",children:m.jsx(FT,{style:Fe.badgeMargin,badgeContent:this.getDebugBadge(),children:m.jsx(wS,{})})},"debug")]},"toolbar1")}return null}getScriptEditor(){return!this.props.debugMode&&this.state.selected&&this.props.objects[this.state.selected]&&this.state.blockly!==null&&(!this.state.blockly||this.state.showCompiledCode)&&(!this.state.rules||this.state.showCompiledCode)?(this.scripts[this.state.selected]||=this.getScriptFromObject(this.state.selected),m.jsx(wt,{sx:Fe.editorDiv,children:m.jsx(_n,{fallback:m.jsx(En,{}),children:m.jsx(GA,{name:this.state.selected,adapterName:this.props.adapterName,insert:this.state.insert,onInserted:()=>this.setState({insert:""}),onForceSave:()=>this.onSave(),searchText:this.state.searchText,onRegisterSelect:s=>this.onRegisterSelect(s),readOnly:this.state.showCompiledCode,changed:this.state.changed[this.state.selected],code:this.scripts[this.state.selected].source||"",isDark:this.state.themeType==="dark",socket:this.props.socket,runningInstances:this.state.runningInstances,triggerPrettier:this.state.triggerPrettier,onChange:s=>this.onChange({script:s}),language:this.scripts[this.state.selected].engineType==="TypeScript/ts"?"typescript":"javascript"},"scriptEditor1")})},"scriptEditorDiv")):null}getBlocklyEditor(){return!this.props.debugMode&&this.state.instancesLoaded&&this.state.selected&&this.props.objects[this.state.selected]&&this.state.blockly&&!this.state.showCompiledCode&&this.state.visible?(this.scripts[this.state.selected]||=this.getScriptFromObject(this.state.selected),m.jsx(wt,{sx:Fe.editorDiv,children:m.jsx(_n,{fallback:m.jsx(En,{}),children:m.jsx(UA,{command:this.state.cmdToBlockly,themeType:this.state.themeType,searchText:this.state.searchText,code:this.scripts[this.state.selected].source||"",scriptId:this.state.selected,onChange:s=>this.onChange({script:s})},"BlocklyEditor")})},"blocklyEditorDiv")):null}getRulesEditor(){var s,i;if(!this.props.debugMode&&this.state.instancesLoaded&&this.state.selected&&this.props.objects[this.state.selected]&&this.state.rules&&!this.state.showCompiledCode&&this.state.visible){this.scripts[this.state.selected]||=this.getScriptFromObject(this.state.selected);const r=!!this.state.selected&&!!((s=this.scripts[this.state.selected])!=null&&s.engine)&&this.state.runningInstances[this.scripts[this.state.selected].engine],l=!!this.state.selected&&((i=this.scripts[this.state.selected])==null?void 0:i.enabled);return m.jsx(wt,{sx:Fe.editorDiv,children:m.jsx(_n,{fallback:m.jsx(En,{}),children:m.jsx(HA,{scriptId:this.state.selected,setTourStep:this.setTourStep,tourStep:this.state.tourStep,isTourOpen:this.state.isTourOpen,changed:this.state.changed[this.state.selected],running:r&&l,command:this.state.cmdToRules,themeType:this.state.themeType,themeName:this.props.themeName,theme:this.props.theme,searchText:this.state.searchText,resizing:this.props.resizing,code:this.scripts[this.state.selected].source||"",onChange:c=>this.onChange({script:c})},"flowEditor")})},"flowEditorDiv")}return null}getScriptConflictDialog(){var r,l;if(!this.state.scriptConflict)return null;const s=this.state.scriptConflict,i=((l=(r=this.props.objects[s])==null?void 0:r.common)==null?void 0:l.name)||s;return m.jsxs(Pt,{open:!0,onClose:()=>this.setState({scriptConflict:""}),children:[m.jsx(Xt,{children:x.I18n.t("Script was modified externally")}),m.jsx(Wt,{children:x.I18n.t('The script "%s" has been modified by another user or in another window. Do you want to reload the script or keep your local changes?',i)}),m.jsxs(Bt,{children:[m.jsx(Ue,{variant:"contained",onClick:()=>{var d;this.scripts[s]=this.getScriptFromObject(s),this.lastKnownTs[s]=((d=this.props.objects[s])==null?void 0:d.ts)||0;const c={...this.state.changed};c[s]=!1,this.setState({scriptConflict:"",changed:c},()=>this.setChangedInAdmin())},color:"primary",autoFocus:!0,children:x.I18n.t("Reload")}),m.jsx(Ue,{variant:"contained",onClick:()=>{var c;this.lastKnownTs[s]=((c=this.props.objects[s])==null?void 0:c.ts)||0,this.setState({scriptConflict:""})},color:"secondary",children:x.I18n.t("Keep my changes")})]})]},"dialogScriptConflict")}getConfirmDialog(){return this.state.confirm?m.jsx(x.DialogConfirm,{text:this.state.confirm,onClose:s=>{if(this.confirmCallback){const i=this.confirmCallback;this.confirmCallback=null,i(s)}this.setState({confirm:""})}},"dialogConfirm1"):null}getSelectIdDialog(){var s;if(this.state.showSelectId){const i=["state","channel","device","adapter","instance","enum","host","config","script","user","group"],r=["adapter","instance","enum","host","config","script","user","group"];let l=this.selectId.callback?this.selectId.initValue||"":this.getSelect&&this.getSelect()||"",c=l.indexOf("/*");c!==-1&&(l=l.substring(0,c)),c=l.indexOf("//"),c!==-1&&(l=l.substring(0,c));let d=l.match(/"([^"]+)"/);return d&&(l=d[1]),d=l.match(/'([^']+)'/),d&&(l=d[1]),m.jsx(x.DialogSelectID,{theme:this.props.theme,imagePrefix:"../..",themeName:this.props.themeName,themeType:this.state.themeType,socket:this.props.socket,selected:l,expertMode:this.selectId.type&&this.selectId.type!=="all"&&r.includes(this.selectId.type)?!0:void 0,types:((s=this.selectId)==null?void 0:s.type)==="all"?i:[this.selectId.type||"state"],onClose:()=>{this.setState({showSelectId:!1}),this.selectId.callback&&(this.selectId.callback=null)},onOk:(h,p)=>{this.selectId.initValue=null,this.selectId.callback?(this.selectId.callback(h),this.selectId.callback=null):this.setState({insert:`'${h}'/*${p}*/`})}},"dialogSelectID1")}return null}getCronDialog(){return this.state.showCron?m.jsx(x.DialogCron,{theme:this.props.theme,cron:this.cron.callback?this.cron.initValue||"":this.getSelect?this.getSelect():"* * * * *",onClose:()=>this.setState({showCron:!1}),onOk:s=>{this.cron.initValue=null,this.cron.callback?(this.cron.callback(s),this.cron.callback=null):this.setState({insert:`'${s}'`})}},"dialogCron1"):null}getAstroDialog(){return this.state.showAstro?m.jsxs(Pt,{open:!0,onClose:()=>this.setState({showAstro:!1}),children:[m.jsx(Xt,{children:x.I18n.t("Astronomical events today")}),m.jsx(Wt,{children:this.state.astroEvents?m.jsx(UT,{component:Rw,children:m.jsxs(HT,{size:"small",children:[m.jsx(WT,{children:m.jsxs(i_,{children:[m.jsx(wn,{children:x.I18n.t("Name")}),m.jsx(wn,{children:x.I18n.t("Server time")}),m.jsx(wn,{children:x.I18n.t("Description")})]})}),m.jsx(GT,{children:Object.keys(this.state.astroEvents).map(s=>{var i,r,l,c;return m.jsxs(i_,{children:[m.jsx(wn,{component:"th",scope:"row",children:s.startsWith("next")?"":s}),m.jsx(VT,{title:`${x.I18n.t("Local time")}: ${(i=this.state.astroEvents)!=null&&i[s].isValidDate?new Date((r=this.state.astroEvents)==null?void 0:r[s].date).toLocaleTimeString():"n/a"}`,children:m.jsx(wn,{align:"right",children:(l=this.state.astroEvents)!=null&&l[s].isValidDate?(c=this.state.astroEvents)==null?void 0:c[s].serverTime:"n/a"})}),m.jsx(wn,{children:x.I18n.t(s)})]},s)})})]})}):m.jsx(zT,{})}),m.jsx(Bt,{children:m.jsx(Ue,{variant:"contained",onClick:()=>this.setState({showAstro:!1}),color:"primary",startIcon:m.jsx(sc,{}),children:x.I18n.t("Close")})})]},"dialogAstro"):null}getEditorDialog(){return this.state.showScript?m.jsx(_n,{fallback:m.jsx(En,{}),children:m.jsx(VA,{adapterName:this.props.adapterName,source:this.scriptDialog.initValue||"",args:this.scriptDialog.args?this.scriptDialog.args.join(", "):"",isReturn:this.scriptDialog.isReturn,socket:this.props.socket,runningInstances:this.state.runningInstances,themeType:this.state.themeType,onClose:s=>{this.scriptDialog.initValue=null,this.scriptDialog.callback&&(s!==!1&&this.scriptDialog.callback(s||""),this.scriptDialog.callback=null),this.setState({showScript:!1})}},"scriptEditorDialog")}):null}getToast(){return m.jsx(KT,{anchorOrigin:{vertical:"bottom",horizontal:"left"},open:!!this.state.toast,autoHideDuration:6e3,onClose:()=>this.setState({toast:""}),slotProps:{content:{"aria-describedby":"message-id"}},message:m.jsx("span",{id:"message-id",children:this.state.toast}),action:[m.jsx(qe,{"aria-label":"close",color:"inherit",style:Fe.closeToast,onClick:()=>this.setState({toast:""}),size:"medium",children:m.jsx(sc,{})},"close")]},"toast")}setTourStep=s=>this.setState({tourStep:s});getTour(){return this.state.instancesLoaded&&this.state.selected&&this.props.isAnyRulesExists===1&&this.props.objects[this.state.selected]&&this.state.rules&&this.state.visible?m.jsx(Um,{steps:zA,isOpen:this.state.isTourOpen,onRequestClose:()=>{this.setState({isTourOpen:!1}),window.localStorage.setItem("tour","true"),this.props.socket.setState("javascript.0.variables.rulesTour",{val:!0,ack:!0})},goToStep:this.state.tourStep},"tour"):null}getDebug(){return this.props.debugMode?this.state.selected&&this.scripts[this.state.selected]&&this.scripts[this.state.selected].engine&&this.state.runningInstances[this.scripts[this.state.selected].engine]?m.jsx(_n,{fallback:m.jsx(En,{}),children:m.jsx(WA,{runningInstances:this.state.runningInstances,adapterName:this.props.adapterName,socket:this.props.socket,themeName:this.props.themeName,themeType:this.props.themeType,src:this.props.debugInstance?this.props.debugInstance.adapter:this.state.selected,debugInstance:this.props.debugInstance},"debugger")}):(setTimeout(()=>this.props.onDebugModeChange(!1)),null):null}getScriptFromObject(s){var r,l;if(!((r=this.props.objects[s])!=null&&r.common))return;const i=JSON.parse(JSON.stringify(this.props.objects[s].common));return(l=this.props.objects[s].native)!=null&&l.protected&&this.props.password&&(i.source=Vg(this.props.password,i.source)),i}render(){var s,i,r;return this.state.selected&&this.props.objects[this.state.selected]&&this.state.blockly===null&&this.state.rules===null&&(this.scripts[this.state.selected]||(this.scripts[this.state.selected]=this.getScriptFromObject(this.state.selected),this.lastKnownTs[this.state.selected]=((s=this.props.objects[this.state.selected])==null?void 0:s.ts)||0),setTimeout(()=>{const l={blockly:this.scripts[this.state.selected].engineType==="Blockly",rules:this.scripts[this.state.selected].engineType==="Rules",showCompiledCode:!1,debugEnabled:this.scripts[this.state.selected].debug,verboseEnabled:this.scripts[this.state.selected].verbose};this.removeNonExistingScripts(null,l),this.setState(l)},100)),this.state.selected&&!this.props.password&&((r=(i=this.props.objects[this.state.selected])==null?void 0:i.native)!=null&&r.protected)&&setTimeout(()=>{const l=this.state.editing.find(c=>{var d,h;return!((h=(d=this.props.objects[c])==null?void 0:d.native)!=null&&h.protected)})||"";Object.keys(this.scripts).forEach(c=>{var d,h;(h=(d=this.props.objects[c])==null?void 0:d.native)!=null&&h.protected&&delete this.scripts[c]}),this.setState({selected:l},()=>{var c,d;(d=(c=this.props).onSelectedChange)==null||d.call(c,l,this.state.editing),this.state.selected?window.localStorage.setItem("Editor.selected",this.state.selected):window.localStorage.removeItem("Editor.selected")})},50),!this.state.selected&&this.props.password&&this.state.editing.length&&setTimeout(()=>{const l=this.state.editing[0];this.setState({selected:l},()=>{var c,d;(d=(c=this.props).onSelectedChange)==null||d.call(c,l,this.state.editing),window.localStorage.setItem("Editor.selected",this.state.selected)})},50),[this.getTabs(),this.getToolbar(),this.getScriptEditor(),this.getAskAboutDebug(),this.getBlocklyEditor(),this.getRulesEditor(),this.getDebug(),this.getConfirmDialog(),this.getScriptConflictDialog(),this.getSelectIdDialog(),this.getCronDialog(),this.getEditorDialog(),this.getAstroDialog(),this.getDebugMenu(),this.renderOpenAiDialog(),this.getToast(),this.getTour()]}}const Jt={dialog:{height:"95%"},dropzone:{marginTop:20,width:"100%",borderWidth:5,borderStyle:"dashed",borderColor:"#d0cccc",textAlign:"center",boxSizing:"border-box",paddingTop:45,borderRadius:10,height:"calc(100% - 10px)"},dropzoneDiv:{width:"100%",height:"100%"},dropzoneRejected:{borderColor:"#970000"},dropzoneAccepted:{borderColor:"#17cd02"},icon:{height:"30%",width:"30%",color:"#eeeeee",position:"absolute",top:"50%",left:"50%",transform:"translate(-50%,-50%)",zIndex:0},iconError:{color:"#ffc3c6"},iconOk:{color:"#aaeebc"},text:{top:"50%",left:"50%",transform:"translate(-50%,-50%)",color:"#868686",position:"absolute",zIndex:1}};class Hm extends _e.Component{constructor(s){super(s),this.state={error:"",imageStatus:""}}componentDidMount(){setTimeout(()=>{var s;try{(s=window.document.getElementById("import-text-area"))==null||s.focus()}catch{}},100)}handleCancel(){this.props.onClose()}static readFileDataUrl(s,i){const r=new FileReader;r.onload=()=>{i(null,{data:r.result,name:s.name})},r.onabort=()=>{console.error("file reading was aborted"),i(x.I18n.t("file reading was aborted"))},r.onerror=l=>{console.error("file reading has failed"),i(x.I18n.t("file reading has failed: %s",l))},r.readAsDataURL(s)}handleDropFile(s){if(!(s!=null&&s.length))return;const i=s[s.length-1];i&&Hm.readFileDataUrl(i,(r,l)=>{var c;r||!l?this.setState({error:r||"No data"}):this.props.onClose(((c=l.data)==null?void 0:c.toString())||"",l.name)})}render(){const s={...Jt.dropzone,...this.state.imageStatus==="accepted"?Jt.dropzoneAccepted:this.state.imageStatus==="rejected"?Jt.dropzoneRejected:void 0};return m.jsxs(Pt,{onClose:()=>!1,maxWidth:"lg",sx:{"& .MuiDialog-paper":Jt.dialog},fullWidth:!0,open:!0,"aria-labelledby":"import-dialog-title",PaperProps:{style:{minHeight:"90%",maxHeight:"90%"}},children:[m.jsx(Xt,{id:"import-dialog-title",children:x.I18n.t("Import scripts")}),m.jsxs(Wt,{children:[m.jsx(Lw,{maxSize:5e7,onDrop:(i,r)=>{var l,c,d;i.length?this.handleDropFile(i):window.alert(((d=(c=(l=r==null?void 0:r[0])==null?void 0:l.errors)==null?void 0:c[0])==null?void 0:d.message)||x.I18n.t("ra_Cannot upload"))},multiple:!1,accept:{"application/zip":[],"application/x-zip-compressed":[]},children:({getRootProps:i,getInputProps:r,isDragActive:l,isDragReject:c})=>c?(this.state.imageStatus!=="rejected"&&this.setState({imageStatus:"rejected"}),m.jsxs("div",{style:{...s,...Jt.dropzoneDiv},...i(),children:[m.jsx("input",{...r()}),m.jsx("span",{style:Jt.text,children:x.I18n.t("Some files will be rejected")},"text"),m.jsx(Yc,{style:{...Jt.icon,...Jt.iconError}},"icon")]})):l?(this.state.imageStatus!=="accepted"&&this.setState({imageStatus:"accepted"}),m.jsxs("div",{style:{...s,...Jt.dropzoneDiv},...i(),children:[m.jsx("input",{...r()}),m.jsx("span",{style:Jt.text,children:x.I18n.t("All files will be accepted")},"text"),m.jsx(Pw,{style:{...Jt.icon,...Jt.iconOk}},"icon")]})):(this.state.imageStatus!=="wait"&&this.setState({imageStatus:"wait"}),m.jsxs("div",{style:{...s,...Jt.dropzoneDiv},...i(),children:[m.jsx("input",{...r()}),m.jsx("span",{style:Jt.text,children:x.I18n.t("Drop some files here or click...")},"text"),m.jsx(Bw,{style:Jt.icon},"icon")]}))},"image-drop"),this.state.error?m.jsx(su,{text:this.state.error,onClose:()=>this.setState({error:""})}):null]}),m.jsx(Bt,{children:m.jsx(Ue,{color:"grey",variant:"contained",onClick:()=>this.handleCancel(),startIcon:m.jsx(so,{}),children:x.I18n.t("Close")})})]})}}var Wm={exports:{}},XA=Wm.exports;(function(a,s){(function(i,r){a.exports=r()})(XA,function(){var i={},r,l,c,d,h,p,f,b,y,w,v,_,$,S,T,E,D,M,P,W,G,z,Z,he,Ce,O,K,C,Q,ve,ce,ne,me,re,B,N,te,q,se,F,Te,ae,we,Ie,Ne,Ae,We,k,X,Y,R,A,U,H,ue,V,be,pe,fe,Le,He,Be,jt,ie,Re,Ps,ze,Zo,Ze,At,Qo,io,no,Un,Io,Bs,ro,Hn,Km,pu,js,xo,gu,mu,ma,fu,Wn,fa,$u,bu,Ym,Jm,qm,Li,Xm,$a,Zm,Gn,ba,Qm,va,ef,ya,vu,yu,_a,wa,ka,Vn,tf,Pi,Kn,Ca,sf,of,nf,Do,xt,Yn,_u,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of $e)&&typeof e!="string"||`${e}`.trim()==="")throw Error('Invalid type "'+e+'". The type must be a non-empty string or a Blockly.registry.Type.');if(e=`${e}`.toLowerCase(),typeof t!="string"||t.trim()==="")throw Error('Invalid name "'+t+'". The name must be a non-empty string.');const u=t.toLowerCase();if(!o)throw Error("Can not register a null value");let g=No[e],I=ol[e];if(g||(g=No[e]=Object.create(null),I=ol[e]=Object.create(null)),l(e,o),!n&&g[u]&&g[u]!==o)throw Error('Name "'+u+'" with type "'+e+'" already registered.');g[u]=o,I[u]=t},l=function(e,t){switch(e){case String($e.FIELD):if(typeof t.fromJson!="function")throw Error('Type "'+e+'" must have a fromJson function')}},c=function(e,t){e=`${e}`.toLowerCase(),t=t.toLowerCase();const o=No[e];o&&o[t]?(delete No[e][t],delete ol[e][t]):console.warn("Unable to unregister ["+t+"]["+e+"] from the registry.")},d=function(e,t,o){e=`${e}`.toLowerCase(),t=t.toLowerCase();const n=No[e];if(!n||!n[t]){if(t="Unable to find ["+t+"]["+e+"] in the registry.",o)throw Error(t+" You must require or register a "+e+" plugin.");return console.warn(t),null}return n[t]},h=function(e,t){return e=`${e}`.toLowerCase(),t=t.toLowerCase(),(e=No[e])?!!e[t]:!1},p=function(e,t,o){return d(e,t,o)},f=function(e,t,o){return d(e,t,o)},b=function(e,t,o){e=`${e}`.toLowerCase();var n=No[e];if(!n){if(n=`Unable to find [${e}] in the registry.`,o)throw Error(`${n} You must require or register a ${e} plugin.`);return console.warn(n),null}if(!t)return n;e=ol[e],o=Object.create(null);for(const u of Object.keys(n))o[e[u]]=n[u];return o},y=function(e,t,o){return t=t.plugins[String(e)]||Ws,typeof t=="function"?t:p(e,t,o)},w=function(e,t,o,n){e=e+" was deprecated in "+t+" and will be deleted in "+o+".",n&&(e+=` -Use `+n+" instead."),gb.has(e)||(gb.add(e),console.warn(e))},v=function(){return"blockly-"+(LC++).toString(36)},_=function(){return $b.genUid()},$=function(e){return e.type===ee.BLOCK_CREATE},S=function(e){return e.type===ee.BLOCK_DELETE},T=function(e){return e.type===ee.BLOCK_CHANGE},E=function(e){return e.type===ee.BLOCK_FIELD_INTERMEDIATE_CHANGE},D=function(e){return e.type===ee.BLOCK_MOVE},M=function(e){return e.type===ee.CLICK},P=function(e){return e.type===ee.BUBBLE_OPEN},W=function(e){return e.type===ee.VIEWPORT_CHANGE},i.setRecordUndo$$module$build$src$core$events$utils=function(e){ur=e},G=function(){return ur},z=function(e){vb.fireInternal(e)},Z=function(e){if(C()){if(!po.length)try{requestAnimationFrame(()=>{setTimeout(he,0)})}catch{setTimeout(he,0)}Ce(e)}},he=function(){const e=O(po,!0);po.length=0;for(const t of e){if(!t.workspaceId)continue;let o;(o=re(t.workspaceId))==null||o.fireChangeListener(t)}},Ce=function(e){if(T(e)&&e.element==="mutation"){let t;for(t=po.length;0!n.isNull()),t||e.reverse(),e},K=function(){for(let e=0,t;t=po[e];e++)t.recordUndo=!1},i.disable$$module$build$src$core$events$utils=function(){fh++},i.enable$$module$build$src$core$events$utils=function(){fh--},C=function(){return fh===0},i.getGroup$$module$build$src$core$events$utils=function(){return bb},i.setGroup$$module$build$src$core$events$utils=function(e){vb.setGroupInternal(e)},Q=function(e){bb=typeof e=="boolean"?e?_():"":e},ve=function(e){const t=[];e=e.getDescendants(!1);for(let o=0,n;n=e[o];o++)t[o]=n.id;return t},ce=function(e,t){const o=ne(e.type);if(!o)throw Error("Unknown event type.");return o.fromJson(e,t)},ne=function(e){const t=p($e.EVENT,e);if(!t)throw Error(`Event type ${e} not found in registry.`);return t},me=function(e){if((D(e)||$(e))&&e.workspaceId){var t=re(e.workspaceId);if(!e.blockId)throw Error("Encountered a blockEvent without a proper blockId");if(e=t.getBlockById(e.blockId)){const o=ur;try{ur=!1;const n=e.getParent();if(n&&!n.hasDisabledReason($h)){const u=e.getDescendants(!1);for(let g=0,I;I=u[g];g++)I.setDisabledReason(!1,$h)}else if((e.outputConnection||e.previousConnection)&&!t.isDragging())do e.setDisabledReason(!0,$h),e=e.getNextBlock();while(e)}finally{ur=o}}}},re=function(e){return dr[e]||null},B=function(){const e=[];for(const t in dr)e.push(dr[t]);return e},N=function(e){dr[e.id]=e},te=function(e){delete dr[e.id]},q=function(){return yb},se=function(e){yb=e},F=function(){return ai},i.setSelected$$module$build$src$core$common=function(e){if(ai!==e){var t,o,n,u,g,I,L=new(ne(ee.SELECTED))((n=(t=ai)==null?void 0:t.id)!=null?n:null,(u=e==null?void 0:e.id)!=null?u:null,(I=(g=e==null?void 0:e.workspace.id)!=null?g:(o=ai)==null?void 0:o.workspace.id)!=null?I:"");z(L);var le;(le=ai)==null||le.unselect(),ai=e;var Ee;(Ee=ai)==null||Ee.select()}},Te=function(){return _b},ae=function(e){_b=e},we=function(e){for(;e.options.parentWorkspace;)e=e.options.parentWorkspace;const t=e.getParentSvg(),o=e.getCachedParentSvgSize();var n=t.parentElement;if(n instanceof HTMLElement){var u=n.offsetWidth;n=n.offsetHeight,o.width!==u&&(t.setAttribute("width",u+"px"),e.setCachedParentSvgSize(u,null)),o.height!==n&&(t.setAttribute("height",n+"px"),e.setCachedParentSvgSize(null,n)),e.resize()}},Ie=function(e,t){const o=Object.create(null),n=e.getDescendants(!0);t&&(e=e.getNextBlock())&&(e=n.indexOf(e),n.splice(e,n.length-e));for(let u=0,g;g=n[u];u++)o[g.type]?o[g.type]++:o[g.type]=1;return o},Ne=function(e){return function(){this.jsonInit(e)}},Ae=function(e){wb.defineBlocksWithJsonArrayInternal(e)},We=function(e){i.defineBlocks$$module$build$src$core$common(i.createBlockDefinitionsFromJsonArray$$module$build$src$core$common(e))},i.createBlockDefinitionsFromJsonArray$$module$build$src$core$common=function(e){const t={};for(let o=0;o>>/g,e),Th="",e=document.createElement("style"),e.id="blockly-common-style",t=document.createTextNode(t),e.appendChild(t),document.head.insertBefore(e,document.head.firstChild)))},ie=function(e,t,o){e=document.createElementNS(pr,`${e}`);for(const n in t)e.setAttribute(n,`${t[n]}`);return o&&o.appendChild(e),e},Re=function(e,t){return t=t.split(" "),t.every(o=>e.classList.contains(o))?!1:(e.classList.add(...t),!0)},Ps=function(e,t){e.classList.remove(...t.split(" "))},ze=function(e,t){return t=t.split(" "),t.every(o=>!e.classList.contains(o))?!1:(e.classList.remove(...t),!0)},Zo=function(e,t){return e.classList.contains(t)},Ze=function(e){return e&&e.parentNode?e.parentNode.removeChild(e):null},At=function(e,t){const o=t.nextSibling;if(t=t.parentNode,!t)throw Error("Reference node has no parent.");o?t.insertBefore(e,o):t.appendChild(e)},Qo=function(e,t){e.style.transform=t,e.style["-webkit-transform"]=t},io=function(){Eh++,Es||(Es=Object.create(null))},no=function(){Eh--,Eh||(Es=null)},Un=function(e){const t=e.textContent+` +`);const l=this.state.selected,c={...this.state.changed};c[this.state.selected]=!0,this.setState({changed:c,blockly:!1,selected:""},()=>{this.setChangedInAdmin(),setTimeout(()=>this.setState({selected:l}),100)})}})}onChange(s){if(s.script!==void 0){if(s.script===this.scripts[this.state.selected].source)return;this.scripts[this.state.selected].source=s.script}s.debug!==void 0&&(this.scripts[this.state.selected].debug=s.debug),s.verbose!==void 0&&(this.scripts[this.state.selected].verbose=s.verbose);const i=JSON.stringify(this.scripts[this.state.selected])!==JSON.stringify(this.getScriptFromObject(this.state.selected));if(i!==!!this.state.changed[this.state.selected]){const r={...this.state.changed};r[this.state.selected]=i,this.objects[this.state.selected].from="system.adapter.admin.0",this.setState({changed:r},()=>this.setChangedInAdmin())}}onTabChange(s){var r,l;if(this.props.debugMode)return;window.localStorage.setItem("Editor.selected",s);const i=this.scripts[s]||this.getScriptFromObject(s);this.scripts[s]||(this.scripts[s]=i),this.lastKnownTs[s]===void 0&&this.props.objects[s]&&(this.lastKnownTs[s]=this.props.objects[s].ts||0),this.setState({selected:s,rules:i.engineType==="Rules",blockly:i.engineType==="Blockly",showCompiledCode:!1,verboseEnabled:i.verbose,debugEnabled:i.debug}),(l=(r=this.props).onSelectedChange)==null||l.call(r,s,this.state.editing)}isScriptChanged(s){return!!(this.scripts[s]&&this.props.objects[s]&&JSON.stringify(this.scripts[s])!==JSON.stringify(this.getScriptFromObject(s)))}onTabClose(s,i){i==null||i.stopPropagation();const r=this.state.editing.indexOf(s);if(this.state.editing.includes(s))if(this.isScriptChanged(s))this.showConfirmDialog(x.I18n.t("Discard changes for %s",this.props.objects[s].common.name),l=>{l&&(delete this.scripts[s],delete this.lastKnownTs[s],this.onTabClose(s))});else{const l=[...this.state.editing];l.splice(r,1);const c={editing:l};if(s===this.state.selected?l.length?r===0||l.length===1?c.selected=l[0]:c.selected=l[r-1]:c.selected="":this.state.selected&&!l.length&&(c.selected=""),window.localStorage.setItem("Editor.editing",JSON.stringify(l)),c.selected!==void 0){c.changed||={...this.state.changed},c.changed[c.selected]=this.isScriptChanged(c.selected);const d=c.selected?this.scripts[c.selected]||this.getScriptFromObject(c.selected):void 0;c.blockly=(d==null?void 0:d.engineType)==="Blockly",c.rules=(d==null?void 0:d.engineType)==="Rules",c.verboseEnabled=!!(d!=null&&d.verbose),c.debugEnabled=!!(d!=null&&d.debug),c.showCompiledCode=!1}this.setState(c,()=>{var d,h,p,f;this.setChangedInAdmin(),c.selected!==void 0?((h=(d=this.props).onSelectedChange)==null||h.call(d,c.selected,this.state.editing),window.localStorage.setItem("Editor.selected",c.selected)):(f=(p=this.props).onSelectedChange)==null||f.call(p,this.state.selected,this.state.editing)})}}showConfirmDialog(s,i){this.confirmCallback=i,this.setState({confirm:s})}sendCommandToBlockly(s){this.setState({cmdToBlockly:s},()=>setTimeout(()=>this.setState({cmdToBlockly:""}),200))}sendCommandToRules(s){this.setState({cmdToRules:s},()=>setTimeout(()=>this.setState({cmdToRules:""}),200))}static getText(s){return typeof s=="object"?s[x.I18n.getLanguage()]||s.en:s}getScriptFullName(s){var c;const i=s.split(".");i.shift(),i.shift();const r=[];let l="script.js";for(let d=0;dthis.onTabChange(i),indicatorColor:"primary",style:{position:"relative",marginLeft:10,width:this.state.editing.length>1?"calc(100% - 50px)":"100%",display:"inline-block"},textColor:"primary",variant:"scrollable",scrollButtons:"auto",allowScrollButtonsMobile:!0,children:[this.state.editing.map(s=>{var h,p;if(!this.props.objects[s]){const f=[m.jsx(wt,{sx:this.isScriptChanged(s)?Fe.tabChanged:void 0,style:Fe.tabText,children:s.split(".").pop()},"text"),m.jsx(qe,{onClick:b=>this.onTabClose(s,b),style:Fe.closeButton,size:"small",component:"span",children:m.jsx(oc,{})},"icon")];return m.jsx(qp,{wrapped:!0,href:`#${s}`,label:f,value:s,sx:{"& .MuiTab-wrapper":Fe.tabButtonWrapper}},s)}if(!this.props.password&&((h=this.props.objects[s].native)!=null&&h.protected))return null;let i=On.getText(this.props.objects[s].common.name)||"";const r=this.getScriptFullName(s);i.length>18&&(i=`${i.substring(0,15)}...`);const l=(p=this.getScriptFromObject(s))==null?void 0:p.source,c=this.scripts[s]&&l!==this.scripts[s].source,d=[m.jsx(wt,{sx:this.isScriptChanged(s)?Fe.tabChanged:void 0,style:Fe.tabText,children:i},"text"),c?m.jsx("span",{style:Fe.tabChangedIcon,children:"▣"},"changedSign"):null,!this.props.debugInstance&&(!this.props.debugMode||this.state.selected!==s)&&m.jsx(qe,{onClick:f=>this.onTabClose(s,f),style:Fe.closeButton,size:"small",component:"span",children:m.jsx(oc,{})},"icon")];return m.jsx(qp,{disabled:!!this.props.debugInstance||this.state.selected!==s&&this.props.debugMode,wrapped:!0,iconPosition:"start",icon:m.jsx("img",{alt:"",src:uw[this.props.objects[s].common.engineType]||uw.def,style:Fe.tabIcon},"icon"),href:`#${s}`,label:d,style:Fe.tabButton,value:s,title:r,sx:{"& .MuiTab-wrapper":Fe.tabButtonWrapper}},s)}),this.props.debugInstance?m.jsx(qp,{disabled:!1,wrapped:!0,href:`#${this.props.debugInstance.adapter}`,label:this.props.debugInstance.adapter,style:Fe.tabButton,value:this.props.debugInstance.adapter,title:this.props.debugInstance.adapter,sx:{"& .MuiTab-wrapper":Fe.tabButtonWrapper}},this.props.debugInstance.adapter):""]},"tabs1"),this.state.editing.length>1?m.jsx(qe,{href:"#","aria-label":"Close all but current",style:Fe.tabMenuButton,title:x.I18n.t("Close all but current"),"aria-haspopup":"false",onClick:s=>{const i=[this.state.selected];Object.keys(this.scripts).forEach(r=>r!==this.state.selected&&JSON.stringify(this.scripts[r])!==JSON.stringify(this.getScriptFromObject(r))&&i.push(r)),window.localStorage.setItem("Editor.editing",JSON.stringify(i)),this.setState({menuTabsOpened:!1,editing:i})},size:"medium",children:m.jsx(dS,{})},"menuButton"):null]:m.jsx(wt,{sx:Fe.toolbar,children:m.jsxs(Ue,{color:"grey",disabled:!0,style:Fe.hintButton,href:"",children:[m.jsx("span",{children:x.I18n.t("Click on this icon")},"select2"),m.jsx(hS,{style:Fe.hintIcon},"select3"),m.jsx("span",{children:x.I18n.t("for edit or create script")},"select4")]},"select1")},"tabs2")}getDebugMenu(){return this.state.showDebugMenu?m.jsxs(kc,{id:"menu-debug",anchorEl:this.state.menuDebugAnchorEl,open:this.state.showDebugMenu,onClose:()=>this.setState({showDebugMenu:!1,menuDebugAnchorEl:null}),slotProps:{root:{style:{maxHeight:QA*7.5}}},children:[m.jsxs(tt,{title:x.I18n.t("debug_help"),onClick:s=>{s.stopPropagation(),s.preventDefault(),this.setState({showDebugMenu:!1,menuDebugAnchorEl:null,debugEnabled:!this.state.debugEnabled},()=>this.onChange({debug:this.state.debugEnabled}))},children:[m.jsx(Yr,{checked:this.state.debugEnabled}),m.jsx(ic,{style:{...Fe.menuIcon,color:dw}}),x.I18n.t("debug_label")]},"debugEnabled"),m.jsxs(tt,{title:x.I18n.t("verbose_help"),onClick:s=>{s.stopPropagation(),s.preventDefault(),this.setState({showDebugMenu:!1,menuDebugAnchorEl:null,verboseEnabled:!this.state.verboseEnabled},()=>this.onChange({verbose:this.state.verboseEnabled}))},children:[m.jsx(Yr,{checked:this.state.verboseEnabled}),m.jsx(r_,{style:{...Fe.menuIcon,color:yg}}),x.I18n.t("verbose_label")]},"verboseEnabled")]},"menuDebug"):null}getDebugBadge(){return[this.state.debugEnabled&&this.state.verboseEnabled?m.jsx(ic,{style:{...Fe.menuIcon,color:yg}},"DebugVerbose"):null,this.state.debugEnabled&&!this.state.verboseEnabled?m.jsx(ic,{style:{...Fe.menuIcon,color:dw}},"DebugNoVerbose"):null,!this.state.debugEnabled&&this.state.verboseEnabled?m.jsx(r_,{style:{...Fe.menuIcon,color:yg}},"noDebugVerbose"):null]}getAskAboutDebug(){return this.state.askAboutDebug?m.jsx(x.DialogConfirm,{onClose:()=>{this.setState({askAboutDebug:!1},()=>this.props.onDebugModeChange(!0))},ok:x.I18n.t("Yes"),cancel:x.I18n.t("Cancel"),text:x.I18n.t("The script will be stopped and must be activated manually after debugging. Continue?")}):null}renderOpenAiDialog(){return this.state.openAiDialog?m.jsx(_n,{fallback:m.jsx(En,{}),children:m.jsx(ZA,{adapterName:this.props.adapterName,socket:this.props.socket,runningInstances:this.state.runningInstances,themeType:this.state.themeType,onClose:()=>this.setState({openAiDialog:!1}),language:this.scripts[this.state.selected].engineType==="TypeScript/ts"?"typescript":"javascript",onAddCode:s=>this.setState({insert:s})})}):null}getToolbar(){var r,l;const s=!!(this.state.selected&&((r=this.scripts[this.state.selected])!=null&&r.engine)&&this.state.runningInstances[this.scripts[this.state.selected].engine]),i=!!(this.state.selected&&((l=this.scripts[this.state.selected])!=null&&l.enabled));if(this.state.selected){const c=Object.keys(this.state.changed).filter(h=>this.state.changed[h]).length,d=this.state.changed[this.state.selected];return m.jsxs(FT,{variant:"dense",sx:Fe.toolbar,children:[!this.props.debugInstance&&this.state.menuOpened&&this.props.onLocate&&m.jsx(qe,{style:Fe.toolbarButtons,title:x.I18n.t("Locate file"),onClick:()=>this.props.onLocate(this.state.selected),size:"medium",children:m.jsx(pS,{})},"locate"),!this.props.debugInstance&&!d&&s?m.jsx(qe,{disabled:this.props.debugMode,style:Fe.toolbarButtons,onClick:()=>this.onRestart(),title:x.I18n.t("Restart"),size:"medium",children:m.jsx(gS,{})},"restart"):null,!this.props.debugInstance&&!d?m.jsx(qe,{disabled:this.props.debugMode,onClick:()=>this.onStartStop(),title:i?x.I18n.t("Pause script"):x.I18n.t("Run script"),size:"medium",style:{...Fe.toolbarButtons,color:i?eO:tO},children:i?m.jsx(mS,{}):m.jsx(fS,{})},"start-stop"):null,!this.props.debugInstance&&!d&&!i?m.jsx("span",{style:Fe.notRunning,children:x.I18n.t("Script is not running")}):null,!d&&i&&!s?m.jsx("span",{style:Fe.notRunning,children:x.I18n.t("Instance is disabled")}):null,d?m.jsx(Ue,{color:"grey",variant:"contained",style:{...Fe.textButton,...Fe.saveButton},className:"button-save",onClick:()=>this.onSave(),endIcon:m.jsx(a_,{}),children:x.I18n.t("Save")},"save"):null,c>1||c===1&&!d?m.jsx(Ue,{color:"grey",variant:"contained",style:Fe.textButton,onClick:()=>this.onSaveAll(),endIcon:m.jsx(a_,{}),children:x.I18n.t("Save all")},"saveall"):null,d?m.jsx(Ue,{color:"grey",variant:"contained",style:Fe.textButton,onClick:()=>this.onCancel(),endIcon:m.jsx(Jc,{}),children:x.I18n.t("Cancel")},"cancel"):null,m.jsx("div",{style:{flex:2}}),this.state.blockly&&!this.state.showCompiledCode&&m.jsx(qe,{"aria-label":"OID display mode",title:x.I18n.t("OID display mode"),style:Fe.toolbarButtons,onClick:h=>this.setState({menuOidDisplayAnchorEl:h.currentTarget}),size:"medium",children:m.jsx("img",{src:vg[this.state.oidDisplayMode]||vg[0],alt:"OID",width:36,height:22})},"oid-display-mode"),m.jsxs(kc,{anchorEl:this.state.menuOidDisplayAnchorEl,open:!!this.state.menuOidDisplayAnchorEl,onClose:()=>this.setState({menuOidDisplayAnchorEl:null}),children:[vg.map((h,p)=>m.jsxs(tt,{selected:this.state.oidDisplayMode===p,onClick:()=>{var b,y,w;this.setState({oidDisplayMode:p,menuOidDisplayAnchorEl:null});const f=(b=window.scripts)==null?void 0:b.blocklyWorkspace;f&&((w=(y=window.Blockly)==null?void 0:y.FieldOID)!=null&&w.setDisplayMode)&&window.Blockly.FieldOID.setDisplayMode(p,f)},children:[m.jsx("img",{src:h,alt:"",width:48,height:28,style:{marginRight:8}}),(()=>{var y,w,v,_,$,T,S,E,D;const f=(v=(w=(y=window.Blockly)==null?void 0:y.FieldOID)==null?void 0:w.DISPLAY_MODE_KEYS)==null?void 0:v[p],b=["Show name","Show name path","Show ID","Show full ID"];return f&&(((T=($=(_=window.Blockly)==null?void 0:_.Words)==null?void 0:$[f])==null?void 0:T[x.I18n.getLanguage()])||((D=(E=(S=window.Blockly)==null?void 0:S.Words)==null?void 0:E[f])==null?void 0:D.en))||b[p]})()]},`oid-mode-${p}`)),m.jsx(Pg,{}),m.jsxs(tt,{onClick:()=>{var f,b,y;const h=!this.state.oidShowIcon;this.setState({oidShowIcon:h});const p=(f=window.scripts)==null?void 0:f.blocklyWorkspace;p&&((y=(b=window.Blockly)==null?void 0:b.FieldOID)!=null&&y.setShowIcon)&&window.Blockly.FieldOID.setShowIcon(h,p)},children:[m.jsx(Yr,{checked:this.state.oidShowIcon,style:{padding:0,marginRight:8}}),(()=>{var p,f,b,y,w,v;const h="oid_show_icon";return((b=(f=(p=window.Blockly)==null?void 0:p.Words)==null?void 0:f[h])==null?void 0:b[x.I18n.getLanguage()])||((v=(w=(y=window.Blockly)==null?void 0:y.Words)==null?void 0:w[h])==null?void 0:v.en)||"Show icon"})()]},"oid-show-icon")]},"menuOidDisplay"),!this.props.debugInstance&&!this.state.showCompiledCode&&m.jsx(qe,{style:Fe.toolbarButtons,title:x.I18n.t("Prettify the script"),onClick:()=>this.setState({triggerPrettier:this.state.triggerPrettier+1}),size:"medium",children:m.jsx($S,{})},"prettier"),this.state.blockly&&!this.state.showCompiledCode?m.jsx(qe,{"aria-label":"Export Blocks",title:x.I18n.t("Export blocks"),style:Fe.toolbarButtons,onClick:()=>this.sendCommandToBlockly("export"),size:"medium",children:m.jsx(Cc,{})},"export"):null,this.state.blockly&&!this.state.showCompiledCode&&m.jsx(qe,{"aria-label":"Import Blocks",title:x.I18n.t("Import blocks"),style:Fe.toolbarButtons,onClick:()=>this.sendCommandToBlockly("import"),size:"medium",children:m.jsx(jg,{})},"import"),this.state.blockly&&!this.state.showCompiledCode&&m.jsx(qe,{"aria-label":"Check code",title:x.I18n.t("Check blocks"),style:Fe.toolbarButtons,onClick:()=>this.sendCommandToBlockly("check"),size:"medium",children:m.jsx(bS,{})},"check"),!this.props.debugMode&&!this.state.blockly&&!this.state.rules&&!this.state.showCompiledCode?m.jsx(qe,{"aria-label":"create CRON",title:x.I18n.t("Create or edit CRON or time wizard"),style:Fe.toolbarButtons,onClick:()=>this.setState({showCron:!0}),size:"medium",children:m.jsx(vS,{})},"select-cron"):null,this.scripts[this.state.selected]&&this.scripts[this.state.selected].engineType!=="Blockly"&&this.scripts[this.state.selected].engineType!=="Rules"?m.jsx(qe,{"aria-label":"AI",title:x.I18n.t("AI code generator"),style:Fe.toolbarButtons,size:"medium",onClick:()=>this.setState({openAiDialog:!0}),children:m.jsx(yS,{})},"ai"):null,m.jsx(qe,{"aria-label":"Show astronomical events",title:x.I18n.t("Show astronomical events"),style:Fe.toolbarButtons,disabled:!s,onClick:()=>{this.setState({showAstro:!0,astroEvents:null}),this.props.socket.sendTo(this.scripts[this.state.selected].engine.replace("system.adapter.",""),"calcAstroAll",{}).then(h=>this.setState({astroEvents:h}))},size:"medium",children:m.jsx(_S,{})},"show-astro"),!this.props.debugMode&&!this.state.blockly&&!this.state.rules&&!this.state.showCompiledCode&&m.jsx(qe,{"aria-label":"select ID",title:x.I18n.t("Insert object ID"),style:Fe.toolbarButtons,onClick:()=>this.setState({showSelectId:!0}),size:"medium",children:m.jsx(wS,{})},"select-id"),this.state.blockly&&!this.state.rules&&this.state.showCompiledCode&&m.jsx(Ue,{color:"grey","aria-label":"convert to javascript",title:x.I18n.t("Convert blockly to javascript for ever."),onClick:()=>this.onConvertBlockly2JS(),children:"Blockly=>JS"},"convert2js"),this.state.rules&&!this.state.showCompiledCode&&m.jsx(qe,{"aria-label":"Export Blocks",title:x.I18n.t("Export blocks"),style:Fe.toolbarButtons,onClick:()=>this.sendCommandToRules("export"),size:"medium",children:m.jsx(Cc,{})},"export"),this.state.rules&&!this.state.showCompiledCode&&m.jsx(qe,{"aria-label":"Import Blocks",title:x.I18n.t("Import blocks"),style:Fe.toolbarButtons,onClick:()=>this.sendCommandToRules("import"),size:"medium",children:m.jsx(jg,{})},"import"),this.props.expertMode&&!d&&(this.props.debugMode||!this.state.blockly&&!this.state.rules||(this.state.blockly||this.state.rules)&&this.state.showCompiledCode)&&m.jsx(qe,{style:Fe.toolbarButtons,color:this.props.debugMode?"primary":"default",disabled:!this.props.debugMode&&!s,onClick:()=>{!this.props.debugMode&&i?this.setState({askAboutDebug:!0}):this.props.onDebugModeChange(!this.props.debugMode)},size:"medium",children:m.jsx(ic,{style:{fontSize:32}})}),(this.state.blockly||this.state.rules)&&m.jsx(Ue,{"aria-label":"blockly",title:x.I18n.t("Show javascript code"),className:"button-js-code",color:this.state.showCompiledCode?"secondary":"inherit",disabled:this.props.debugMode,style:{...Fe.toolbarButtons,...this.props.debugMode?Fe.toolbarButtonsDisabled:void 0,padding:"0 5px"},onClick:()=>{this.props.debugMode||(this.setState({showCompiledCode:!this.state.showCompiledCode}),this.state.isTourOpen&&this.state.tourStep===Ms.showJavascript&&this.setState({tourStep:Ms.switchBackToRules}),this.state.isTourOpen&&this.state.tourStep===Ms.switchBackToRules&&this.setState({tourStep:Ms.saveTheScript}))},children:m.jsx("img",{alt:this.state.blockly?"blockly2js":"rules2js",src:this.state.blockly?FA:zA})},"blockly-code"),m.jsx(qe,{disabled:this.props.debugMode,"aria-label":"Debug menu",title:x.I18n.t("Debug options"),style:Fe.toolbarButtons,onClick:h=>this.setState({showDebugMenu:!0,menuDebugAnchorEl:h.currentTarget}),size:"medium",children:m.jsx(zT,{style:Fe.badgeMargin,badgeContent:this.getDebugBadge(),children:m.jsx(kS,{})})},"debug")]},"toolbar1")}return null}getScriptEditor(){return!this.props.debugMode&&this.state.selected&&this.props.objects[this.state.selected]&&this.state.blockly!==null&&(!this.state.blockly||this.state.showCompiledCode)&&(!this.state.rules||this.state.showCompiledCode)?(this.scripts[this.state.selected]||=this.getScriptFromObject(this.state.selected),m.jsx(wt,{sx:Fe.editorDiv,children:m.jsx(_n,{fallback:m.jsx(En,{}),children:m.jsx(XA,{name:this.state.selected,adapterName:this.props.adapterName,insert:this.state.insert,onInserted:()=>this.setState({insert:""}),onForceSave:()=>this.onSave(),searchText:this.state.searchText,onRegisterSelect:s=>this.onRegisterSelect(s),readOnly:this.state.showCompiledCode,changed:this.state.changed[this.state.selected],code:this.scripts[this.state.selected].source||"",isDark:this.state.themeType==="dark",socket:this.props.socket,runningInstances:this.state.runningInstances,triggerPrettier:this.state.triggerPrettier,onChange:s=>this.onChange({script:s}),language:this.scripts[this.state.selected].engineType==="TypeScript/ts"?"typescript":"javascript"},"scriptEditor1")})},"scriptEditorDiv")):null}getBlocklyEditor(){return!this.props.debugMode&&this.state.instancesLoaded&&this.state.selected&&this.props.objects[this.state.selected]&&this.state.blockly&&!this.state.showCompiledCode&&this.state.visible?(this.scripts[this.state.selected]||=this.getScriptFromObject(this.state.selected),m.jsx(wt,{sx:Fe.editorDiv,children:m.jsx(_n,{fallback:m.jsx(En,{}),children:m.jsx(YA,{command:this.state.cmdToBlockly,themeType:this.state.themeType,searchText:this.state.searchText,code:this.scripts[this.state.selected].source||"",scriptId:this.state.selected,onChange:s=>this.onChange({script:s})},"BlocklyEditor")})},"blocklyEditorDiv")):null}getRulesEditor(){var s,i;if(!this.props.debugMode&&this.state.instancesLoaded&&this.state.selected&&this.props.objects[this.state.selected]&&this.state.rules&&!this.state.showCompiledCode&&this.state.visible){this.scripts[this.state.selected]||=this.getScriptFromObject(this.state.selected);const r=!!this.state.selected&&!!((s=this.scripts[this.state.selected])!=null&&s.engine)&&this.state.runningInstances[this.scripts[this.state.selected].engine],l=!!this.state.selected&&((i=this.scripts[this.state.selected])==null?void 0:i.enabled);return m.jsx(wt,{sx:Fe.editorDiv,children:m.jsx(_n,{fallback:m.jsx(En,{}),children:m.jsx(KA,{scriptId:this.state.selected,setTourStep:this.setTourStep,tourStep:this.state.tourStep,isTourOpen:this.state.isTourOpen,changed:this.state.changed[this.state.selected],running:r&&l,command:this.state.cmdToRules,themeType:this.state.themeType,themeName:this.props.themeName,theme:this.props.theme,searchText:this.state.searchText,resizing:this.props.resizing,code:this.scripts[this.state.selected].source||"",onChange:c=>this.onChange({script:c})},"flowEditor")})},"flowEditorDiv")}return null}getScriptConflictDialog(){var r,l;if(!this.state.scriptConflict)return null;const s=this.state.scriptConflict,i=((l=(r=this.props.objects[s])==null?void 0:r.common)==null?void 0:l.name)||s;return m.jsxs(Pt,{open:!0,onClose:()=>this.setState({scriptConflict:""}),children:[m.jsx(qt,{children:x.I18n.t("Script was modified externally")}),m.jsx(Wt,{children:x.I18n.t('The script "%s" has been modified by another user or in another window. Do you want to reload the script or keep your local changes?',i)}),m.jsxs(Bt,{children:[m.jsx(Ue,{variant:"contained",onClick:()=>{var d;this.scripts[s]=this.getScriptFromObject(s),this.lastKnownTs[s]=((d=this.props.objects[s])==null?void 0:d.ts)||0;const c={...this.state.changed};c[s]=!1,this.setState({scriptConflict:"",changed:c},()=>this.setChangedInAdmin())},color:"primary",autoFocus:!0,children:x.I18n.t("Reload")}),m.jsx(Ue,{variant:"contained",onClick:()=>{var c;this.lastKnownTs[s]=((c=this.props.objects[s])==null?void 0:c.ts)||0,this.setState({scriptConflict:""})},color:"secondary",children:x.I18n.t("Keep my changes")})]})]},"dialogScriptConflict")}getConfirmDialog(){return this.state.confirm?m.jsx(x.DialogConfirm,{text:this.state.confirm,onClose:s=>{if(this.confirmCallback){const i=this.confirmCallback;this.confirmCallback=null,i(s)}this.setState({confirm:""})}},"dialogConfirm1"):null}getSelectIdDialog(){var s;if(this.state.showSelectId){const i=["state","channel","device","adapter","instance","enum","host","config","script","user","group"],r=["adapter","instance","enum","host","config","script","user","group"];let l=this.selectId.callback?this.selectId.initValue||"":this.getSelect&&this.getSelect()||"",c=l.indexOf("/*");c!==-1&&(l=l.substring(0,c)),c=l.indexOf("//"),c!==-1&&(l=l.substring(0,c));let d=l.match(/"([^"]+)"/);return d&&(l=d[1]),d=l.match(/'([^']+)'/),d&&(l=d[1]),m.jsx(x.DialogSelectID,{theme:this.props.theme,imagePrefix:"../..",themeName:this.props.themeName,themeType:this.state.themeType,socket:this.props.socket,selected:l,expertMode:this.selectId.type&&this.selectId.type!=="all"&&r.includes(this.selectId.type)?!0:void 0,types:((s=this.selectId)==null?void 0:s.type)==="all"?i:[this.selectId.type||"state"],onClose:()=>{this.setState({showSelectId:!1}),this.selectId.callback&&(this.selectId.callback=null)},onOk:(h,p)=>{this.selectId.initValue=null,this.selectId.callback?(this.selectId.callback(h),this.selectId.callback=null):this.setState({insert:`'${h}'/*${p}*/`})}},"dialogSelectID1")}return null}getCronDialog(){return this.state.showCron?m.jsx(x.DialogCron,{theme:this.props.theme,cron:this.cron.callback?this.cron.initValue||"":this.getSelect?this.getSelect():"* * * * *",onClose:()=>this.setState({showCron:!1}),onOk:s=>{this.cron.initValue=null,this.cron.callback?(this.cron.callback(s),this.cron.callback=null):this.setState({insert:`'${s}'`})}},"dialogCron1"):null}getAstroDialog(){return this.state.showAstro?m.jsxs(Pt,{open:!0,onClose:()=>this.setState({showAstro:!1}),children:[m.jsx(qt,{children:x.I18n.t("Astronomical events today")}),m.jsx(Wt,{children:this.state.astroEvents?m.jsx(HT,{component:Rw,children:m.jsxs(WT,{size:"small",children:[m.jsx(GT,{children:m.jsxs(n_,{children:[m.jsx(wn,{children:x.I18n.t("Name")}),m.jsx(wn,{children:x.I18n.t("Server time")}),m.jsx(wn,{children:x.I18n.t("Description")})]})}),m.jsx(VT,{children:Object.keys(this.state.astroEvents).map(s=>{var i,r,l,c;return m.jsxs(n_,{children:[m.jsx(wn,{component:"th",scope:"row",children:s.startsWith("next")?"":s}),m.jsx(YT,{title:`${x.I18n.t("Local time")}: ${(i=this.state.astroEvents)!=null&&i[s].isValidDate?new Date((r=this.state.astroEvents)==null?void 0:r[s].date).toLocaleTimeString():"n/a"}`,children:m.jsx(wn,{align:"right",children:(l=this.state.astroEvents)!=null&&l[s].isValidDate?(c=this.state.astroEvents)==null?void 0:c[s].serverTime:"n/a"})}),m.jsx(wn,{children:x.I18n.t(s)})]},s)})})]})}):m.jsx(UT,{})}),m.jsx(Bt,{children:m.jsx(Ue,{variant:"contained",onClick:()=>this.setState({showAstro:!1}),color:"primary",startIcon:m.jsx(oc,{}),children:x.I18n.t("Close")})})]},"dialogAstro"):null}getEditorDialog(){return this.state.showScript?m.jsx(_n,{fallback:m.jsx(En,{}),children:m.jsx(qA,{adapterName:this.props.adapterName,source:this.scriptDialog.initValue||"",args:this.scriptDialog.args?this.scriptDialog.args.join(", "):"",isReturn:this.scriptDialog.isReturn,socket:this.props.socket,runningInstances:this.state.runningInstances,themeType:this.state.themeType,onClose:s=>{this.scriptDialog.initValue=null,this.scriptDialog.callback&&(s!==!1&&this.scriptDialog.callback(s||""),this.scriptDialog.callback=null),this.setState({showScript:!1})}},"scriptEditorDialog")}):null}getToast(){return m.jsx(KT,{anchorOrigin:{vertical:"bottom",horizontal:"left"},open:!!this.state.toast,autoHideDuration:6e3,onClose:()=>this.setState({toast:""}),slotProps:{content:{"aria-describedby":"message-id"}},message:m.jsx("span",{id:"message-id",children:this.state.toast}),action:[m.jsx(qe,{"aria-label":"close",color:"inherit",style:Fe.closeToast,onClick:()=>this.setState({toast:""}),size:"medium",children:m.jsx(oc,{})},"close")]},"toast")}setTourStep=s=>this.setState({tourStep:s});getTour(){return this.state.instancesLoaded&&this.state.selected&&this.props.isAnyRulesExists===1&&this.props.objects[this.state.selected]&&this.state.rules&&this.state.visible?m.jsx(Wm,{steps:VA,isOpen:this.state.isTourOpen,onRequestClose:()=>{this.setState({isTourOpen:!1}),window.localStorage.setItem("tour","true"),this.props.socket.setState("javascript.0.variables.rulesTour",{val:!0,ack:!0})},goToStep:this.state.tourStep},"tour"):null}getDebug(){return this.props.debugMode?this.state.selected&&this.scripts[this.state.selected]&&this.scripts[this.state.selected].engine&&this.state.runningInstances[this.scripts[this.state.selected].engine]?m.jsx(_n,{fallback:m.jsx(En,{}),children:m.jsx(JA,{runningInstances:this.state.runningInstances,adapterName:this.props.adapterName,socket:this.props.socket,themeName:this.props.themeName,themeType:this.props.themeType,src:this.props.debugInstance?this.props.debugInstance.adapter:this.state.selected,debugInstance:this.props.debugInstance},"debugger")}):(setTimeout(()=>this.props.onDebugModeChange(!1)),null):null}getScriptFromObject(s){var r,l;if(!((r=this.props.objects[s])!=null&&r.common))return;const i=JSON.parse(JSON.stringify(this.props.objects[s].common));return(l=this.props.objects[s].native)!=null&&l.protected&&this.props.password&&(i.source=Jg(this.props.password,i.source)),i}render(){var s,i,r;return this.state.selected&&this.props.objects[this.state.selected]&&this.state.blockly===null&&this.state.rules===null&&(this.scripts[this.state.selected]||(this.scripts[this.state.selected]=this.getScriptFromObject(this.state.selected),this.lastKnownTs[this.state.selected]=((s=this.props.objects[this.state.selected])==null?void 0:s.ts)||0),setTimeout(()=>{const l={blockly:this.scripts[this.state.selected].engineType==="Blockly",rules:this.scripts[this.state.selected].engineType==="Rules",showCompiledCode:!1,debugEnabled:this.scripts[this.state.selected].debug,verboseEnabled:this.scripts[this.state.selected].verbose};this.removeNonExistingScripts(null,l),this.setState(l)},100)),this.state.selected&&!this.props.password&&((r=(i=this.props.objects[this.state.selected])==null?void 0:i.native)!=null&&r.protected)&&setTimeout(()=>{const l=this.state.editing.find(c=>{var d,h;return!((h=(d=this.props.objects[c])==null?void 0:d.native)!=null&&h.protected)})||"";Object.keys(this.scripts).forEach(c=>{var d,h;(h=(d=this.props.objects[c])==null?void 0:d.native)!=null&&h.protected&&delete this.scripts[c]}),this.setState({selected:l},()=>{var c,d;(d=(c=this.props).onSelectedChange)==null||d.call(c,l,this.state.editing),this.state.selected?window.localStorage.setItem("Editor.selected",this.state.selected):window.localStorage.removeItem("Editor.selected")})},50),!this.state.selected&&this.props.password&&this.state.editing.length&&setTimeout(()=>{const l=this.state.editing[0];this.setState({selected:l},()=>{var c,d;(d=(c=this.props).onSelectedChange)==null||d.call(c,l,this.state.editing),window.localStorage.setItem("Editor.selected",this.state.selected)})},50),[this.getTabs(),this.getToolbar(),this.getScriptEditor(),this.getAskAboutDebug(),this.getBlocklyEditor(),this.getRulesEditor(),this.getDebug(),this.getConfirmDialog(),this.getScriptConflictDialog(),this.getSelectIdDialog(),this.getCronDialog(),this.getEditorDialog(),this.getAstroDialog(),this.getDebugMenu(),this.renderOpenAiDialog(),this.getToast(),this.getTour()]}}const Jt={dialog:{height:"95%"},dropzone:{marginTop:20,width:"100%",borderWidth:5,borderStyle:"dashed",borderColor:"#d0cccc",textAlign:"center",boxSizing:"border-box",paddingTop:45,borderRadius:10,height:"calc(100% - 10px)"},dropzoneDiv:{width:"100%",height:"100%"},dropzoneRejected:{borderColor:"#970000"},dropzoneAccepted:{borderColor:"#17cd02"},icon:{height:"30%",width:"30%",color:"#eeeeee",position:"absolute",top:"50%",left:"50%",transform:"translate(-50%,-50%)",zIndex:0},iconError:{color:"#ffc3c6"},iconOk:{color:"#aaeebc"},text:{top:"50%",left:"50%",transform:"translate(-50%,-50%)",color:"#868686",position:"absolute",zIndex:1}};class Gm extends _e.Component{constructor(s){super(s),this.state={error:"",imageStatus:""}}componentDidMount(){setTimeout(()=>{var s;try{(s=window.document.getElementById("import-text-area"))==null||s.focus()}catch{}},100)}handleCancel(){this.props.onClose()}static readFileDataUrl(s,i){const r=new FileReader;r.onload=()=>{i(null,{data:r.result,name:s.name})},r.onabort=()=>{console.error("file reading was aborted"),i(x.I18n.t("file reading was aborted"))},r.onerror=l=>{console.error("file reading has failed"),i(x.I18n.t("file reading has failed: %s",l))},r.readAsDataURL(s)}handleDropFile(s){if(!(s!=null&&s.length))return;const i=s[s.length-1];i&&Gm.readFileDataUrl(i,(r,l)=>{var c;r||!l?this.setState({error:r||"No data"}):this.props.onClose(((c=l.data)==null?void 0:c.toString())||"",l.name)})}render(){const s={...Jt.dropzone,...this.state.imageStatus==="accepted"?Jt.dropzoneAccepted:this.state.imageStatus==="rejected"?Jt.dropzoneRejected:void 0};return m.jsxs(Pt,{onClose:()=>!1,maxWidth:"lg",sx:{"& .MuiDialog-paper":Jt.dialog},fullWidth:!0,open:!0,"aria-labelledby":"import-dialog-title",PaperProps:{style:{minHeight:"90%",maxHeight:"90%"}},children:[m.jsx(qt,{id:"import-dialog-title",children:x.I18n.t("Import scripts")}),m.jsxs(Wt,{children:[m.jsx(Pw,{maxSize:5e7,onDrop:(i,r)=>{var l,c,d;i.length?this.handleDropFile(i):window.alert(((d=(c=(l=r==null?void 0:r[0])==null?void 0:l.errors)==null?void 0:c[0])==null?void 0:d.message)||x.I18n.t("ra_Cannot upload"))},multiple:!1,accept:{"application/zip":[],"application/x-zip-compressed":[]},children:({getRootProps:i,getInputProps:r,isDragActive:l,isDragReject:c})=>c?(this.state.imageStatus!=="rejected"&&this.setState({imageStatus:"rejected"}),m.jsxs("div",{style:{...s,...Jt.dropzoneDiv},...i(),children:[m.jsx("input",{...r()}),m.jsx("span",{style:Jt.text,children:x.I18n.t("Some files will be rejected")},"text"),m.jsx(Jc,{style:{...Jt.icon,...Jt.iconError}},"icon")]})):l?(this.state.imageStatus!=="accepted"&&this.setState({imageStatus:"accepted"}),m.jsxs("div",{style:{...s,...Jt.dropzoneDiv},...i(),children:[m.jsx("input",{...r()}),m.jsx("span",{style:Jt.text,children:x.I18n.t("All files will be accepted")},"text"),m.jsx(Bw,{style:{...Jt.icon,...Jt.iconOk}},"icon")]})):(this.state.imageStatus!=="wait"&&this.setState({imageStatus:"wait"}),m.jsxs("div",{style:{...s,...Jt.dropzoneDiv},...i(),children:[m.jsx("input",{...r()}),m.jsx("span",{style:Jt.text,children:x.I18n.t("Drop some files here or click...")},"text"),m.jsx(jw,{style:Jt.icon},"icon")]}))},"image-drop"),this.state.error?m.jsx(ou,{text:this.state.error,onClose:()=>this.setState({error:""})}):null]}),m.jsx(Bt,{children:m.jsx(Ue,{color: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wa,k$,C$,yd,Ga,_d,Va,wd,kd,Yi,ri,uo,Us,T$,S$,E$,Cd,Ya,I$,x$,D$,Td,Ka,Sd,Ja,A$,O$,R$,M$,Ne,Zt,St,pt,Hs,Ki,De,vt,Ed,N$,Oo,Xa,qa,Id,L$,xd,Za,Dd,Ad,P$,Od,B$,Qa,j$,F$,z$,U$,H$,Rd,W$,rr,ar,G$,Md,Nd,Ld,Pd,el,Bd,V$,Y$,K$,Ji,jd,J$,tl,ds,X$,Ro,Fd,q$,lr,zd,Ud,Hd,Wd,Gd,Vd,Yd,Kd,Jd,Xd,Z$,Q$,eb,tb,sb,ob,sl,ib,nb,qd,Zd,Qd,eh,th,sh,oh,ol,cr,ih,rb,nh,rh,ah,lh,ch,uh,dh,hh,ph,gh,ab,lb,cb,mh,ub,db,hb,pb,gb,ge;r=function(e,t,o,n){if(!(e instanceof $e)&&typeof e!="string"||`${e}`.trim()==="")throw Error('Invalid type "'+e+'". The type must be a non-empty string or a Blockly.registry.Type.');if(e=`${e}`.toLowerCase(),typeof t!="string"||t.trim()==="")throw Error('Invalid name "'+t+'". The name must be a non-empty string.');const u=t.toLowerCase();if(!o)throw Error("Can not register a null value");let g=Mo[e],I=il[e];if(g||(g=Mo[e]=Object.create(null),I=il[e]=Object.create(null)),l(e,o),!n&&g[u]&&g[u]!==o)throw Error('Name "'+u+'" with type "'+e+'" already registered.');g[u]=o,I[u]=t},l=function(e,t){switch(e){case String($e.FIELD):if(typeof t.fromJson!="function")throw Error('Type "'+e+'" must have a fromJson function')}},c=function(e,t){e=`${e}`.toLowerCase(),t=t.toLowerCase();const o=Mo[e];o&&o[t]?(delete Mo[e][t],delete il[e][t]):console.warn("Unable to unregister ["+t+"]["+e+"] from the registry.")},d=function(e,t,o){e=`${e}`.toLowerCase(),t=t.toLowerCase();const n=Mo[e];if(!n||!n[t]){if(t="Unable to find ["+t+"]["+e+"] in the registry.",o)throw Error(t+" You must require or register a "+e+" plugin.");return console.warn(t),null}return n[t]},h=function(e,t){return e=`${e}`.toLowerCase(),t=t.toLowerCase(),(e=Mo[e])?!!e[t]:!1},p=function(e,t,o){return d(e,t,o)},f=function(e,t,o){return d(e,t,o)},b=function(e,t,o){e=`${e}`.toLowerCase();var n=Mo[e];if(!n){if(n=`Unable to find [${e}] in the registry.`,o)throw Error(`${n} You must require or register a ${e} plugin.`);return console.warn(n),null}if(!t)return n;e=il[e],o=Object.create(null);for(const u of Object.keys(n))o[e[u]]=n[u];return o},y=function(e,t,o){return t=t.plugins[String(e)]||Ws,typeof t=="function"?t:p(e,t,o)},w=function(e,t,o,n){e=e+" was deprecated in "+t+" and will be deleted in "+o+".",n&&(e+=` +Use `+n+" instead."),fb.has(e)||(fb.add(e),console.warn(e))},v=function(){return"blockly-"+(PC++).toString(36)},_=function(){return vb.genUid()},$=function(e){return e.type===ee.BLOCK_CREATE},T=function(e){return e.type===ee.BLOCK_DELETE},S=function(e){return e.type===ee.BLOCK_CHANGE},E=function(e){return e.type===ee.BLOCK_FIELD_INTERMEDIATE_CHANGE},D=function(e){return e.type===ee.BLOCK_MOVE},R=function(e){return e.type===ee.CLICK},L=function(e){return e.type===ee.BUBBLE_OPEN},H=function(e){return e.type===ee.VIEWPORT_CHANGE},i.setRecordUndo$$module$build$src$core$events$utils=function(e){ur=e},G=function(){return ur},z=function(e){_b.fireInternal(e)},Z=function(e){if(C()){if(!po.length)try{requestAnimationFrame(()=>{setTimeout(he,0)})}catch{setTimeout(he,0)}Ce(e)}},he=function(){const e=M(po,!0);po.length=0;for(const t of e){if(!t.workspaceId)continue;let o;(o=re(t.workspaceId))==null||o.fireChangeListener(t)}},Ce=function(e){if(S(e)&&e.element==="mutation"){let t;for(t=po.length;0!n.isNull()),t||e.reverse(),e},Y=function(){for(let e=0,t;t=po[e];e++)t.recordUndo=!1},i.disable$$module$build$src$core$events$utils=function(){$h++},i.enable$$module$build$src$core$events$utils=function(){$h--},C=function(){return $h===0},i.getGroup$$module$build$src$core$events$utils=function(){return yb},i.setGroup$$module$build$src$core$events$utils=function(e){_b.setGroupInternal(e)},Q=function(e){yb=typeof e=="boolean"?e?_():"":e},ve=function(e){const t=[];e=e.getDescendants(!1);for(let o=0,n;n=e[o];o++)t[o]=n.id;return t},ce=function(e,t){const o=ne(e.type);if(!o)throw Error("Unknown event type.");return o.fromJson(e,t)},ne=function(e){const t=p($e.EVENT,e);if(!t)throw Error(`Event type ${e} not found in registry.`);return t},me=function(e){if((D(e)||$(e))&&e.workspaceId){var t=re(e.workspaceId);if(!e.blockId)throw Error("Encountered a blockEvent without a proper blockId");if(e=t.getBlockById(e.blockId)){const o=ur;try{ur=!1;const n=e.getParent();if(n&&!n.hasDisabledReason(bh)){const u=e.getDescendants(!1);for(let g=0,I;I=u[g];g++)I.setDisabledReason(!1,bh)}else if((e.outputConnection||e.previousConnection)&&!t.isDragging())do e.setDisabledReason(!0,bh),e=e.getNextBlock();while(e)}finally{ur=o}}}},re=function(e){return dr[e]||null},B=function(){const e=[];for(const t in dr)e.push(dr[t]);return e},N=function(e){dr[e.id]=e},te=function(e){delete dr[e.id]},X=function(){return wb},se=function(e){wb=e},F=function(){return ai},i.setSelected$$module$build$src$core$common=function(e){if(ai!==e){var t,o,n,u,g,I,P=new(ne(ee.SELECTED))((n=(t=ai)==null?void 0:t.id)!=null?n:null,(u=e==null?void 0:e.id)!=null?u:null,(I=(g=e==null?void 0:e.workspace.id)!=null?g:(o=ai)==null?void 0:o.workspace.id)!=null?I:"");z(P);var le;(le=ai)==null||le.unselect(),ai=e;var Ee;(Ee=ai)==null||Ee.select()}},Te=function(){return kb},ae=function(e){kb=e},we=function(e){for(;e.options.parentWorkspace;)e=e.options.parentWorkspace;const t=e.getParentSvg(),o=e.getCachedParentSvgSize();var n=t.parentElement;if(n instanceof HTMLElement){var u=n.offsetWidth;n=n.offsetHeight,o.width!==u&&(t.setAttribute("width",u+"px"),e.setCachedParentSvgSize(u,null)),o.height!==n&&(t.setAttribute("height",n+"px"),e.setCachedParentSvgSize(null,n)),e.resize()}},Ie=function(e,t){const o=Object.create(null),n=e.getDescendants(!0);t&&(e=e.getNextBlock())&&(e=n.indexOf(e),n.splice(e,n.length-e));for(let u=0,g;g=n[u];u++)o[g.type]?o[g.type]++:o[g.type]=1;return o},Me=function(e){return function(){this.jsonInit(e)}},Ae=function(e){Cb.defineBlocksWithJsonArrayInternal(e)},We=function(e){i.defineBlocks$$module$build$src$core$common(i.createBlockDefinitionsFromJsonArray$$module$build$src$core$common(e))},i.createBlockDefinitionsFromJsonArray$$module$build$src$core$common=function(e){const t={};for(let o=0;o>>/g,e),Sh="",e=document.createElement("style"),e.id="blockly-common-style",t=document.createTextNode(t),e.appendChild(t),document.head.insertBefore(e,document.head.firstChild)))},ie=function(e,t,o){e=document.createElementNS(pr,`${e}`);for(const n in t)e.setAttribute(n,`${t[n]}`);return o&&o.appendChild(e),e},Oe=function(e,t){return t=t.split(" "),t.every(o=>e.classList.contains(o))?!1:(e.classList.add(...t),!0)},Ps=function(e,t){e.classList.remove(...t.split(" "))},ze=function(e,t){return t=t.split(" "),t.every(o=>!e.classList.contains(o))?!1:(e.classList.remove(...t),!0)},Zo=function(e,t){return e.classList.contains(t)},Qe=function(e){return e&&e.parentNode?e.parentNode.removeChild(e):null},At=function(e,t){const o=t.nextSibling;if(t=t.parentNode,!t)throw Error("Reference node has no parent.");o?t.insertBefore(e,o):t.appendChild(e)},Qo=function(e,t){e.style.transform=t,e.style["-webkit-transform"]=t},io=function(){Ih++,Es||(Es=Object.create(null))},no=function(){Ih--,Ih||(Es=null)},Un=function(e){const t=e.textContent+` `+e.className.baseVal;let o;if(Es&&(o=Es[t]))return o;try{o=e.getComputedTextLength()}catch{return 8*e.textContent.length}return Es&&(Es[t]=o),o},Io=function(e,t,o,n){return Bs(e,t+"pt",o,n)},Bs=function(e,t,o,n){const u=e.textContent;e=u+` -`+e.className.baseVal;var g;return Es&&(g=Es[e])||(cl||(g=document.createElement("canvas"),g.className="blocklyComputeCanvas",document.body.appendChild(g),cl=g.getContext("2d")),cl.font=o+" "+t+" "+n,g=u?cl.measureText(u).width:0,Es&&(Es[e]=g)),g},ro=function(e,t,o,n){const u=document.createElement("span");u.style.font=o+" "+t+" "+n,u.textContent=e,e=document.createElement("div"),e.style.width="1px",e.style.height="0",t=document.createElement("div"),t.style.display="flex",t.style.position="fixed",t.style.top="0",t.style.left="0",t.appendChild(u),t.appendChild(e),document.body.appendChild(t),o={height:0,baseline:0};try{t.style.alignItems="baseline",o.baseline=e.offsetTop-u.offsetTop,t.style.alignItems="flex-end",o.height=e.offsetTop-u.offsetTop}finally{document.body.removeChild(t)}return o},Hn=function(e){return Pb.getSizeInternal(e)},Km=function(e){if(js(e,"display")!=="none")return pu(e);const t=e.style,o=t.display,n=t.visibility,u=t.position;t.visibility="hidden",t.position="absolute",t.display="inline";const g=e.offsetWidth;return e=e.offsetHeight,t.display=o,t.position=u,t.visibility=n,new Xe(g,e)},pu=function(e){return new Xe(e.offsetWidth,e.offsetHeight)},js=function(e,t){return e=window.getComputedStyle(e),e[t]||e.getPropertyValue(t)},xo=function(e){const t=new ye(0,0);e=e.getBoundingClientRect();var o=document.documentElement;return o=new ye(window.pageXOffset||o.scrollLeft,window.pageYOffset||o.scrollTop),t.x=e.left+o.x,t.y=e.top+o.y,t},gu=function(){const e=document.body,t=document.documentElement;return new ye(e.scrollLeft||t.scrollLeft,e.scrollTop||t.scrollTop)},mu=function(e){const t=parseFloat(js(e,"borderLeftWidth")),o=parseFloat(js(e,"borderRightWidth")),n=parseFloat(js(e,"borderTopWidth"));return e=parseFloat(js(e,"borderBottomWidth")),new rt(n,e,t,o)},ma=function(e,t,o){e=fu(e,t,o),t.scrollLeft=e.x,t.scrollTop=e.y},fu=function(e,t,o){var n=xo(e),u=xo(t),g=mu(t);const I=n.x-u.x-g.left;return n=n.y-u.y-g.top,u=pu(e),e=t.clientWidth-u.width,u=t.clientHeight-u.height,g=t.scrollLeft,t=t.scrollTop,o?(g+=I-e/2,t+=n-u/2):(g+=Math.min(I,Math.max(I-e,0)),t+=Math.min(n,Math.max(n-u,0))),new ye(g,t)},Wn=function(e){const t=new ye(0,0);var o=e.x&&e.getAttribute("x");const n=e.y&&e.getAttribute("y");return o&&(t.x=parseInt(o)),n&&(t.y=parseInt(n)),(o=(o=e.getAttribute("transform"))&&o.match(Bb))&&(t.x+=Number(o[1]),o[3]&&(t.y+=Number(o[3]))),(e=e.getAttribute("style"))&&e.includes("translate")&&(e=e.match(jb))&&(t.x+=Number(e[1]),e[3]&&(t.y+=Number(e[3]))),t},fa=function(e){let t=0,o=0;for(;e;){const n=Wn(e);if(t+=n.x,o+=n.y,(" "+(e.getAttribute("class")||"")+" ").includes(" injectionDiv "))break;e=e.parentNode}return new ye(t,o)},$u=function(){const e=gu();return new rt(e.y,document.documentElement.clientHeight+e.y,e.x,document.documentElement.clientWidth+e.x)},bu=function(){const e=document.documentElement,t=window;return new ye(t.pageXOffset||e.scrollLeft,t.pageYOffset||e.scrollTop)},Ym=function(e,t){var o=t.x;t=t.y;const n=e.getInjectionDiv().getBoundingClientRect();return o=new ye(o-n.left,t-n.top),t=e.getOriginOffsetInPixels(),ye.difference(o,t).scale(1/e.scale)},Jm=function(e,t){var o=t.scale(e.scale);t=o.x,o=o.y;const n=e.getInjectionDiv().getBoundingClientRect();return e=e.getOriginOffsetInPixels(),new ye(t+n.left+e.x,o+n.top+e.y)},qm=function(e){({document:dl=dl,DOMParser:gr=gr,XMLSerializer:mr=mr}=e),ul=new gr,Ih=new mr},i.createElement$$module$build$src$core$utils$xml=function(e){return dl.createElementNS(Fb,e)},i.createTextNode$$module$build$src$core$utils$xml=function(e){return dl.createTextNode(e)},i.textToDom$$module$build$src$core$utils$xml=function(e){let t=ul.parseFromString(e,"text/xml");if(t&&t.documentElement&&!t.getElementsByTagName("parsererror").length)return t.documentElement;if((t=ul.parseFromString(e,"text/html"))&&t.body.firstChild&&t.body.firstChild.nodeName.toLowerCase()==="xml")return t.body.firstChild;throw Error(`DOMParser was unable to parse: ${e}`)},Li=function(e){return Xm(Ih.serializeToString(e))},Xm=function(e){return e.replace(zC,t=>`&#${t.charCodeAt(0)};`)},$a=function(e){return e?((e instanceof Element||typeof e=="string")&&(e=yu(e),e=ef(e)),Zm(e),e):null},Zm=function(e){const t=e.kind;if(e=e.contents,t&&t!==zb&&t!==xh)throw Error("Invalid toolbox kind "+t+". Please supply either "+zb+" or "+xh);if(!e)throw Error("Toolbox must have a contents attribute.")},Gn=function(e){return e?e.contents?e.contents:Array.isArray(e)&&0o.kind.toUpperCase()==="CATEGORY").length},va=function(e){return e&&e.contents?!!e.contents.filter(function(t){return t.kind.toUpperCase()==="CATEGORY"}).length:!1},ef=function(e){const t={contents:ya(e)};return e instanceof Node&&vu(e,t),t},ya=function(e){const t=[];let o=e.childNodes;o||(o=e);for(let n=0,u;u=o[n];n++){if(!u.tagName)continue;e={};const g=u.tagName.toUpperCase();e.kind=g,g==="BLOCK"?e.blockxml=u:u.childNodes&&0 document.")}else e instanceof Element&&(t=e);return t},_a=function(e,t,o,n,u,g){const I=g.scrollbar&&g.scrollbar.canScrollVertically();return e.horizontal===Zi.LEFT?(o=u.absoluteMetrics.left+o,I&&g.RTL&&(o+=yt.scrollbarThickness)):(o=u.absoluteMetrics.left+u.viewMetrics.width-t.width-o,I&&!g.RTL&&(o-=yt.scrollbarThickness)),e.vertical===$o.TOP?e=u.absoluteMetrics.top+n:(e=u.absoluteMetrics.top+u.viewMetrics.height-t.height-n,g.scrollbar&&g.scrollbar.canScrollHorizontally()&&(e-=yt.scrollbarThickness)),new rt(e,e+t.height,o,o+t.width)},wa=function(e,t){return{horizontal:t.toolboxMetrics.position===Ge.LEFT||e.horizontalLayout&&!e.RTL?Zi.RIGHT:Zi.LEFT,vertical:t.toolboxMetrics.position===Ge.BOTTOM?$o.TOP:$o.BOTTOM}},ka=function(e,t,o,n){const u=e.left,g=e.right-e.left,I=e.bottom-e.top;for(let L=0;Lg.id!==e.id).map(g=>g.getRelativeToSurfaceXY());for(;nf(ye.sum(o,n),u);)n.translate(t.RTL?-30:30,30);e.moveTo(ye.sum(o,n))},nf=function(e,t){return t.some(o=>1>=Math.abs(o.x-e.x)&&1>=Math.abs(o.y-e.y))},Do=function(e,t){e.setAttribute(WC,t)},xt=function(e,t,o){Array.isArray(o)&&(o=o.join(" ")),e.setAttribute(HC+t,`${o}`)},Yn=function(e){return e.saveState!==void 0&&e.loadState!==void 0},_u=function(e){return wu(e),rf()?(Ta(),Promise.resolve()):(Qi||(Qi=new Promise(t=>{Ph=t,Jb=window.requestAnimationFrame(()=>{Ta(),t()})})),Qi)},Ts=function(){return Qi||Promise.resolve()},ao=function(e){e||window.cancelAnimationFrame(Jb),Ta(e),!e&&Ph&&Ph()},rf=function(){return Db},wu=function(e){Mh.add(e),Lh.set(e,i.getGroup$$module$build$src$core$events$utils());const t=e.getParent();t?wu(t):ml.add(e)},Ta=function(e){const t=e?new Set([e]):new Set([...ml].map(g=>g.workspace)),o=[...ml].filter(af).filter(g=>t.has(g.workspace));for(var n of o)Cu(n);for(const g of t)g.resizeContents();for(var u of o)n=u.getRelativeToSurfaceXY(),u.updateComponentLocations(n);for(const g of o)u=i.getGroup$$module$build$src$core$events$utils(),(n=Lh.get(g))&&i.setGroup$$module$build$src$core$events$utils(n),g.bumpNeighbours(),i.setGroup$$module$build$src$core$events$utils(u);for(const g of o)ku(g);e||(Qi=null)},ku=function(e){ml.delete(e),Mh.delete(e),Lh.delete(e);for(const t of e.getChildren(!1))ku(t)},af=function(e){return!e.isDisposed()&&!e.getParent()},Cu=function(e){if(Mh.has(e)&&e.initialized){for(const t of e.getChildren(!1))Cu(t);e.renderEfficiently()}},Jn=function(e,t){qb(e,t)},lf=function(e){qb=e},Sa=function(e,t){Qb.confirmInternal(e,t)},cf=function(e,t){Xb(e,t)},uf=function(e){Xb=e},Ea=function(e,t,o){Zb(e,t,o)},df=function(e){Zb=e},Bi=function(e){return e.getProcedureDef!==void 0},hf=function(e){return e.getProcedureCall!==void 0&&e.renameProcedure!==void 0},Tu=function(e){return e.getVariableModel!==void 0},i.allUsedVarModels$$module$build$src$core$variables=function(e){e=e.getAllBlocks(!1);const t=new Set;for(let o=0;o1'),n.appendChild(o),t.push(n)),Qt.variables_get){e.sort(vr.compareByName);for(let u=0,g;g=e[u];u++)o=i.createElement$$module$build$src$core$utils$xml("block"),o.setAttribute("type","variables_get"),o.setAttribute("gap","8"),o.appendChild(ei(g)),t.push(o)}}return t},Eu=function(e){return tv.generateUniqueNameInternal(e)},pf=function(e){return xa(zh.charAt(0),e.getAllVariableNames())},xa=function(e,t){if(!t.length)return e;const o=zh;let n="",u=o.indexOf(e);for(;;){let g=!1;for(let I=0;Ig.getVariableModel().name);if(n&&(o=n.some(g=>g.toLowerCase()===e),n=n.some(g=>g.toLowerCase()===t),o&&n))return u.getName()}return null},ff=function(e,t,o){e=e.toLowerCase(),t=t.toLowerCase(),o=o.getAllBlocks(!1);for(const u of o){if(!Bi(u))continue;o=u.getProcedureDef();var n=o[1];const g=n.some(I=>I.toLowerCase()===e);if(n=n.some(I=>I.toLowerCase()===t),g&&n)return o[0]}return null},ei=function(e){const t=i.createElement$$module$build$src$core$utils$xml("field");return t.setAttribute("name","VAR"),t.setAttribute("id",e.getId()),t.setAttribute("variabletype",e.type),e=i.createTextNode$$module$build$src$core$utils$xml(e.name),t.appendChild(e),t},i.getOrCreateVariablePackage$$module$build$src$core$variables=function(e,t,o,n){let u=i.getVariable$$module$build$src$core$variables(e,t,o,n);return u||(u=$f(e,t,o,n)),u},i.getVariable$$module$build$src$core$variables=function(e,t,o,n){const u=e.getPotentialVariableMap();let g=null;if(t&&(g=e.getVariableById(t),!g&&u&&(g=u.getVariableById(t)),g))return g;if(o){if(n===void 0)throw Error("Tried to look up a variable by name without a type");g=e.getVariable(o,n),!g&&u&&(g=u.getVariable(o,n))}return g},$f=function(e,t,o,n){const u=e.getPotentialVariableMap();return o||(o=Eu(e.isFlyout?e.targetWorkspace:e)),u?u.createVariable(o,n,t):e.createVariable(o,n,t)},qn=function(e,t){e=e.getAllVariables();const o=[];if(t.length!==e.length)for(let n=0;n{le.disposed||le.setConnectionTracking(!0)},1)}return L},Au=function(e,t,{parentConnection:o,isShadow:n=!1}={}){if(!e.type)throw new sv(e);const u=t.newBlock(e.type,e.id);return u.setShadow(n),Sf(u,e),Ef(u,e),If(u,e),xf(o,u,e),Df(u,e),Af(u,e),Rf(u,e),Of(u,e),Nf(u,t.rendered),u},Tf=function(e,t){if(C())for(e=qn(e,t),t=0;tt&&(t=o[n].length);var u=-1/0;let g,I=1;do{n=u,g=e,e=[],u=o.length/I;let L=1;for(let le=0;len);return g},Ma=function(e,t,o){const n=[0],u=[];for(var g=0;gn&&(n=L,u=I)}return u?Ju(e,u,o):t},jf=function(e,t){const o=[];for(let n=0;nhv&&co()}else Cr!==hs&&(clearTimeout(bi),Vh=e.pageX,Kh=e.pageY,bi=setTimeout(Jf,pv))},Qu=function(){Cr=hs=null,co()},co=function(){kr&&(kr=!1,Tt&&(Tt.style.display="none")),bi&&(clearTimeout(bi),bi=0)},ed=function(){co(),rn=!0},td=function(){rn=!1},Vf=function(){Tt&&hs&&(typeof yl=="function"?yl(Tt,hs):Kf())},Kf=function(){var e=Hi(hs);e=i.wrap$$module$build$src$core$utils$string(e,uv),e=e.split(` -`);for(let t=0;to+window.scrollY&&(u-=Tt.offsetHeight+2*Jh),e?n=Math.max(_l-window.scrollX,n):n+Tt.offsetWidth>t+window.scrollX-2*_l&&(n=t-Tt.offsetWidth-2*_l),{x:n,y:u}},Jf=function(){if(!rn&&(Cr=hs,Tt)){Tt.textContent="",Vf();var e=hs.RTL;Tt.style.direction=e?"rtl":"ltr",Tt.style.display="block",kr=!0;var{x:t,y:o}=Yf(e);Tt.style.left=t+"px",Tt.style.top=o+"px"}},sd=function(){return qh},qf=function(e){qh=e},od=function(){return Xh},Xf=function(e){Xh=e},ti=function(e){e=`${e}`.toLowerCase().trim();var t=gv[e];if(t||(t=e.substring(0,2)==="0x"?"#"+e.substring(2):e,t=t[0]==="#"?t:"#"+t,/^#[0-9a-f]{6}$/.test(t)))return t;if(/^#[0-9a-f]{3}$/.test(t))return["#",t[1],t[1],t[2],t[2],t[3],t[3]].join("");var o=e.match(/^(?:rgb)?\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/);return o&&(e=Number(o[1]),t=Number(o[2]),o=Number(o[3]),0<=e&&256>e&&0<=t&&256>t&&0<=o&&256>o)?er(e,t,o):null},er=function(e,t,o){return t=e<<16|t<<8|o,16>e?"#"+(16777216|t).toString(16).substr(1):"#"+t.toString(16)},Pa=function(e){return e=ti(e),e?(e=parseInt(e.substr(1),16),[e>>16,e>>8&255,e&255]):[0,0,0]},Ba=function(e,t,o){let n=0,u=0,g=0;if(t===0)g=u=n=o;else{const I=Math.floor(e/60),L=e/60-I;e=o*(1-t);const le=o*(1-t*L);switch(t=o*(1-t*(1-L)),I){case 1:n=le,u=o,g=e;break;case 2:n=e,u=o,g=t;break;case 3:n=e,u=le,g=o;break;case 4:n=t,u=e,g=o;break;case 5:n=o,u=e,g=le;break;case 6:case 0:n=o,u=t,g=e}}return er(Math.floor(n),Math.floor(u),Math.floor(g))},si=function(e,t,o){return e=ti(e),!e||(t=ti(t),!t)?null:(e=Pa(e),t=Pa(t),er(Math.round(t[0]+o*(e[0]-t[0])),Math.round(t[1]+o*(e[1]-t[1])),Math.round(t[2]+o*(e[2]-t[2]))))},id=function(e){return Ba(e,qh,255*Xh)},ja=function(e,t,o){const n=[];var u=e.split("");u.push("");var g=0;e=[];let I=null;for(let Ee=0;Ee=L?(g=2,I=L,(L=e.join(""))&&n.push(L),e.length=0):L==="{"?g=3:(e.push("%",L),g=0);else if(g===2)if("0"<=L&&"9">=L)I+=L;else{var le=void 0;n.push(parseInt((le=I)!=null?le:"",10)),Ee--,g=0}else g===3&&(L===""?(e.splice(0,0,"%{"),Ee--,g=0):L!=="}"?e.push(L):(g=e.join(""),/[A-Z]\w*/i.test(g)?(L=g.toUpperCase(),(L=L.startsWith("BKY_")?L.substring(4):null)&&L in i.Msg$$module$build$src$core$msg?(g=i.Msg$$module$build$src$core$msg[L],typeof g=="string"?Array.prototype.push.apply(n,ja(g,t,o)):t?n.push(`${g}`):n.push(g)):n.push("%{"+g+"}")):n.push("%{"+g+"}"),g=e.length=0))}for((t=e.join(""))&&n.push(t),le=[],e.length=0,u=0;u=o)return{hue:o,hex:Ba(o,sd(),255*od())};if(o=ti(t))return{hue:null,hex:o};throw o='Invalid colour: "'+t+'"',e!==t&&(o+=' (from "'+e+'")'),Error(o)},oi=function(){return xs},Qf=function(e){if(xs=e,e===null){let t;(t=document.querySelector("."+kl))==null||t.remove()}},rd=function(){const e=Te()||document.body;document.querySelector("."+kl)?xs=document.querySelector("."+kl):(xs=document.createElement("div"),xs.className=kl),e.appendChild(xs)},Fa=function(e,t,o,n){if(Vi(),an=e,wl=o,o=xs){if(o.style.direction=t?"rtl":"ltr",o.style.display="block",!n&&e instanceof lt){let I;n=(I=e.getSourceBlock())==null?void 0:I.workspace}var u;Zh=(u=n)!=null?u:null;var g;e=(g=n)!=null?g:q(),ln=e.getRenderer().getClassName(),cn=e.getTheme().getClassName(),ln&&Re(o,ln),cn&&Re(o,cn)}},Vi=function(){if(ad()){an=null;var e=xs;e&&(e.style.display="none",e.style.left="",e.style.top="",wl&&wl(),wl=null,e.textContent="",ln&&(ze(e,ln),ln=""),cn&&(ze(e,cn),cn=""),q().markFocused())}},ad=function(){return!!an},ii=function(e){an===e&&Vi()},tr=function(e){Zh!==null&&Zh!==e||Vi()},ld=function(e,t,o){xs.style.left=e+"px",xs.style.top=t+"px",xs.style.height=o+"px"},cd=function(e,t,o,n){const u=t$(e,t,o);e=e$(e,t,o,n),0>u?ld(e,0,o.height+u):ld(e,u,o.height)},e$=function(e,t,o,n){return n?Math.min(Math.max(t.right-o.width,e.left),e.right-o.width):Math.max(Math.min(t.left,e.right-o.width),e.left)},t$=function(e,t,o){return t.bottom+o.height>=e.bottom?t.top-o.height:t.bottom},s$=function(e){return!(e==null||!e.repositionForWindowResize)},ud=function(){s$(an)&&an.repositionForWindowResize()||Vi()},o$=function(){return Cl},dd=function(e){Cl=e},sr=function(e,t,o,n){if(Fa(mv,o,hd,n),t.length){var u=i$(t,o,e);Tl=u,n$(u,e,o),setTimeout(function(){u.focus()},1),Cl=null}else or()},i$=function(e,t,o){const n=new Oh;n.setRole(Is.MENU);for(let u=0;u{setTimeout(()=>{g.callback(g.scope,o)},0)})},{})}return n},n$=function(e,t,o){const n=$u();t=new rt(t.clientY+n.top,t.clientY+n.top,t.clientX+n.left,t.clientX+n.left),r$(e);const u=e.getSize();o&&(t.left+=u.width,t.right+=u.width,n.left+=u.width,n.right+=u.width),cd(n,t,u,o),e.focus()},r$=function(e){var t=oi();if(!t)throw Error("Attempting to create a context menu when widget div is null");t=e.render(t),Re(t,"blocklyContextMenu"),H(t,"contextmenu",null,a$),e.focus()},a$=function(e){e.preventDefault(),e.stopPropagation()},or=function(){ii(mv),Cl=null},hd=function(){Tl&&(Tl.dispose(),Tl=null)},i.callbackFactory$$module$build$src$core$contextmenu=function(e,t){return()=>{i.disable$$module$build$src$core$events$utils();let o;try{o=t instanceof Element?ni(t,e.workspace):Fi(t,e.workspace);const n=e.getRelativeToSurfaceXY();n.x=e.RTL?n.x-i.config$$module$build$src$core$config.snapRadius:n.x+i.config$$module$build$src$core$config.snapRadius,n.y+=2*i.config$$module$build$src$core$config.snapRadius,o.moveBy(n.x,n.y)}finally{i.enable$$module$build$src$core$events$utils()}return C()&&!o.isShadow()&&z(new(ne(ee.BLOCK_CREATE))(o)),i.setSelected$$module$build$src$core$common(o),o}},pd=function(e,t){return t=fe(t,e.getParentSvg(),e.getInverseScreenCTM()),t.x/=e.scale,t.y/=e.scale,t},za=function(e,t,o){t=pd(e,t),$v.set(e,ye.difference(o,t))},Ua=function(e,t){if(t=pd(e,t),e=$v.get(e),!e)throw Error("Drag not initialized");return ye.sum(e,t)},l$=function(e,t=!1){const o=i.createElement$$module$build$src$core$utils$xml("xml");var n=gd(i.allUsedVarModels$$module$build$src$core$variables(e));n.hasChildNodes()&&o.appendChild(n);for(const u of e.getTopComments())o.appendChild(ir(u,t));for(e=e.getTopBlocks(!0),n=0;n/g,"<$1$2>")},d$=function(e){e=zs(e).split("<");let t="";for(let o=1;o"&&(t+=" ")}return e=e.join(` -`),e=e.replace(/(<(\w+)\b[^>]*>[^\n]*)\n *<\/\2>/g,"$1"),e.replace(/^\n/,"")},h$=function(e,t){return t.setResizesEnabled(!1),t.clear(),e=i.domToWorkspace$$module$build$src$core$xml(e,t),t.setResizesEnabled(!0),e},i.domToWorkspace$$module$build$src$core$xml=function(e,t){let o=0;t.RTL&&(o=t.getWidth());const n=[];io();const u=i.getGroup$$module$build$src$core$events$utils();u||i.setGroup$$module$build$src$core$events$utils(!0),t.setResizesEnabled&&t.setResizesEnabled(!1);let g=!0;try{for(let I=0,L;L=e.childNodes[I];I++){const le=L.nodeName.toLowerCase(),Ee=L;if(le==="block"||le==="shadow"&&!G()){const dt=ni(Ee,t);n.push(dt.id);let ut;const ts=parseInt((ut=Ee.getAttribute("x"))!=null?ut:"10",10);let yn;const Fr=parseInt((yn=Ee.getAttribute("y"))!=null?yn:"10",10);isNaN(ts)||isNaN(Fr)||dt.moveBy(t.RTL?o-ts:ts,Fr,["create"]),g=!1}else{if(le==="shadow")throw TypeError("Shadow block cannot be a top-level block.");if(le==="comment")fd(Ee,t);else if(le==="variables"){if(g)$d(Ee,t);else throw Error("'variables' tag must exist once before block and shadow tag elements in the workspace XML, but it was found in another location.");g=!1}}}}finally{i.setGroup$$module$build$src$core$events$utils(u),t.setResizesEnabled&&t.setResizesEnabled(!0),t.rendered&&ao(),no()}return z(new(ne(ee.FINISHED_LOADING))(t)),n},fd=function(e,t){var o;const n=(o=e.getAttribute("id"))!=null?o:void 0;o=t.rendered?new Il(t,n):new El(t,n);var u;o.setText((u=e.textContent)!=null?u:"");var g;u=parseInt((g=e.getAttribute("x"))!=null?g:"",10);let I;g=parseInt((I=e.getAttribute("y"))!=null?I:"",10),isNaN(u)||isNaN(g)||(u=t.RTL?t.getWidth()-u:u,o.moveTo(new ye(u,g)));var L;t=parseInt((L=e.getAttribute("w"))!=null?L:"",10);let le;return L=parseInt((le=e.getAttribute("h"))!=null?le:"",10),isNaN(t)||isNaN(L)||o.setSize(new Xe(t,L)),e.getAttribute("collapsed")==="true"&&o.setCollapsed(!0),e.getAttribute("editable")==="false"&&o.setEditable(!1),e.getAttribute("movable")==="false"&&o.setMovable(!1),e.getAttribute("deletable")==="false"&&o.setDeletable(!1),o},p$=function(e,t){if(!t.getBlocksBoundingBox)return i.domToWorkspace$$module$build$src$core$xml(e,t);var o=t.getBlocksBoundingBox();if(e=i.domToWorkspace$$module$build$src$core$xml(e,t),o&&o.top!==o.bottom){var n=o.bottom;o=t.RTL?o.right:o.left;var u=1/0;let g=-1/0,I=1/0;for(let L=0;Lg&&(g=le.x)}for(n=n-I+10,o=t.RTL?o-g:o-u,u=0;uEe.setBubbleVisible(g),1)}},$$=function(e,t){for(let o=0;ou}),yd(u,{x:n.x,y:n.y,width:e.width,height:e.height},t.RTL,new Date)}},yd=function(e,t,o,n){const u=(new Date().getTime()-n.getTime())/150;1o)){var n=t.getSvgXY(e.getSvgRoot());e.outputConnection?(n.x+=(e.RTL?3:-3)*o,n.y+=13*o):e.previousConnection&&(n.x+=(e.RTL?-23:23)*o,n.y+=3*o);var u=ie(J.CIRCLE,{cx:n.x,cy:n.y,r:0,fill:"none",stroke:"#888","stroke-width":10},t.getParentSvg());e=ie(J.ANIMATE,{id:"animationCircle",begin:"indefinite",attributeName:"r",dur:"150ms",from:0,to:25*o},u),t=ie(J.ANIMATE,{id:"animationOpacity",begin:"indefinite",attributeName:"opacity",dur:"150ms",from:1,to:0},u),e.beginElement(),t.beginElement(),setTimeout(()=>{Ze(u)},150)}},_d=function(e){if(Ki(),e.workspace.getAudioManager().play("disconnect"),!(1>e.workspace.scale)){var t=e.getHeightWidth().height;t=Math.atan(10/t)/Math.PI*180,e.RTL||(t*=-1),Sr=e,wd(e,t,new Date,0)}},wd=function(e,t,o,n){const u=[.66,1,.66,0,-.66,-1,-.66,0];let g="";o.getTime()+200>new Date().getTime()&&(g=`skewX(${Math.round(u[n%u.length]*t)})`,xl=setTimeout(wd,15,e,t,o,n+1)),e.getSvgRoot().setAttribute("transform",`${e.getTranslation()} ${g}`)},Ki=function(){Sr&&(xl&&(clearTimeout(xl),xl=null),Sr.getSvgRoot().setAttribute("transform",Sr.getTranslation()),Sr=null)},ri=function(e){return e.getRelativeToSurfaceXY!==void 0&&e.isMovable!==void 0&&e.startDrag!==void 0&&e.drag!==void 0&&e.endDrag!==void 0&&e.revertDrag!==void 0},uo=function(e,t){for(const o in t)e[o]=t[o]!==null&&typeof t[o]=="object"?uo(e[o]||Object.create(null),t[o]):t[o];return e},Us=function(e,t){r($e.FIELD,e,t)},k$=function(e){c($e.FIELD,e)},i.fromJson$$module$build$src$core$field_registry=function(e){return _v.fromJsonInternal(e)},C$=function(e){const t=f($e.FIELD,e.type);return t?t.fromJson(e):(console.warn("Blockly could not create a field of type "+e.type+". The field is probably not being registered. This could be because the file is not loaded, the field does not register itself (Issue #1584), or the registration is not being reached."),null)},i.register$$module$build$src$core$extensions=function(e,t){if(typeof e!="string"||e.trim()==="")throw Error('Error: Invalid extension name "'+e+'"');if(dn[e])throw Error('Error: Extension "'+e+'" is already registered.');if(typeof t!="function")throw Error('Error: Extension "'+e+'" must be a function');dn[e]=t},i.registerMixin$$module$build$src$core$extensions=function(e,t){if(!t||typeof t!="object")throw Error('Error: Mixin "'+e+'" must be a object');i.register$$module$build$src$core$extensions(e,function(){this.mixin(t)})},i.registerMutator$$module$build$src$core$extensions=function(e,t,o,n){const u='Error when registering mutator "'+e+'": ';Td(u,t);const g=Cd(t,u);if(o&&typeof o!="function")throw Error(u+'Extension "'+e+'" is not a function');i.register$$module$build$src$core$extensions(e,function(){g&&this.setMutator(new i.MutatorIcon$$module$build$src$core$icons$mutator_icon(n||[],this)),this.mixin(t),o&&o.apply(this)})},T$=function(e){kd(e)?delete dn[e]:console.warn('No extension mapping for name "'+e+'" found to unregister')},kd=function(e){return!!dn[e]},Va=function(e,t,o){const n=dn[e];if(typeof n!="function")throw Error('Error: Extension "'+e+'" not found.');let u;if(o?S$(e,t):u=Ya(t),n.apply(t),o)Td('Error after applying mutator "'+e+'": ',t);else if(!x$(u,t))throw Error('Error when applying extension "'+e+'": mutation properties changed when applying a non-mutator extension.')},S$=function(e,t){if(Ya(t).length)throw Error('Error: tried to apply mutation "'+e+'" to a block that already has mutator functions. Block id: '+t.id)},E$=function(e,t){return Ka(e.mutationToDom,e.domToMutation,t+" mutationToDom/domToMutation")},I$=function(e,t){return Ka(e.saveExtraState,e.loadExtraState,t+" saveExtraState/loadExtraState")},Cd=function(e,t){return Ka(e.compose,e.decompose,t+" compose/decompose")},Ka=function(e,t,o){if(e&&t){if(typeof e!="function"||typeof t!="function")throw Error(o+" must be a function");return!0}if(!e&&!t)return!1;throw Error(o+"Must have both or neither functions")},Td=function(e,t){const o=E$(t,e),n=I$(t,e);if(!o&&!n)throw Error(e+"Mutations must contain either XML hooks, or JSON hooks, or both");Cd(t,e)},Ya=function(e){const t=[];return e.domToMutation!==void 0&&t.push(e.domToMutation),e.mutationToDom!==void 0&&t.push(e.mutationToDom),e.saveExtraState!==void 0&&t.push(e.saveExtraState),e.loadExtraState!==void 0&&t.push(e.loadExtraState),e.compose!==void 0&&t.push(e.compose),e.decompose!==void 0&&t.push(e.decompose),t},x$=function(e,t){if(t=Ya(t),t.length!==e.length)return!1;for(let o=0;o!n.getReturnTypes()).map(n=>[n.getName(),n.getParameters().map(u=>u.getName()),!1]);e.getBlocksByType("procedures_defnoreturn",!1).forEach(n=>{!Ro(n)&&Bi(n)&&t.push(n.getProcedureDef())});const o=e.getProcedureMap().getProcedures().filter(n=>!!n.getReturnTypes()).map(n=>[n.getName(),n.getParameters().map(u=>u.getName()),!0]);return e.getBlocksByType("procedures_defreturn",!1).forEach(n=>{!Ro(n)&&Bi(n)&&o.push(n.getProcedureDef())}),t.sort(Ed),o.sort(Ed),[t,o]},Ed=function(e,t){return e[0].localeCompare(t[0],void 0,{sensitivity:"base"})},i.findLegalName$$module$build$src$core$procedures=function(e,t){if(t.isInFlyout)return e;for(e=e||i.Msg$$module$build$src$core$msg.UNNAMED_KEY||"unnamed";!N$(e,t.workspace,t);){const o=e.match(/^(.*?)(\d+)$/);e=o?o[1]+(parseInt(o[2])+1):e+"2"}return e},N$=function(e,t,o){return!Id(e,t,o)},Id=function(e,t,o){for(const n of t.getAllBlocks(!1))if(n!==o&&Bi(n)&&i.Names$$module$build$src$core$names.equals(n.getProcedureDef()[0],e))return!0;o=o&&Ro(o)?o==null?void 0:o.getProcedureModel():void 0;for(const n of t.getProcedureMap().getProcedures())if(n!==o&&i.Names$$module$build$src$core$names.equals(n.getName(),e))return!0;return!1},i.rename$$module$build$src$core$procedures=function(e){var t=this.getSourceBlock();if(!t)throw new _t;e=e.trim();const o=i.findLegalName$$module$build$src$core$procedures(e,t);Ro(t)&&!t.isInsertionMarker()&&t.getProcedureModel().setName(o);const n=this.getValue();if(n!==e&&n!==o)for(e=t.workspace.getAllBlocks(!1),t=0;tL$(o,e)||hf(o)&&i.Names$$module$build$src$core$names.equals(o.getProcedureCall(),e))},L$=function(e,t){return Ro(e)&&!e.isProcedureDef()&&e.getProcedureModel()&&i.Names$$module$build$src$core$names.equals(e.getProcedureModel().getName(),t)},i.mutateCallers$$module$build$src$core$procedures=function(e){const t=G();var o=e.getProcedureDef()[0];const n=e.mutationToDom(!0);e=Ad(o,e.workspace);for(let g=0,I;I=e[g];g++){o=(o=I.mutationToDom())&&Li(o),I.domToMutation&&I.domToMutation(n);var u=I.mutationToDom();u=u&&Li(u),o!==u&&(i.setRecordUndo$$module$build$src$core$events$utils(!1),z(new(ne(ee.BLOCK_CHANGE))(I,"mutation",null,o,u)),i.setRecordUndo$$module$build$src$core$events$utils(t))}},i.getDefinition$$module$build$src$core$procedures=function(e,t){for(const o of t.getAllBlocks(!1))if(Ro(o)&&o.isProcedureDef()&&i.Names$$module$build$src$core$names.equals(o.getProcedureModel().getName(),e)||Bi(o)&&i.Names$$module$build$src$core$names.equals(o.getProcedureDef()[0],e))return o;return null},Za=function(e){return e.isDynamic},P$=function(e){return e.pathDown!==void 0&&e.pathUp!==void 0},B$=function(e){return e.pathLeft!==void 0&&e.pathRight!==void 0},j$=function(e,t){if(!e||!t)throw Error("Cannot connect null connections.");e.targetConnection=t,t.targetConnection=e},F$=function(e,t){let o=null;t=t.outputConnection;const n=t==null?void 0:t.getConnectionChecker();for(let u=0,g;g=e.inputList[u];u++){const I=g.connection;let L;if(I&&((L=n)!=null&&L.canConnect(t,I,!1))){if(o)return null;o=I}}return o},z$=function(e,t){let o;for(;o=F$(e,t);)if(e=o.targetBlock(),!e||e.isShadow())return o;return null},Rd=function(e){return e.getType!==void 0&&e.initView!==void 0&&e.dispose!==void 0&&e.getWeight!==void 0&&e.getSize!==void 0&&e.applyColour!==void 0&&e.hideForInsertionMarker!==void 0&&e.updateEditable!==void 0&&e.updateCollapsed!==void 0&&e.isShownWhenCollapsed!==void 0&&e.setOffsetInBlock!==void 0&&e.onLocationChange!==void 0&&e.onClick!==void 0},U$=function(e){return Rd(e)&&zi(e)&&Yn(e)&&e.setText!==void 0&&e.getText!==void 0&&e.setBubbleSize!==void 0&&e.getBubbleSize!==void 0&&e.getType()===Ct.COMMENT},rr=function(e){let t=e.outputConnection;return(!t||e.previousConnection&&e.previousConnection.isConnected())&&(t=e.previousConnection),t},ar=function(e,t){r($e.RENDERER,e,t)},H$=function(e){c($e.RENDERER,e)},Od=function(e,t,o){return e=new(p($e.RENDERER,e))(e),e.init(t,o),e},Nd=function(e){ji(e.getTargetWorkspace(),void 0,"String")},Md=function(e){ji(e.getTargetWorkspace(),void 0,"Number")},Ld=function(e){ji(e.getTargetWorkspace(),void 0,"Colour")},Qa=function(e){let t=[],o=document.createElement("button");return o.setAttribute("text",i.Msg$$module$build$src$core$msg.NEW_STRING_VARIABLE),o.setAttribute("callbackKey","CREATE_VARIABLE_STRING"),t.push(o),o=document.createElement("button"),o.setAttribute("text",i.Msg$$module$build$src$core$msg.NEW_NUMBER_VARIABLE),o.setAttribute("callbackKey","CREATE_VARIABLE_NUMBER"),t.push(o),o=document.createElement("button"),o.setAttribute("text",i.Msg$$module$build$src$core$msg.NEW_COLOUR_VARIABLE),o.setAttribute("callbackKey","CREATE_VARIABLE_COLOUR"),t.push(o),e.registerButtonCallback("CREATE_VARIABLE_STRING",Nd),e.registerButtonCallback("CREATE_VARIABLE_NUMBER",Md),e.registerButtonCallback("CREATE_VARIABLE_COLOUR",Ld),e=Pd(e),t=t.concat(e)},Pd=function(e){e=e.getAllVariables();const t=[];if(0L.id!=e.id).map(L=>L.getRelativeToSurfaceXY());for(;G$(ye.sum(t,g),I)||V$(e,ye.sum(u,g),n);)o.RTL?g.translate(-n,2*n):g.translate(n,2*n);e.moveTo(ye.sum(t,g))},G$=function(e,t){return t.some(o=>1>=Math.abs(o.x-e.x)&&1>=Math.abs(o.y-e.y))},V$=function(e,t,o){return e.getConnections_(!1).some(n=>!!n.closest(o,t).connection)},Ji=function(e,t,o){const n=o.getBoundingRectangle(),u=n.right-n.left,g=Ui(t.top,n.top,t.top+t.height-(n.bottom-n.top))-n.top;let I=t.left;return t=t.left+t.width-u,e.RTL?I=Math.min(t,I):t=Math.max(I,t),(e=Ui(I,n.left,t)-n.left)||g?(o.moveBy(e,g,["inbounds"]),!0):!1},Bd=function(e){return t=>{var o=e.getMetricsManager();if(o.hasFixedEdges()&&!e.isDragging()){var n;if(pb.includes((n=t.type)!=null?n:"")){n=o.getScrollMetrics(!0);const u=K$(e,t);u&&(o=i.getGroup$$module$build$src$core$events$utils()||!1,i.setGroup$$module$build$src$core$events$utils(t.group),Ji(e,n,u)&&!t.group&&console.warn("Moved object in bounds but there was no event group. This may break undo."),i.setGroup$$module$build$src$core$events$utils(o))}else W(t)&&t.scale&&t.oldScale&&t.scale>t.oldScale&&el(e)}}},K$=function(e,t){let o=null;switch(t.type){case ee.BLOCK_CREATE:case ee.BLOCK_MOVE:(o=e.getBlockById(t.blockId))&&(o=o.getRootBlock());break;case ee.COMMENT_CREATE:case ee.COMMENT_MOVE:case ee.COMMENT_RESIZE:o=e.getCommentById(t.commentId)}return o},el=function(e){var t=e.getMetricsManager();if(t.hasFixedEdges()&&!e.isDragging()){t=t.getScrollMetrics(!0);var o=e.getTopBoundedElements();for(let n=0,u;u=o[n];n++)Ji(e,t,u)}},ds=function(e){return e.isDeletable!==void 0&&e.dispose!==void 0&&e.setDeleteStyle!==void 0},Y$=function(e){const t=e.toCopyData();Sp=t;let o;return Ep=(o=e.workspace)!=null?o:null,t},Oo=function(e,t,o){return e&&t?jd(e,t,o):Sp&&Ep?jd(Sp,Ep):null},jd=function(e,t,o){let n;t=t.isMutator?t:(n=t.getRootWorkspace())!=null?n:t;let u,g;return(g=(u=f($e.PASTER,e.paster,!1))==null?void 0:u.paste(e,t,o))!=null?g:null},J$=function(e){const t=e.toCopyData();return t?Oo(t,e.workspace):null},lr=function(e){return e.toCopyData!==void 0},Fd=function(){st.registry.register({name:Ys.ESCAPE,preconditionFn(e){return!e.options.readOnly},callback(e){return e.hideChaff(),!0},keyCodes:[Ye.ESC]})},zd=function(){st.registry.register({name:Ys.DELETE,preconditionFn(e){const t=F();return!e.options.readOnly&&t!=null&&ds(t)&&t.isDeletable()&&!bo.inProgress()},callback(e,t){return t.preventDefault(),e=F(),e instanceof $s?e.checkAndDelete():ds(e)&&e.isDeletable()&&(i.setGroup$$module$build$src$core$events$utils(!0),e.dispose(),i.setGroup$$module$build$src$core$events$utils(!1)),!0},keyCodes:[Ye.DELETE,Ye.BACKSPACE]})},Ud=function(){const e=st.registry.createSerializedKey(Ye.C,[Ye.CTRL]),t=st.registry.createSerializedKey(Ye.C,[Ye.ALT]),o=st.registry.createSerializedKey(Ye.C,[Ye.META]);st.registry.register({name:Ys.COPY,preconditionFn(n){const u=F();return!n.options.readOnly&&!bo.inProgress()&&u!=null&&ds(u)&&u.isDeletable()&&ri(u)&&u.isMovable()&&lr(u)},callback(n,u){return u.preventDefault(),n.hideChaff(),u=F(),!u||!lr(u)?!1:(Ho=u.toCopyData(),Wo=u.workspace instanceof cs?u.workspace:n,$n=ri(u)?u.getRelativeToSurfaceXY():null,!!Ho)},keyCodes:[e,t,o]})},Hd=function(){const e=st.registry.createSerializedKey(Ye.X,[Ye.CTRL]),t=st.registry.createSerializedKey(Ye.X,[Ye.ALT]),o=st.registry.createSerializedKey(Ye.X,[Ye.META]);st.registry.register({name:Ys.CUT,preconditionFn(n){const u=F();return!n.options.readOnly&&!bo.inProgress()&&u!=null&&ds(u)&&u.isDeletable()&&ri(u)&&u.isMovable()&&!u.workspace.isFlyout},callback(n){const u=F();return u instanceof $s?(Ho=u.toCopyData(),Wo=n,$n=u.getRelativeToSurfaceXY(),u.checkAndDelete(),!0):ds(u)&&u.isDeletable()&&lr(u)?(Ho=u.toCopyData(),Wo=n,$n=ri(u)?u.getRelativeToSurfaceXY():null,u.dispose(),!0):!1},keyCodes:[e,t,o]})},Wd=function(){const e=st.registry.createSerializedKey(Ye.V,[Ye.CTRL]),t=st.registry.createSerializedKey(Ye.V,[Ye.ALT]),o=st.registry.createSerializedKey(Ye.V,[Ye.META]);st.registry.register({name:Ys.PASTE,preconditionFn(n){return!n.options.readOnly&&!bo.inProgress()},callback(){if(!Ho||!Wo)return!1;if(!$n)return!!Oo(Ho,Wo);const{left:n,top:u,width:g,height:I}=Wo.getMetricsManager().getViewMetrics(!0);if(new rt(u,u+I,n,n+g).contains($n.x,$n.y))return!!Oo(Ho,Wo);const L=new ye(n+g/2,u+I/2);return!!Oo(Ho,Wo,L)},keyCodes:[e,t,o]})},Gd=function(){const e=st.registry.createSerializedKey(Ye.Z,[Ye.CTRL]),t=st.registry.createSerializedKey(Ye.Z,[Ye.ALT]),o=st.registry.createSerializedKey(Ye.Z,[Ye.META]);st.registry.register({name:Ys.UNDO,preconditionFn(n){return!n.options.readOnly&&!bo.inProgress()},callback(n,u){return n.hideChaff(),n.undo(!1),u.preventDefault(),!0},keyCodes:[e,t,o]})},Vd=function(){const e=st.registry.createSerializedKey(Ye.Z,[Ye.SHIFT,Ye.CTRL]),t=st.registry.createSerializedKey(Ye.Z,[Ye.SHIFT,Ye.ALT]),o=st.registry.createSerializedKey(Ye.Z,[Ye.SHIFT,Ye.META]),n=st.registry.createSerializedKey(Ye.Y,[Ye.CTRL]);st.registry.register({name:Ys.REDO,preconditionFn(u){return!bo.inProgress()&&!u.options.readOnly},callback(u,g){return u.hideChaff(),u.undo(!0),g.preventDefault(),!0},keyCodes:[e,t,o,n]})},Kd=function(){Fd(),zd(),Ud(),Hd(),Wd(),Gd(),Vd()},Yd=function(e){const t=e.saveState();return e.getParameters().length&&(t.parameters=e.getParameters().map(o=>o.saveState())),t},Jd=function(e,t,o,n){if(e=e.loadState(o,n),!o.parameters)return e;for(const[u,g]of o.parameters.entries())e.insertParameter(t.loadState(g,n),u);return e},q$=function(e){const t=Object.create(null),o=b($e.SERIALIZER,!0);for(const n in o){let u;const g=(u=o[n])==null?void 0:u.save(e);g&&(t[n]=g)}return t},X$=function(e,t,{recordUndo:o=!1}={}){var n=b($e.SERIALIZER,!0);if(n){n=Object.entries(n).sort((g,I)=>I[1].priority-g[1].priority);var u=G();i.setRecordUndo$$module$build$src$core$events$utils(o),(o=i.getGroup$$module$build$src$core$events$utils())||i.setGroup$$module$build$src$core$events$utils(!0),io(),t instanceof cs&&t.setResizesEnabled(!1);for(const[,g]of n.reverse()){let I;(I=g)==null||I.clear(t)}for(const[g,I]of n.reverse())if(e[g]){let L;(L=I)==null||L.load(e[g],t)}t instanceof cs&&t.setResizesEnabled(!0),no(),z(new(ne(ee.FINISHED_LOADING))(t)),i.setGroup$$module$build$src$core$events$utils(o),i.setRecordUndo$$module$build$src$core$events$utils(u)}},Z$=function(e,t){let o=null;o=typeof e=="string"?document.getElementById(e)||document.querySelector(e):e;var n;if(!document.contains(o)&&document!==((n=o)==null?void 0:n.ownerDocument))throw Error("Error: container is not in current document");e=new gs(t||{}),n=document.createElement("div"),Re(n,"injectionDiv"),t!=null&&t.rtl&&Re(n,"blocklyRTL"),n.tabIndex=0,xt(n,Et.LABEL,i.Msg$$module$build$src$core$msg.WORKSPACE_ARIA_LABEL),o.appendChild(n),t=Q$(n,e);const u=eb(n,t,e);return tb(u),se(u),we(u),n.addEventListener("focusin",function(){se(u)}),H(n,"keydown",null,tl),H(Xn(),"keydown",null,tl),(t=oi())&&H(t,"keydown",null,tl),u},Q$=function(e,t){e.setAttribute("dir","LTR"),jt(t.hasCss,t.pathToMedia),e=ie(J.SVG,{xmlns:pr,"xmlns:html":Gs,"xmlns:xlink":is,version:"1.1",class:"blocklySvg",tabindex:"0"},e);const o=ie(J.DEFS,{},e),n=String(Math.random()).substring(2);return t.gridPattern=sp.createDom(n,t.gridOptions,o),e},eb=function(e,t,o){o.parentWorkspace=null,o=new cs(o);const n=o.options;o.scale=n.zoomOptions.startScale,t.appendChild(o.createDom("blocklyMainBackground",e));var u=o.getRenderer().getClassName();return u&&Re(e,u),(u=o.getTheme().getClassName())&&Re(e,u),!n.hasCategories&&n.languageTree&&(e=o.addFlyout(J.SVG),At(e,t)),n.hasTrashcan&&o.addTrashcan(),n.zoomOptions&&n.zoomOptions.controls&&o.addZoomControls(),o.getThemeManager().subscribe(t,"workspaceBackgroundColour","background-color"),o.translate(0,0),o.addChangeListener(Bd(o)),we(o),rd(),Ou(),Xu(),o},tb=function(e){const t=e.options;var o=e.getParentSvg();if(H(o.parentNode,"contextmenu",null,function(n){be(n)||n.preventDefault()}),o=H(window,"resize",null,function(){co(),e.hideComponents(!0),Vu(),ud(),we(e),el(e)}),e.setResizeHandlerWrapper(o),sb(),t.languageTree){o=e.getToolbox();const n=e.getFlyout(!0);o?o.init():n&&(n.init(e),n.show(t.languageTree),typeof n.scrollToStart=="function"&&n.scrollToStart())}t.hasTrashcan&&e.trashcan.init(),t.zoomOptions&&t.zoomOptions.controls&&e.zoomControls_.init(),t.moveOptions&&t.moveOptions.scrollbars?(e.scrollbar=new xp(e,t.moveOptions.scrollbars===!0||!!t.moveOptions.scrollbars.horizontal,t.moveOptions.scrollbars===!0||!!t.moveOptions.scrollbars.vertical,"blocklyMainWorkspaceScrollbar"),e.scrollbar.resize()):e.setMetrics({x:.5,y:.5}),t.hasSounds&&ob(t.pathToMedia,e)},tl=function(e){const t=q();t&&!(be(e)||t.rendered&&!t.isVisible())&&st.registry.onKeyDown(t,e)},sb=function(){ry||(H(document,"scroll",null,function(){const e=B();for(let t=0,o;o=e[t];t++)o instanceof cs&&o.updateInverseScreenCTM()}),ue(document,"touchend",null,X),ue(document,"touchcancel",null,X)),ry=!0},ob=function(e,t){function o(){for(;u.length;){const g=u.pop();g&&V(g)}n.preload()}const n=t.getAudioManager();n.load([e+"click.mp3",e+"click.wav",e+"click.ogg"],"click"),n.load([e+"disconnect.wav",e+"disconnect.mp3",e+"disconnect.ogg"],"disconnect"),n.load([e+"delete.mp3",e+"delete.ogg",e+"delete.wav"],"delete");const u=[];u.push(H(document,"pointermove",null,o,!0)),u.push(H(document,"touchstart",null,o,!0))},qd=function(){Ke.registry.register({displayText(){return i.Msg$$module$build$src$core$msg.UNDO},preconditionFn(e){return 0t.length?cr(t):Sa(i.Msg$$module$build$src$core$msg.DELETE_ALL_BLOCKS.replace("%1",String(t.length)),function(o){o&&cr(t)})}},scopeType:Ke.ScopeType.WORKSPACE,id:"workspaceDelete",weight:6})},ib=function(){qd(),Xd(),Zd(),eh(),th(),oh()},ih=function(){Ke.registry.register({displayText(){return i.Msg$$module$build$src$core$msg.DUPLICATE_BLOCK},preconditionFn(e){return e=e.block,!e.isInFlyout&&e.isDeletable()&&e.isMovable()?e.isDuplicatable()?"enabled":"disabled":"hidden"},callback(e){if(e.block){var t=e.block.toCopyData();t&&Oo(t,e.block.workspace)}},scopeType:Ke.ScopeType.BLOCK,id:"blockDuplicate",weight:1})},nh=function(){Ke.registry.register({displayText(e){return e.block.hasIcon(_o.TYPE)?i.Msg$$module$build$src$core$msg.REMOVE_COMMENT:i.Msg$$module$build$src$core$msg.ADD_COMMENT},preconditionFn(e){return e=e.block,!e.isInFlyout&&e.workspace.options.comments&&!e.isCollapsed()&&e.isEditable()?"enabled":"hidden"},callback(e){e=e.block,e.hasIcon(_o.TYPE)?e.setCommentText(null):e.setCommentText("")},scopeType:Ke.ScopeType.BLOCK,id:"blockComment",weight:2})},rh=function(){Ke.registry.register({displayText(e){return e.block.getInputsInline()?i.Msg$$module$build$src$core$msg.EXTERNAL_INPUTS:i.Msg$$module$build$src$core$msg.INLINE_INPUTS},preconditionFn(e){if(e=e.block,!e.isInFlyout&&e.isMovable()&&!e.isCollapsed()){for(let t=1;t(t.has(Vt)?1:0),e.getInheritedDisabled()||t?"disabled":"enabled"}return"hidden"},callback(e){e=e.block;const t=i.getGroup$$module$build$src$core$events$utils();t||i.setGroup$$module$build$src$core$events$utils(!0),e.setDisabledReason(!e.hasDisabledReason(Vt),Vt),i.setGroup$$module$build$src$core$events$utils(t)},scopeType:Ke.ScopeType.BLOCK,id:"blockDisable",weight:5})},ch=function(){Ke.registry.register({displayText(e){var t=e.block;return e=t.getDescendants(!1).length,(t=t.getNextBlock())&&(e-=t.getDescendants(!1).length),e===1?i.Msg$$module$build$src$core$msg.DELETE_BLOCK:i.Msg$$module$build$src$core$msg.DELETE_X_BLOCKS.replace("%1",`${e}`)},preconditionFn(e){return!e.block.isInFlyout&&e.block.isDeletable()?"enabled":"hidden"},callback(e){e.block&&e.block.checkAndDelete()},scopeType:Ke.ScopeType.BLOCK,id:"blockDelete",weight:6})},uh=function(){Ke.registry.register({displayText(){return i.Msg$$module$build$src$core$msg.HELP},preconditionFn(e){return e=e.block,(typeof e.helpUrl=="function"?e.helpUrl():e.helpUrl)?"enabled":"hidden"},callback(e){e.block.showHelp()},scopeType:Ke.ScopeType.BLOCK,id:"blockHelp",weight:7})},dh=function(){Ke.registry.register({displayText:()=>i.Msg$$module$build$src$core$msg.REMOVE_COMMENT,preconditionFn(e){let t;return(t=e.comment)!=null&&t.isDeletable()?"enabled":"hidden"},callback(e){i.setGroup$$module$build$src$core$events$utils(!0);let t;(t=e.comment)==null||t.dispose(),i.setGroup$$module$build$src$core$events$utils(!1)},scopeType:Ke.ScopeType.COMMENT,id:"commentDelete",weight:6})},hh=function(){Ke.registry.register({displayText:()=>i.Msg$$module$build$src$core$msg.DUPLICATE_COMMENT,preconditionFn(e){let t;return(t=e.comment)!=null&&t.isMovable()?"enabled":"hidden"},callback(e){if(e.comment){var t=e.comment.toCopyData();t&&Oo(t,e.comment.workspace)}},scopeType:Ke.ScopeType.COMMENT,id:"commentDuplicate",weight:1})},ph=function(){Ke.registry.register({displayText:()=>i.Msg$$module$build$src$core$msg.ADD_COMMENT,preconditionFn:e=>{let t;return(t=e.workspace)!=null&&t.isMutator?"hidden":"enabled"},callback:(e,t)=>{if(e=e.workspace){i.setGroup$$module$build$src$core$events$utils(!0);var o=new Il(e);o.setText(i.Msg$$module$build$src$core$msg.WORKSPACE_COMMENT_DEFAULT_TEXT),o.moveTo(nb(new ye(t.clientX,t.clientY),e)),i.setSelected$$module$build$src$core$common(o),i.setGroup$$module$build$src$core$events$utils(!1)}},scopeType:Ke.ScopeType.WORKSPACE,id:"commentCreate",weight:8})},nb=function(e,t){var o=t.getInjectionDiv().getBoundingClientRect();return e=new ye(e.x-o.left,e.y-o.top),o=t.getOriginOffsetInPixels(),e=ye.difference(e,o),e.scale(1/t.scale),e},rb=function(){ih(),nh(),rh(),ah(),lh(),ch(),uh()},ab=function(){hh(),dh(),ph()},gh=function(){ib(),rb()},lb=function(e){return e.paste!==void 0},cb=function(e){return e.getSvgRoot!==void 0},ub=function(e){return typeof e.id=="string"&&e.workspace!==void 0&&e.select!==void 0&&e.unselect!==void 0},db=function(e){return e.isSelectable()},hb=function(e){q().hideChaff(e)},ge=ge||{},ge.scope={},ge.ASSUME_ES5=!1,ge.ASSUME_NO_NATIVE_MAP=!1,ge.ASSUME_NO_NATIVE_SET=!1,ge.SIMPLE_FROUND_POLYFILL=!1,ge.ISOLATE_POLYFILLS=!1,ge.FORCE_POLYFILL_PROMISE=!1,ge.FORCE_POLYFILL_PROMISE_WHEN_NO_UNHANDLED_REJECTION=!1,ge.defineProperty=ge.ASSUME_ES5||typeof Object.defineProperties=="function"?Object.defineProperty:function(e,t,o){return e==Array.prototype||e==Object.prototype||(e[t]=o.value),e},ge.getGlobal=function(e){e=[typeof globalThis=="object"&&globalThis,e,typeof window=="object"&&window,typeof self=="object"&&self,typeof eo=="object"&&eo];for(var t=0;t>>0,ge.propertyToPolyfillSymbol[u]=ge.IS_SYMBOL_NATIVE?ge.global.Symbol(u):ge.POLYFILL_PREFIX+o+"$"+u),ge.defineProperty(n,ge.propertyToPolyfillSymbol[u],{configurable:!0,writable:!0,value:t})))},ge.underscoreProtoCanBeSet=function(){var e={a:!0},t={};try{return t.__proto__=e,t.a}catch{}return!1},ge.setPrototypeOf=ge.TRUST_ES6_POLYFILLS&&typeof Object.setPrototypeOf=="function"?Object.setPrototypeOf:ge.underscoreProtoCanBeSet()?function(e,t){if(e.__proto__=t,e.__proto__!==t)throw new TypeError(e+" is not extensible");return e}:null,ge.arrayIteratorImpl=function(e){var t=0;return function(){return to&&(o=Math.max(o+u,0));o{const e=fb.length,t=[];for(let o=0;20>o;o++)t[o]=fb.charAt(Math.random()*e);return t.join("")}},LC=0,mh={TEST_ONLY:$b};mh.genUid=_,mh.getNextUniqueId=v;var bb="",ur=!0,fh=0,$h="ORPHANED_BLOCK",po=[],vb={FIRE_QUEUE:po,enqueueEvent:Ce,fireNow:he,fireInternal:Z,setGroupInternal:Q};i.disable$$module$build$src$core$events$utils,i.enable$$module$build$src$core$events$utils,i.getGroup$$module$build$src$core$events$utils,i.setGroup$$module$build$src$core$events$utils,i.setRecordUndo$$module$build$src$core$events$utils;var dr=Object.create(null),yb,ai=null,_b,hr=[],wb={defineBlocksWithJsonArrayInternal:We},Rt={TEST_ONLY:wb};Rt.createBlockDefinitionsFromJsonArray=i.createBlockDefinitionsFromJsonArray$$module$build$src$core$common,Rt.defineBlocks=i.defineBlocks$$module$build$src$core$common,Rt.defineBlocksWithJsonArray=Ae,Rt.draggingConnections=hr,Rt.getAllWorkspaces=B,Rt.getBlockTypeCounts=Ie,Rt.getMainWorkspace=q,Rt.getParentContainer=Te,Rt.getSelected=F,Rt.getWorkspaceById=re,Rt.registerWorkspace=N,Rt.setMainWorkspace=se,Rt.setParentContainer=ae,Rt.setSelected=i.setSelected$$module$build$src$core$common,Rt.svgResize=we,Rt.unregisterWorkpace=te;var qi=class{constructor(){this.workspaceId=void 0,this.isUiEvent=!1,this.type="",this.group=i.getGroup$$module$build$src$core$events$utils(),this.recordUndo=G()}toJson(){return{type:this.type,group:this.group}}static fromJson(e,t,o){return o.isBlank=!1,o.group=e.group||"",o.workspaceId=t.id,o}isNull(){return!1}run(e){}getEventWorkspace_(){let e;if(this.workspaceId&&(e=re(this.workspaceId)),!e)throw Error("Workspace is null. Event must have been generated from real Blockly events.");return e}},Ss=class extends qi{constructor(e){super(),this.recordUndo=!1,this.isUiEvent=!0,this.isBlank=typeof e>"u",this.workspaceId=e||""}},bh=class extends Ss{constructor(e,t,o){t=e?e.workspace.id:t,t===null&&(t=void 0),super(t),this.type=ee.CLICK,this.blockId=e?e.id:void 0,this.targetType=o}toJson(){const e=super.toJson();if(!this.targetType)throw Error("The click target type is undefined. Either pass a block to the constructor, or call fromJson");return e.targetType=this.targetType,e.blockId=this.blockId,e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new bh),t.targetType=e.targetType,t.blockId=e.blockId,t}},vh;(function(e){e.BLOCK="block",e.WORKSPACE="workspace",e.ZOOM_CONTROLS="zoom_controls"})(vh||(vh={})),r($e.EVENT,ee.CLICK,bh);var PC=750,kb="ontouchstart"in globalThis||!!(globalThis.document&&document.documentElement&&"ontouchstart"in document.documentElement)||!(!globalThis.navigator||!globalThis.navigator.maxTouchPoints&&!globalThis.navigator.msMaxTouchPoints),il=null,li={mousedown:["pointerdown"],mouseenter:["pointerenter"],mouseleave:["pointerleave"],mousemove:["pointermove"],mouseout:["pointerout"],mouseover:["pointerover"],mouseup:["pointerup","pointercancel"],touchend:["pointerup"],touchcancel:["pointercancel"]},nl=0,ci={TOUCH_ENABLED:kb,TOUCH_MAP:li};ci.checkTouchIdentifier=U,ci.clearTouchIdentifier=Y,ci.getTouchIdentifierFromEvent=A,ci.longStart=k,ci.longStop=X,ci.shouldHandleEvent=R;var yh,Cb,Tb,Sb,rl,al,_h,Eb,Ib,xb;(function(e){function t(n){return o.includes(n.toUpperCase())}yh=e;const o=yh.toUpperCase();Cb=t("JavaFX"),Tb=t("WebKit"),Sb=t("Gecko")&&!Tb,rl=t("Android"),e=globalThis.navigator&&globalThis.navigator.maxTouchPoints,al=t("iPad")||t("Macintosh")&&0{n.push(this.componentData.get(u))}),n.sort(function(u,g){return u.weight-g.weight}),n.forEach(function(u){o.push(u.component)})}else e.forEach(n=>{o.push(this.componentData.get(n).component)});return o}};gt.Capability=mo,(function(e){e=e.ComponentWeight||(e.ComponentWeight={}),e[e.TOOLBOX_WEIGHT=0]="TOOLBOX_WEIGHT",e[e.FLYOUT_WEIGHT=1]="FLYOUT_WEIGHT",e[e.TRASHCAN_WEIGHT=2]="TRASHCAN_WEIGHT",e[e.ZOOM_CONTROLS_WEIGHT=3]="ZOOM_CONTROLS_WEIGHT"})(gt||(gt={})),gt.ComponentWeight;var Ch=!1,Th=` +`+e.className.baseVal;var g;return Es&&(g=Es[e])||(ul||(g=document.createElement("canvas"),g.className="blocklyComputeCanvas",document.body.appendChild(g),ul=g.getContext("2d")),ul.font=o+" "+t+" "+n,g=u?ul.measureText(u).width:0,Es&&(Es[e]=g)),g},ro=function(e,t,o,n){const u=document.createElement("span");u.style.font=o+" "+t+" "+n,u.textContent=e,e=document.createElement("div"),e.style.width="1px",e.style.height="0",t=document.createElement("div"),t.style.display="flex",t.style.position="fixed",t.style.top="0",t.style.left="0",t.appendChild(u),t.appendChild(e),document.body.appendChild(t),o={height:0,baseline:0};try{t.style.alignItems="baseline",o.baseline=e.offsetTop-u.offsetTop,t.style.alignItems="flex-end",o.height=e.offsetTop-u.offsetTop}finally{document.body.removeChild(t)}return o},Hn=function(e){return jb.getSizeInternal(e)},Jm=function(e){if(js(e,"display")!=="none")return gu(e);const t=e.style,o=t.display,n=t.visibility,u=t.position;t.visibility="hidden",t.position="absolute",t.display="inline";const g=e.offsetWidth;return e=e.offsetHeight,t.display=o,t.position=u,t.visibility=n,new Ze(g,e)},gu=function(e){return new Ze(e.offsetWidth,e.offsetHeight)},js=function(e,t){return e=window.getComputedStyle(e),e[t]||e.getPropertyValue(t)},xo=function(e){const t=new ye(0,0);e=e.getBoundingClientRect();var o=document.documentElement;return o=new ye(window.pageXOffset||o.scrollLeft,window.pageYOffset||o.scrollTop),t.x=e.left+o.x,t.y=e.top+o.y,t},mu=function(){const e=document.body,t=document.documentElement;return new ye(e.scrollLeft||t.scrollLeft,e.scrollTop||t.scrollTop)},fu=function(e){const t=parseFloat(js(e,"borderLeftWidth")),o=parseFloat(js(e,"borderRightWidth")),n=parseFloat(js(e,"borderTopWidth"));return e=parseFloat(js(e,"borderBottomWidth")),new rt(n,e,t,o)},fa=function(e,t,o){e=$u(e,t,o),t.scrollLeft=e.x,t.scrollTop=e.y},$u=function(e,t,o){var n=xo(e),u=xo(t),g=fu(t);const I=n.x-u.x-g.left;return n=n.y-u.y-g.top,u=gu(e),e=t.clientWidth-u.width,u=t.clientHeight-u.height,g=t.scrollLeft,t=t.scrollTop,o?(g+=I-e/2,t+=n-u/2):(g+=Math.min(I,Math.max(I-e,0)),t+=Math.min(n,Math.max(n-u,0))),new ye(g,t)},Wn=function(e){const t=new ye(0,0);var o=e.x&&e.getAttribute("x");const n=e.y&&e.getAttribute("y");return o&&(t.x=parseInt(o)),n&&(t.y=parseInt(n)),(o=(o=e.getAttribute("transform"))&&o.match(Fb))&&(t.x+=Number(o[1]),o[3]&&(t.y+=Number(o[3]))),(e=e.getAttribute("style"))&&e.includes("translate")&&(e=e.match(zb))&&(t.x+=Number(e[1]),e[3]&&(t.y+=Number(e[3]))),t},$a=function(e){let t=0,o=0;for(;e;){const n=Wn(e);if(t+=n.x,o+=n.y,(" "+(e.getAttribute("class")||"")+" ").includes(" injectionDiv "))break;e=e.parentNode}return new ye(t,o)},bu=function(){const e=mu();return new rt(e.y,document.documentElement.clientHeight+e.y,e.x,document.documentElement.clientWidth+e.x)},vu=function(){const e=document.documentElement,t=window;return new ye(t.pageXOffset||e.scrollLeft,t.pageYOffset||e.scrollTop)},Xm=function(e,t){var o=t.x;t=t.y;const n=e.getInjectionDiv().getBoundingClientRect();return o=new ye(o-n.left,t-n.top),t=e.getOriginOffsetInPixels(),ye.difference(o,t).scale(1/e.scale)},qm=function(e,t){var o=t.scale(e.scale);t=o.x,o=o.y;const n=e.getInjectionDiv().getBoundingClientRect();return e=e.getOriginOffsetInPixels(),new ye(t+n.left+e.x,o+n.top+e.y)},Zm=function(e){({document:hl=hl,DOMParser:gr=gr,XMLSerializer:mr=mr}=e),dl=new gr,xh=new mr},i.createElement$$module$build$src$core$utils$xml=function(e){return hl.createElementNS(Ub,e)},i.createTextNode$$module$build$src$core$utils$xml=function(e){return hl.createTextNode(e)},i.textToDom$$module$build$src$core$utils$xml=function(e){let t=dl.parseFromString(e,"text/xml");if(t&&t.documentElement&&!t.getElementsByTagName("parsererror").length)return t.documentElement;if((t=dl.parseFromString(e,"text/html"))&&t.body.firstChild&&t.body.firstChild.nodeName.toLowerCase()==="xml")return t.body.firstChild;throw Error(`DOMParser was unable to parse: ${e}`)},Li=function(e){return Qm(xh.serializeToString(e))},Qm=function(e){return e.replace(UC,t=>`&#${t.charCodeAt(0)};`)},ba=function(e){return e?((e instanceof Element||typeof e=="string")&&(e=_u(e),e=sf(e)),ef(e),e):null},ef=function(e){const t=e.kind;if(e=e.contents,t&&t!==Hb&&t!==Dh)throw Error("Invalid toolbox kind "+t+". Please supply either "+Hb+" or "+Dh);if(!e)throw Error("Toolbox must have a contents attribute.")},Gn=function(e){return e?e.contents?e.contents:Array.isArray(e)&&0o.kind.toUpperCase()==="CATEGORY").length},ya=function(e){return e&&e.contents?!!e.contents.filter(function(t){return t.kind.toUpperCase()==="CATEGORY"}).length:!1},sf=function(e){const t={contents:_a(e)};return e instanceof Node&&yu(e,t),t},_a=function(e){const t=[];let o=e.childNodes;o||(o=e);for(let n=0,u;u=o[n];n++){if(!u.tagName)continue;e={};const g=u.tagName.toUpperCase();e.kind=g,g==="BLOCK"?e.blockxml=u:u.childNodes&&0 document.")}else e instanceof Element&&(t=e);return t},wa=function(e,t,o,n,u,g){const I=g.scrollbar&&g.scrollbar.canScrollVertically();return e.horizontal===Zi.LEFT?(o=u.absoluteMetrics.left+o,I&&g.RTL&&(o+=yt.scrollbarThickness)):(o=u.absoluteMetrics.left+u.viewMetrics.width-t.width-o,I&&!g.RTL&&(o-=yt.scrollbarThickness)),e.vertical===$o.TOP?e=u.absoluteMetrics.top+n:(e=u.absoluteMetrics.top+u.viewMetrics.height-t.height-n,g.scrollbar&&g.scrollbar.canScrollHorizontally()&&(e-=yt.scrollbarThickness)),new rt(e,e+t.height,o,o+t.width)},ka=function(e,t){return{horizontal:t.toolboxMetrics.position===Ge.LEFT||e.horizontalLayout&&!e.RTL?Zi.RIGHT:Zi.LEFT,vertical:t.toolboxMetrics.position===Ge.BOTTOM?$o.TOP:$o.BOTTOM}},Ca=function(e,t,o,n){const u=e.left,g=e.right-e.left,I=e.bottom-e.top;for(let P=0;Pg.id!==e.id).map(g=>g.getRelativeToSurfaceXY());for(;af(ye.sum(o,n),u);)n.translate(t.RTL?-30:30,30);e.moveTo(ye.sum(o,n))},af=function(e,t){return t.some(o=>1>=Math.abs(o.x-e.x)&&1>=Math.abs(o.y-e.y))},Do=function(e,t){e.setAttribute(GC,t)},xt=function(e,t,o){Array.isArray(o)&&(o=o.join(" ")),e.setAttribute(WC+t,`${o}`)},Kn=function(e){return e.saveState!==void 0&&e.loadState!==void 0},wu=function(e){return ku(e),lf()?(Sa(),Promise.resolve()):(Qi||(Qi=new Promise(t=>{Bh=t,qb=window.requestAnimationFrame(()=>{Sa(),t()})})),Qi)},Ts=function(){return Qi||Promise.resolve()},ao=function(e){e||window.cancelAnimationFrame(qb),Sa(e),!e&&Bh&&Bh()},lf=function(){return Ob},ku=function(e){Lh.add(e),Ph.set(e,i.getGroup$$module$build$src$core$events$utils());const t=e.getParent();t?ku(t):fl.add(e)},Sa=function(e){const t=e?new Set([e]):new Set([...fl].map(g=>g.workspace)),o=[...fl].filter(cf).filter(g=>t.has(g.workspace));for(var n of o)Tu(n);for(const g of t)g.resizeContents();for(var u of o)n=u.getRelativeToSurfaceXY(),u.updateComponentLocations(n);for(const g of o)u=i.getGroup$$module$build$src$core$events$utils(),(n=Ph.get(g))&&i.setGroup$$module$build$src$core$events$utils(n),g.bumpNeighbours(),i.setGroup$$module$build$src$core$events$utils(u);for(const g of o)Cu(g);e||(Qi=null)},Cu=function(e){fl.delete(e),Lh.delete(e),Ph.delete(e);for(const t of e.getChildren(!1))Cu(t)},cf=function(e){return!e.isDisposed()&&!e.getParent()},Tu=function(e){if(Lh.has(e)&&e.initialized){for(const t of e.getChildren(!1))Tu(t);e.renderEfficiently()}},Jn=function(e,t){Zb(e,t)},uf=function(e){Zb=e},Ea=function(e,t){tv.confirmInternal(e,t)},df=function(e,t){Qb(e,t)},hf=function(e){Qb=e},Ia=function(e,t,o){ev(e,t,o)},pf=function(e){ev=e},Bi=function(e){return e.getProcedureDef!==void 0},gf=function(e){return e.getProcedureCall!==void 0&&e.renameProcedure!==void 0},Su=function(e){return e.getVariableModel!==void 0},i.allUsedVarModels$$module$build$src$core$variables=function(e){e=e.getAllBlocks(!1);const t=new Set;for(let o=0;o1'),n.appendChild(o),t.push(n)),Qt.variables_get){e.sort(vr.compareByName);for(let u=0,g;g=e[u];u++)o=i.createElement$$module$build$src$core$utils$xml("block"),o.setAttribute("type","variables_get"),o.setAttribute("gap","8"),o.appendChild(ei(g)),t.push(o)}}return t},Iu=function(e){return ov.generateUniqueNameInternal(e)},mf=function(e){return Da(Uh.charAt(0),e.getAllVariableNames())},Da=function(e,t){if(!t.length)return e;const o=Uh;let n="",u=o.indexOf(e);for(;;){let g=!1;for(let I=0;Ig.getVariableModel().name);if(n&&(o=n.some(g=>g.toLowerCase()===e),n=n.some(g=>g.toLowerCase()===t),o&&n))return u.getName()}return null},bf=function(e,t,o){e=e.toLowerCase(),t=t.toLowerCase(),o=o.getAllBlocks(!1);for(const u of o){if(!Bi(u))continue;o=u.getProcedureDef();var n=o[1];const g=n.some(I=>I.toLowerCase()===e);if(n=n.some(I=>I.toLowerCase()===t),g&&n)return o[0]}return null},ei=function(e){const t=i.createElement$$module$build$src$core$utils$xml("field");return t.setAttribute("name","VAR"),t.setAttribute("id",e.getId()),t.setAttribute("variabletype",e.type),e=i.createTextNode$$module$build$src$core$utils$xml(e.name),t.appendChild(e),t},i.getOrCreateVariablePackage$$module$build$src$core$variables=function(e,t,o,n){let u=i.getVariable$$module$build$src$core$variables(e,t,o,n);return u||(u=vf(e,t,o,n)),u},i.getVariable$$module$build$src$core$variables=function(e,t,o,n){const u=e.getPotentialVariableMap();let g=null;if(t&&(g=e.getVariableById(t),!g&&u&&(g=u.getVariableById(t)),g))return g;if(o){if(n===void 0)throw Error("Tried to look up a variable by name without a type");g=e.getVariable(o,n),!g&&u&&(g=u.getVariable(o,n))}return g},vf=function(e,t,o,n){const u=e.getPotentialVariableMap();return o||(o=Iu(e.isFlyout?e.targetWorkspace:e)),u?u.createVariable(o,n,t):e.createVariable(o,n,t)},Xn=function(e,t){e=e.getAllVariables();const o=[];if(t.length!==e.length)for(let n=0;n{le.disposed||le.setConnectionTracking(!0)},1)}return P},Ou=function(e,t,{parentConnection:o,isShadow:n=!1}={}){if(!e.type)throw new iv(e);const u=t.newBlock(e.type,e.id);return u.setShadow(n),If(u,e),xf(u,e),Df(u,e),Af(o,u,e),Of(u,e),Rf(u,e),Mf(u,e),Nf(u,e),Lf(u,t.rendered),u},Ef=function(e,t){if(C())for(e=Xn(e,t),t=0;tt&&(t=o[n].length);var u=-1/0;let g,I=1;do{n=u,g=e,e=[],u=o.length/I;let P=1;for(let le=0;len);return g},La=function(e,t,o){const n=[0],u=[];for(var g=0;gn&&(n=P,u=I)}return u?Xu(e,u,o):t},zf=function(e,t){const o=[];for(let n=0;ngv&&co()}else Cr!==hs&&(clearTimeout(bi),Yh=e.pageX,Kh=e.pageY,bi=setTimeout(qf,mv))},ed=function(){Cr=hs=null,co()},co=function(){kr&&(kr=!1,Tt&&(Tt.style.display="none")),bi&&(clearTimeout(bi),bi=0)},td=function(){co(),rn=!0},sd=function(){rn=!1},Kf=function(){Tt&&hs&&(typeof _l=="function"?_l(Tt,hs):Jf())},Jf=function(){var e=Hi(hs);e=i.wrap$$module$build$src$core$utils$string(e,hv),e=e.split(` +`);for(let t=0;to+window.scrollY&&(u-=Tt.offsetHeight+2*Xh),e?n=Math.max(wl-window.scrollX,n):n+Tt.offsetWidth>t+window.scrollX-2*wl&&(n=t-Tt.offsetWidth-2*wl),{x:n,y:u}},qf=function(){if(!rn&&(Cr=hs,Tt)){Tt.textContent="",Kf();var e=hs.RTL;Tt.style.direction=e?"rtl":"ltr",Tt.style.display="block",kr=!0;var{x:t,y:o}=Xf(e);Tt.style.left=t+"px",Tt.style.top=o+"px"}},od=function(){return qh},Zf=function(e){qh=e},id=function(){return Zh},Qf=function(e){Zh=e},ti=function(e){e=`${e}`.toLowerCase().trim();var t=fv[e];if(t||(t=e.substring(0,2)==="0x"?"#"+e.substring(2):e,t=t[0]==="#"?t:"#"+t,/^#[0-9a-f]{6}$/.test(t)))return t;if(/^#[0-9a-f]{3}$/.test(t))return["#",t[1],t[1],t[2],t[2],t[3],t[3]].join("");var o=e.match(/^(?:rgb)?\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/);return o&&(e=Number(o[1]),t=Number(o[2]),o=Number(o[3]),0<=e&&256>e&&0<=t&&256>t&&0<=o&&256>o)?er(e,t,o):null},er=function(e,t,o){return t=e<<16|t<<8|o,16>e?"#"+(16777216|t).toString(16).substr(1):"#"+t.toString(16)},Ba=function(e){return e=ti(e),e?(e=parseInt(e.substr(1),16),[e>>16,e>>8&255,e&255]):[0,0,0]},ja=function(e,t,o){let n=0,u=0,g=0;if(t===0)g=u=n=o;else{const I=Math.floor(e/60),P=e/60-I;e=o*(1-t);const le=o*(1-t*P);switch(t=o*(1-t*(1-P)),I){case 1:n=le,u=o,g=e;break;case 2:n=e,u=o,g=t;break;case 3:n=e,u=le,g=o;break;case 4:n=t,u=e,g=o;break;case 5:n=o,u=e,g=le;break;case 6:case 0:n=o,u=t,g=e}}return er(Math.floor(n),Math.floor(u),Math.floor(g))},si=function(e,t,o){return e=ti(e),!e||(t=ti(t),!t)?null:(e=Ba(e),t=Ba(t),er(Math.round(t[0]+o*(e[0]-t[0])),Math.round(t[1]+o*(e[1]-t[1])),Math.round(t[2]+o*(e[2]-t[2]))))},nd=function(e){return ja(e,qh,255*Zh)},Fa=function(e,t,o){const n=[];var u=e.split("");u.push("");var g=0;e=[];let I=null;for(let Ee=0;Ee=P?(g=2,I=P,(P=e.join(""))&&n.push(P),e.length=0):P==="{"?g=3:(e.push("%",P),g=0);else if(g===2)if("0"<=P&&"9">=P)I+=P;else{var le=void 0;n.push(parseInt((le=I)!=null?le:"",10)),Ee--,g=0}else g===3&&(P===""?(e.splice(0,0,"%{"),Ee--,g=0):P!=="}"?e.push(P):(g=e.join(""),/[A-Z]\w*/i.test(g)?(P=g.toUpperCase(),(P=P.startsWith("BKY_")?P.substring(4):null)&&P in i.Msg$$module$build$src$core$msg?(g=i.Msg$$module$build$src$core$msg[P],typeof g=="string"?Array.prototype.push.apply(n,Fa(g,t,o)):t?n.push(`${g}`):n.push(g)):n.push("%{"+g+"}")):n.push("%{"+g+"}"),g=e.length=0))}for((t=e.join(""))&&n.push(t),le=[],e.length=0,u=0;u=o)return{hue:o,hex:ja(o,od(),255*id())};if(o=ti(t))return{hue:null,hex:o};throw o='Invalid colour: "'+t+'"',e!==t&&(o+=' (from "'+e+'")'),Error(o)},oi=function(){return xs},t$=function(e){if(xs=e,e===null){let t;(t=document.querySelector("."+Cl))==null||t.remove()}},ad=function(){const e=Te()||document.body;document.querySelector("."+Cl)?xs=document.querySelector("."+Cl):(xs=document.createElement("div"),xs.className=Cl),e.appendChild(xs)},za=function(e,t,o,n){if(Vi(),an=e,kl=o,o=xs){if(o.style.direction=t?"rtl":"ltr",o.style.display="block",!n&&e instanceof lt){let I;n=(I=e.getSourceBlock())==null?void 0:I.workspace}var u;Qh=(u=n)!=null?u:null;var g;e=(g=n)!=null?g:X(),ln=e.getRenderer().getClassName(),cn=e.getTheme().getClassName(),ln&&Oe(o,ln),cn&&Oe(o,cn)}},Vi=function(){if(ld()){an=null;var e=xs;e&&(e.style.display="none",e.style.left="",e.style.top="",kl&&kl(),kl=null,e.textContent="",ln&&(ze(e,ln),ln=""),cn&&(ze(e,cn),cn=""),X().markFocused())}},ld=function(){return!!an},ii=function(e){an===e&&Vi()},tr=function(e){Qh!==null&&Qh!==e||Vi()},cd=function(e,t,o){xs.style.left=e+"px",xs.style.top=t+"px",xs.style.height=o+"px"},ud=function(e,t,o,n){const u=o$(e,t,o);e=s$(e,t,o,n),0>u?cd(e,0,o.height+u):cd(e,u,o.height)},s$=function(e,t,o,n){return n?Math.min(Math.max(t.right-o.width,e.left),e.right-o.width):Math.max(Math.min(t.left,e.right-o.width),e.left)},o$=function(e,t,o){return t.bottom+o.height>=e.bottom?t.top-o.height:t.bottom},i$=function(e){return!(e==null||!e.repositionForWindowResize)},dd=function(){i$(an)&&an.repositionForWindowResize()||Vi()},n$=function(){return Tl},hd=function(e){Tl=e},sr=function(e,t,o,n){if(za($v,o,pd,n),t.length){var u=r$(t,o,e);Sl=u,a$(u,e,o),setTimeout(function(){u.focus()},1),Tl=null}else or()},r$=function(e,t,o){const n=new Mh;n.setRole(Is.MENU);for(let u=0;u{setTimeout(()=>{g.callback(g.scope,o)},0)})},{})}return n},a$=function(e,t,o){const n=bu();t=new rt(t.clientY+n.top,t.clientY+n.top,t.clientX+n.left,t.clientX+n.left),l$(e);const u=e.getSize();o&&(t.left+=u.width,t.right+=u.width,n.left+=u.width,n.right+=u.width),ud(n,t,u,o),e.focus()},l$=function(e){var t=oi();if(!t)throw Error("Attempting to create a context menu when widget div is null");t=e.render(t),Oe(t,"blocklyContextMenu"),W(t,"contextmenu",null,c$),e.focus()},c$=function(e){e.preventDefault(),e.stopPropagation()},or=function(){ii($v),Tl=null},pd=function(){Sl&&(Sl.dispose(),Sl=null)},i.callbackFactory$$module$build$src$core$contextmenu=function(e,t){return()=>{i.disable$$module$build$src$core$events$utils();let o;try{o=t instanceof Element?ni(t,e.workspace):Fi(t,e.workspace);const n=e.getRelativeToSurfaceXY();n.x=e.RTL?n.x-i.config$$module$build$src$core$config.snapRadius:n.x+i.config$$module$build$src$core$config.snapRadius,n.y+=2*i.config$$module$build$src$core$config.snapRadius,o.moveBy(n.x,n.y)}finally{i.enable$$module$build$src$core$events$utils()}return C()&&!o.isShadow()&&z(new(ne(ee.BLOCK_CREATE))(o)),i.setSelected$$module$build$src$core$common(o),o}},gd=function(e,t){return t=fe(t,e.getParentSvg(),e.getInverseScreenCTM()),t.x/=e.scale,t.y/=e.scale,t},Ua=function(e,t,o){t=gd(e,t),vv.set(e,ye.difference(o,t))},Ha=function(e,t){if(t=gd(e,t),e=vv.get(e),!e)throw Error("Drag not initialized");return ye.sum(e,t)},u$=function(e,t=!1){const o=i.createElement$$module$build$src$core$utils$xml("xml");var n=md(i.allUsedVarModels$$module$build$src$core$variables(e));n.hasChildNodes()&&o.appendChild(n);for(const u of e.getTopComments())o.appendChild(ir(u,t));for(e=e.getTopBlocks(!0),n=0;n/g,"<$1$2>")},p$=function(e){e=zs(e).split("<");let t="";for(let o=1;o"&&(t+=" ")}return e=e.join(` +`),e=e.replace(/(<(\w+)\b[^>]*>[^\n]*)\n *<\/\2>/g,"$1"),e.replace(/^\n/,"")},g$=function(e,t){return t.setResizesEnabled(!1),t.clear(),e=i.domToWorkspace$$module$build$src$core$xml(e,t),t.setResizesEnabled(!0),e},i.domToWorkspace$$module$build$src$core$xml=function(e,t){let o=0;t.RTL&&(o=t.getWidth());const n=[];io();const u=i.getGroup$$module$build$src$core$events$utils();u||i.setGroup$$module$build$src$core$events$utils(!0),t.setResizesEnabled&&t.setResizesEnabled(!1);let g=!0;try{for(let I=0,P;P=e.childNodes[I];I++){const le=P.nodeName.toLowerCase(),Ee=P;if(le==="block"||le==="shadow"&&!G()){const dt=ni(Ee,t);n.push(dt.id);let ut;const ts=parseInt((ut=Ee.getAttribute("x"))!=null?ut:"10",10);let yn;const Fr=parseInt((yn=Ee.getAttribute("y"))!=null?yn:"10",10);isNaN(ts)||isNaN(Fr)||dt.moveBy(t.RTL?o-ts:ts,Fr,["create"]),g=!1}else{if(le==="shadow")throw TypeError("Shadow block cannot be a top-level block.");if(le==="comment")$d(Ee,t);else if(le==="variables"){if(g)bd(Ee,t);else throw Error("'variables' tag must exist once before block and shadow tag elements in the workspace XML, but it was found in another location.");g=!1}}}}finally{i.setGroup$$module$build$src$core$events$utils(u),t.setResizesEnabled&&t.setResizesEnabled(!0),t.rendered&&ao(),no()}return z(new(ne(ee.FINISHED_LOADING))(t)),n},$d=function(e,t){var o;const n=(o=e.getAttribute("id"))!=null?o:void 0;o=t.rendered?new xl(t,n):new Il(t,n);var u;o.setText((u=e.textContent)!=null?u:"");var g;u=parseInt((g=e.getAttribute("x"))!=null?g:"",10);let I;g=parseInt((I=e.getAttribute("y"))!=null?I:"",10),isNaN(u)||isNaN(g)||(u=t.RTL?t.getWidth()-u:u,o.moveTo(new ye(u,g)));var P;t=parseInt((P=e.getAttribute("w"))!=null?P:"",10);let le;return P=parseInt((le=e.getAttribute("h"))!=null?le:"",10),isNaN(t)||isNaN(P)||o.setSize(new Ze(t,P)),e.getAttribute("collapsed")==="true"&&o.setCollapsed(!0),e.getAttribute("editable")==="false"&&o.setEditable(!1),e.getAttribute("movable")==="false"&&o.setMovable(!1),e.getAttribute("deletable")==="false"&&o.setDeletable(!1),o},m$=function(e,t){if(!t.getBlocksBoundingBox)return i.domToWorkspace$$module$build$src$core$xml(e,t);var o=t.getBlocksBoundingBox();if(e=i.domToWorkspace$$module$build$src$core$xml(e,t),o&&o.top!==o.bottom){var n=o.bottom;o=t.RTL?o.right:o.left;var u=1/0;let g=-1/0,I=1/0;for(let P=0;Pg&&(g=le.x)}for(n=n-I+10,o=t.RTL?o-g:o-u,u=0;uEe.setBubbleVisible(g),1)}},v$=function(e,t){for(let o=0;ou}),_d(u,{x:n.x,y:n.y,width:e.width,height:e.height},t.RTL,new Date)}},_d=function(e,t,o,n){const u=(new Date().getTime()-n.getTime())/150;1o)){var n=t.getSvgXY(e.getSvgRoot());e.outputConnection?(n.x+=(e.RTL?3:-3)*o,n.y+=13*o):e.previousConnection&&(n.x+=(e.RTL?-23:23)*o,n.y+=3*o);var u=ie(J.CIRCLE,{cx:n.x,cy:n.y,r:0,fill:"none",stroke:"#888","stroke-width":10},t.getParentSvg());e=ie(J.ANIMATE,{id:"animationCircle",begin:"indefinite",attributeName:"r",dur:"150ms",from:0,to:25*o},u),t=ie(J.ANIMATE,{id:"animationOpacity",begin:"indefinite",attributeName:"opacity",dur:"150ms",from:1,to:0},u),e.beginElement(),t.beginElement(),setTimeout(()=>{Qe(u)},150)}},wd=function(e){if(Yi(),e.workspace.getAudioManager().play("disconnect"),!(1>e.workspace.scale)){var t=e.getHeightWidth().height;t=Math.atan(10/t)/Math.PI*180,e.RTL||(t*=-1),Sr=e,kd(e,t,new Date,0)}},kd=function(e,t,o,n){const u=[.66,1,.66,0,-.66,-1,-.66,0];let g="";o.getTime()+200>new Date().getTime()&&(g=`skewX(${Math.round(u[n%u.length]*t)})`,Dl=setTimeout(kd,15,e,t,o,n+1)),e.getSvgRoot().setAttribute("transform",`${e.getTranslation()} ${g}`)},Yi=function(){Sr&&(Dl&&(clearTimeout(Dl),Dl=null),Sr.getSvgRoot().setAttribute("transform",Sr.getTranslation()),Sr=null)},ri=function(e){return e.getRelativeToSurfaceXY!==void 0&&e.isMovable!==void 0&&e.startDrag!==void 0&&e.drag!==void 0&&e.endDrag!==void 0&&e.revertDrag!==void 0},uo=function(e,t){for(const o in t)e[o]=t[o]!==null&&typeof t[o]=="object"?uo(e[o]||Object.create(null),t[o]):t[o];return e},Us=function(e,t){r($e.FIELD,e,t)},T$=function(e){c($e.FIELD,e)},i.fromJson$$module$build$src$core$field_registry=function(e){return kv.fromJsonInternal(e)},S$=function(e){const t=f($e.FIELD,e.type);return t?t.fromJson(e):(console.warn("Blockly could not create a field of type "+e.type+". The field is probably not being registered. This could be because the file is not loaded, the field does not register itself (Issue #1584), or the registration is not being reached."),null)},i.register$$module$build$src$core$extensions=function(e,t){if(typeof e!="string"||e.trim()==="")throw Error('Error: Invalid extension name "'+e+'"');if(dn[e])throw Error('Error: Extension "'+e+'" is already registered.');if(typeof t!="function")throw Error('Error: Extension "'+e+'" must be a function');dn[e]=t},i.registerMixin$$module$build$src$core$extensions=function(e,t){if(!t||typeof t!="object")throw Error('Error: Mixin "'+e+'" must be a object');i.register$$module$build$src$core$extensions(e,function(){this.mixin(t)})},i.registerMutator$$module$build$src$core$extensions=function(e,t,o,n){const u='Error when registering mutator "'+e+'": ';Sd(u,t);const g=Td(t,u);if(o&&typeof o!="function")throw Error(u+'Extension "'+e+'" is not a function');i.register$$module$build$src$core$extensions(e,function(){g&&this.setMutator(new i.MutatorIcon$$module$build$src$core$icons$mutator_icon(n||[],this)),this.mixin(t),o&&o.apply(this)})},E$=function(e){Cd(e)?delete dn[e]:console.warn('No extension mapping for name "'+e+'" found to unregister')},Cd=function(e){return!!dn[e]},Ya=function(e,t,o){const n=dn[e];if(typeof n!="function")throw Error('Error: Extension "'+e+'" not found.');let u;if(o?I$(e,t):u=Ja(t),n.apply(t),o)Sd('Error after applying mutator "'+e+'": ',t);else if(!A$(u,t))throw Error('Error when applying extension "'+e+'": mutation properties changed when applying a non-mutator extension.')},I$=function(e,t){if(Ja(t).length)throw Error('Error: tried to apply mutation "'+e+'" to a block that already has mutator functions. Block id: '+t.id)},x$=function(e,t){return Ka(e.mutationToDom,e.domToMutation,t+" mutationToDom/domToMutation")},D$=function(e,t){return Ka(e.saveExtraState,e.loadExtraState,t+" saveExtraState/loadExtraState")},Td=function(e,t){return Ka(e.compose,e.decompose,t+" compose/decompose")},Ka=function(e,t,o){if(e&&t){if(typeof e!="function"||typeof t!="function")throw Error(o+" must be a function");return!0}if(!e&&!t)return!1;throw Error(o+"Must have both or neither functions")},Sd=function(e,t){const o=x$(t,e),n=D$(t,e);if(!o&&!n)throw Error(e+"Mutations must contain either XML hooks, or JSON hooks, or both");Td(t,e)},Ja=function(e){const t=[];return e.domToMutation!==void 0&&t.push(e.domToMutation),e.mutationToDom!==void 0&&t.push(e.mutationToDom),e.saveExtraState!==void 0&&t.push(e.saveExtraState),e.loadExtraState!==void 0&&t.push(e.loadExtraState),e.compose!==void 0&&t.push(e.compose),e.decompose!==void 0&&t.push(e.decompose),t},A$=function(e,t){if(t=Ja(t),t.length!==e.length)return!1;for(let o=0;o!n.getReturnTypes()).map(n=>[n.getName(),n.getParameters().map(u=>u.getName()),!1]);e.getBlocksByType("procedures_defnoreturn",!1).forEach(n=>{!Oo(n)&&Bi(n)&&t.push(n.getProcedureDef())});const o=e.getProcedureMap().getProcedures().filter(n=>!!n.getReturnTypes()).map(n=>[n.getName(),n.getParameters().map(u=>u.getName()),!0]);return e.getBlocksByType("procedures_defreturn",!1).forEach(n=>{!Oo(n)&&Bi(n)&&o.push(n.getProcedureDef())}),t.sort(Id),o.sort(Id),[t,o]},Id=function(e,t){return e[0].localeCompare(t[0],void 0,{sensitivity:"base"})},i.findLegalName$$module$build$src$core$procedures=function(e,t){if(t.isInFlyout)return e;for(e=e||i.Msg$$module$build$src$core$msg.UNNAMED_KEY||"unnamed";!L$(e,t.workspace,t);){const o=e.match(/^(.*?)(\d+)$/);e=o?o[1]+(parseInt(o[2])+1):e+"2"}return e},L$=function(e,t,o){return!xd(e,t,o)},xd=function(e,t,o){for(const n of t.getAllBlocks(!1))if(n!==o&&Bi(n)&&i.Names$$module$build$src$core$names.equals(n.getProcedureDef()[0],e))return!0;o=o&&Oo(o)?o==null?void 0:o.getProcedureModel():void 0;for(const n of t.getProcedureMap().getProcedures())if(n!==o&&i.Names$$module$build$src$core$names.equals(n.getName(),e))return!0;return!1},i.rename$$module$build$src$core$procedures=function(e){var t=this.getSourceBlock();if(!t)throw new _t;e=e.trim();const o=i.findLegalName$$module$build$src$core$procedures(e,t);Oo(t)&&!t.isInsertionMarker()&&t.getProcedureModel().setName(o);const n=this.getValue();if(n!==e&&n!==o)for(e=t.workspace.getAllBlocks(!1),t=0;tB$(o,e)||gf(o)&&i.Names$$module$build$src$core$names.equals(o.getProcedureCall(),e))},B$=function(e,t){return Oo(e)&&!e.isProcedureDef()&&e.getProcedureModel()&&i.Names$$module$build$src$core$names.equals(e.getProcedureModel().getName(),t)},i.mutateCallers$$module$build$src$core$procedures=function(e){const t=G();var o=e.getProcedureDef()[0];const n=e.mutationToDom(!0);e=Od(o,e.workspace);for(let g=0,I;I=e[g];g++){o=(o=I.mutationToDom())&&Li(o),I.domToMutation&&I.domToMutation(n);var u=I.mutationToDom();u=u&&Li(u),o!==u&&(i.setRecordUndo$$module$build$src$core$events$utils(!1),z(new(ne(ee.BLOCK_CHANGE))(I,"mutation",null,o,u)),i.setRecordUndo$$module$build$src$core$events$utils(t))}},i.getDefinition$$module$build$src$core$procedures=function(e,t){for(const o of t.getAllBlocks(!1))if(Oo(o)&&o.isProcedureDef()&&i.Names$$module$build$src$core$names.equals(o.getProcedureModel().getName(),e)||Bi(o)&&i.Names$$module$build$src$core$names.equals(o.getProcedureDef()[0],e))return o;return null},Qa=function(e){return e.isDynamic},j$=function(e){return e.pathDown!==void 0&&e.pathUp!==void 0},F$=function(e){return e.pathLeft!==void 0&&e.pathRight!==void 0},z$=function(e,t){if(!e||!t)throw Error("Cannot connect null connections.");e.targetConnection=t,t.targetConnection=e},U$=function(e,t){let o=null;t=t.outputConnection;const n=t==null?void 0:t.getConnectionChecker();for(let u=0,g;g=e.inputList[u];u++){const I=g.connection;let P;if(I&&((P=n)!=null&&P.canConnect(t,I,!1))){if(o)return null;o=I}}return o},H$=function(e,t){let o;for(;o=U$(e,t);)if(e=o.targetBlock(),!e||e.isShadow())return o;return null},Rd=function(e){return e.getType!==void 0&&e.initView!==void 0&&e.dispose!==void 0&&e.getWeight!==void 0&&e.getSize!==void 0&&e.applyColour!==void 0&&e.hideForInsertionMarker!==void 0&&e.updateEditable!==void 0&&e.updateCollapsed!==void 0&&e.isShownWhenCollapsed!==void 0&&e.setOffsetInBlock!==void 0&&e.onLocationChange!==void 0&&e.onClick!==void 0},W$=function(e){return Rd(e)&&zi(e)&&Kn(e)&&e.setText!==void 0&&e.getText!==void 0&&e.setBubbleSize!==void 0&&e.getBubbleSize!==void 0&&e.getType()===Ct.COMMENT},rr=function(e){let t=e.outputConnection;return(!t||e.previousConnection&&e.previousConnection.isConnected())&&(t=e.previousConnection),t},ar=function(e,t){r($e.RENDERER,e,t)},G$=function(e){c($e.RENDERER,e)},Md=function(e,t,o){return e=new(p($e.RENDERER,e))(e),e.init(t,o),e},Nd=function(e){ji(e.getTargetWorkspace(),void 0,"String")},Ld=function(e){ji(e.getTargetWorkspace(),void 0,"Number")},Pd=function(e){ji(e.getTargetWorkspace(),void 0,"Colour")},el=function(e){let t=[],o=document.createElement("button");return o.setAttribute("text",i.Msg$$module$build$src$core$msg.NEW_STRING_VARIABLE),o.setAttribute("callbackKey","CREATE_VARIABLE_STRING"),t.push(o),o=document.createElement("button"),o.setAttribute("text",i.Msg$$module$build$src$core$msg.NEW_NUMBER_VARIABLE),o.setAttribute("callbackKey","CREATE_VARIABLE_NUMBER"),t.push(o),o=document.createElement("button"),o.setAttribute("text",i.Msg$$module$build$src$core$msg.NEW_COLOUR_VARIABLE),o.setAttribute("callbackKey","CREATE_VARIABLE_COLOUR"),t.push(o),e.registerButtonCallback("CREATE_VARIABLE_STRING",Nd),e.registerButtonCallback("CREATE_VARIABLE_NUMBER",Ld),e.registerButtonCallback("CREATE_VARIABLE_COLOUR",Pd),e=Bd(e),t=t.concat(e)},Bd=function(e){e=e.getAllVariables();const t=[];if(0P.id!=e.id).map(P=>P.getRelativeToSurfaceXY());for(;Y$(ye.sum(t,g),I)||K$(e,ye.sum(u,g),n);)o.RTL?g.translate(-n,2*n):g.translate(n,2*n);e.moveTo(ye.sum(t,g))},Y$=function(e,t){return t.some(o=>1>=Math.abs(o.x-e.x)&&1>=Math.abs(o.y-e.y))},K$=function(e,t,o){return e.getConnections_(!1).some(n=>!!n.closest(o,t).connection)},Ji=function(e,t,o){const n=o.getBoundingRectangle(),u=n.right-n.left,g=Ui(t.top,n.top,t.top+t.height-(n.bottom-n.top))-n.top;let I=t.left;return t=t.left+t.width-u,e.RTL?I=Math.min(t,I):t=Math.max(I,t),(e=Ui(I,n.left,t)-n.left)||g?(o.moveBy(e,g,["inbounds"]),!0):!1},jd=function(e){return t=>{var o=e.getMetricsManager();if(o.hasFixedEdges()&&!e.isDragging()){var n;if(mb.includes((n=t.type)!=null?n:"")){n=o.getScrollMetrics(!0);const u=J$(e,t);u&&(o=i.getGroup$$module$build$src$core$events$utils()||!1,i.setGroup$$module$build$src$core$events$utils(t.group),Ji(e,n,u)&&!t.group&&console.warn("Moved object in bounds but there was no event group. This may break undo."),i.setGroup$$module$build$src$core$events$utils(o))}else H(t)&&t.scale&&t.oldScale&&t.scale>t.oldScale&&tl(e)}}},J$=function(e,t){let o=null;switch(t.type){case ee.BLOCK_CREATE:case ee.BLOCK_MOVE:(o=e.getBlockById(t.blockId))&&(o=o.getRootBlock());break;case ee.COMMENT_CREATE:case ee.COMMENT_MOVE:case ee.COMMENT_RESIZE:o=e.getCommentById(t.commentId)}return o},tl=function(e){var t=e.getMetricsManager();if(t.hasFixedEdges()&&!e.isDragging()){t=t.getScrollMetrics(!0);var o=e.getTopBoundedElements();for(let n=0,u;u=o[n];n++)Ji(e,t,u)}},ds=function(e){return e.isDeletable!==void 0&&e.dispose!==void 0&&e.setDeleteStyle!==void 0},X$=function(e){const t=e.toCopyData();Ep=t;let o;return Ip=(o=e.workspace)!=null?o:null,t},Ro=function(e,t,o){return e&&t?Fd(e,t,o):Ep&&Ip?Fd(Ep,Ip):null},Fd=function(e,t,o){let n;t=t.isMutator?t:(n=t.getRootWorkspace())!=null?n:t;let u,g;return(g=(u=f($e.PASTER,e.paster,!1))==null?void 0:u.paste(e,t,o))!=null?g:null},q$=function(e){const t=e.toCopyData();return t?Ro(t,e.workspace):null},lr=function(e){return e.toCopyData!==void 0},zd=function(){ot.registry.register({name:Ks.ESCAPE,preconditionFn(e){return!e.options.readOnly},callback(e){return e.hideChaff(),!0},keyCodes:[Ke.ESC]})},Ud=function(){ot.registry.register({name:Ks.DELETE,preconditionFn(e){const t=F();return!e.options.readOnly&&t!=null&&ds(t)&&t.isDeletable()&&!bo.inProgress()},callback(e,t){return t.preventDefault(),e=F(),e instanceof $s?e.checkAndDelete():ds(e)&&e.isDeletable()&&(i.setGroup$$module$build$src$core$events$utils(!0),e.dispose(),i.setGroup$$module$build$src$core$events$utils(!1)),!0},keyCodes:[Ke.DELETE,Ke.BACKSPACE]})},Hd=function(){const e=ot.registry.createSerializedKey(Ke.C,[Ke.CTRL]),t=ot.registry.createSerializedKey(Ke.C,[Ke.ALT]),o=ot.registry.createSerializedKey(Ke.C,[Ke.META]);ot.registry.register({name:Ks.COPY,preconditionFn(n){const u=F();return!n.options.readOnly&&!bo.inProgress()&&u!=null&&ds(u)&&u.isDeletable()&&ri(u)&&u.isMovable()&&lr(u)},callback(n,u){return u.preventDefault(),n.hideChaff(),u=F(),!u||!lr(u)?!1:(Ho=u.toCopyData(),Wo=u.workspace instanceof cs?u.workspace:n,$n=ri(u)?u.getRelativeToSurfaceXY():null,!!Ho)},keyCodes:[e,t,o]})},Wd=function(){const e=ot.registry.createSerializedKey(Ke.X,[Ke.CTRL]),t=ot.registry.createSerializedKey(Ke.X,[Ke.ALT]),o=ot.registry.createSerializedKey(Ke.X,[Ke.META]);ot.registry.register({name:Ks.CUT,preconditionFn(n){const u=F();return!n.options.readOnly&&!bo.inProgress()&&u!=null&&ds(u)&&u.isDeletable()&&ri(u)&&u.isMovable()&&!u.workspace.isFlyout},callback(n){const u=F();return u instanceof $s?(Ho=u.toCopyData(),Wo=n,$n=u.getRelativeToSurfaceXY(),u.checkAndDelete(),!0):ds(u)&&u.isDeletable()&&lr(u)?(Ho=u.toCopyData(),Wo=n,$n=ri(u)?u.getRelativeToSurfaceXY():null,u.dispose(),!0):!1},keyCodes:[e,t,o]})},Gd=function(){const e=ot.registry.createSerializedKey(Ke.V,[Ke.CTRL]),t=ot.registry.createSerializedKey(Ke.V,[Ke.ALT]),o=ot.registry.createSerializedKey(Ke.V,[Ke.META]);ot.registry.register({name:Ks.PASTE,preconditionFn(n){return!n.options.readOnly&&!bo.inProgress()},callback(){if(!Ho||!Wo)return!1;if(!$n)return!!Ro(Ho,Wo);const{left:n,top:u,width:g,height:I}=Wo.getMetricsManager().getViewMetrics(!0);if(new rt(u,u+I,n,n+g).contains($n.x,$n.y))return!!Ro(Ho,Wo);const P=new ye(n+g/2,u+I/2);return!!Ro(Ho,Wo,P)},keyCodes:[e,t,o]})},Vd=function(){const e=ot.registry.createSerializedKey(Ke.Z,[Ke.CTRL]),t=ot.registry.createSerializedKey(Ke.Z,[Ke.ALT]),o=ot.registry.createSerializedKey(Ke.Z,[Ke.META]);ot.registry.register({name:Ks.UNDO,preconditionFn(n){return!n.options.readOnly&&!bo.inProgress()},callback(n,u){return n.hideChaff(),n.undo(!1),u.preventDefault(),!0},keyCodes:[e,t,o]})},Yd=function(){const e=ot.registry.createSerializedKey(Ke.Z,[Ke.SHIFT,Ke.CTRL]),t=ot.registry.createSerializedKey(Ke.Z,[Ke.SHIFT,Ke.ALT]),o=ot.registry.createSerializedKey(Ke.Z,[Ke.SHIFT,Ke.META]),n=ot.registry.createSerializedKey(Ke.Y,[Ke.CTRL]);ot.registry.register({name:Ks.REDO,preconditionFn(u){return!bo.inProgress()&&!u.options.readOnly},callback(u,g){return u.hideChaff(),u.undo(!0),g.preventDefault(),!0},keyCodes:[e,t,o,n]})},Kd=function(){zd(),Ud(),Hd(),Wd(),Gd(),Vd(),Yd()},Jd=function(e){const t=e.saveState();return e.getParameters().length&&(t.parameters=e.getParameters().map(o=>o.saveState())),t},Xd=function(e,t,o,n){if(e=e.loadState(o,n),!o.parameters)return e;for(const[u,g]of o.parameters.entries())e.insertParameter(t.loadState(g,n),u);return e},Z$=function(e){const t=Object.create(null),o=b($e.SERIALIZER,!0);for(const n in o){let u;const g=(u=o[n])==null?void 0:u.save(e);g&&(t[n]=g)}return t},Q$=function(e,t,{recordUndo:o=!1}={}){var n=b($e.SERIALIZER,!0);if(n){n=Object.entries(n).sort((g,I)=>I[1].priority-g[1].priority);var u=G();i.setRecordUndo$$module$build$src$core$events$utils(o),(o=i.getGroup$$module$build$src$core$events$utils())||i.setGroup$$module$build$src$core$events$utils(!0),io(),t instanceof cs&&t.setResizesEnabled(!1);for(const[,g]of n.reverse()){let I;(I=g)==null||I.clear(t)}for(const[g,I]of n.reverse())if(e[g]){let P;(P=I)==null||P.load(e[g],t)}t instanceof cs&&t.setResizesEnabled(!0),no(),z(new(ne(ee.FINISHED_LOADING))(t)),i.setGroup$$module$build$src$core$events$utils(o),i.setRecordUndo$$module$build$src$core$events$utils(u)}},eb=function(e,t){let o=null;o=typeof e=="string"?document.getElementById(e)||document.querySelector(e):e;var n;if(!document.contains(o)&&document!==((n=o)==null?void 0:n.ownerDocument))throw Error("Error: container is not in current document");e=new gs(t||{}),n=document.createElement("div"),Oe(n,"injectionDiv"),t!=null&&t.rtl&&Oe(n,"blocklyRTL"),n.tabIndex=0,xt(n,Et.LABEL,i.Msg$$module$build$src$core$msg.WORKSPACE_ARIA_LABEL),o.appendChild(n),t=tb(n,e);const u=sb(n,t,e);return ob(u),se(u),we(u),n.addEventListener("focusin",function(){se(u)}),W(n,"keydown",null,sl),W(qn(),"keydown",null,sl),(t=oi())&&W(t,"keydown",null,sl),u},tb=function(e,t){e.setAttribute("dir","LTR"),jt(t.hasCss,t.pathToMedia),e=ie(J.SVG,{xmlns:pr,"xmlns:html":Gs,"xmlns:xlink":is,version:"1.1",class:"blocklySvg",tabindex:"0"},e);const o=ie(J.DEFS,{},e),n=String(Math.random()).substring(2);return t.gridPattern=op.createDom(n,t.gridOptions,o),e},sb=function(e,t,o){o.parentWorkspace=null,o=new cs(o);const n=o.options;o.scale=n.zoomOptions.startScale,t.appendChild(o.createDom("blocklyMainBackground",e));var u=o.getRenderer().getClassName();return u&&Oe(e,u),(u=o.getTheme().getClassName())&&Oe(e,u),!n.hasCategories&&n.languageTree&&(e=o.addFlyout(J.SVG),At(e,t)),n.hasTrashcan&&o.addTrashcan(),n.zoomOptions&&n.zoomOptions.controls&&o.addZoomControls(),o.getThemeManager().subscribe(t,"workspaceBackgroundColour","background-color"),o.translate(0,0),o.addChangeListener(jd(o)),we(o),ad(),Mu(),Zu(),o},ob=function(e){const t=e.options;var o=e.getParentSvg();if(W(o.parentNode,"contextmenu",null,function(n){be(n)||n.preventDefault()}),o=W(window,"resize",null,function(){co(),e.hideComponents(!0),Yu(),dd(),we(e),tl(e)}),e.setResizeHandlerWrapper(o),ib(),t.languageTree){o=e.getToolbox();const n=e.getFlyout(!0);o?o.init():n&&(n.init(e),n.show(t.languageTree),typeof n.scrollToStart=="function"&&n.scrollToStart())}t.hasTrashcan&&e.trashcan.init(),t.zoomOptions&&t.zoomOptions.controls&&e.zoomControls_.init(),t.moveOptions&&t.moveOptions.scrollbars?(e.scrollbar=new Dp(e,t.moveOptions.scrollbars===!0||!!t.moveOptions.scrollbars.horizontal,t.moveOptions.scrollbars===!0||!!t.moveOptions.scrollbars.vertical,"blocklyMainWorkspaceScrollbar"),e.scrollbar.resize()):e.setMetrics({x:.5,y:.5}),t.hasSounds&&nb(t.pathToMedia,e)},sl=function(e){const t=X();t&&!(be(e)||t.rendered&&!t.isVisible())&&ot.registry.onKeyDown(t,e)},ib=function(){ly||(W(document,"scroll",null,function(){const e=B();for(let t=0,o;o=e[t];t++)o instanceof cs&&o.updateInverseScreenCTM()}),ue(document,"touchend",null,q),ue(document,"touchcancel",null,q)),ly=!0},nb=function(e,t){function o(){for(;u.length;){const g=u.pop();g&&V(g)}n.preload()}const n=t.getAudioManager();n.load([e+"click.mp3",e+"click.wav",e+"click.ogg"],"click"),n.load([e+"disconnect.wav",e+"disconnect.mp3",e+"disconnect.ogg"],"disconnect"),n.load([e+"delete.mp3",e+"delete.ogg",e+"delete.wav"],"delete");const u=[];u.push(W(document,"pointermove",null,o,!0)),u.push(W(document,"touchstart",null,o,!0))},qd=function(){Ye.registry.register({displayText(){return i.Msg$$module$build$src$core$msg.UNDO},preconditionFn(e){return 0t.length?cr(t):Ea(i.Msg$$module$build$src$core$msg.DELETE_ALL_BLOCKS.replace("%1",String(t.length)),function(o){o&&cr(t)})}},scopeType:Ye.ScopeType.WORKSPACE,id:"workspaceDelete",weight:6})},rb=function(){qd(),Zd(),Qd(),th(),sh(),ih()},nh=function(){Ye.registry.register({displayText(){return i.Msg$$module$build$src$core$msg.DUPLICATE_BLOCK},preconditionFn(e){return e=e.block,!e.isInFlyout&&e.isDeletable()&&e.isMovable()?e.isDuplicatable()?"enabled":"disabled":"hidden"},callback(e){if(e.block){var t=e.block.toCopyData();t&&Ro(t,e.block.workspace)}},scopeType:Ye.ScopeType.BLOCK,id:"blockDuplicate",weight:1})},rh=function(){Ye.registry.register({displayText(e){return e.block.hasIcon(_o.TYPE)?i.Msg$$module$build$src$core$msg.REMOVE_COMMENT:i.Msg$$module$build$src$core$msg.ADD_COMMENT},preconditionFn(e){return e=e.block,!e.isInFlyout&&e.workspace.options.comments&&!e.isCollapsed()&&e.isEditable()?"enabled":"hidden"},callback(e){e=e.block,e.hasIcon(_o.TYPE)?e.setCommentText(null):e.setCommentText("")},scopeType:Ye.ScopeType.BLOCK,id:"blockComment",weight:2})},ah=function(){Ye.registry.register({displayText(e){return e.block.getInputsInline()?i.Msg$$module$build$src$core$msg.EXTERNAL_INPUTS:i.Msg$$module$build$src$core$msg.INLINE_INPUTS},preconditionFn(e){if(e=e.block,!e.isInFlyout&&e.isMovable()&&!e.isCollapsed()){for(let t=1;t(t.has(Vt)?1:0),e.getInheritedDisabled()||t?"disabled":"enabled"}return"hidden"},callback(e){e=e.block;const t=i.getGroup$$module$build$src$core$events$utils();t||i.setGroup$$module$build$src$core$events$utils(!0),e.setDisabledReason(!e.hasDisabledReason(Vt),Vt),i.setGroup$$module$build$src$core$events$utils(t)},scopeType:Ye.ScopeType.BLOCK,id:"blockDisable",weight:5})},uh=function(){Ye.registry.register({displayText(e){var t=e.block;return e=t.getDescendants(!1).length,(t=t.getNextBlock())&&(e-=t.getDescendants(!1).length),e===1?i.Msg$$module$build$src$core$msg.DELETE_BLOCK:i.Msg$$module$build$src$core$msg.DELETE_X_BLOCKS.replace("%1",`${e}`)},preconditionFn(e){return!e.block.isInFlyout&&e.block.isDeletable()?"enabled":"hidden"},callback(e){e.block&&e.block.checkAndDelete()},scopeType:Ye.ScopeType.BLOCK,id:"blockDelete",weight:6})},dh=function(){Ye.registry.register({displayText(){return i.Msg$$module$build$src$core$msg.HELP},preconditionFn(e){return e=e.block,(typeof e.helpUrl=="function"?e.helpUrl():e.helpUrl)?"enabled":"hidden"},callback(e){e.block.showHelp()},scopeType:Ye.ScopeType.BLOCK,id:"blockHelp",weight:7})},hh=function(){Ye.registry.register({displayText:()=>i.Msg$$module$build$src$core$msg.REMOVE_COMMENT,preconditionFn(e){let t;return(t=e.comment)!=null&&t.isDeletable()?"enabled":"hidden"},callback(e){i.setGroup$$module$build$src$core$events$utils(!0);let t;(t=e.comment)==null||t.dispose(),i.setGroup$$module$build$src$core$events$utils(!1)},scopeType:Ye.ScopeType.COMMENT,id:"commentDelete",weight:6})},ph=function(){Ye.registry.register({displayText:()=>i.Msg$$module$build$src$core$msg.DUPLICATE_COMMENT,preconditionFn(e){let t;return(t=e.comment)!=null&&t.isMovable()?"enabled":"hidden"},callback(e){if(e.comment){var t=e.comment.toCopyData();t&&Ro(t,e.comment.workspace)}},scopeType:Ye.ScopeType.COMMENT,id:"commentDuplicate",weight:1})},gh=function(){Ye.registry.register({displayText:()=>i.Msg$$module$build$src$core$msg.ADD_COMMENT,preconditionFn:e=>{let t;return(t=e.workspace)!=null&&t.isMutator?"hidden":"enabled"},callback:(e,t)=>{if(e=e.workspace){i.setGroup$$module$build$src$core$events$utils(!0);var o=new xl(e);o.setText(i.Msg$$module$build$src$core$msg.WORKSPACE_COMMENT_DEFAULT_TEXT),o.moveTo(ab(new ye(t.clientX,t.clientY),e)),i.setSelected$$module$build$src$core$common(o),i.setGroup$$module$build$src$core$events$utils(!1)}},scopeType:Ye.ScopeType.WORKSPACE,id:"commentCreate",weight:8})},ab=function(e,t){var o=t.getInjectionDiv().getBoundingClientRect();return e=new ye(e.x-o.left,e.y-o.top),o=t.getOriginOffsetInPixels(),e=ye.difference(e,o),e.scale(1/t.scale),e},lb=function(){nh(),rh(),ah(),lh(),ch(),uh(),dh()},cb=function(){ph(),hh(),gh()},mh=function(){rb(),lb()},ub=function(e){return e.paste!==void 0},db=function(e){return e.getSvgRoot!==void 0},hb=function(e){return typeof e.id=="string"&&e.workspace!==void 0&&e.select!==void 0&&e.unselect!==void 0},pb=function(e){return e.isSelectable()},gb=function(e){X().hideChaff(e)},ge=ge||{},ge.scope={},ge.ASSUME_ES5=!1,ge.ASSUME_NO_NATIVE_MAP=!1,ge.ASSUME_NO_NATIVE_SET=!1,ge.SIMPLE_FROUND_POLYFILL=!1,ge.ISOLATE_POLYFILLS=!1,ge.FORCE_POLYFILL_PROMISE=!1,ge.FORCE_POLYFILL_PROMISE_WHEN_NO_UNHANDLED_REJECTION=!1,ge.defineProperty=ge.ASSUME_ES5||typeof Object.defineProperties=="function"?Object.defineProperty:function(e,t,o){return e==Array.prototype||e==Object.prototype||(e[t]=o.value),e},ge.getGlobal=function(e){e=[typeof globalThis=="object"&&globalThis,e,typeof window=="object"&&window,typeof self=="object"&&self,typeof eo=="object"&&eo];for(var t=0;t>>0,ge.propertyToPolyfillSymbol[u]=ge.IS_SYMBOL_NATIVE?ge.global.Symbol(u):ge.POLYFILL_PREFIX+o+"$"+u),ge.defineProperty(n,ge.propertyToPolyfillSymbol[u],{configurable:!0,writable:!0,value:t})))},ge.underscoreProtoCanBeSet=function(){var e={a:!0},t={};try{return t.__proto__=e,t.a}catch{}return!1},ge.setPrototypeOf=ge.TRUST_ES6_POLYFILLS&&typeof Object.setPrototypeOf=="function"?Object.setPrototypeOf:ge.underscoreProtoCanBeSet()?function(e,t){if(e.__proto__=t,e.__proto__!==t)throw new TypeError(e+" is not extensible");return e}:null,ge.arrayIteratorImpl=function(e){var t=0;return function(){return to&&(o=Math.max(o+u,0));o{const e=bb.length,t=[];for(let o=0;20>o;o++)t[o]=bb.charAt(Math.random()*e);return t.join("")}},PC=0,fh={TEST_ONLY:vb};fh.genUid=_,fh.getNextUniqueId=v;var yb="",ur=!0,$h=0,bh="ORPHANED_BLOCK",po=[],_b={FIRE_QUEUE:po,enqueueEvent:Ce,fireNow:he,fireInternal:Z,setGroupInternal:Q};i.disable$$module$build$src$core$events$utils,i.enable$$module$build$src$core$events$utils,i.getGroup$$module$build$src$core$events$utils,i.setGroup$$module$build$src$core$events$utils,i.setRecordUndo$$module$build$src$core$events$utils;var dr=Object.create(null),wb,ai=null,kb,hr=[],Cb={defineBlocksWithJsonArrayInternal:We},Ot={TEST_ONLY:Cb};Ot.createBlockDefinitionsFromJsonArray=i.createBlockDefinitionsFromJsonArray$$module$build$src$core$common,Ot.defineBlocks=i.defineBlocks$$module$build$src$core$common,Ot.defineBlocksWithJsonArray=Ae,Ot.draggingConnections=hr,Ot.getAllWorkspaces=B,Ot.getBlockTypeCounts=Ie,Ot.getMainWorkspace=X,Ot.getParentContainer=Te,Ot.getSelected=F,Ot.getWorkspaceById=re,Ot.registerWorkspace=N,Ot.setMainWorkspace=se,Ot.setParentContainer=ae,Ot.setSelected=i.setSelected$$module$build$src$core$common,Ot.svgResize=we,Ot.unregisterWorkpace=te;var Xi=class{constructor(){this.workspaceId=void 0,this.isUiEvent=!1,this.type="",this.group=i.getGroup$$module$build$src$core$events$utils(),this.recordUndo=G()}toJson(){return{type:this.type,group:this.group}}static fromJson(e,t,o){return o.isBlank=!1,o.group=e.group||"",o.workspaceId=t.id,o}isNull(){return!1}run(e){}getEventWorkspace_(){let e;if(this.workspaceId&&(e=re(this.workspaceId)),!e)throw Error("Workspace is null. Event must have been generated from real Blockly events.");return e}},Ss=class extends Xi{constructor(e){super(),this.recordUndo=!1,this.isUiEvent=!0,this.isBlank=typeof e>"u",this.workspaceId=e||""}},vh=class extends Ss{constructor(e,t,o){t=e?e.workspace.id:t,t===null&&(t=void 0),super(t),this.type=ee.CLICK,this.blockId=e?e.id:void 0,this.targetType=o}toJson(){const e=super.toJson();if(!this.targetType)throw Error("The click target type is undefined. Either pass a block to the constructor, or call fromJson");return e.targetType=this.targetType,e.blockId=this.blockId,e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new vh),t.targetType=e.targetType,t.blockId=e.blockId,t}},yh;(function(e){e.BLOCK="block",e.WORKSPACE="workspace",e.ZOOM_CONTROLS="zoom_controls"})(yh||(yh={})),r($e.EVENT,ee.CLICK,vh);var BC=750,Tb="ontouchstart"in globalThis||!!(globalThis.document&&document.documentElement&&"ontouchstart"in document.documentElement)||!(!globalThis.navigator||!globalThis.navigator.maxTouchPoints&&!globalThis.navigator.msMaxTouchPoints),nl=null,li={mousedown:["pointerdown"],mouseenter:["pointerenter"],mouseleave:["pointerleave"],mousemove:["pointermove"],mouseout:["pointerout"],mouseover:["pointerover"],mouseup:["pointerup","pointercancel"],touchend:["pointerup"],touchcancel:["pointercancel"]},rl=0,ci={TOUCH_ENABLED:Tb,TOUCH_MAP:li};ci.checkTouchIdentifier=U,ci.clearTouchIdentifier=K,ci.getTouchIdentifierFromEvent=A,ci.longStart=k,ci.longStop=q,ci.shouldHandleEvent=O;var _h,Sb,Eb,Ib,al,ll,wh,xb,Db,Ab;(function(e){function t(n){return o.includes(n.toUpperCase())}_h=e;const o=_h.toUpperCase();Sb=t("JavaFX"),Eb=t("WebKit"),Ib=t("Gecko")&&!Eb,al=t("Android"),e=globalThis.navigator&&globalThis.navigator.maxTouchPoints,ll=t("iPad")||t("Macintosh")&&0{n.push(this.componentData.get(u))}),n.sort(function(u,g){return u.weight-g.weight}),n.forEach(function(u){o.push(u.component)})}else e.forEach(n=>{o.push(this.componentData.get(n).component)});return o}};gt.Capability=mo,(function(e){e=e.ComponentWeight||(e.ComponentWeight={}),e[e.TOOLBOX_WEIGHT=0]="TOOLBOX_WEIGHT",e[e.FLYOUT_WEIGHT=1]="FLYOUT_WEIGHT",e[e.TRASHCAN_WEIGHT=2]="TRASHCAN_WEIGHT",e[e.ZOOM_CONTROLS_WEIGHT=3]="ZOOM_CONTROLS_WEIGHT"})(gt||(gt={})),gt.ComponentWeight;var Th=!1,Sh=` .blocklySvg { background-color: #fff; outline: none; @@ -719,7 +719,7 @@ input[type=number] { z-index: 80; pointer-events: none; } -`,Sh={};Sh.inject=jt,Sh.register=Be;var ye=class{constructor(e,t){this.x=e,this.y=t}clone(){return new ye(this.x,this.y)}scale(e){return this.x*=e,this.y*=e,this}translate(e,t){return this.x+=e,this.y+=t,this}static equals(e,t){return e===t?!0:e&&t?e.x===t.x&&e.y===t.y:!1}static distance(e,t){const o=e.x-t.x;return e=e.y-t.y,Math.sqrt(o*o+e*e)}static magnitude(e){return Math.sqrt(e.x*e.x+e.y*e.y)}static difference(e,t){return new ye(e.x-t.x,e.y-t.y)}static sum(e,t){return new ye(e.x+t.x,e.y+t.y)}},pr="http://www.w3.org/2000/svg",Gs="http://www.w3.org/1999/xhtml",is="http://www.w3.org/1999/xlink",fo;(function(e){e[e.ELEMENT_NODE=1]="ELEMENT_NODE",e[e.TEXT_NODE=3]="TEXT_NODE",e[e.COMMENT_NODE=8]="COMMENT_NODE"})(fo||(fo={}));var Es=null,Eh=0,cl=null,Dt={HTML_NS:Gs};Dt.NodeType=fo,Dt.SVG_NS=pr,Dt.XLINK_NS=is,Dt.addClass=Re,Dt.createSvgElement=ie,Dt.getFastTextWidth=Io,Dt.getFastTextWidthWithSizeString=Bs,Dt.getTextWidth=Un,Dt.hasClass=Zo,Dt.insertAfter=At,Dt.measureFontMetrics=ro,Dt.removeClass=ze,Dt.removeClasses=Ps,Dt.removeNode=Ze,Dt.setCssTransform=Qo,Dt.startTextWidthCache=io,Dt.stopTextWidthCache=no;var J=class{constructor(e){this.tagName=e}toString(){return this.tagName}};J.ANIMATE=new J("animate"),J.CIRCLE=new J("circle"),J.CLIPPATH=new J("clipPath"),J.DEFS=new J("defs"),J.FECOMPOSITE=new J("feComposite"),J.FECOMPONENTTRANSFER=new J("feComponentTransfer"),J.FEFLOOD=new J("feFlood"),J.FEFUNCA=new J("feFuncA"),J.FEGAUSSIANBLUR=new J("feGaussianBlur"),J.FEPOINTLIGHT=new J("fePointLight"),J.FESPECULARLIGHTING=new J("feSpecularLighting"),J.FILTER=new J("filter"),J.FOREIGNOBJECT=new J("foreignObject"),J.G=new J("g"),J.IMAGE=new J("image"),J.LINE=new J("line"),J.PATH=new J("path"),J.PATTERN=new J("pattern"),J.POLYGON=new J("polygon"),J.RECT=new J("rect"),J.SVG=new J("svg"),J.TEXT=new J("text"),J.TSPAN=new J("tspan");var rt=class{constructor(e,t,o,n){this.top=e,this.bottom=t,this.left=o,this.right=n}clone(){return new rt(this.top,this.bottom,this.left,this.right)}getHeight(){return this.bottom-this.top}getWidth(){return this.right-this.left}contains(e,t){return e>=this.left&&e<=this.right&&t>=this.top&&t<=this.bottom}intersects(e){return this.left<=e.right&&this.right>=e.left&&this.bottom>=e.top&&this.top<=e.bottom}static equals(e,t){return e===t?!0:e&&t?e.top===t.top&&e.bottom===t.bottom&&e.left===t.left&&e.right===t.right:!1}static createFromPoint(e,t,o){const n=e.x;return e=e.y,new rt(e,e+o,n,n+t)}},Xe=class{constructor(e,t){this.width=e,this.height=t}static equals(e,t){return e===t?!0:e&&t?e.width===t.width&&e.height===t.height:!1}static max(e,t){return new Xe(Math.max(e.width,t.width),Math.max(e.height,t.height))}static min(e,t){return new Xe(Math.min(e.width,t.width),Math.min(e.height,t.height))}},Pb={getSizeInternal:Km},Mo={TEST_ONLY:Pb};Mo.getBorderBox=mu,Mo.getComputedStyle=js,Mo.getContainerOffsetToScrollInto=fu,Mo.getPageOffset=xo,Mo.getSize=Hn,Mo.getViewportPageOffset=gu,Mo.scrollIntoContainerView=ma;var Bb=/translate\(\s*([-+\d.e]+)([ ,]\s*([-+\d.e]+)\s*)?/,jb=/transform:\s*translate(?:3d)?\(\s*([-+\d.e]+)\s*px([ ,]\s*([-+\d.e]+)\s*px)?/,FC={XY_REGEX:Bb,XY_STYLE_REGEX:jb},ui={TEST_ONLY:FC};ui.getDocumentScroll=bu,ui.getInjectionDivXY=fa,ui.getRelativeXY=Wn,ui.getViewportBBox=$u,ui.screenToWsCoordinates=Ym,ui.wsToScreenCoordinates=Jm;var yt=class{constructor(e,t,o,n,u){this.workspace=e,this.horizontal=t,this.oldHostMetrics=null,this.ratio=1,this.origin=new ye(0,0),this.startDragHandle=this.handlePosition=this.handleLength=this.scrollbarLength=this.startDragMouse=0,this.containerVisible=this.isHandleVisible=!0,this.position=new ye(0,0),this.onMouseMoveWrapper_=this.onMouseUpWrapper_=null,this.pair=o||!1,this.margin=u!==void 0?u:yt.DEFAULT_SCROLLBAR_MARGIN,e="blocklyScrollbar"+(this.horizontal?"Horizontal":"Vertical"),n&&(e+=" "+n),this.outerSvg=ie(J.SVG,{class:e}),n=ie(J.G,{},this.outerSvg),this.svgBackground=ie(J.RECT,{class:"blocklyScrollbarBackground"},n),e=Math.floor((yt.scrollbarThickness-5)/2),this.svgHandle=ie(J.RECT,{class:"blocklyScrollbarHandle",rx:e,ry:e},n),this.workspace.getThemeManager().subscribe(this.svgHandle,"scrollbarColour","fill"),this.workspace.getThemeManager().subscribe(this.svgHandle,"scrollbarOpacity","fill-opacity"),At(this.outerSvg,this.workspace.getParentSvg()),this.setInitialThickness(),t?(this.lengthAttribute_="width",this.positionAttribute_="x"):(this.lengthAttribute_="height",this.positionAttribute_="y"),this.onMouseDownBarWrapper_=H(this.svgBackground,"pointerdown",this,this.onMouseDownBar),this.onMouseDownHandleWrapper_=H(this.svgHandle,"pointerdown",this,this.onMouseDownHandle)}setInitialThickness(){const e=yt.scrollbarThickness;this.horizontal?(this.svgBackground.setAttribute("height",String(e)),this.outerSvg.setAttribute("height",String(e)),this.svgHandle.setAttribute("height",String(e-5)),this.svgHandle.setAttribute("y","2.5")):(this.svgBackground.setAttribute("width",String(e)),this.outerSvg.setAttribute("width",String(e)),this.svgHandle.setAttribute("width",String(e-5)),this.svgHandle.setAttribute("x","2.5"))}dispose(){this.cleanUp(),V(this.onMouseDownBarWrapper_),V(this.onMouseDownHandleWrapper_),Ze(this.outerSvg),this.workspace.getThemeManager().unsubscribe(this.svgHandle)}constrainHandleLength(e){return e=0>=e||isNaN(e)?0:Math.min(e,this.scrollbarLength)}setHandleLength(e){this.handleLength=e,this.svgHandle.setAttribute(this.lengthAttribute_,String(this.handleLength))}constrainHandlePosition(e){return e=0>=e||isNaN(e)?0:Math.min(e,this.scrollbarLength-this.handleLength)}setHandlePosition(e){this.handlePosition=e,this.svgHandle.setAttribute(this.positionAttribute_,String(this.handlePosition))}setScrollbarLength(e){this.scrollbarLength=e,this.outerSvg.setAttribute(this.lengthAttribute_,String(this.scrollbarLength)),this.svgBackground.setAttribute(this.lengthAttribute_,String(this.scrollbarLength))}setPosition(e,t){this.position.x=e,this.position.y=t,Qo(this.outerSvg,"translate("+(this.position.x+this.origin.x)+"px,"+(this.position.y+this.origin.y)+"px)")}resize(e){!e&&(e=this.workspace.getMetrics(),!e)||this.oldHostMetrics&&yt.metricsAreEquivalent(e,this.oldHostMetrics)||(this.horizontal?this.resizeHorizontal(e):this.resizeVertical(e),this.oldHostMetrics=e,this.updateMetrics())}requiresViewResize(e){return this.oldHostMetrics?this.oldHostMetrics.viewWidth!==e.viewWidth||this.oldHostMetrics.viewHeight!==e.viewHeight||this.oldHostMetrics.absoluteLeft!==e.absoluteLeft||this.oldHostMetrics.absoluteTop!==e.absoluteTop:!0}resizeHorizontal(e){this.requiresViewResize(e)?this.resizeViewHorizontal(e):this.resizeContentHorizontal(e)}resizeViewHorizontal(e){var t=e.viewWidth-2*this.margin;this.pair&&(t-=yt.scrollbarThickness),this.setScrollbarLength(Math.max(0,t)),t=e.absoluteLeft+this.margin,this.pair&&this.workspace.RTL&&(t+=yt.scrollbarThickness),this.setPosition(t,e.absoluteTop+e.viewHeight-yt.scrollbarThickness-this.margin),this.resizeContentHorizontal(e)}resizeContentHorizontal(e){if(e.viewWidth>=e.scrollWidth)this.setHandleLength(this.scrollbarLength),this.setHandlePosition(0),this.pair||this.setVisible(!1);else{this.pair||this.setVisible(!0);var t=this.scrollbarLength*e.viewWidth/e.scrollWidth;t=this.constrainHandleLength(t),this.setHandleLength(t),t=e.scrollWidth-e.viewWidth;var o=this.scrollbarLength-this.handleLength;e=(e.viewLeft-e.scrollLeft)/t*o,e=this.constrainHandlePosition(e),this.setHandlePosition(e),this.ratio=o/t}}resizeVertical(e){this.requiresViewResize(e)?this.resizeViewVertical(e):this.resizeContentVertical(e)}resizeViewVertical(e){let t=e.viewHeight-2*this.margin;this.pair&&(t-=yt.scrollbarThickness),this.setScrollbarLength(Math.max(0,t)),this.setPosition(this.workspace.RTL?e.absoluteLeft+this.margin:e.absoluteLeft+e.viewWidth-yt.scrollbarThickness-this.margin,e.absoluteTop+this.margin),this.resizeContentVertical(e)}resizeContentVertical(e){if(e.viewHeight>=e.scrollHeight)this.setHandleLength(this.scrollbarLength),this.setHandlePosition(0),this.pair||this.setVisible(!1);else{this.pair||this.setVisible(!0);var t=this.scrollbarLength*e.viewHeight/e.scrollHeight;t=this.constrainHandleLength(t),this.setHandleLength(t),t=e.scrollHeight-e.viewHeight;var o=this.scrollbarLength-this.handleLength;e=(e.viewTop-e.scrollTop)/t*o,e=this.constrainHandlePosition(e),this.setHandlePosition(e),this.ratio=o/t}}isVisible(){return this.isHandleVisible}setContainerVisible(e){const t=e!==this.containerVisible;this.containerVisible=e,t&&this.updateDisplay_()}setVisible(e){if(this.pair)throw Error("Unable to toggle visibility of paired scrollbars.");this.setVisibleInternal(e)}setVisibleInternal(e){const t=e!==this.isVisible();this.isHandleVisible=e,t&&this.updateDisplay_()}updateDisplay_(){this.containerVisible&&this.isVisible()?this.outerSvg.setAttribute("display","block"):this.outerSvg.setAttribute("display","none")}onMouseDownBar(e){if(this.workspace.markFocused(),Y(),this.cleanUp(),pe(e))e.stopPropagation();else{var t=fe(e,this.workspace.getParentSvg(),this.workspace.getInverseScreenCTM());t=this.horizontal?t.x:t.y;var o=fa(this.svgHandle);o=this.horizontal?o.x:o.y;var n=this.handlePosition,u=.95*this.handleLength;t<=o?n-=u:t>=o+this.handleLength&&(n+=u),this.setHandlePosition(this.constrainHandlePosition(n)),this.updateMetrics(),e.stopPropagation(),e.preventDefault()}}onMouseDownHandle(e){this.workspace.markFocused(),this.cleanUp(),pe(e)?e.stopPropagation():(this.startDragHandle=this.handlePosition,this.startDragMouse=this.horizontal?e.clientX:e.clientY,this.onMouseUpWrapper_=H(document,"pointerup",this,this.onMouseUpHandle),this.onMouseMoveWrapper_=H(document,"pointermove",this,this.onMouseMoveHandle),e.stopPropagation(),e.preventDefault())}onMouseMoveHandle(e){this.setHandlePosition(this.constrainHandlePosition(this.startDragHandle+((this.horizontal?e.clientX:e.clientY)-this.startDragMouse))),this.updateMetrics()}onMouseUpHandle(){Y(),this.cleanUp()}cleanUp(){this.workspace.hideChaff(!0),this.onMouseUpWrapper_&&(V(this.onMouseUpWrapper_),this.onMouseUpWrapper_=null),this.onMouseMoveWrapper_&&(V(this.onMouseMoveWrapper_),this.onMouseMoveWrapper_=null)}getRatio_(){let e=this.handlePosition/(this.scrollbarLength-this.handleLength);return isNaN(e)&&(e=0),e}updateMetrics(){const e=this.getRatio_();this.horizontal?this.workspace.setMetrics({x:e}):this.workspace.setMetrics({y:e})}set(e,t){this.setHandlePosition(this.constrainHandlePosition(e*this.ratio)),(t||t===void 0)&&this.updateMetrics()}setOrigin(e,t){this.origin=new ye(e,t)}static metricsAreEquivalent(e,t){return e.viewWidth===t.viewWidth&&e.viewHeight===t.viewHeight&&e.viewLeft===t.viewLeft&&e.viewTop===t.viewTop&&e.absoluteTop===t.absoluteTop&&e.absoluteLeft===t.absoluteLeft&&e.scrollWidth===t.scrollWidth&&e.scrollHeight===t.scrollHeight&&e.scrollLeft===t.scrollLeft&&e.scrollTop===t.scrollTop}};yt.scrollbarThickness=kb?25:15,yt.DEFAULT_SCROLLBAR_MARGIN=.5;var ul={parseFromString:function(){throw Error("DOMParser was not found in the global scope and was not properly injected using injectDependencies")}},Ih={serializeToString:function(){throw Error("XMLSerializer was not foundin the global scope and was not properly injected using injectDependencies")}},{document:dl,DOMParser:gr,XMLSerializer:mr}=globalThis;gr&&(ul=new gr),mr&&(Ih=new mr);var Fb="https://developers.google.com/blockly/xml",zC=/[\x00-\x09\x0B\x0C\x0E-\x1F]/g,Xi={NAME_SPACE:Fb};Xi.createElement=i.createElement$$module$build$src$core$utils$xml,Xi.createTextNode=i.createTextNode$$module$build$src$core$utils$xml,Xi.domToText=Li,Xi.injectDependencies=qm,Xi.textToDom=i.textToDom$$module$build$src$core$utils$xml;var xh="categoryToolbox",zb="flyoutToolbox",Ge;(function(e){e[e.TOP=0]="TOP",e[e.BOTTOM=1]="BOTTOM",e[e.LEFT=2]="LEFT",e[e.RIGHT=3]="RIGHT"})(Ge||(Ge={}));var Ub={hasCategoriesInternal:Qm},Lo={};Lo.Position=Ge,Lo.TEST_ONLY=Ub,Lo.convertFlyoutDefToJsonArray=Gn,Lo.convertToolboxDefToJson=$a,Lo.hasCategories=ba,Lo.isCategoryCollapsible=va,Lo.parseToolboxTree=yu;var $o;(function(e){e[e.TOP=0]="TOP",e[e.BOTTOM=1]="BOTTOM"})($o||($o={}));var Zi;(function(e){e[e.LEFT=0]="LEFT",e[e.RIGHT=1]="RIGHT"})(Zi||(Zi={}));var Po;(function(e){e[e.UP=0]="UP",e[e.DOWN=1]="DOWN"})(Po||(Po={}));var di={};di.bumpDirection=Po,di.bumpPositionRect=ka,di.getCornerOppositeToolbox=wa,di.getStartPositionRect=_a,di.horizontalPosition=Zi,di.verticalPosition=$o;var Gt={width:96,height:124,url:"sprites.png"},Hb=class{constructor(e){this.workspace=e,this.id="zoomControls",this.boundEvents=[],this.zoomResetGroup=this.zoomOutGroup=this.zoomInGroup=null,this.HEIGHT=this.WIDTH=32,this.SMALL_SPACING=2,this.LARGE_SPACING=11,this.MARGIN_HORIZONTAL=this.MARGIN_VERTICAL=20,this.svgGroup=null,this.top=this.left=0,this.initialized=!1}createDom(){this.svgGroup=ie(J.G,{});const e=String(Math.random()).substring(2);return this.createZoomOutSvg(e),this.createZoomInSvg(e),this.workspace.isMovable()&&this.createZoomResetSvg(e),this.svgGroup}init(){this.workspace.getComponentManager().addComponent({component:this,weight:gt.ComponentWeight.ZOOM_CONTROLS_WEIGHT,capabilities:[gt.Capability.POSITIONABLE]}),this.initialized=!0}dispose(){this.workspace.getComponentManager().removeComponent("zoomControls"),this.svgGroup&&Ze(this.svgGroup);for(const e of this.boundEvents)V(e);this.boundEvents.length=0}getBoundingRectangle(){let e=this.SMALL_SPACING+2*this.HEIGHT;return this.zoomResetGroup&&(e+=this.LARGE_SPACING+this.HEIGHT),new rt(this.top,this.top+e,this.left,this.left+this.WIDTH)}position(e,t){if(this.initialized){var o=wa(this.workspace,e),n=this.SMALL_SPACING+2*this.HEIGHT;if(this.zoomResetGroup&&(n+=this.LARGE_SPACING+this.HEIGHT),e=_a(o,new Xe(this.WIDTH,n),this.MARGIN_HORIZONTAL,this.MARGIN_VERTICAL,e,this.workspace),o=o.vertical,t=ka(e,this.MARGIN_VERTICAL,o===$o.TOP?Po.DOWN:Po.UP,t),o===$o.TOP){var u=this.SMALL_SPACING+this.HEIGHT,g;(g=this.zoomInGroup)==null||g.setAttribute("transform","translate(0, "+u+")"),this.zoomResetGroup&&this.zoomResetGroup.setAttribute("transform","translate(0, "+(u+this.LARGE_SPACING+this.HEIGHT)+")")}else{g=this.zoomResetGroup?this.LARGE_SPACING+this.HEIGHT:0;let L;(L=this.zoomInGroup)==null||L.setAttribute("transform","translate(0, "+g+")"),g=g+this.SMALL_SPACING+this.HEIGHT,(u=this.zoomOutGroup)==null||u.setAttribute("transform","translate(0, "+g+")")}this.top=t.top,this.left=t.left;var I;(I=this.svgGroup)==null||I.setAttribute("transform","translate("+this.left+","+this.top+")")}}createZoomOutSvg(e){this.zoomOutGroup=ie(J.G,{class:"blocklyZoom blocklyZoomOut"},this.svgGroup);const t=ie(J.CLIPPATH,{id:"blocklyZoomoutClipPath"+e},this.zoomOutGroup);ie(J.RECT,{width:32,height:32},t),ie(J.IMAGE,{width:Gt.width,height:Gt.height,x:-64,y:-92,"clip-path":"url(#blocklyZoomoutClipPath"+e+")"},this.zoomOutGroup).setAttributeNS(is,"xlink:href",this.workspace.options.pathToMedia+Gt.url),this.boundEvents.push(H(this.zoomOutGroup,"pointerdown",null,this.zoom.bind(this,-1)))}createZoomInSvg(e){this.zoomInGroup=ie(J.G,{class:"blocklyZoom blocklyZoomIn"},this.svgGroup);const t=ie(J.CLIPPATH,{id:"blocklyZoominClipPath"+e},this.zoomInGroup);ie(J.RECT,{width:32,height:32},t),ie(J.IMAGE,{width:Gt.width,height:Gt.height,x:-32,y:-92,"clip-path":"url(#blocklyZoominClipPath"+e+")"},this.zoomInGroup).setAttributeNS(is,"xlink:href",this.workspace.options.pathToMedia+Gt.url),this.boundEvents.push(H(this.zoomInGroup,"pointerdown",null,this.zoom.bind(this,1)))}zoom(e,t){this.workspace.markFocused(),this.workspace.zoomCenter(e),this.fireZoomEvent(),Y(),t.stopPropagation(),t.preventDefault()}createZoomResetSvg(e){this.zoomResetGroup=ie(J.G,{class:"blocklyZoom blocklyZoomReset"},this.svgGroup);const t=ie(J.CLIPPATH,{id:"blocklyZoomresetClipPath"+e},this.zoomResetGroup);ie(J.RECT,{width:32,height:32},t),ie(J.IMAGE,{width:Gt.width,height:Gt.height,y:-92,"clip-path":"url(#blocklyZoomresetClipPath"+e+")"},this.zoomResetGroup).setAttributeNS(is,"xlink:href",this.workspace.options.pathToMedia+Gt.url),this.boundEvents.push(H(this.zoomResetGroup,"pointerdown",null,this.resetZoom.bind(this)))}resetZoom(e){this.workspace.markFocused();const t=Math.log(this.workspace.options.zoomOptions.startScale/this.workspace.scale)/Math.log(this.workspace.options.zoomOptions.scaleSpeed);this.workspace.beginCanvasTransition(),this.workspace.zoomCenter(t),this.workspace.scrollCenter(),setTimeout(this.workspace.endCanvasTransition.bind(this.workspace),500),this.fireZoomEvent(),Y(),e.stopPropagation(),e.preventDefault()}fireZoomEvent(){const e=new(ne(ee.CLICK))(null,this.workspace.id,"zoom_controls");z(e)}};Be(` +`,Eh={};Eh.inject=jt,Eh.register=Be;var ye=class{constructor(e,t){this.x=e,this.y=t}clone(){return new ye(this.x,this.y)}scale(e){return this.x*=e,this.y*=e,this}translate(e,t){return this.x+=e,this.y+=t,this}static equals(e,t){return e===t?!0:e&&t?e.x===t.x&&e.y===t.y:!1}static distance(e,t){const o=e.x-t.x;return e=e.y-t.y,Math.sqrt(o*o+e*e)}static magnitude(e){return Math.sqrt(e.x*e.x+e.y*e.y)}static difference(e,t){return new ye(e.x-t.x,e.y-t.y)}static sum(e,t){return new ye(e.x+t.x,e.y+t.y)}},pr="http://www.w3.org/2000/svg",Gs="http://www.w3.org/1999/xhtml",is="http://www.w3.org/1999/xlink",fo;(function(e){e[e.ELEMENT_NODE=1]="ELEMENT_NODE",e[e.TEXT_NODE=3]="TEXT_NODE",e[e.COMMENT_NODE=8]="COMMENT_NODE"})(fo||(fo={}));var Es=null,Ih=0,ul=null,Dt={HTML_NS:Gs};Dt.NodeType=fo,Dt.SVG_NS=pr,Dt.XLINK_NS=is,Dt.addClass=Oe,Dt.createSvgElement=ie,Dt.getFastTextWidth=Io,Dt.getFastTextWidthWithSizeString=Bs,Dt.getTextWidth=Un,Dt.hasClass=Zo,Dt.insertAfter=At,Dt.measureFontMetrics=ro,Dt.removeClass=ze,Dt.removeClasses=Ps,Dt.removeNode=Qe,Dt.setCssTransform=Qo,Dt.startTextWidthCache=io,Dt.stopTextWidthCache=no;var J=class{constructor(e){this.tagName=e}toString(){return this.tagName}};J.ANIMATE=new J("animate"),J.CIRCLE=new J("circle"),J.CLIPPATH=new J("clipPath"),J.DEFS=new J("defs"),J.FECOMPOSITE=new J("feComposite"),J.FECOMPONENTTRANSFER=new J("feComponentTransfer"),J.FEFLOOD=new J("feFlood"),J.FEFUNCA=new J("feFuncA"),J.FEGAUSSIANBLUR=new J("feGaussianBlur"),J.FEPOINTLIGHT=new J("fePointLight"),J.FESPECULARLIGHTING=new J("feSpecularLighting"),J.FILTER=new J("filter"),J.FOREIGNOBJECT=new J("foreignObject"),J.G=new J("g"),J.IMAGE=new J("image"),J.LINE=new J("line"),J.PATH=new J("path"),J.PATTERN=new J("pattern"),J.POLYGON=new J("polygon"),J.RECT=new J("rect"),J.SVG=new J("svg"),J.TEXT=new J("text"),J.TSPAN=new J("tspan");var rt=class{constructor(e,t,o,n){this.top=e,this.bottom=t,this.left=o,this.right=n}clone(){return new rt(this.top,this.bottom,this.left,this.right)}getHeight(){return this.bottom-this.top}getWidth(){return this.right-this.left}contains(e,t){return e>=this.left&&e<=this.right&&t>=this.top&&t<=this.bottom}intersects(e){return this.left<=e.right&&this.right>=e.left&&this.bottom>=e.top&&this.top<=e.bottom}static equals(e,t){return e===t?!0:e&&t?e.top===t.top&&e.bottom===t.bottom&&e.left===t.left&&e.right===t.right:!1}static createFromPoint(e,t,o){const n=e.x;return e=e.y,new rt(e,e+o,n,n+t)}},Ze=class{constructor(e,t){this.width=e,this.height=t}static equals(e,t){return e===t?!0:e&&t?e.width===t.width&&e.height===t.height:!1}static max(e,t){return new Ze(Math.max(e.width,t.width),Math.max(e.height,t.height))}static min(e,t){return new Ze(Math.min(e.width,t.width),Math.min(e.height,t.height))}},jb={getSizeInternal:Jm},No={TEST_ONLY:jb};No.getBorderBox=fu,No.getComputedStyle=js,No.getContainerOffsetToScrollInto=$u,No.getPageOffset=xo,No.getSize=Hn,No.getViewportPageOffset=mu,No.scrollIntoContainerView=fa;var Fb=/translate\(\s*([-+\d.e]+)([ ,]\s*([-+\d.e]+)\s*)?/,zb=/transform:\s*translate(?:3d)?\(\s*([-+\d.e]+)\s*px([ ,]\s*([-+\d.e]+)\s*px)?/,zC={XY_REGEX:Fb,XY_STYLE_REGEX:zb},ui={TEST_ONLY:zC};ui.getDocumentScroll=vu,ui.getInjectionDivXY=$a,ui.getRelativeXY=Wn,ui.getViewportBBox=bu,ui.screenToWsCoordinates=Xm,ui.wsToScreenCoordinates=qm;var yt=class{constructor(e,t,o,n,u){this.workspace=e,this.horizontal=t,this.oldHostMetrics=null,this.ratio=1,this.origin=new ye(0,0),this.startDragHandle=this.handlePosition=this.handleLength=this.scrollbarLength=this.startDragMouse=0,this.containerVisible=this.isHandleVisible=!0,this.position=new ye(0,0),this.onMouseMoveWrapper_=this.onMouseUpWrapper_=null,this.pair=o||!1,this.margin=u!==void 0?u:yt.DEFAULT_SCROLLBAR_MARGIN,e="blocklyScrollbar"+(this.horizontal?"Horizontal":"Vertical"),n&&(e+=" "+n),this.outerSvg=ie(J.SVG,{class:e}),n=ie(J.G,{},this.outerSvg),this.svgBackground=ie(J.RECT,{class:"blocklyScrollbarBackground"},n),e=Math.floor((yt.scrollbarThickness-5)/2),this.svgHandle=ie(J.RECT,{class:"blocklyScrollbarHandle",rx:e,ry:e},n),this.workspace.getThemeManager().subscribe(this.svgHandle,"scrollbarColour","fill"),this.workspace.getThemeManager().subscribe(this.svgHandle,"scrollbarOpacity","fill-opacity"),At(this.outerSvg,this.workspace.getParentSvg()),this.setInitialThickness(),t?(this.lengthAttribute_="width",this.positionAttribute_="x"):(this.lengthAttribute_="height",this.positionAttribute_="y"),this.onMouseDownBarWrapper_=W(this.svgBackground,"pointerdown",this,this.onMouseDownBar),this.onMouseDownHandleWrapper_=W(this.svgHandle,"pointerdown",this,this.onMouseDownHandle)}setInitialThickness(){const e=yt.scrollbarThickness;this.horizontal?(this.svgBackground.setAttribute("height",String(e)),this.outerSvg.setAttribute("height",String(e)),this.svgHandle.setAttribute("height",String(e-5)),this.svgHandle.setAttribute("y","2.5")):(this.svgBackground.setAttribute("width",String(e)),this.outerSvg.setAttribute("width",String(e)),this.svgHandle.setAttribute("width",String(e-5)),this.svgHandle.setAttribute("x","2.5"))}dispose(){this.cleanUp(),V(this.onMouseDownBarWrapper_),V(this.onMouseDownHandleWrapper_),Qe(this.outerSvg),this.workspace.getThemeManager().unsubscribe(this.svgHandle)}constrainHandleLength(e){return e=0>=e||isNaN(e)?0:Math.min(e,this.scrollbarLength)}setHandleLength(e){this.handleLength=e,this.svgHandle.setAttribute(this.lengthAttribute_,String(this.handleLength))}constrainHandlePosition(e){return e=0>=e||isNaN(e)?0:Math.min(e,this.scrollbarLength-this.handleLength)}setHandlePosition(e){this.handlePosition=e,this.svgHandle.setAttribute(this.positionAttribute_,String(this.handlePosition))}setScrollbarLength(e){this.scrollbarLength=e,this.outerSvg.setAttribute(this.lengthAttribute_,String(this.scrollbarLength)),this.svgBackground.setAttribute(this.lengthAttribute_,String(this.scrollbarLength))}setPosition(e,t){this.position.x=e,this.position.y=t,Qo(this.outerSvg,"translate("+(this.position.x+this.origin.x)+"px,"+(this.position.y+this.origin.y)+"px)")}resize(e){!e&&(e=this.workspace.getMetrics(),!e)||this.oldHostMetrics&&yt.metricsAreEquivalent(e,this.oldHostMetrics)||(this.horizontal?this.resizeHorizontal(e):this.resizeVertical(e),this.oldHostMetrics=e,this.updateMetrics())}requiresViewResize(e){return this.oldHostMetrics?this.oldHostMetrics.viewWidth!==e.viewWidth||this.oldHostMetrics.viewHeight!==e.viewHeight||this.oldHostMetrics.absoluteLeft!==e.absoluteLeft||this.oldHostMetrics.absoluteTop!==e.absoluteTop:!0}resizeHorizontal(e){this.requiresViewResize(e)?this.resizeViewHorizontal(e):this.resizeContentHorizontal(e)}resizeViewHorizontal(e){var t=e.viewWidth-2*this.margin;this.pair&&(t-=yt.scrollbarThickness),this.setScrollbarLength(Math.max(0,t)),t=e.absoluteLeft+this.margin,this.pair&&this.workspace.RTL&&(t+=yt.scrollbarThickness),this.setPosition(t,e.absoluteTop+e.viewHeight-yt.scrollbarThickness-this.margin),this.resizeContentHorizontal(e)}resizeContentHorizontal(e){if(e.viewWidth>=e.scrollWidth)this.setHandleLength(this.scrollbarLength),this.setHandlePosition(0),this.pair||this.setVisible(!1);else{this.pair||this.setVisible(!0);var t=this.scrollbarLength*e.viewWidth/e.scrollWidth;t=this.constrainHandleLength(t),this.setHandleLength(t),t=e.scrollWidth-e.viewWidth;var o=this.scrollbarLength-this.handleLength;e=(e.viewLeft-e.scrollLeft)/t*o,e=this.constrainHandlePosition(e),this.setHandlePosition(e),this.ratio=o/t}}resizeVertical(e){this.requiresViewResize(e)?this.resizeViewVertical(e):this.resizeContentVertical(e)}resizeViewVertical(e){let t=e.viewHeight-2*this.margin;this.pair&&(t-=yt.scrollbarThickness),this.setScrollbarLength(Math.max(0,t)),this.setPosition(this.workspace.RTL?e.absoluteLeft+this.margin:e.absoluteLeft+e.viewWidth-yt.scrollbarThickness-this.margin,e.absoluteTop+this.margin),this.resizeContentVertical(e)}resizeContentVertical(e){if(e.viewHeight>=e.scrollHeight)this.setHandleLength(this.scrollbarLength),this.setHandlePosition(0),this.pair||this.setVisible(!1);else{this.pair||this.setVisible(!0);var t=this.scrollbarLength*e.viewHeight/e.scrollHeight;t=this.constrainHandleLength(t),this.setHandleLength(t),t=e.scrollHeight-e.viewHeight;var o=this.scrollbarLength-this.handleLength;e=(e.viewTop-e.scrollTop)/t*o,e=this.constrainHandlePosition(e),this.setHandlePosition(e),this.ratio=o/t}}isVisible(){return this.isHandleVisible}setContainerVisible(e){const t=e!==this.containerVisible;this.containerVisible=e,t&&this.updateDisplay_()}setVisible(e){if(this.pair)throw Error("Unable to toggle visibility of paired scrollbars.");this.setVisibleInternal(e)}setVisibleInternal(e){const t=e!==this.isVisible();this.isHandleVisible=e,t&&this.updateDisplay_()}updateDisplay_(){this.containerVisible&&this.isVisible()?this.outerSvg.setAttribute("display","block"):this.outerSvg.setAttribute("display","none")}onMouseDownBar(e){if(this.workspace.markFocused(),K(),this.cleanUp(),pe(e))e.stopPropagation();else{var t=fe(e,this.workspace.getParentSvg(),this.workspace.getInverseScreenCTM());t=this.horizontal?t.x:t.y;var o=$a(this.svgHandle);o=this.horizontal?o.x:o.y;var n=this.handlePosition,u=.95*this.handleLength;t<=o?n-=u:t>=o+this.handleLength&&(n+=u),this.setHandlePosition(this.constrainHandlePosition(n)),this.updateMetrics(),e.stopPropagation(),e.preventDefault()}}onMouseDownHandle(e){this.workspace.markFocused(),this.cleanUp(),pe(e)?e.stopPropagation():(this.startDragHandle=this.handlePosition,this.startDragMouse=this.horizontal?e.clientX:e.clientY,this.onMouseUpWrapper_=W(document,"pointerup",this,this.onMouseUpHandle),this.onMouseMoveWrapper_=W(document,"pointermove",this,this.onMouseMoveHandle),e.stopPropagation(),e.preventDefault())}onMouseMoveHandle(e){this.setHandlePosition(this.constrainHandlePosition(this.startDragHandle+((this.horizontal?e.clientX:e.clientY)-this.startDragMouse))),this.updateMetrics()}onMouseUpHandle(){K(),this.cleanUp()}cleanUp(){this.workspace.hideChaff(!0),this.onMouseUpWrapper_&&(V(this.onMouseUpWrapper_),this.onMouseUpWrapper_=null),this.onMouseMoveWrapper_&&(V(this.onMouseMoveWrapper_),this.onMouseMoveWrapper_=null)}getRatio_(){let e=this.handlePosition/(this.scrollbarLength-this.handleLength);return isNaN(e)&&(e=0),e}updateMetrics(){const e=this.getRatio_();this.horizontal?this.workspace.setMetrics({x:e}):this.workspace.setMetrics({y:e})}set(e,t){this.setHandlePosition(this.constrainHandlePosition(e*this.ratio)),(t||t===void 0)&&this.updateMetrics()}setOrigin(e,t){this.origin=new ye(e,t)}static metricsAreEquivalent(e,t){return e.viewWidth===t.viewWidth&&e.viewHeight===t.viewHeight&&e.viewLeft===t.viewLeft&&e.viewTop===t.viewTop&&e.absoluteTop===t.absoluteTop&&e.absoluteLeft===t.absoluteLeft&&e.scrollWidth===t.scrollWidth&&e.scrollHeight===t.scrollHeight&&e.scrollLeft===t.scrollLeft&&e.scrollTop===t.scrollTop}};yt.scrollbarThickness=Tb?25:15,yt.DEFAULT_SCROLLBAR_MARGIN=.5;var dl={parseFromString:function(){throw Error("DOMParser was not found in the global scope and was not properly injected using injectDependencies")}},xh={serializeToString:function(){throw Error("XMLSerializer was not foundin the global scope and was not properly injected using injectDependencies")}},{document:hl,DOMParser:gr,XMLSerializer:mr}=globalThis;gr&&(dl=new gr),mr&&(xh=new mr);var Ub="https://developers.google.com/blockly/xml",UC=/[\x00-\x09\x0B\x0C\x0E-\x1F]/g,qi={NAME_SPACE:Ub};qi.createElement=i.createElement$$module$build$src$core$utils$xml,qi.createTextNode=i.createTextNode$$module$build$src$core$utils$xml,qi.domToText=Li,qi.injectDependencies=Zm,qi.textToDom=i.textToDom$$module$build$src$core$utils$xml;var Dh="categoryToolbox",Hb="flyoutToolbox",Ge;(function(e){e[e.TOP=0]="TOP",e[e.BOTTOM=1]="BOTTOM",e[e.LEFT=2]="LEFT",e[e.RIGHT=3]="RIGHT"})(Ge||(Ge={}));var Wb={hasCategoriesInternal:tf},Lo={};Lo.Position=Ge,Lo.TEST_ONLY=Wb,Lo.convertFlyoutDefToJsonArray=Gn,Lo.convertToolboxDefToJson=ba,Lo.hasCategories=va,Lo.isCategoryCollapsible=ya,Lo.parseToolboxTree=_u;var $o;(function(e){e[e.TOP=0]="TOP",e[e.BOTTOM=1]="BOTTOM"})($o||($o={}));var Zi;(function(e){e[e.LEFT=0]="LEFT",e[e.RIGHT=1]="RIGHT"})(Zi||(Zi={}));var Po;(function(e){e[e.UP=0]="UP",e[e.DOWN=1]="DOWN"})(Po||(Po={}));var di={};di.bumpDirection=Po,di.bumpPositionRect=Ca,di.getCornerOppositeToolbox=ka,di.getStartPositionRect=wa,di.horizontalPosition=Zi,di.verticalPosition=$o;var Gt={width:96,height:124,url:"sprites.png"},Gb=class{constructor(e){this.workspace=e,this.id="zoomControls",this.boundEvents=[],this.zoomResetGroup=this.zoomOutGroup=this.zoomInGroup=null,this.HEIGHT=this.WIDTH=32,this.SMALL_SPACING=2,this.LARGE_SPACING=11,this.MARGIN_HORIZONTAL=this.MARGIN_VERTICAL=20,this.svgGroup=null,this.top=this.left=0,this.initialized=!1}createDom(){this.svgGroup=ie(J.G,{});const e=String(Math.random()).substring(2);return this.createZoomOutSvg(e),this.createZoomInSvg(e),this.workspace.isMovable()&&this.createZoomResetSvg(e),this.svgGroup}init(){this.workspace.getComponentManager().addComponent({component:this,weight:gt.ComponentWeight.ZOOM_CONTROLS_WEIGHT,capabilities:[gt.Capability.POSITIONABLE]}),this.initialized=!0}dispose(){this.workspace.getComponentManager().removeComponent("zoomControls"),this.svgGroup&&Qe(this.svgGroup);for(const e of this.boundEvents)V(e);this.boundEvents.length=0}getBoundingRectangle(){let e=this.SMALL_SPACING+2*this.HEIGHT;return this.zoomResetGroup&&(e+=this.LARGE_SPACING+this.HEIGHT),new rt(this.top,this.top+e,this.left,this.left+this.WIDTH)}position(e,t){if(this.initialized){var o=ka(this.workspace,e),n=this.SMALL_SPACING+2*this.HEIGHT;if(this.zoomResetGroup&&(n+=this.LARGE_SPACING+this.HEIGHT),e=wa(o,new Ze(this.WIDTH,n),this.MARGIN_HORIZONTAL,this.MARGIN_VERTICAL,e,this.workspace),o=o.vertical,t=Ca(e,this.MARGIN_VERTICAL,o===$o.TOP?Po.DOWN:Po.UP,t),o===$o.TOP){var u=this.SMALL_SPACING+this.HEIGHT,g;(g=this.zoomInGroup)==null||g.setAttribute("transform","translate(0, "+u+")"),this.zoomResetGroup&&this.zoomResetGroup.setAttribute("transform","translate(0, "+(u+this.LARGE_SPACING+this.HEIGHT)+")")}else{g=this.zoomResetGroup?this.LARGE_SPACING+this.HEIGHT:0;let P;(P=this.zoomInGroup)==null||P.setAttribute("transform","translate(0, "+g+")"),g=g+this.SMALL_SPACING+this.HEIGHT,(u=this.zoomOutGroup)==null||u.setAttribute("transform","translate(0, "+g+")")}this.top=t.top,this.left=t.left;var I;(I=this.svgGroup)==null||I.setAttribute("transform","translate("+this.left+","+this.top+")")}}createZoomOutSvg(e){this.zoomOutGroup=ie(J.G,{class:"blocklyZoom blocklyZoomOut"},this.svgGroup);const t=ie(J.CLIPPATH,{id:"blocklyZoomoutClipPath"+e},this.zoomOutGroup);ie(J.RECT,{width:32,height:32},t),ie(J.IMAGE,{width:Gt.width,height:Gt.height,x:-64,y:-92,"clip-path":"url(#blocklyZoomoutClipPath"+e+")"},this.zoomOutGroup).setAttributeNS(is,"xlink:href",this.workspace.options.pathToMedia+Gt.url),this.boundEvents.push(W(this.zoomOutGroup,"pointerdown",null,this.zoom.bind(this,-1)))}createZoomInSvg(e){this.zoomInGroup=ie(J.G,{class:"blocklyZoom blocklyZoomIn"},this.svgGroup);const t=ie(J.CLIPPATH,{id:"blocklyZoominClipPath"+e},this.zoomInGroup);ie(J.RECT,{width:32,height:32},t),ie(J.IMAGE,{width:Gt.width,height:Gt.height,x:-32,y:-92,"clip-path":"url(#blocklyZoominClipPath"+e+")"},this.zoomInGroup).setAttributeNS(is,"xlink:href",this.workspace.options.pathToMedia+Gt.url),this.boundEvents.push(W(this.zoomInGroup,"pointerdown",null,this.zoom.bind(this,1)))}zoom(e,t){this.workspace.markFocused(),this.workspace.zoomCenter(e),this.fireZoomEvent(),K(),t.stopPropagation(),t.preventDefault()}createZoomResetSvg(e){this.zoomResetGroup=ie(J.G,{class:"blocklyZoom blocklyZoomReset"},this.svgGroup);const t=ie(J.CLIPPATH,{id:"blocklyZoomresetClipPath"+e},this.zoomResetGroup);ie(J.RECT,{width:32,height:32},t),ie(J.IMAGE,{width:Gt.width,height:Gt.height,y:-92,"clip-path":"url(#blocklyZoomresetClipPath"+e+")"},this.zoomResetGroup).setAttributeNS(is,"xlink:href",this.workspace.options.pathToMedia+Gt.url),this.boundEvents.push(W(this.zoomResetGroup,"pointerdown",null,this.resetZoom.bind(this)))}resetZoom(e){this.workspace.markFocused();const t=Math.log(this.workspace.options.zoomOptions.startScale/this.workspace.scale)/Math.log(this.workspace.options.zoomOptions.scaleSpeed);this.workspace.beginCanvasTransition(),this.workspace.zoomCenter(t),this.workspace.scrollCenter(),setTimeout(this.workspace.endCanvasTransition.bind(this.workspace),500),this.fireZoomEvent(),K(),e.stopPropagation(),e.preventDefault()}fireZoomEvent(){const e=new(ne(ee.CLICK))(null,this.workspace.id,"zoom_controls");z(e)}};Be(` .blocklyZoom>image, .blocklyZoom>svg>image { opacity: .4; } @@ -731,11 +731,11 @@ input[type=number] { .blocklyZoom>image:active, .blocklyZoom>svg>image:active { opacity: .8; } -`);var Wb=100,Gb=75,Vb=50,Kb=25,UC={BLOCKS:Vb,PROCEDURES:Gb,VARIABLES:Wb,WORKSPACE_COMMENTS:Kb},Dh={};Dh.register=Vn,Dh.unregister=tf;var Yb=class{constructor(){this.priority=Kb}save(e){const t=[];for(const o of e.getTopComments())(e=Pi(o,{addCoordinates:!0,saveIds:!0}))&&t.push(e);return t.length?t:null}load(e,t){for(const o of e)Kn(o,t,{recordUndo:G()})}clear(e){for(const t of e.getTopComments())t.dispose()}};Vn("workspaceComments",new Yb);var hl={};hl.WorkspaceCommentSerializer=Yb,hl.append=Kn,hl.save=Pi;var Ah={};Ah.register=Ca,Ah.unregister=sf;var pl=class{paste(e,t,o){e=e.commentState,o&&(e.x=o.x,e.y=o.y),i.disable$$module$build$src$core$events$utils();let n;try{n=Kn(e,t),of(n)}finally{i.enable$$module$build$src$core$events$utils()}return n?(C()&&z(new(ne(ee.COMMENT_CREATE))(n)),i.setSelected$$module$build$src$core$common(n),n):null}};pl.TYPE="workspace-comment",Ca(pl.TYPE,new pl);var Rh;Rh=28,i.config$$module$build$src$core$config={dragRadius:5,flyoutDragRadius:10,snapRadius:Rh,connectingSnapRadius:Rh,currentConnectionPreference:8,bumpDelay:250},i.config$$module$build$src$core$config;var HC="aria-",WC="role",Is;(function(e){e.GRID="grid",e.GRIDCELL="gridcell",e.GROUP="group",e.LISTBOX="listbox",e.MENU="menu",e.MENUITEM="menuitem",e.MENUITEMCHECKBOX="menuitemcheckbox",e.OPTION="option",e.PRESENTATION="presentation",e.ROW="row",e.TREE="tree",e.TREEITEM="treeitem"})(Is||(Is={}));var Et;(function(e){e.ACTIVEDESCENDANT="activedescendant",e.COLCOUNT="colcount",e.DISABLED="disabled",e.EXPANDED="expanded",e.INVALID="invalid",e.LABEL="label",e.LABELLEDBY="labelledby",e.LEVEL="level",e.ORIENTATION="orientation",e.POSINSET="posinset",e.ROWCOUNT="rowcount",e.SELECTED="selected",e.SETSIZE="setsize",e.VALUEMAX="valuemax",e.VALUEMIN="valuemin"})(Et||(Et={}));var fr={};fr.Role=Is,fr.State=Et,fr.setRole=Do,fr.setState=xt;var Oh=class{constructor(){this.menuItems=[],this.roleName=this.element=this.onKeyDownHandler=this.pointerLeaveHandler=this.pointerEnterHandler=this.clickHandler=this.pointerMoveHandler=this.highlightedItem=this.openingCoords=null}addChild(e){this.menuItems.push(e)}render(e){const t=document.createElement("div");t.className="blocklyMenu goog-menu blocklyNonSelectable",t.tabIndex=0,this.roleName&&Do(t,this.roleName),this.element=t;for(let o=0,n;n=this.menuItems[o];o++)t.appendChild(n.createDom());return this.pointerMoveHandler=H(t,"pointermove",this,this.handlePointerMove,!0),this.clickHandler=H(t,"pointerup",this,this.handleClick,!0),this.pointerEnterHandler=H(t,"pointerenter",this,this.handlePointerEnter,!0),this.pointerLeaveHandler=H(t,"pointerleave",this,this.handlePointerLeave,!0),this.onKeyDownHandler=H(t,"keydown",this,this.handleKeyEvent),e.appendChild(t),t}getElement(){return this.element}focus(){const e=this.getElement();e&&(e.focus({preventScroll:!0}),Re(e,"blocklyFocused"))}blur(){const e=this.getElement();e&&(e.blur(),ze(e,"blocklyFocused"))}setRole(e){this.roleName=e}dispose(){this.pointerMoveHandler&&(V(this.pointerMoveHandler),this.pointerMoveHandler=null),this.clickHandler&&(V(this.clickHandler),this.clickHandler=null),this.pointerEnterHandler&&(V(this.pointerEnterHandler),this.pointerEnterHandler=null),this.pointerLeaveHandler&&(V(this.pointerLeaveHandler),this.pointerLeaveHandler=null),this.onKeyDownHandler&&(V(this.onKeyDownHandler),this.onKeyDownHandler=null);for(let e=0,t;t=this.menuItems[e];e++)t.dispose();this.element=null}getMenuItem(e){const t=this.getElement();for(;e&&e!==t;){if(e.classList.contains("blocklyMenuItem")){for(let o=0,n;n=this.menuItems[o];o++)if(n.getElement()===e)return n}e=e.parentElement}return null}setHighlighted(e){var t=this.highlightedItem;if(t&&(t.setHighlighted(!1),this.highlightedItem=null),e){e.setHighlighted(!0),this.highlightedItem=e,t=this.getElement();const o=t==null?void 0:t.parentElement,n=e.getElement();o&&n&&(ma(n,o),xt(t,Et.ACTIVEDESCENDANT,e.getId()))}}highlightNext(){const e=this.highlightedItem?this.menuItems.indexOf(this.highlightedItem):-1;this.highlightHelper(e,1)}highlightPrevious(){const e=this.highlightedItem?this.menuItems.indexOf(this.highlightedItem):-1;this.highlightHelper(0>e?this.menuItems.length:e,-1)}highlightFirst(){this.highlightHelper(-1,1)}highlightLast(){this.highlightHelper(this.menuItems.length,-1)}highlightHelper(e,t){e+=t;let o;for(;o=this.menuItems[e];){if(o.isEnabled()){this.setHighlighted(o);break}e+=t}}handlePointerMove(e){Math.max(Math.abs(e.movementX),Math.abs(e.movementY))!==0&&(e=this.getMenuItem(e.target))&&(e.isEnabled()?this.highlightedItem!==e&&this.setHighlighted(e):this.setHighlighted(null))}handleClick(e){const t=this.openingCoords;if(this.openingCoords=null,t&&typeof e.clientX=="number"){const o=new ye(e.clientX,e.clientY);if(1>ye.distance(t,o))return}(e=this.getMenuItem(e.target))&&e.performAction()}handlePointerEnter(e){this.focus()}handlePointerLeave(e){this.getElement()&&this.setHighlighted(null)}handleKeyEvent(e){if(this.menuItems.length&&!(e.shiftKey||e.ctrlKey||e.metaKey||e.altKey)){var t=this.highlightedItem;switch(e.key){case"Enter":case" ":t&&t.performAction();break;case"ArrowUp":this.highlightPrevious();break;case"ArrowDown":this.highlightNext();break;case"PageUp":case"Home":this.highlightFirst();break;case"PageDown":case"End":this.highlightLast();break;default:return}e.preventDefault(),e.stopPropagation()}}getSize(){const e=this.getElement(),t=Hn(e);return t.height=e.scrollHeight,t}},Nh=class{constructor(e,t){this.content=e,this.opt_value=t,this.enabled=!0,this.element=null,this.rightToLeft=!1,this.roleName=null,this.highlight=this.checked=this.checkable=!1,this.actionHandler=null}createDom(){const e=document.createElement("div");e.id=v(),this.element=e,e.className="blocklyMenuItem goog-menuitem "+(this.enabled?"":"blocklyMenuItemDisabled goog-menuitem-disabled ")+(this.checked?"blocklyMenuItemSelected goog-option-selected ":"")+(this.highlight?"blocklyMenuItemHighlight goog-menuitem-highlight ":"")+(this.rightToLeft?"blocklyMenuItemRtl goog-menuitem-rtl ":"");const t=document.createElement("div");if(t.className="blocklyMenuItemContent goog-menuitem-content",this.checkable){var o=document.createElement("div");o.className="blocklyMenuItemCheckbox goog-menuitem-checkbox",t.appendChild(o)}return o=this.content,typeof this.content=="string"&&(o=document.createTextNode(this.content)),t.appendChild(o),e.appendChild(t),this.roleName&&Do(e,this.roleName),xt(e,Et.SELECTED,this.checkable&&this.checked||!1),xt(e,Et.DISABLED,!this.enabled),e}dispose(){this.element=null}getElement(){return this.element}getId(){return this.element.id}getValue(){let e;return(e=this.opt_value)!=null?e:null}setRightToLeft(e){this.rightToLeft=e}setRole(e){this.roleName=e}setCheckable(e){this.checkable=e}setChecked(e){this.checked=e}setHighlighted(e){this.highlight=e;const t=this.getElement();t&&this.isEnabled()&&(e?(Re(t,"blocklyMenuItemHighlight"),Re(t,"goog-menuitem-highlight")):(ze(t,"blocklyMenuItemHighlight"),ze(t,"goog-menuitem-highlight")))}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}performAction(){this.isEnabled()&&this.actionHandler&&this.actionHandler(this)}onAction(e,t){this.actionHandler=e.bind(t)}},$r="_TEMP_COLLAPSED_INPUT",gl="_TEMP_COLLAPSED_FIELD",Vt="MANUALLY_DISABLED",GC={COLLAPSED_FIELD_NAME:gl,COLLAPSED_INPUT_NAME:$r,MANUALLY_DISABLED:Vt};(function(e){e[e.VALUE=1]="VALUE",e[e.STATEMENT=3]="STATEMENT",e[e.DUMMY=5]="DUMMY",e[e.CUSTOM=6]="CUSTOM",e[e.END_ROW=7]="END_ROW"})(i.inputTypes$$module$build$src$core$inputs$input_types||(i.inputTypes$$module$build$src$core$inputs$input_types={})),i.inputTypes$$module$build$src$core$inputs$input_types;var ml=new Set,Mh=new WeakSet,Lh=new WeakMap,Qi=null,Ph=null,Jb=0,fl={};fl.finishQueuedRenders=Ts,fl.queueRender=_u,fl.triggerQueuedRenders=ao;var qb=function(e,t){window.alert(e),t&&t()},Xb=function(e,t){t(window.confirm(e))},Zb=function(e,t,o){o(window.prompt(e,t))},Qb={confirmInternal:cf},hi={TEST_ONLY:Qb};hi.alert=Jn,hi.confirm=Sa,hi.prompt=Ea,hi.setAlert=lf,hi.setConfirm=uf,hi.setPrompt=df;var Bh,ev;i.Msg$$module$build$src$core$msg=Object.create(null),Bh=function(e){Object.keys(e).forEach(function(t){i.Msg$$module$build$src$core$msg[t]=e[t]})},ev={Msg:i.Msg$$module$build$src$core$msg,setLocale:Bh};var br=class extends qi{constructor(e){super(),this.isBlank=typeof e>"u",e&&(this.varId=e.getId(),this.workspaceId=e.workspace.id)}toJson(){const e=super.toJson();if(!this.varId)throw Error("The var ID is undefined. Either pass a variable to the constructor, or call fromJson");return e.varId=this.varId,e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new br),t.varId=e.varId,t}},jh=class extends br{constructor(e){super(e),this.type=ee.VAR_CREATE,e&&(this.varType=e.type,this.varName=e.name)}toJson(){const e=super.toJson();if(this.varType===void 0)throw Error("The var type is undefined. Either pass a variable to the constructor, or call fromJson");if(!this.varName)throw Error("The var name is undefined. Either pass a variable to the constructor, or call fromJson");return e.varType=this.varType,e.varName=this.varName,e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new jh),t.varType=e.varType,t.varName=e.varName,t}run(e){const t=this.getEventWorkspace_();if(!this.varId)throw Error("The var ID is undefined. Either pass a variable to the constructor, or call fromJson");if(!this.varName)throw Error("The var name is undefined. Either pass a variable to the constructor, or call fromJson");e?t.createVariable(this.varName,this.varType,this.varId):t.deleteVariableById(this.varId)}};r($e.EVENT,ee.VAR_CREATE,jh);var vr=class{constructor(e,t,o,n){this.workspace=e,this.name=t,this.type=o||"",this.id=n||_()}getId(){return this.id}static compareByName(e,t){return e.name.localeCompare(t.name,void 0,{sensitivity:"base"})}},Fh="VARIABLE",zh="ijkmnopqrstuvwxyzabcdefgh",tv={generateUniqueNameInternal:pf},Ot={CATEGORY_NAME:Fh,TEST_ONLY:tv,VAR_LETTER_OPTIONS:zh};Ot.allDeveloperVariables=i.allDeveloperVariables$$module$build$src$core$variables,Ot.allUsedVarModels=i.allUsedVarModels$$module$build$src$core$variables,Ot.createVariableButtonHandler=ji,Ot.flyoutCategory=Ia,Ot.flyoutCategoryBlocks=Su,Ot.generateUniqueName=Eu,Ot.generateUniqueNameFromOptions=xa,Ot.generateVariableFieldDom=ei,Ot.getAddedVariables=qn,Ot.getOrCreateVariablePackage=i.getOrCreateVariablePackage$$module$build$src$core$variables,Ot.getVariable=i.getVariable$$module$build$src$core$variables,Ot.nameUsedWithAnyType=Iu,Ot.nameUsedWithConflictingParam=xu,Ot.promptName=Da,Ot.renameVariable=i.renameVariable$$module$build$src$core$variables;var en=class extends Error{},sv=class extends en{constructor(e){super("Expected to find a 'type' property, defining the block type"),this.state=e}},yr=class extends en{constructor(e,t,o){super(`The block ${t.toDevString()} is missing a(n) ${e} -connection`),this.block=t,this.state=o}},ov=class extends en{constructor(e,t,o,n){super(`The block ${o.toDevString()} could not connect its -${t} to its parent, because: ${e}`),this.childBlock=o,this.childState=n}},iv=class extends en{constructor(e){super(`Encountered a real block which is defined as a child of a shadow +`);var Vb=100,Yb=75,Kb=50,Jb=25,HC={BLOCKS:Kb,PROCEDURES:Yb,VARIABLES:Vb,WORKSPACE_COMMENTS:Jb},Ah={};Ah.register=Vn,Ah.unregister=of;var Xb=class{constructor(){this.priority=Jb}save(e){const t=[];for(const o of e.getTopComments())(e=Pi(o,{addCoordinates:!0,saveIds:!0}))&&t.push(e);return t.length?t:null}load(e,t){for(const o of e)Yn(o,t,{recordUndo:G()})}clear(e){for(const t of e.getTopComments())t.dispose()}};Vn("workspaceComments",new Xb);var pl={};pl.WorkspaceCommentSerializer=Xb,pl.append=Yn,pl.save=Pi;var Oh={};Oh.register=Ta,Oh.unregister=nf;var gl=class{paste(e,t,o){e=e.commentState,o&&(e.x=o.x,e.y=o.y),i.disable$$module$build$src$core$events$utils();let n;try{n=Yn(e,t),rf(n)}finally{i.enable$$module$build$src$core$events$utils()}return n?(C()&&z(new(ne(ee.COMMENT_CREATE))(n)),i.setSelected$$module$build$src$core$common(n),n):null}};gl.TYPE="workspace-comment",Ta(gl.TYPE,new gl);var Rh;Rh=28,i.config$$module$build$src$core$config={dragRadius:5,flyoutDragRadius:10,snapRadius:Rh,connectingSnapRadius:Rh,currentConnectionPreference:8,bumpDelay:250},i.config$$module$build$src$core$config;var WC="aria-",GC="role",Is;(function(e){e.GRID="grid",e.GRIDCELL="gridcell",e.GROUP="group",e.LISTBOX="listbox",e.MENU="menu",e.MENUITEM="menuitem",e.MENUITEMCHECKBOX="menuitemcheckbox",e.OPTION="option",e.PRESENTATION="presentation",e.ROW="row",e.TREE="tree",e.TREEITEM="treeitem"})(Is||(Is={}));var Et;(function(e){e.ACTIVEDESCENDANT="activedescendant",e.COLCOUNT="colcount",e.DISABLED="disabled",e.EXPANDED="expanded",e.INVALID="invalid",e.LABEL="label",e.LABELLEDBY="labelledby",e.LEVEL="level",e.ORIENTATION="orientation",e.POSINSET="posinset",e.ROWCOUNT="rowcount",e.SELECTED="selected",e.SETSIZE="setsize",e.VALUEMAX="valuemax",e.VALUEMIN="valuemin"})(Et||(Et={}));var fr={};fr.Role=Is,fr.State=Et,fr.setRole=Do,fr.setState=xt;var Mh=class{constructor(){this.menuItems=[],this.roleName=this.element=this.onKeyDownHandler=this.pointerLeaveHandler=this.pointerEnterHandler=this.clickHandler=this.pointerMoveHandler=this.highlightedItem=this.openingCoords=null}addChild(e){this.menuItems.push(e)}render(e){const t=document.createElement("div");t.className="blocklyMenu goog-menu blocklyNonSelectable",t.tabIndex=0,this.roleName&&Do(t,this.roleName),this.element=t;for(let o=0,n;n=this.menuItems[o];o++)t.appendChild(n.createDom());return this.pointerMoveHandler=W(t,"pointermove",this,this.handlePointerMove,!0),this.clickHandler=W(t,"pointerup",this,this.handleClick,!0),this.pointerEnterHandler=W(t,"pointerenter",this,this.handlePointerEnter,!0),this.pointerLeaveHandler=W(t,"pointerleave",this,this.handlePointerLeave,!0),this.onKeyDownHandler=W(t,"keydown",this,this.handleKeyEvent),e.appendChild(t),t}getElement(){return this.element}focus(){const e=this.getElement();e&&(e.focus({preventScroll:!0}),Oe(e,"blocklyFocused"))}blur(){const e=this.getElement();e&&(e.blur(),ze(e,"blocklyFocused"))}setRole(e){this.roleName=e}dispose(){this.pointerMoveHandler&&(V(this.pointerMoveHandler),this.pointerMoveHandler=null),this.clickHandler&&(V(this.clickHandler),this.clickHandler=null),this.pointerEnterHandler&&(V(this.pointerEnterHandler),this.pointerEnterHandler=null),this.pointerLeaveHandler&&(V(this.pointerLeaveHandler),this.pointerLeaveHandler=null),this.onKeyDownHandler&&(V(this.onKeyDownHandler),this.onKeyDownHandler=null);for(let e=0,t;t=this.menuItems[e];e++)t.dispose();this.element=null}getMenuItem(e){const t=this.getElement();for(;e&&e!==t;){if(e.classList.contains("blocklyMenuItem")){for(let o=0,n;n=this.menuItems[o];o++)if(n.getElement()===e)return n}e=e.parentElement}return null}setHighlighted(e){var t=this.highlightedItem;if(t&&(t.setHighlighted(!1),this.highlightedItem=null),e){e.setHighlighted(!0),this.highlightedItem=e,t=this.getElement();const o=t==null?void 0:t.parentElement,n=e.getElement();o&&n&&(fa(n,o),xt(t,Et.ACTIVEDESCENDANT,e.getId()))}}highlightNext(){const e=this.highlightedItem?this.menuItems.indexOf(this.highlightedItem):-1;this.highlightHelper(e,1)}highlightPrevious(){const e=this.highlightedItem?this.menuItems.indexOf(this.highlightedItem):-1;this.highlightHelper(0>e?this.menuItems.length:e,-1)}highlightFirst(){this.highlightHelper(-1,1)}highlightLast(){this.highlightHelper(this.menuItems.length,-1)}highlightHelper(e,t){e+=t;let o;for(;o=this.menuItems[e];){if(o.isEnabled()){this.setHighlighted(o);break}e+=t}}handlePointerMove(e){Math.max(Math.abs(e.movementX),Math.abs(e.movementY))!==0&&(e=this.getMenuItem(e.target))&&(e.isEnabled()?this.highlightedItem!==e&&this.setHighlighted(e):this.setHighlighted(null))}handleClick(e){const t=this.openingCoords;if(this.openingCoords=null,t&&typeof e.clientX=="number"){const o=new ye(e.clientX,e.clientY);if(1>ye.distance(t,o))return}(e=this.getMenuItem(e.target))&&e.performAction()}handlePointerEnter(e){this.focus()}handlePointerLeave(e){this.getElement()&&this.setHighlighted(null)}handleKeyEvent(e){if(this.menuItems.length&&!(e.shiftKey||e.ctrlKey||e.metaKey||e.altKey)){var t=this.highlightedItem;switch(e.key){case"Enter":case" ":t&&t.performAction();break;case"ArrowUp":this.highlightPrevious();break;case"ArrowDown":this.highlightNext();break;case"PageUp":case"Home":this.highlightFirst();break;case"PageDown":case"End":this.highlightLast();break;default:return}e.preventDefault(),e.stopPropagation()}}getSize(){const e=this.getElement(),t=Hn(e);return t.height=e.scrollHeight,t}},Nh=class{constructor(e,t){this.content=e,this.opt_value=t,this.enabled=!0,this.element=null,this.rightToLeft=!1,this.roleName=null,this.highlight=this.checked=this.checkable=!1,this.actionHandler=null}createDom(){const e=document.createElement("div");e.id=v(),this.element=e,e.className="blocklyMenuItem goog-menuitem "+(this.enabled?"":"blocklyMenuItemDisabled goog-menuitem-disabled ")+(this.checked?"blocklyMenuItemSelected goog-option-selected ":"")+(this.highlight?"blocklyMenuItemHighlight goog-menuitem-highlight ":"")+(this.rightToLeft?"blocklyMenuItemRtl goog-menuitem-rtl ":"");const t=document.createElement("div");if(t.className="blocklyMenuItemContent goog-menuitem-content",this.checkable){var o=document.createElement("div");o.className="blocklyMenuItemCheckbox goog-menuitem-checkbox",t.appendChild(o)}return o=this.content,typeof this.content=="string"&&(o=document.createTextNode(this.content)),t.appendChild(o),e.appendChild(t),this.roleName&&Do(e,this.roleName),xt(e,Et.SELECTED,this.checkable&&this.checked||!1),xt(e,Et.DISABLED,!this.enabled),e}dispose(){this.element=null}getElement(){return this.element}getId(){return this.element.id}getValue(){let e;return(e=this.opt_value)!=null?e:null}setRightToLeft(e){this.rightToLeft=e}setRole(e){this.roleName=e}setCheckable(e){this.checkable=e}setChecked(e){this.checked=e}setHighlighted(e){this.highlight=e;const t=this.getElement();t&&this.isEnabled()&&(e?(Oe(t,"blocklyMenuItemHighlight"),Oe(t,"goog-menuitem-highlight")):(ze(t,"blocklyMenuItemHighlight"),ze(t,"goog-menuitem-highlight")))}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}performAction(){this.isEnabled()&&this.actionHandler&&this.actionHandler(this)}onAction(e,t){this.actionHandler=e.bind(t)}},$r="_TEMP_COLLAPSED_INPUT",ml="_TEMP_COLLAPSED_FIELD",Vt="MANUALLY_DISABLED",VC={COLLAPSED_FIELD_NAME:ml,COLLAPSED_INPUT_NAME:$r,MANUALLY_DISABLED:Vt};(function(e){e[e.VALUE=1]="VALUE",e[e.STATEMENT=3]="STATEMENT",e[e.DUMMY=5]="DUMMY",e[e.CUSTOM=6]="CUSTOM",e[e.END_ROW=7]="END_ROW"})(i.inputTypes$$module$build$src$core$inputs$input_types||(i.inputTypes$$module$build$src$core$inputs$input_types={})),i.inputTypes$$module$build$src$core$inputs$input_types;var fl=new Set,Lh=new WeakSet,Ph=new WeakMap,Qi=null,Bh=null,qb=0,$l={};$l.finishQueuedRenders=Ts,$l.queueRender=wu,$l.triggerQueuedRenders=ao;var Zb=function(e,t){window.alert(e),t&&t()},Qb=function(e,t){t(window.confirm(e))},ev=function(e,t,o){o(window.prompt(e,t))},tv={confirmInternal:df},hi={TEST_ONLY:tv};hi.alert=Jn,hi.confirm=Ea,hi.prompt=Ia,hi.setAlert=uf,hi.setConfirm=hf,hi.setPrompt=pf;var jh,sv;i.Msg$$module$build$src$core$msg=Object.create(null),jh=function(e){Object.keys(e).forEach(function(t){i.Msg$$module$build$src$core$msg[t]=e[t]})},sv={Msg:i.Msg$$module$build$src$core$msg,setLocale:jh};var br=class extends Xi{constructor(e){super(),this.isBlank=typeof e>"u",e&&(this.varId=e.getId(),this.workspaceId=e.workspace.id)}toJson(){const e=super.toJson();if(!this.varId)throw Error("The var ID is undefined. Either pass a variable to the constructor, or call fromJson");return e.varId=this.varId,e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new br),t.varId=e.varId,t}},Fh=class extends br{constructor(e){super(e),this.type=ee.VAR_CREATE,e&&(this.varType=e.type,this.varName=e.name)}toJson(){const e=super.toJson();if(this.varType===void 0)throw Error("The var type is undefined. Either pass a variable to the constructor, or call fromJson");if(!this.varName)throw Error("The var name is undefined. Either pass a variable to the constructor, or call fromJson");return e.varType=this.varType,e.varName=this.varName,e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new Fh),t.varType=e.varType,t.varName=e.varName,t}run(e){const t=this.getEventWorkspace_();if(!this.varId)throw Error("The var ID is undefined. Either pass a variable to the constructor, or call fromJson");if(!this.varName)throw Error("The var name is undefined. Either pass a variable to the constructor, or call fromJson");e?t.createVariable(this.varName,this.varType,this.varId):t.deleteVariableById(this.varId)}};r($e.EVENT,ee.VAR_CREATE,Fh);var vr=class{constructor(e,t,o,n){this.workspace=e,this.name=t,this.type=o||"",this.id=n||_()}getId(){return this.id}static compareByName(e,t){return e.name.localeCompare(t.name,void 0,{sensitivity:"base"})}},zh="VARIABLE",Uh="ijkmnopqrstuvwxyzabcdefgh",ov={generateUniqueNameInternal:mf},Rt={CATEGORY_NAME:zh,TEST_ONLY:ov,VAR_LETTER_OPTIONS:Uh};Rt.allDeveloperVariables=i.allDeveloperVariables$$module$build$src$core$variables,Rt.allUsedVarModels=i.allUsedVarModels$$module$build$src$core$variables,Rt.createVariableButtonHandler=ji,Rt.flyoutCategory=xa,Rt.flyoutCategoryBlocks=Eu,Rt.generateUniqueName=Iu,Rt.generateUniqueNameFromOptions=Da,Rt.generateVariableFieldDom=ei,Rt.getAddedVariables=Xn,Rt.getOrCreateVariablePackage=i.getOrCreateVariablePackage$$module$build$src$core$variables,Rt.getVariable=i.getVariable$$module$build$src$core$variables,Rt.nameUsedWithAnyType=xu,Rt.nameUsedWithConflictingParam=Du,Rt.promptName=Aa,Rt.renameVariable=i.renameVariable$$module$build$src$core$variables;var en=class extends Error{},iv=class extends en{constructor(e){super("Expected to find a 'type' property, defining the block type"),this.state=e}},yr=class extends en{constructor(e,t,o){super(`The block ${t.toDevString()} is missing a(n) ${e} +connection`),this.block=t,this.state=o}},nv=class extends en{constructor(e,t,o,n){super(`The block ${o.toDevString()} could not connect its +${t} to its parent, because: ${e}`),this.childBlock=o,this.childState=n}},rv=class extends en{constructor(e){super(`Encountered a real block which is defined as a child of a shadow block. It is an invariant of Blockly that shadow blocks only have shadow -children`),this.state=e}},nv=class extends en{constructor(e,t,o){super(`Cannot add an icon of type '${e}' to the block ${t.toDevString()}, because there is no icon registered with type '${e}'. Make sure that all of your icons have been registered.`),this.block=t,this.state=o}},pi={};pi.BadConnectionCheck=ov,pi.DeserializationError=en,pi.MissingBlockType=sv,pi.MissingConnection=yr,pi.RealChildOfShadow=iv,pi.UnregisteredIcon=nv;var rv=class{constructor(){this.priority=Vb}save(e){const t=[];for(const o of e.getTopBlocks(!1))(e=os(o,{addCoordinates:!0,doFullSerialization:!1}))&&t.push(e);return t.length?{languageVersion:0,blocks:t}:null}load(e,t){e=e.blocks;for(const o of e)lo(o,t,{recordUndo:G()})}clear(e){for(const t of e.getTopBlocks(!1))t.dispose(!1)}};Vn("blocks",new rv);var _r={};_r.BlockSerializer=rv,_r.append=lo,_r.appendInternal=Fi,_r.save=os;var Ct=class{constructor(e){this.name=e}toString(){return this.name}equals(e){return this.name===e.toString()}};Ct.MUTATOR=new Ct("mutator"),Ct.WARNING=new Ct("warning"),Ct.COMMENT=new Ct("comment");var gi=class extends qi{constructor(e){super(),this.isBlank=!e,e&&(this.blockId=e.id,this.workspaceId=e.workspace.id)}toJson(){const e=super.toJson();if(!this.blockId)throw Error("The block ID is undefined. Either pass a block to the constructor, or call fromJson");return e.blockId=this.blockId,e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new gi),t.blockId=e.blockId,t}},mi=class extends gi{constructor(e,t,o,n,u){super(e),this.type=ee.BLOCK_CHANGE,e&&(this.element=t,this.name=o||void 0,this.oldValue=n,this.newValue=u)}toJson(){const e=super.toJson();if(!this.element)throw Error("The changed element is undefined. Either pass an element to the constructor, or call fromJson");return e.element=this.element,e.name=this.name,e.oldValue=this.oldValue,e.newValue=this.newValue,this.disabledReason&&(e.disabledReason=this.disabledReason),e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new mi),t.element=e.element,t.name=e.name,t.oldValue=e.oldValue,t.newValue=e.newValue,e.disabledReason!==void 0&&(t.disabledReason=e.disabledReason),t}setDisabledReason(e){if(this.element!=="disabled")throw Error('Cannot set the disabled reason for a BlockChange event if the element is not "disabled".');this.disabledReason=e}isNull(){return this.oldValue===this.newValue}run(e){var t=this.getEventWorkspace_();if(!this.blockId)throw Error("The block ID is undefined. Either pass a block to the constructor, or call fromJson");if(t=t.getBlockById(this.blockId),!t)throw Error("The associated block is undefined. Either pass a block to the constructor, or call fromJson");const o=t.getIcon(Ct.MUTATOR);switch(o&&zi(o)&&o.bubbleIsVisible()&&o.setBubbleVisible(!1),e=e?this.newValue:this.oldValue,this.element){case"field":(t=t.getField(this.name))?t.setValue(e):console.warn("Can't set non-existent field: "+this.name);break;case"comment":t.setCommentText(e||null);break;case"collapsed":t.setCollapsed(!!e);break;case"disabled":var n;t.setDisabledReason(!!e,(n=this.disabledReason)!=null?n:Vt);break;case"inline":t.setInputsInline(!!e);break;case"mutation":n=mi.getExtraBlockState_(t),t.loadExtraState?t.loadExtraState(JSON.parse(e||"{}")):t.domToMutation&&t.domToMutation(i.textToDom$$module$build$src$core$utils$xml(e||"")),z(new mi(t,"mutation",null,n,e));break;default:console.warn("Unknown change type: "+this.element)}}static getExtraBlockState_(e){return e.saveExtraState?(e=e.saveExtraState(!0))?JSON.stringify(e):"":e.mutationToDom&&(e=e.mutationToDom())?zs(e):""}};r($e.EVENT,ee.BLOCK_CHANGE,mi);var $l={};$l.clamp=Ui,$l.toDegrees=Mf,$l.toRadians=Aa;var bl=16,av=1,lv=12,Uh=16,vl=.25,Hh=null,fi=null,tn="",sn="",tt,on,$i,Wh=null,Bo=null,cv=null,Gh={getBoundsInfo:function(){const e=xo(Wh),t=Hn(Wh);return{left:e.x,right:e.x+t.width,top:e.y,bottom:e.y+t.height,width:t.width,height:t.height}},getPositionMetrics:function(e,t,o,n){const u=Gh.getBoundsInfo(),g=Hn(tt);return t+g.heightu.top?Hu(o,n,u,g):t+g.heightdocument.documentElement.clientTop?Hu(o,n,u,g):Pf(e,u,g)}},Ft={ANIMATION_TIME:vl,ARROW_HORIZONTAL_PADDING:lv,ARROW_SIZE:bl,BORDER_SIZE:av,PADDING_Y:Uh,TEST_ONLY:Gh};Ft.clearContent=Ra,Ft.createDom=Ou,Ft.getContentDiv=Xn,Ft.getOwner=Mu,Ft.getPositionX=Zn,Ft.hide=Na,Ft.hideIfOwner=Oa,Ft.hideWithoutAnimation=Fs,Ft.isVisible=Wu,Ft.repositionForWindowResize=Vu,Ft.setBoundsElement=Nu,Ft.setColour=Lu,Ft.show=zu,Ft.showPositionedByBlock=Lf,Ft.showPositionedByField=Pu;var wr=class{constructor(e){this.workspace=e,this.cursorSvg=this.cursor=null,this.markers=new Map,this.markerSvg=null}registerMarker(e,t){this.markers.has(e)&&this.unregisterMarker(e),t.setDrawer(this.workspace.getRenderer().makeMarkerDrawer(this.workspace,t)),this.setMarkerSvg(t.getDrawer().createDom()),this.markers.set(e,t)}unregisterMarker(e){const t=this.markers.get(e);if(t)t.dispose(),this.markers.delete(e);else throw Error("Marker with ID "+e+" does not exist. Can only unregister markers that exist.")}getCursor(){return this.cursor}getMarker(e){return this.markers.get(e)||null}setCursor(e){this.cursor&&this.cursor.getDrawer()&&this.cursor.getDrawer().dispose(),(this.cursor=e)&&(e=this.workspace.getRenderer().makeMarkerDrawer(this.workspace,this.cursor),this.cursor.setDrawer(e),this.setCursorSvg(this.cursor.getDrawer().createDom()))}setCursorSvg(e){e?(this.workspace.getBlockCanvas().appendChild(e),this.cursorSvg=e):this.cursorSvg=null}setMarkerSvg(e){e?this.workspace.getBlockCanvas()&&(this.cursorSvg?this.workspace.getBlockCanvas().insertBefore(e,this.cursorSvg):this.workspace.getBlockCanvas().appendChild(e)):this.markerSvg=null}updateMarkers(){this.workspace.keyboardAccessibilityMode&&this.cursorSvg&&this.workspace.getCursor().draw()}dispose(){const e=Object.keys(this.markers);for(let t=0,o;o=e[t];t++)this.unregisterMarker(o);this.markers.clear(),this.cursor&&(this.cursor.dispose(),this.cursor=null)}};wr.LOCAL_MARKER="local_marker_1";var nn={};nn.commonWordPrefix=Ku,nn.commonWordSuffix=Yu,nn.isNumber=i.isNumber$$module$build$src$core$utils$string,nn.shortestStringLength=Qn,nn.wrap=i.wrap$$module$build$src$core$utils$string;var yl=void 0,kr=!1,rn=!1,uv=50,dv=0,bi=0,Vh=0,Kh=0,hs=null,Cr=null,Yh=0,Jh=10,hv=10,pv=750,_l=5,Tt=null,ns={HOVER_MS:pv,LIMIT:uv,MARGINS:_l,OFFSET_X:Yh,OFFSET_Y:Jh,RADIUS_OK:hv};ns.bindMouseEvents=Wi,ns.block=ed,ns.createDom=Xu,ns.dispose=Qu,ns.getCustomTooltip=zf,ns.getDiv=Hf,ns.getTooltipOfObject=Hi,ns.hide=co,ns.isVisible=Uf,ns.setCustomTooltip=Ff,ns.unbindMouseEvents=La,ns.unblock=td;var qh=.45,Xh=.65,gv={aqua:"#00ffff",black:"#000000",blue:"#0000ff",fuchsia:"#ff00ff",gray:"#808080",green:"#008000",lime:"#00ff00",maroon:"#800000",navy:"#000080",olive:"#808000",purple:"#800080",red:"#ff0000",silver:"#c0c0c0",teal:"#008080",white:"#ffffff",yellow:"#ffff00"},ps={};ps.blend=si,ps.getHsvSaturation=sd,ps.getHsvValue=od,ps.hexToRgb=Pa,ps.hsvToHex=Ba,ps.hueToHex=id,ps.names=gv,ps.parse=ti,ps.rgbToHex=er,ps.setHsvSaturation=qf,ps.setHsvValue=Xf;var Tr={};Tr.checkMessageReferences=Zf,Tr.parseBlockColour=Gi,Tr.replaceMessageReferences=bt,Tr.tokenizeInterpolation=nd;var lt=class{constructor(e,t,o){this.DEFAULT_VALUE=null,this.name=void 0,this.constants_=this.mouseDownWrapper=this.textContent_=this.textElement_=this.borderRect_=this.fieldGroup_=this.markerSvg=this.cursorSvg=this.tooltip=this.validator_=null,this.disposed=!1,this.maxDisplayLength=50,this.sourceBlock_=null,this.enabled_=this.visible_=this.isDirty_=!0,this.suffixField=this.prefixField=this.clickTarget_=null,this.EDITABLE=!0,this.SERIALIZABLE=!1,this.CURSOR="",this.value_="DEFAULT_VALUE"in new.target.prototype?new.target.prototype.DEFAULT_VALUE:this.DEFAULT_VALUE,this.size_=new Xe(0,0),e!==lt.SKIP_SETUP&&(o&&this.configure_(o),this.setValue(e),t&&this.setValidator(t))}configure_(e){e.tooltip&&this.setTooltip(bt(e.tooltip))}setSourceBlock(e){if(this.sourceBlock_)throw Error("Field already bound to a block");this.sourceBlock_=e}getConstants(){return!this.constants_&&this.sourceBlock_&&!this.sourceBlock_.isDeadOrDying()&&this.sourceBlock_.workspace.rendered&&(this.constants_=this.sourceBlock_.workspace.getRenderer().getConstants()),this.constants_}getSourceBlock(){return this.sourceBlock_}init(){this.fieldGroup_||(this.fieldGroup_=ie(J.G,{}),this.isVisible()||(this.fieldGroup_.style.display="none"),this.sourceBlock_.getSvgRoot().appendChild(this.fieldGroup_),this.initView(),this.updateEditable(),this.setTooltip(this.tooltip),this.bindEvents_(),this.initModel(),this.applyColour())}initView(){this.createBorderRect_(),this.createTextElement_()}initModel(){}isFullBlockField(){return!this.borderRect_}createBorderRect_(){this.borderRect_=ie(J.RECT,{rx:this.getConstants().FIELD_BORDER_RECT_RADIUS,ry:this.getConstants().FIELD_BORDER_RECT_RADIUS,x:0,y:0,height:this.size_.height,width:this.size_.width,class:"blocklyFieldRect"},this.fieldGroup_)}createTextElement_(){this.textElement_=ie(J.TEXT,{class:"blocklyText"},this.fieldGroup_),this.getConstants().FIELD_TEXT_BASELINE_CENTER&&this.textElement_.setAttribute("dominant-baseline","central"),this.textContent_=document.createTextNode(""),this.textElement_.appendChild(this.textContent_)}bindEvents_(){const e=this.getClickTarget_();if(!e)throw Error("A click target has not been set.");Wi(e),this.mouseDownWrapper=H(e,"pointerdown",this,this.onMouseDown_)}fromXml(e){this.setValue(e.textContent)}toXml(e){return e.textContent=this.getValue(),e}saveState(e){return e=this.saveLegacyState(lt),e!==null?e:this.getValue()}loadState(e){this.loadLegacyState(lt,e)||this.setValue(e)}saveLegacyState(e){return e.prototype.saveState===this.saveState&&e.prototype.toXml!==this.toXml?(e=i.createElement$$module$build$src$core$utils$xml("field"),e.setAttribute("name",this.name||""),Li(this.toXml(e)).replace(' xmlns="https://developers.google.com/blockly/xml"',"")):null}loadLegacyState(e,t){return e.prototype.loadState===this.loadState&&e.prototype.fromXml!==this.fromXml?(this.fromXml(i.textToDom$$module$build$src$core$utils$xml(t)),!0):!1}dispose(){Oa(this),ii(this);let e;(e=this.getSourceBlock())!=null&&e.isDeadOrDying()||Ze(this.fieldGroup_),this.disposed=!0}updateEditable(){const e=this.fieldGroup_,t=this.getSourceBlock();this.EDITABLE&&e&&t&&(this.enabled_&&t.isEditable()?(Re(e,"blocklyEditableText"),ze(e,"blocklyNonEditableText"),e.style.cursor=this.CURSOR):(Re(e,"blocklyNonEditableText"),ze(e,"blocklyEditableText"),e.style.cursor=""))}setEnabled(e){this.enabled_=e,this.updateEditable()}isEnabled(){return this.enabled_}isClickable(){return this.enabled_&&!!this.sourceBlock_&&this.sourceBlock_.isEditable()&&this.showEditor_!==lt.prototype.showEditor_}isClickableInFlyout(e){return!e}isCurrentlyEditable(){return this.enabled_&&this.EDITABLE&&!!this.sourceBlock_&&this.sourceBlock_.isEditable()}isSerializable(){let e=!1;return this.name&&(this.SERIALIZABLE?e=!0:this.EDITABLE&&(console.warn("Detected an editable field that was not serializable. Please define SERIALIZABLE property as true on all editable custom fields. Proceeding with serialization."),e=!0)),e}isVisible(){return this.visible_}setVisible(e){if(this.visible_!==e){this.visible_=e;var t=this.fieldGroup_;t&&(t.style.display=e?"block":"none")}}setValidator(e){this.validator_=e}getValidator(){return this.validator_}getSvgRoot(){return this.fieldGroup_}getBorderRect(){if(!this.borderRect_)throw Error(`The border rectangle is ${this.borderRect_}.`);return this.borderRect_}getTextElement(){if(!this.textElement_)throw Error(`The text element is ${this.textElement_}.`);return this.textElement_}getTextContent(){if(!this.textContent_)throw Error(`The text content is ${this.textContent_}.`);return this.textContent_}applyColour(){}render_(){this.textContent_&&(this.textContent_.nodeValue=this.getDisplayText_()),this.updateSize_()}showEditor(e){this.isClickable()&&this.showEditor_(e)}showEditor_(e){}repositionForWindowResize(){return!1}updateSize_(e){const t=this.getConstants();e=e!==void 0?e:this.isFullBlockField()?0:this.getConstants().FIELD_BORDER_RECT_X_PADDING;let o=2*e,n=t.FIELD_TEXT_HEIGHT,u=0;this.textElement_&&(u=Io(this.textElement_,t.FIELD_TEXT_FONTSIZE,t.FIELD_TEXT_FONTWEIGHT,t.FIELD_TEXT_FONTFAMILY),o+=u),this.isFullBlockField()||(n=Math.max(n,t.FIELD_BORDER_RECT_HEIGHT)),this.size_.height=n,this.size_.width=o,this.positionTextElement_(e,u),this.positionBorderRect_()}positionTextElement_(e,t){if(this.textElement_){var o=this.getConstants(),n=this.size_.height/2,u;this.textElement_.setAttribute("x",String((u=this.getSourceBlock())!=null&&u.RTL?this.size_.width-t-e:e)),this.textElement_.setAttribute("y",String(o.FIELD_TEXT_BASELINE_CENTER?n:n-o.FIELD_TEXT_HEIGHT/2+o.FIELD_TEXT_BASELINE))}}positionBorderRect_(){this.borderRect_&&(this.borderRect_.setAttribute("width",String(this.size_.width)),this.borderRect_.setAttribute("height",String(this.size_.height)),this.borderRect_.setAttribute("rx",String(this.getConstants().FIELD_BORDER_RECT_RADIUS)),this.borderRect_.setAttribute("ry",String(this.getConstants().FIELD_BORDER_RECT_RADIUS)))}getSize(){return this.isVisible()?(this.isDirty_?(this.render_(),this.isDirty_=!1):this.visible_&&this.size_.width===0&&(this.render_(),this.size_.width!==0&&console.warn("Deprecated use of setting size_.width to 0 to rerender a field. Set field.isDirty_ to true instead.")),this.size_):new Xe(0,0)}getScaledBBox(){let e;var t=this.getSourceBlock();if(!t)throw new _t;if(this.isFullBlockField()){var o=this.sourceBlock_.getHeightWidth();const n=t.workspace.scale;e=this.getAbsoluteXY_(),t=(o.width+1)*n,o=(o.height+1)*n,Ab?(e.x+=1.5*n,e.y+=1.5*n):(e.x-=.5*n,e.y-=.5*n)}else o=this.borderRect_.getBoundingClientRect(),e=xo(this.borderRect_),t=o.width,o=o.height;return new rt(e.y,e.y+o,e.x,e.x+t)}onLocationChange(e){}getDisplayText_(){let e=this.getText();return e?(e.length>this.maxDisplayLength&&(e=e.substring(0,this.maxDisplayLength-2)+"…"),e=e.replace(/\s/g,lt.NBSP),this.sourceBlock_&&this.sourceBlock_.RTL&&(e+="‏"),e):lt.NBSP}getText(){const e=this.getText_();return String(e!==null?e:this.getValue())}getText_(){return null}markDirty(){this.isDirty_=!0,this.constants_=null}forceRerender(){this.isDirty_=!0,this.sourceBlock_&&this.sourceBlock_.rendered&&this.sourceBlock_.queueRender()}setValue(e,t=!0){if(e!==null){var o=i.getGroup$$module$build$src$core$events$utils();o||i.setGroup$$module$build$src$core$events$utils(!0);try{const le=this.doClassValidation_(e),Ee=this.processValidation(e,le,t);if(!(Ee instanceof Error)){var n,u=(n=this.getValidator())==null?void 0:n.call(this,Ee),g=this.processValidation(Ee,u,t);if(!(g instanceof Error)){var I=this.sourceBlock_;if(!I||!I.disposed){var L=this.getValue();L===g?this.doValueUpdate_(g):(this.doValueUpdate_(g),t&&I&&C()&&z(new(ne(ee.BLOCK_CHANGE))(I,"field",this.name||null,L,g)),this.isDirty_&&this.forceRerender())}}}}finally{i.setGroup$$module$build$src$core$events$utils(o)}}}processValidation(e,t,o){return t===null?(this.doValueInvalid_(e,o),this.isDirty_&&this.forceRerender(),Error()):t===void 0?e:t}getValue(){return this.value_}doClassValidation_(e){return e??null}doValueUpdate_(e){this.value_=e,this.isDirty_=!0}doValueInvalid_(e,t){}onMouseDown_(e){this.sourceBlock_&&!this.sourceBlock_.isDeadOrDying()&&(e=this.sourceBlock_.workspace.getGesture(e))&&e.setStartField(this)}setTooltip(e){e||e===""||(e=this.sourceBlock_);const t=this.getClickTarget_();t?t.tooltip=e:this.tooltip=e}getTooltip(){const e=this.getClickTarget_();return Hi(e||{tooltip:this.tooltip})}getClickTarget_(){return this.clickTarget_||this.getSvgRoot()}getAbsoluteXY_(){return xo(this.getClickTarget_())}referencesVariables(){return!1}refreshVariableName(){}getParentInput(){let e=null;const t=this.getSourceBlock();if(!t)throw new _t;const o=t.inputList;for(let n=0;n")),z(new mi(t,"mutation",null,n,e));break;default:console.warn("Unknown change type: "+this.element)}}static getExtraBlockState_(e){return e.saveExtraState?(e=e.saveExtraState(!0))?JSON.stringify(e):"":e.mutationToDom&&(e=e.mutationToDom())?zs(e):""}};r($e.EVENT,ee.BLOCK_CHANGE,mi);var bl={};bl.clamp=Ui,bl.toDegrees=Pf,bl.toRadians=Oa;var vl=16,cv=1,uv=12,Hh=16,yl=.25,Wh=null,fi=null,tn="",sn="",st,on,$i,Gh=null,Bo=null,dv=null,Vh={getBoundsInfo:function(){const e=xo(Gh),t=Hn(Gh);return{left:e.x,right:e.x+t.width,top:e.y,bottom:e.y+t.height,width:t.width,height:t.height}},getPositionMetrics:function(e,t,o,n){const u=Vh.getBoundsInfo(),g=Hn(st);return t+g.heightu.top?Wu(o,n,u,g):t+g.heightdocument.documentElement.clientTop?Wu(o,n,u,g):jf(e,u,g)}},Ft={ANIMATION_TIME:yl,ARROW_HORIZONTAL_PADDING:uv,ARROW_SIZE:vl,BORDER_SIZE:cv,PADDING_Y:Hh,TEST_ONLY:Vh};Ft.clearContent=Ra,Ft.createDom=Mu,Ft.getContentDiv=qn,Ft.getOwner=Lu,Ft.getPositionX=Zn,Ft.hide=Na,Ft.hideIfOwner=Ma,Ft.hideWithoutAnimation=Fs,Ft.isVisible=Gu,Ft.repositionForWindowResize=Yu,Ft.setBoundsElement=Nu,Ft.setColour=Pu,Ft.show=Uu,Ft.showPositionedByBlock=Bf,Ft.showPositionedByField=Bu;var wr=class{constructor(e){this.workspace=e,this.cursorSvg=this.cursor=null,this.markers=new Map,this.markerSvg=null}registerMarker(e,t){this.markers.has(e)&&this.unregisterMarker(e),t.setDrawer(this.workspace.getRenderer().makeMarkerDrawer(this.workspace,t)),this.setMarkerSvg(t.getDrawer().createDom()),this.markers.set(e,t)}unregisterMarker(e){const t=this.markers.get(e);if(t)t.dispose(),this.markers.delete(e);else throw Error("Marker with ID "+e+" does not exist. Can only unregister markers that exist.")}getCursor(){return this.cursor}getMarker(e){return this.markers.get(e)||null}setCursor(e){this.cursor&&this.cursor.getDrawer()&&this.cursor.getDrawer().dispose(),(this.cursor=e)&&(e=this.workspace.getRenderer().makeMarkerDrawer(this.workspace,this.cursor),this.cursor.setDrawer(e),this.setCursorSvg(this.cursor.getDrawer().createDom()))}setCursorSvg(e){e?(this.workspace.getBlockCanvas().appendChild(e),this.cursorSvg=e):this.cursorSvg=null}setMarkerSvg(e){e?this.workspace.getBlockCanvas()&&(this.cursorSvg?this.workspace.getBlockCanvas().insertBefore(e,this.cursorSvg):this.workspace.getBlockCanvas().appendChild(e)):this.markerSvg=null}updateMarkers(){this.workspace.keyboardAccessibilityMode&&this.cursorSvg&&this.workspace.getCursor().draw()}dispose(){const e=Object.keys(this.markers);for(let t=0,o;o=e[t];t++)this.unregisterMarker(o);this.markers.clear(),this.cursor&&(this.cursor.dispose(),this.cursor=null)}};wr.LOCAL_MARKER="local_marker_1";var nn={};nn.commonWordPrefix=Ku,nn.commonWordSuffix=Ju,nn.isNumber=i.isNumber$$module$build$src$core$utils$string,nn.shortestStringLength=Qn,nn.wrap=i.wrap$$module$build$src$core$utils$string;var _l=void 0,kr=!1,rn=!1,hv=50,pv=0,bi=0,Yh=0,Kh=0,hs=null,Cr=null,Jh=0,Xh=10,gv=10,mv=750,wl=5,Tt=null,ns={HOVER_MS:mv,LIMIT:hv,MARGINS:wl,OFFSET_X:Jh,OFFSET_Y:Xh,RADIUS_OK:gv};ns.bindMouseEvents=Wi,ns.block=td,ns.createDom=Zu,ns.dispose=ed,ns.getCustomTooltip=Hf,ns.getDiv=Gf,ns.getTooltipOfObject=Hi,ns.hide=co,ns.isVisible=Wf,ns.setCustomTooltip=Uf,ns.unbindMouseEvents=Pa,ns.unblock=sd;var qh=.45,Zh=.65,fv={aqua:"#00ffff",black:"#000000",blue:"#0000ff",fuchsia:"#ff00ff",gray:"#808080",green:"#008000",lime:"#00ff00",maroon:"#800000",navy:"#000080",olive:"#808000",purple:"#800080",red:"#ff0000",silver:"#c0c0c0",teal:"#008080",white:"#ffffff",yellow:"#ffff00"},ps={};ps.blend=si,ps.getHsvSaturation=od,ps.getHsvValue=id,ps.hexToRgb=Ba,ps.hsvToHex=ja,ps.hueToHex=nd,ps.names=fv,ps.parse=ti,ps.rgbToHex=er,ps.setHsvSaturation=Zf,ps.setHsvValue=Qf;var Tr={};Tr.checkMessageReferences=e$,Tr.parseBlockColour=Gi,Tr.replaceMessageReferences=bt,Tr.tokenizeInterpolation=rd;var lt=class{constructor(e,t,o){this.DEFAULT_VALUE=null,this.name=void 0,this.constants_=this.mouseDownWrapper=this.textContent_=this.textElement_=this.borderRect_=this.fieldGroup_=this.markerSvg=this.cursorSvg=this.tooltip=this.validator_=null,this.disposed=!1,this.maxDisplayLength=50,this.sourceBlock_=null,this.enabled_=this.visible_=this.isDirty_=!0,this.suffixField=this.prefixField=this.clickTarget_=null,this.EDITABLE=!0,this.SERIALIZABLE=!1,this.CURSOR="",this.value_="DEFAULT_VALUE"in new.target.prototype?new.target.prototype.DEFAULT_VALUE:this.DEFAULT_VALUE,this.size_=new Ze(0,0),e!==lt.SKIP_SETUP&&(o&&this.configure_(o),this.setValue(e),t&&this.setValidator(t))}configure_(e){e.tooltip&&this.setTooltip(bt(e.tooltip))}setSourceBlock(e){if(this.sourceBlock_)throw Error("Field already bound to a block");this.sourceBlock_=e}getConstants(){return!this.constants_&&this.sourceBlock_&&!this.sourceBlock_.isDeadOrDying()&&this.sourceBlock_.workspace.rendered&&(this.constants_=this.sourceBlock_.workspace.getRenderer().getConstants()),this.constants_}getSourceBlock(){return this.sourceBlock_}init(){this.fieldGroup_||(this.fieldGroup_=ie(J.G,{}),this.isVisible()||(this.fieldGroup_.style.display="none"),this.sourceBlock_.getSvgRoot().appendChild(this.fieldGroup_),this.initView(),this.updateEditable(),this.setTooltip(this.tooltip),this.bindEvents_(),this.initModel(),this.applyColour())}initView(){this.createBorderRect_(),this.createTextElement_()}initModel(){}isFullBlockField(){return!this.borderRect_}createBorderRect_(){this.borderRect_=ie(J.RECT,{rx:this.getConstants().FIELD_BORDER_RECT_RADIUS,ry:this.getConstants().FIELD_BORDER_RECT_RADIUS,x:0,y:0,height:this.size_.height,width:this.size_.width,class:"blocklyFieldRect"},this.fieldGroup_)}createTextElement_(){this.textElement_=ie(J.TEXT,{class:"blocklyText"},this.fieldGroup_),this.getConstants().FIELD_TEXT_BASELINE_CENTER&&this.textElement_.setAttribute("dominant-baseline","central"),this.textContent_=document.createTextNode(""),this.textElement_.appendChild(this.textContent_)}bindEvents_(){const e=this.getClickTarget_();if(!e)throw Error("A click target has not been set.");Wi(e),this.mouseDownWrapper=W(e,"pointerdown",this,this.onMouseDown_)}fromXml(e){this.setValue(e.textContent)}toXml(e){return e.textContent=this.getValue(),e}saveState(e){return e=this.saveLegacyState(lt),e!==null?e:this.getValue()}loadState(e){this.loadLegacyState(lt,e)||this.setValue(e)}saveLegacyState(e){return e.prototype.saveState===this.saveState&&e.prototype.toXml!==this.toXml?(e=i.createElement$$module$build$src$core$utils$xml("field"),e.setAttribute("name",this.name||""),Li(this.toXml(e)).replace(' xmlns="https://developers.google.com/blockly/xml"',"")):null}loadLegacyState(e,t){return e.prototype.loadState===this.loadState&&e.prototype.fromXml!==this.fromXml?(this.fromXml(i.textToDom$$module$build$src$core$utils$xml(t)),!0):!1}dispose(){Ma(this),ii(this);let e;(e=this.getSourceBlock())!=null&&e.isDeadOrDying()||Qe(this.fieldGroup_),this.disposed=!0}updateEditable(){const e=this.fieldGroup_,t=this.getSourceBlock();this.EDITABLE&&e&&t&&(this.enabled_&&t.isEditable()?(Oe(e,"blocklyEditableText"),ze(e,"blocklyNonEditableText"),e.style.cursor=this.CURSOR):(Oe(e,"blocklyNonEditableText"),ze(e,"blocklyEditableText"),e.style.cursor=""))}setEnabled(e){this.enabled_=e,this.updateEditable()}isEnabled(){return this.enabled_}isClickable(){return this.enabled_&&!!this.sourceBlock_&&this.sourceBlock_.isEditable()&&this.showEditor_!==lt.prototype.showEditor_}isClickableInFlyout(e){return!e}isCurrentlyEditable(){return this.enabled_&&this.EDITABLE&&!!this.sourceBlock_&&this.sourceBlock_.isEditable()}isSerializable(){let e=!1;return this.name&&(this.SERIALIZABLE?e=!0:this.EDITABLE&&(console.warn("Detected an editable field that was not serializable. Please define SERIALIZABLE property as true on all editable custom fields. Proceeding with serialization."),e=!0)),e}isVisible(){return this.visible_}setVisible(e){if(this.visible_!==e){this.visible_=e;var t=this.fieldGroup_;t&&(t.style.display=e?"block":"none")}}setValidator(e){this.validator_=e}getValidator(){return this.validator_}getSvgRoot(){return this.fieldGroup_}getBorderRect(){if(!this.borderRect_)throw Error(`The border rectangle is ${this.borderRect_}.`);return this.borderRect_}getTextElement(){if(!this.textElement_)throw Error(`The text element is ${this.textElement_}.`);return this.textElement_}getTextContent(){if(!this.textContent_)throw Error(`The text content is ${this.textContent_}.`);return this.textContent_}applyColour(){}render_(){this.textContent_&&(this.textContent_.nodeValue=this.getDisplayText_()),this.updateSize_()}showEditor(e){this.isClickable()&&this.showEditor_(e)}showEditor_(e){}repositionForWindowResize(){return!1}updateSize_(e){const t=this.getConstants();e=e!==void 0?e:this.isFullBlockField()?0:this.getConstants().FIELD_BORDER_RECT_X_PADDING;let o=2*e,n=t.FIELD_TEXT_HEIGHT,u=0;this.textElement_&&(u=Io(this.textElement_,t.FIELD_TEXT_FONTSIZE,t.FIELD_TEXT_FONTWEIGHT,t.FIELD_TEXT_FONTFAMILY),o+=u),this.isFullBlockField()||(n=Math.max(n,t.FIELD_BORDER_RECT_HEIGHT)),this.size_.height=n,this.size_.width=o,this.positionTextElement_(e,u),this.positionBorderRect_()}positionTextElement_(e,t){if(this.textElement_){var o=this.getConstants(),n=this.size_.height/2,u;this.textElement_.setAttribute("x",String((u=this.getSourceBlock())!=null&&u.RTL?this.size_.width-t-e:e)),this.textElement_.setAttribute("y",String(o.FIELD_TEXT_BASELINE_CENTER?n:n-o.FIELD_TEXT_HEIGHT/2+o.FIELD_TEXT_BASELINE))}}positionBorderRect_(){this.borderRect_&&(this.borderRect_.setAttribute("width",String(this.size_.width)),this.borderRect_.setAttribute("height",String(this.size_.height)),this.borderRect_.setAttribute("rx",String(this.getConstants().FIELD_BORDER_RECT_RADIUS)),this.borderRect_.setAttribute("ry",String(this.getConstants().FIELD_BORDER_RECT_RADIUS)))}getSize(){return this.isVisible()?(this.isDirty_?(this.render_(),this.isDirty_=!1):this.visible_&&this.size_.width===0&&(this.render_(),this.size_.width!==0&&console.warn("Deprecated use of setting size_.width to 0 to rerender a field. Set field.isDirty_ to true instead.")),this.size_):new Ze(0,0)}getScaledBBox(){let e;var t=this.getSourceBlock();if(!t)throw new _t;if(this.isFullBlockField()){var o=this.sourceBlock_.getHeightWidth();const n=t.workspace.scale;e=this.getAbsoluteXY_(),t=(o.width+1)*n,o=(o.height+1)*n,Rb?(e.x+=1.5*n,e.y+=1.5*n):(e.x-=.5*n,e.y-=.5*n)}else o=this.borderRect_.getBoundingClientRect(),e=xo(this.borderRect_),t=o.width,o=o.height;return new rt(e.y,e.y+o,e.x,e.x+t)}onLocationChange(e){}getDisplayText_(){let e=this.getText();return e?(e.length>this.maxDisplayLength&&(e=e.substring(0,this.maxDisplayLength-2)+"…"),e=e.replace(/\s/g,lt.NBSP),this.sourceBlock_&&this.sourceBlock_.RTL&&(e+="‏"),e):lt.NBSP}getText(){const e=this.getText_();return String(e!==null?e:this.getValue())}getText_(){return null}markDirty(){this.isDirty_=!0,this.constants_=null}forceRerender(){this.isDirty_=!0,this.sourceBlock_&&this.sourceBlock_.rendered&&this.sourceBlock_.queueRender()}setValue(e,t=!0){if(e!==null){var o=i.getGroup$$module$build$src$core$events$utils();o||i.setGroup$$module$build$src$core$events$utils(!0);try{const le=this.doClassValidation_(e),Ee=this.processValidation(e,le,t);if(!(Ee instanceof Error)){var n,u=(n=this.getValidator())==null?void 0:n.call(this,Ee),g=this.processValidation(Ee,u,t);if(!(g instanceof Error)){var I=this.sourceBlock_;if(!I||!I.disposed){var P=this.getValue();P===g?this.doValueUpdate_(g):(this.doValueUpdate_(g),t&&I&&C()&&z(new(ne(ee.BLOCK_CHANGE))(I,"field",this.name||null,P,g)),this.isDirty_&&this.forceRerender())}}}}finally{i.setGroup$$module$build$src$core$events$utils(o)}}}processValidation(e,t,o){return t===null?(this.doValueInvalid_(e,o),this.isDirty_&&this.forceRerender(),Error()):t===void 0?e:t}getValue(){return this.value_}doClassValidation_(e){return e??null}doValueUpdate_(e){this.value_=e,this.isDirty_=!0}doValueInvalid_(e,t){}onMouseDown_(e){this.sourceBlock_&&!this.sourceBlock_.isDeadOrDying()&&(e=this.sourceBlock_.workspace.getGesture(e))&&e.setStartField(this)}setTooltip(e){e||e===""||(e=this.sourceBlock_);const t=this.getClickTarget_();t?t.tooltip=e:this.tooltip=e}getTooltip(){const e=this.getClickTarget_();return Hi(e||{tooltip:this.tooltip})}getClickTarget_(){return this.clickTarget_||this.getSvgRoot()}getAbsoluteXY_(){return xo(this.getClickTarget_())}referencesVariables(){return!1}refreshVariableName(){}getParentInput(){let e=null;const t=this.getSourceBlock();if(!t)throw new _t;const o=t.inputList;for(let n=0;n{o.stopPropagation()})}addModelUpdateBindings(){this.view.addTextChangeListener((e,t)=>{super.setText(t)}),this.view.addSizeChangeListener((e,t)=>{super.setSize(t)}),this.view.addOnCollapseListener(()=>{super.setCollapsed(this.view.isCollapsed())}),this.view.addDisposeListener(()=>{this.isDeadOrDying()||this.dispose()})}setText(e){this.view.setText(e)}setSize(e){this.view.setSize(e)}setCollapsed(e){this.view.setCollapsed(e)}setEditable(e){super.setEditable(e),this.view.setEditable(this.isEditable())}getSvgRoot(){return this.view.getSvgRoot()}getSize(){return super.getSize()}getBoundingRectangle(){const e=this.getRelativeToSurfaceXY();var t,o;const n=(o=(t=this.view)==null?void 0:t.getSize())!=null?o:this.getSize();return this.workspace.RTL?(t=e.x-n.width,o=e.x):(t=e.x,o=e.x+n.width),new rt(e.y,e.y+n.height,t,o)}moveBy(e,t,o){const n=this.getRelativeToSurfaceXY();e=new ye(n.x+e,n.y+t),this.moveTo(e,o)}moveTo(e,t){super.moveTo(e,t),this.view.moveTo(e)}moveDuringDrag(e){this.location=e,this.view.moveTo(e)}setDragging(e){e?Re(this.getSvgRoot(),"blocklyDragging"):ze(this.getSvgRoot(),"blocklyDragging")}dispose(){this.disposing=!0,this.view.isDeadOrDying()||this.view.dispose(),super.dispose()}startGesture(e){const t=this.workspace.getGesture(e);if(t){if(be(e))e.stopPropagation();else{t.handleCommentStart(e,this);let o;(o=this.workspace.getLayerManager())==null||o.append(this,jo)}i.setSelected$$module$build$src$core$common(this)}}setDeleteStyle(e){e?Re(this.getSvgRoot(),"blocklyDraggingDelete"):ze(this.getSvgRoot(),"blocklyDraggingDelete")}isMovable(){return this.dragStrategy.isMovable()}startDrag(){this.dragStrategy.startDrag()}drag(e){this.dragStrategy.drag(e)}endDrag(){this.dragStrategy.endDrag()}revertDrag(){this.dragStrategy.revertDrag()}select(){Re(this.getSvgRoot(),"blocklySelected")}unselect(){ze(this.getSvgRoot(),"blocklySelected")}toCopyData(){return{paster:pl.TYPE,commentState:Pi(this,{addCoordinates:!0})}}showContextMenu(e){const t=Ke.registry.getContextMenuOptions(Ke.ScopeType.COMMENT,{comment:this});sr(e,t,this.workspace.RTL,this.workspace)}snapToGrid(){if(!this.isDeadOrDying()){var e=this.workspace.getGrid();if(e!=null&&e.shouldSnap()){var t=this.getRelativeToSurfaceXY();e=e.alignXY(t),e!==t&&this.moveTo(e,["snap"])}}}},zt={};zt.appendDomToWorkspace=p$,zt.blockToDom=Ao,zt.blockToDomWithXY=nr,zt.clearWorkspaceAndLoadFromXml=h$,zt.deleteNext=w$,zt.domToBlock=i.domToBlock$$module$build$src$core$xml,zt.domToBlockInternal=ni,zt.domToPrettyText=d$,zt.domToText=zs,zt.domToVariables=$d,zt.domToWorkspace=i.domToWorkspace$$module$build$src$core$xml,zt.loadWorkspaceComment=fd,zt.saveWorkspaceComment=ir,zt.variablesToDom=gd,zt.workspaceToDom=l$;var Qh=class extends gi{constructor(e){super(e),this.type=ee.BLOCK_CREATE,e&&(e.isShadow()&&(this.recordUndo=!1),this.xml=nr(e),this.ids=ve(e),this.json=os(e,{addCoordinates:!0}))}toJson(){const e=super.toJson();if(!this.xml)throw Error("The block XML is undefined. Either pass a block to the constructor, or call fromJson");if(!this.ids)throw Error("The block IDs are undefined. Either pass a block to the constructor, or call fromJson");if(!this.json)throw Error("The block JSON is undefined. Either pass a block to the constructor, or call fromJson");return e.xml=zs(this.xml),e.ids=this.ids,e.json=this.json,this.recordUndo||(e.recordUndo=this.recordUndo),e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new Qh),t.xml=i.textToDom$$module$build$src$core$utils$xml(e.xml),t.ids=e.ids,t.json=e.json,e.recordUndo!==void 0&&(t.recordUndo=e.recordUndo),t}run(e){const t=this.getEventWorkspace_();if(!this.json)throw Error("The block JSON is undefined. Either pass a block to the constructor, or call fromJson");if(!this.ids)throw Error("The block IDs are undefined. Either pass a block to the constructor, or call fromJson");if(!KC(t,this.ids))if(e)lo(this.json,t);else for(e=0;ee.getBlockById(o)).filter(o=>o&&o.isShadow()).length===t.length};r($e.EVENT,ee.BLOCK_CREATE,Qh);var ep=class extends Ss{constructor(e,t){super(t),this.type=ee.THEME_CHANGE,this.themeName=e}toJson(){const e=super.toJson();if(!this.themeName)throw Error("The theme name is undefined. Either pass a theme name to the constructor, or call fromJson");return e.themeName=this.themeName,e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new ep),t.themeName=e.themeName,t}};r($e.EVENT,ee.THEME_CHANGE,ep);var tp=class extends Ss{constructor(e,t,o,n,u){super(n),this.type=ee.VIEWPORT_CHANGE,this.viewTop=e,this.viewLeft=t,this.scale=o,this.oldScale=u}toJson(){const e=super.toJson();if(this.viewTop===void 0)throw Error("The view top is undefined. Either pass a value to the constructor, or call fromJson");if(this.viewLeft===void 0)throw Error("The view left is undefined. Either pass a value to the constructor, or call fromJson");if(this.scale===void 0)throw Error("The scale is undefined. Either pass a value to the constructor, or call fromJson");if(this.oldScale===void 0)throw Error("The old scale is undefined. Either pass a value to the constructor, or call fromJson");return e.viewTop=this.viewTop,e.viewLeft=this.viewLeft,e.scale=this.scale,e.oldScale=this.oldScale,e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new tp),t.viewTop=e.viewTop,t.viewLeft=e.viewLeft,t.scale=e.scale,t.oldScale=e.oldScale,t}};r($e.EVENT,ee.VIEWPORT_CHANGE,tp);var xe;(function(e){e[e.INPUT_VALUE=1]="INPUT_VALUE",e[e.OUTPUT_VALUE=2]="OUTPUT_VALUE",e[e.NEXT_STATEMENT=3]="NEXT_STATEMENT",e[e.PREVIOUS_STATEMENT=4]="PREVIOUS_STATEMENT"})(xe||(xe={}));var un=class{constructor(e){this.connectionChecker=e,this.connections=[]}addConnection(e,t){t=this.calculateIndexForYPos(t),this.connections.splice(t,0,e)}findIndexOfConnection(e,t){if(!this.connections.length)return-1;const o=this.calculateIndexForYPos(t);if(o>=this.connections.length)return-1;t=e.y;let n=o;for(;0<=n&&this.connections[n].y===t;){if(this.connections[n]===e)return n;n--}for(n=o;ne)o=n;else{t=n;break}}return t}removeConnection(e,t){if(e=this.findIndexOfConnection(e,t),e===-1)throw Error("Unable to find connection in connectionDB.");this.connections.splice(e,1)}getNeighbours(e,t){function o(Ee){const dt=u-n[Ee].x,ut=g-n[Ee].y;return Math.sqrt(dt*dt+ut*ut)<=t&&le.push(n[Ee]),ut(this.flyout?i.config$$module$build$src$core$config.flyoutDragRadius:i.config$$module$build$src$core$config.dragRadius)}updateIsDraggingFromFlyout(){let e;if(!this.targetBlock||(e=this.flyout)==null||!e.isBlockCreatable(this.targetBlock))return!1;if(!this.flyout.targetWorkspace)throw Error(`Cannot update dragging from the flyout because the ' + - 'flyout's target workspace is undefined`);return!this.flyout.isScrollable()||this.flyout.isDragTowardWorkspace(this.currentDragDeltaXY)?(this.startWorkspace_=this.flyout.targetWorkspace,this.startWorkspace_.updateScreenCalculationsIfScrolled(),i.getGroup$$module$build$src$core$events$utils()||i.setGroup$$module$build$src$core$events$utils(!0),this.startBlock=null,this.targetBlock=this.flyout.createBlock(this.targetBlock),i.setSelected$$module$build$src$core$common(this.targetBlock),!0):!1}updateIsDraggingWorkspace(){if(!this.startWorkspace_)throw Error("Cannot update dragging the workspace because the start workspace is undefined");(this.flyout?this.flyout.isScrollable():this.startWorkspace_&&this.startWorkspace_.isDraggable())&&(this.dragging=!0,this.workspaceDragger=new vv(this.startWorkspace_),this.workspaceDragger.startDrag())}updateIsDragging(e){if(!this.startWorkspace_)throw Error("Cannot update dragging because the start workspace is undefined");if(this.calledUpdateIsDragging)throw Error("updateIsDragging_ should only be called once per gesture.");this.calledUpdateIsDragging=!0,this.flyout&&this.updateIsDraggingFromFlyout();const t=F();t&&ri(t)&&t.isMovable()?(this.dragging=!0,this.dragger=this.createDragger(t,this.startWorkspace_),this.dragger.onDragStart(e),this.dragger.onDrag(e,this.currentDragDeltaXY)):this.updateIsDraggingWorkspace()}createDragger(e,t){return new(y($e.BLOCK_DRAGGER,this.creatorWorkspace.options,!0))(e,t)}doStart(e){if(!this.startWorkspace_)throw Error("Cannot start the touch gesture becauase the start workspace is undefined");this.isPinchZoomEnabled=this.startWorkspace_.options.zoomOptions&&this.startWorkspace_.options.zoomOptions.pinch,be(e)?this.cancel():(this.gestureHasStarted=!0,Ki(),this.startWorkspace_.updateScreenCalculationsIfScrolled(),this.startWorkspace_.isMutator&&this.startWorkspace_.resize(),this.currentDropdownOwner=Mu(),this.startWorkspace_.hideChaff(!!this.flyout),this.startWorkspace_.markFocused(),this.mostRecentEvent=e,ed(),pe(e)?this.handleRightClick(e):(e.type.toLowerCase()==="pointerdown"&&e.pointerType!=="mouse"&&k(e,this),this.mouseDownXY=new ye(e.clientX,e.clientY),this.bindMouseEvents(e),this.isEnding_||this.handleTouchStart(e)))}bindMouseEvents(e){this.boundEvents.push(H(document,"pointerdown",null,this.handleStart.bind(this),!0)),this.boundEvents.push(H(document,"pointermove",null,this.handleMove.bind(this),!0)),this.boundEvents.push(H(document,"pointerup",null,this.handleUp.bind(this),!0)),e.preventDefault(),e.stopPropagation()}handleStart(e){this.isDragging()||(this.handleTouchStart(e),this.isMultiTouch()&&X())}handleMove(e){this.isDragging()&&R(e)||!this.isMultiTouch()?(this.updateFromEvent(e),this.workspaceDragger?this.workspaceDragger.drag(this.currentDragDeltaXY):this.dragger&&this.dragger.onDrag(this.mostRecentEvent,this.currentDragDeltaXY),e.preventDefault(),e.stopPropagation()):this.isMultiTouch()&&(this.handleTouchMove(e),X())}handleUp(e){if(this.isDragging()||this.handleTouchEnd(e),!this.isMultiTouch()||this.isDragging()){if(!R(e))return;if(this.updateFromEvent(e),X(),this.isEnding_){console.log("Trying to end a gesture recursively.");return}this.isEnding_=!0,this.dragger?this.dragger.onDragEnd(e,this.currentDragDeltaXY):this.workspaceDragger?this.workspaceDragger.endDrag(this.currentDragDeltaXY):this.isBubbleClick()||this.isCommentClick()||(this.isFieldClick()?this.doFieldClick():this.isIconClick()?this.doIconClick():this.isBlockClick()?this.doBlockClick():this.isWorkspaceClick()&&this.doWorkspaceClick(e))}e.preventDefault(),e.stopPropagation(),this.dispose()}handleTouchStart(e){var t=A(e);this.cachedPoints.set(t,this.getTouchPoint(e));var o=Array.from(this.cachedPoints.keys());o.length===2&&(t=this.cachedPoints.get(o[0]),o=this.cachedPoints.get(o[1]),this.startDistance=ye.distance(t,o),this.multiTouch=!0,e.preventDefault())}handleTouchMove(e){const t=A(e);this.cachedPoints.set(t,this.getTouchPoint(e)),this.isPinchZoomEnabled&&this.cachedPoints.size===2?this.handlePinch(e):(this.updateFromEvent(e),this.workspaceDragger?this.workspaceDragger.drag(this.currentDragDeltaXY):this.dragger&&this.dragger.onDrag(this.mostRecentEvent,this.currentDragDeltaXY),e.preventDefault(),e.stopPropagation())}handlePinch(e){var t=Array.from(this.cachedPoints.keys()),o=this.cachedPoints.get(t[0]);if(t=this.cachedPoints.get(t[1]),o=ye.distance(o,t)/this.startDistance,0this.previousScale){if(t=o-this.previousScale,t=0this.cachedPoints.size&&(this.cachedPoints.clear(),this.previousScale=0)}getTouchPoint(e){return this.startWorkspace_?new ye(e.pageX,e.pageY):null}isMultiTouch(){return this.multiTouch}cancel(){this.isEnding_||(X(),this.dragger?this.dragger.onDragEnd(this.mostRecentEvent,this.currentDragDeltaXY):this.workspaceDragger&&this.workspaceDragger.endDrag(this.currentDragDeltaXY),this.dispose())}handleRightClick(e){this.targetBlock?(this.bringBlockToFront(),this.targetBlock.workspace.hideChaff(!!this.flyout),this.targetBlock.showContextMenu(e)):this.startBubble?this.startBubble.showContextMenu(e):this.startComment?(this.startComment.workspace.hideChaff(),this.startComment.showContextMenu(e)):this.startWorkspace_&&!this.flyout&&(this.startWorkspace_.hideChaff(),this.startWorkspace_.showContextMenu(e)),e.preventDefault(),e.stopPropagation(),this.dispose()}handleWsStart(e,t){if(this.gestureHasStarted)throw Error("Tried to call gesture.handleWsStart, but the gesture had already been started.");this.setStartWorkspace(t),this.mostRecentEvent=e,this.startBlock||this.startBubble||this.startComment||i.setSelected$$module$build$src$core$common(null),this.doStart(e)}fireWorkspaceClick(e){z(new(ne(ee.CLICK))(null,e.id,"workspace"))}handleFlyoutStart(e,t){if(this.gestureHasStarted)throw Error("Tried to call gesture.handleFlyoutStart, but the gesture had already been started.");this.setStartFlyout(t),this.handleWsStart(e,t.getWorkspace())}handleBlockStart(e,t){if(this.gestureHasStarted)throw Error("Tried to call gesture.handleBlockStart, but the gesture had already been started.");this.setStartBlock(t),this.mostRecentEvent=e}handleBubbleStart(e,t){if(this.gestureHasStarted)throw Error("Tried to call gesture.handleBubbleStart, but the gesture had already been started.");this.setStartBubble(t),this.mostRecentEvent=e}handleCommentStart(e,t){if(this.gestureHasStarted)throw Error("Tried to call gesture.handleCommentStart, but the gesture had already been started.");this.setStartComment(t),this.mostRecentEvent=e}doFieldClick(){if(!this.startField)throw Error("Cannot do a field click because the start field is undefined");this.currentDropdownOwner!==this.startField&&this.startField.showEditor(this.mostRecentEvent),this.bringBlockToFront()}doIconClick(){if(!this.startIcon)throw Error("Cannot do an icon click because the start icon is undefined");this.bringBlockToFront(),this.startIcon.onClick()}doBlockClick(){if(this.flyout&&this.flyout.autoClose){if(!this.targetBlock)throw Error("Cannot do a block click because the target block is undefined");if(this.targetBlock.isEnabled()){i.getGroup$$module$build$src$core$events$utils()||i.setGroup$$module$build$src$core$events$utils(!0);var e=this.flyout.createBlock(this.targetBlock);e.snapToGrid(),e.bumpNeighbours()}}else{if(!this.startWorkspace_)throw Error("Cannot do a block click because the start workspace is undefined");e=new(ne(ee.CLICK))(this.startBlock,this.startWorkspace_.id,"block"),z(e)}this.bringBlockToFront(),i.setGroup$$module$build$src$core$events$utils(!1)}doWorkspaceClick(e){e=this.creatorWorkspace,F()&&F().unselect(),this.fireWorkspaceClick(this.startWorkspace_||e)}bringBlockToFront(){this.targetBlock&&!this.flyout&&this.targetBlock.bringToFront()}setStartField(e){if(this.gestureHasStarted)throw Error("Tried to call gesture.setStartField, but the gesture had already been started.");this.startField||(this.startField=e)}setStartIcon(e){if(this.gestureHasStarted)throw Error("Tried to call gesture.setStartIcon, but the gesture had already been started.");this.startIcon||(this.startIcon=e)}setStartBubble(e){this.startBubble||(this.startBubble=e)}setStartComment(e){this.startComment||(this.startComment=e)}setStartBlock(e){this.startBlock||this.startBubble||(this.startBlock=e,i.setSelected$$module$build$src$core$common(this.startBlock),e.isInFlyout&&e!==e.getRootBlock()?this.setTargetBlock(e.getRootBlock()):this.setTargetBlock(e))}setTargetBlock(e){e.isShadow()?this.setTargetBlock(e.getParent()):this.targetBlock=e}setStartWorkspace(e){this.startWorkspace_||(this.startWorkspace_=e)}setStartFlyout(e){this.flyout||(this.flyout=e)}isBubbleClick(){return!!this.startBubble&&!this.hasExceededDragRadius}isCommentClick(){return!!this.startComment&&!this.hasExceededDragRadius}isBlockClick(){return!!this.startBlock&&!this.hasExceededDragRadius&&!this.isFieldClick()&&!this.isIconClick()}isFieldClick(){return this.startField?this.startField.isClickable()&&!this.hasExceededDragRadius&&(!this.flyout||this.startField.isClickableInFlyout(this.flyout.autoClose)):!1}isIconClick(){if(!this.startIcon)return!1;const e=!this.flyout||!this.startIcon.isClickableInFlyout||this.startIcon.isClickableInFlyout(this.flyout.autoClose);return!this.hasExceededDragRadius&&e}isWorkspaceClick(){return!this.startBlock&&!this.startBubble&&!this.startField&&!this.hasExceededDragRadius}getCurrentDragger(){let e,t;return(t=(e=this.workspaceDragger)!=null?e:this.dragger)!=null?t:null}isDragging(){return this.dragging}hasStarted(){return this.gestureHasStarted}static inProgress(){const e=B();for(let t=0,o;o=e[t];t++)if(o.currentGesture_)return!0;return!1}},sp=class{constructor(e,t){this.pattern=e,this.scale=1;let o;this.spacing=(o=t.spacing)!=null?o:0;let n;this.length=(n=t.length)!=null?n:1,this.line2=(this.line1=e.firstChild)&&this.line1.nextSibling;let u;this.snapToGrid=(u=t.snap)!=null?u:!1}setSpacing(e){this.spacing=e,this.update(this.scale)}getSpacing(){return this.spacing}setLength(e){this.length=e,this.update(this.scale)}getLength(){return this.length}setSnapToGrid(e){this.snapToGrid=e}shouldSnap(){return this.snapToGrid}getPatternId(){return this.pattern.id}update(e){this.scale=e;var t=this.spacing*e;this.pattern.setAttribute("width",`${t}`),this.pattern.setAttribute("height",`${t}`),t=Math.floor(this.spacing/2)+.5;let o=t-this.length/2,n=t+this.length/2;t*=e,o*=e,n*=e,this.setLineAttributes(this.line1,e,o,n,t,t),this.setLineAttributes(this.line2,e,t,t,o,n)}setLineAttributes(e,t,o,n,u,g){e&&(e.setAttribute("stroke-width",`${t}`),e.setAttribute("x1",`${o}`),e.setAttribute("y1",`${u}`),e.setAttribute("x2",`${n}`),e.setAttribute("y2",`${g}`))}moveTo(e,t){this.pattern.setAttribute("x",`${e}`),this.pattern.setAttribute("y",`${t}`)}alignXY(e){var t=this.getSpacing();const o=t/2,n=Math.round(Math.round((e.x-o)/t)*t+o);return t=Math.round(Math.round((e.y-o)/t)*t+o),n===e.x&&t===e.y?e:new ye(n,t)}static createDom(e,t,o){e=ie(J.PATTERN,{id:"blocklyGridPattern"+e,patternUnits:"userSpaceOnUse"},o);let n,u;if(0<((n=t.length)!=null?n:1)&&0<((u=t.spacing)!=null?u:0)){ie(J.LINE,{stroke:t.colour},e);let g;(g=t.length)!=null&&g&&ie(J.LINE,{stroke:t.colour},e)}else ie(J.LINE,{},e);return e}},qC=class{constructor(e){this.workspace=e,this.layers=new Map,(e=e.getInjectionDiv())&&(this.dragLayer=this.createDragLayer(e),this.animationLayer=this.createAnimationLayer(e)),e=this.createLayer(jo),Re(e,"blocklyBlockCanvas"),e=this.createLayer(Sl),Re(e,"blocklyBubbleCanvas")}createDragLayer(e){const t=ie(J.SVG,{class:"blocklyBlockDragSurface",xmlns:pr,"xmlns:html":Gs,"xmlns:xlink":is,version:"1.1"});return e.append(t),ie(J.G,{},t)}createAnimationLayer(e){const t=ie(J.SVG,{class:"blocklyAnimationLayer",xmlns:pr,"xmlns:html":Gs,"xmlns:xlink":is,version:"1.1"});return e.append(t),ie(J.G,{},t)}appendToAnimationLayer(e){let t;const o=(t=this.dragLayer)==null?void 0:t.getAttribute("transform");if(o){let u;(u=this.animationLayer)==null||u.setAttribute("transform",o)}let n;(n=this.animationLayer)==null||n.appendChild(e.getSvgRoot())}translateLayers(e,t){e=`translate(${e.x}, ${e.y}) scale(${t})`;let o;(o=this.dragLayer)==null||o.setAttribute("transform",e);for(const[,n]of this.layers)n.setAttribute("transform",e)}moveToDragLayer(e){let t;(t=this.dragLayer)==null||t.appendChild(e.getSvgRoot())}moveOffDragLayer(e,t){this.append(e,t)}append(e,t){this.layers.has(t)||this.createLayer(t);let o;(o=this.layers.get(t))==null||o.appendChild(e.getSvgRoot())}createLayer(e){const t=this.workspace.getSvgGroup(),o=ie(J.G,{});let n=!1;const u=[...this.layers].sort((g,I)=>g[0]-I[0]);for(const[g,I]of u)if(et[1]===e)?e:(this.sourceBlock_&&console.warn("Cannot set the dropdown's value to an unavailable option. Block type: "+this.sourceBlock_.type+", Field name: "+this.name+", Value: "+e),null)}doValueUpdate_(e){super.doValueUpdate_(e),e=this.getOptions(!0);for(let t=0,o;o=e[t];t++)o[1]===this.value_&&(this.selectedOption=o)}applyColour(){const e=this.sourceBlock_;this.borderRect_&&(this.borderRect_.setAttribute("stroke",e.getColourTertiary()),this.menu_?this.borderRect_.setAttribute("fill",e.getColourTertiary()):this.borderRect_.setAttribute("fill","transparent")),e&&this.arrow&&(e.isShadow()?this.arrow.style.fill=e.getColourSecondary():this.arrow.style.fill=e.getColour())}render_(){this.getTextContent().nodeValue="",this.imageElement.style.display="none";const e=this.selectedOption&&this.selectedOption[0];e&&typeof e=="object"?this.renderSelectedImage(e):this.renderSelectedText(),this.positionBorderRect_()}renderSelectedImage(e){const t=this.getSourceBlock();if(!t)throw new _t;this.imageElement.style.display="",this.imageElement.setAttributeNS(is,"xlink:href",e.src),this.imageElement.setAttribute("height",String(e.height)),this.imageElement.setAttribute("width",String(e.width));const o=Number(e.height);e=Number(e.width);var n=!!this.borderRect_;const u=Math.max(n?this.getConstants().FIELD_DROPDOWN_BORDER_RECT_HEIGHT:0,o+es.IMAGE_Y_PADDING);n=n?this.getConstants().FIELD_BORDER_RECT_X_PADDING:0;let g;g=this.svgArrow?this.positionSVGArrow(e+n,u/2-this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE/2):Io(this.arrow,this.getConstants().FIELD_TEXT_FONTSIZE,this.getConstants().FIELD_TEXT_FONTWEIGHT,this.getConstants().FIELD_TEXT_FONTFAMILY),this.size_.width=e+g+2*n,this.size_.height=u;let I=0;t.RTL?this.imageElement.setAttribute("x",`${n+g}`):(I=e+g,this.getTextElement().setAttribute("text-anchor","end"),this.imageElement.setAttribute("x",`${n}`)),this.imageElement.setAttribute("y",String(u/2-o/2)),this.positionTextElement_(I+n,e+g)}renderSelectedText(){this.getTextContent().nodeValue=this.getDisplayText_();var e=this.getTextElement();Re(e,"blocklyDropdownText"),e.setAttribute("text-anchor","start");var t=!!this.borderRect_;e=Math.max(t?this.getConstants().FIELD_DROPDOWN_BORDER_RECT_HEIGHT:0,this.getConstants().FIELD_TEXT_HEIGHT);const o=Io(this.getTextElement(),this.getConstants().FIELD_TEXT_FONTSIZE,this.getConstants().FIELD_TEXT_FONTWEIGHT,this.getConstants().FIELD_TEXT_FONTFAMILY);t=t?this.getConstants().FIELD_BORDER_RECT_X_PADDING:0;let n=0;this.svgArrow&&(n=this.positionSVGArrow(o+t,e/2-this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE/2)),this.size_.width=o+n+2*t,this.size_.height=e,this.positionTextElement_(t,o)}positionSVGArrow(e,t){if(!this.svgArrow)return 0;const o=this.getSourceBlock();if(!o)throw new _t;const n=this.borderRect_?this.getConstants().FIELD_BORDER_RECT_X_PADDING:0,u=this.getConstants().FIELD_DROPDOWN_SVG_ARROW_PADDING,g=this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE;return this.svgArrow.setAttribute("transform","translate("+(o.RTL?n:e+u)+","+t+")"),g+u}getText_(){if(!this.selectedOption)return null;const e=this.selectedOption[0];return typeof e=="object"?e.alt:e}static fromJson(e){if(!e.options)throw Error("options are required for the dropdown field. The options property must be assigned an array of [humanReadableValue, languageNeutralValue] tuples.");return new this(e.options,void 0,e)}trimOptions(e){let t=!1;const o=e.map(([I,L])=>typeof I=="string"?[bt(I),L]:(t=!0,[I.alt!==null?Object.assign({},I,{alt:bt(I.alt)}):Object.assign({},I),L]));if(t||2>e.length)return{options:o};var n=o.map(([I])=>I),u=Qn(n);e=Ku(n,u);const g=Yu(n,u);return!e&&!g||u<=e+g?{options:o}:(u=e?n[0].substring(0,e-1):void 0,n=g?n[0].substr(1-g):void 0,{options:this.applyTrim(o,e,g),prefix:u,suffix:n})}applyTrim(e,t,o){return e.map(([n,u])=>[n.substring(t,n.length-o),u])}validateOptions(e){if(!Array.isArray(e))throw TypeError("FieldDropdown options must be an array.");if(!e.length)throw TypeError("FieldDropdown options must not be an empty array.");let t=!1;for(let o=0;o{o.stopPropagation()})}addModelUpdateBindings(){this.view.addTextChangeListener((e,t)=>{super.setText(t)}),this.view.addSizeChangeListener((e,t)=>{super.setSize(t)}),this.view.addOnCollapseListener(()=>{super.setCollapsed(this.view.isCollapsed())}),this.view.addDisposeListener(()=>{this.isDeadOrDying()||this.dispose()})}setText(e){this.view.setText(e)}setSize(e){this.view.setSize(e)}setCollapsed(e){this.view.setCollapsed(e)}setEditable(e){super.setEditable(e),this.view.setEditable(this.isEditable())}getSvgRoot(){return this.view.getSvgRoot()}getSize(){return super.getSize()}getBoundingRectangle(){const e=this.getRelativeToSurfaceXY();var t,o;const n=(o=(t=this.view)==null?void 0:t.getSize())!=null?o:this.getSize();return this.workspace.RTL?(t=e.x-n.width,o=e.x):(t=e.x,o=e.x+n.width),new rt(e.y,e.y+n.height,t,o)}moveBy(e,t,o){const n=this.getRelativeToSurfaceXY();e=new ye(n.x+e,n.y+t),this.moveTo(e,o)}moveTo(e,t){super.moveTo(e,t),this.view.moveTo(e)}moveDuringDrag(e){this.location=e,this.view.moveTo(e)}setDragging(e){e?Oe(this.getSvgRoot(),"blocklyDragging"):ze(this.getSvgRoot(),"blocklyDragging")}dispose(){this.disposing=!0,this.view.isDeadOrDying()||this.view.dispose(),super.dispose()}startGesture(e){const t=this.workspace.getGesture(e);if(t){if(be(e))e.stopPropagation();else{t.handleCommentStart(e,this);let o;(o=this.workspace.getLayerManager())==null||o.append(this,jo)}i.setSelected$$module$build$src$core$common(this)}}setDeleteStyle(e){e?Oe(this.getSvgRoot(),"blocklyDraggingDelete"):ze(this.getSvgRoot(),"blocklyDraggingDelete")}isMovable(){return this.dragStrategy.isMovable()}startDrag(){this.dragStrategy.startDrag()}drag(e){this.dragStrategy.drag(e)}endDrag(){this.dragStrategy.endDrag()}revertDrag(){this.dragStrategy.revertDrag()}select(){Oe(this.getSvgRoot(),"blocklySelected")}unselect(){ze(this.getSvgRoot(),"blocklySelected")}toCopyData(){return{paster:gl.TYPE,commentState:Pi(this,{addCoordinates:!0})}}showContextMenu(e){const t=Ye.registry.getContextMenuOptions(Ye.ScopeType.COMMENT,{comment:this});sr(e,t,this.workspace.RTL,this.workspace)}snapToGrid(){if(!this.isDeadOrDying()){var e=this.workspace.getGrid();if(e!=null&&e.shouldSnap()){var t=this.getRelativeToSurfaceXY();e=e.alignXY(t),e!==t&&this.moveTo(e,["snap"])}}}},zt={};zt.appendDomToWorkspace=m$,zt.blockToDom=Ao,zt.blockToDomWithXY=nr,zt.clearWorkspaceAndLoadFromXml=g$,zt.deleteNext=C$,zt.domToBlock=i.domToBlock$$module$build$src$core$xml,zt.domToBlockInternal=ni,zt.domToPrettyText=p$,zt.domToText=zs,zt.domToVariables=bd,zt.domToWorkspace=i.domToWorkspace$$module$build$src$core$xml,zt.loadWorkspaceComment=$d,zt.saveWorkspaceComment=ir,zt.variablesToDom=md,zt.workspaceToDom=u$;var ep=class extends gi{constructor(e){super(e),this.type=ee.BLOCK_CREATE,e&&(e.isShadow()&&(this.recordUndo=!1),this.xml=nr(e),this.ids=ve(e),this.json=os(e,{addCoordinates:!0}))}toJson(){const e=super.toJson();if(!this.xml)throw Error("The block XML is undefined. Either pass a block to the constructor, or call fromJson");if(!this.ids)throw Error("The block IDs are undefined. Either pass a block to the constructor, or call fromJson");if(!this.json)throw Error("The block JSON is undefined. Either pass a block to the constructor, or call fromJson");return e.xml=zs(this.xml),e.ids=this.ids,e.json=this.json,this.recordUndo||(e.recordUndo=this.recordUndo),e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new ep),t.xml=i.textToDom$$module$build$src$core$utils$xml(e.xml),t.ids=e.ids,t.json=e.json,e.recordUndo!==void 0&&(t.recordUndo=e.recordUndo),t}run(e){const t=this.getEventWorkspace_();if(!this.json)throw Error("The block JSON is undefined. Either pass a block to the constructor, or call fromJson");if(!this.ids)throw Error("The block IDs are undefined. Either pass a block to the constructor, or call fromJson");if(!KC(t,this.ids))if(e)lo(this.json,t);else for(e=0;ee.getBlockById(o)).filter(o=>o&&o.isShadow()).length===t.length};r($e.EVENT,ee.BLOCK_CREATE,ep);var tp=class extends Ss{constructor(e,t){super(t),this.type=ee.THEME_CHANGE,this.themeName=e}toJson(){const e=super.toJson();if(!this.themeName)throw Error("The theme name is undefined. Either pass a theme name to the constructor, or call fromJson");return e.themeName=this.themeName,e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new tp),t.themeName=e.themeName,t}};r($e.EVENT,ee.THEME_CHANGE,tp);var sp=class extends Ss{constructor(e,t,o,n,u){super(n),this.type=ee.VIEWPORT_CHANGE,this.viewTop=e,this.viewLeft=t,this.scale=o,this.oldScale=u}toJson(){const e=super.toJson();if(this.viewTop===void 0)throw Error("The view top is undefined. Either pass a value to the constructor, or call fromJson");if(this.viewLeft===void 0)throw Error("The view left is undefined. Either pass a value to the constructor, or call fromJson");if(this.scale===void 0)throw Error("The scale is undefined. Either pass a value to the constructor, or call fromJson");if(this.oldScale===void 0)throw Error("The old scale is undefined. Either pass a value to the constructor, or call fromJson");return e.viewTop=this.viewTop,e.viewLeft=this.viewLeft,e.scale=this.scale,e.oldScale=this.oldScale,e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new sp),t.viewTop=e.viewTop,t.viewLeft=e.viewLeft,t.scale=e.scale,t.oldScale=e.oldScale,t}};r($e.EVENT,ee.VIEWPORT_CHANGE,sp);var xe;(function(e){e[e.INPUT_VALUE=1]="INPUT_VALUE",e[e.OUTPUT_VALUE=2]="OUTPUT_VALUE",e[e.NEXT_STATEMENT=3]="NEXT_STATEMENT",e[e.PREVIOUS_STATEMENT=4]="PREVIOUS_STATEMENT"})(xe||(xe={}));var un=class{constructor(e){this.connectionChecker=e,this.connections=[]}addConnection(e,t){t=this.calculateIndexForYPos(t),this.connections.splice(t,0,e)}findIndexOfConnection(e,t){if(!this.connections.length)return-1;const o=this.calculateIndexForYPos(t);if(o>=this.connections.length)return-1;t=e.y;let n=o;for(;0<=n&&this.connections[n].y===t;){if(this.connections[n]===e)return n;n--}for(n=o;ne)o=n;else{t=n;break}}return t}removeConnection(e,t){if(e=this.findIndexOfConnection(e,t),e===-1)throw Error("Unable to find connection in connectionDB.");this.connections.splice(e,1)}getNeighbours(e,t){function o(Ee){const dt=u-n[Ee].x,ut=g-n[Ee].y;return Math.sqrt(dt*dt+ut*ut)<=t&&le.push(n[Ee]),ut(this.flyout?i.config$$module$build$src$core$config.flyoutDragRadius:i.config$$module$build$src$core$config.dragRadius)}updateIsDraggingFromFlyout(){let e;if(!this.targetBlock||(e=this.flyout)==null||!e.isBlockCreatable(this.targetBlock))return!1;if(!this.flyout.targetWorkspace)throw Error(`Cannot update dragging from the flyout because the ' + + 'flyout's target workspace is undefined`);return!this.flyout.isScrollable()||this.flyout.isDragTowardWorkspace(this.currentDragDeltaXY)?(this.startWorkspace_=this.flyout.targetWorkspace,this.startWorkspace_.updateScreenCalculationsIfScrolled(),i.getGroup$$module$build$src$core$events$utils()||i.setGroup$$module$build$src$core$events$utils(!0),this.startBlock=null,this.targetBlock=this.flyout.createBlock(this.targetBlock),i.setSelected$$module$build$src$core$common(this.targetBlock),!0):!1}updateIsDraggingWorkspace(){if(!this.startWorkspace_)throw Error("Cannot update dragging the workspace because the start workspace is undefined");(this.flyout?this.flyout.isScrollable():this.startWorkspace_&&this.startWorkspace_.isDraggable())&&(this.dragging=!0,this.workspaceDragger=new _v(this.startWorkspace_),this.workspaceDragger.startDrag())}updateIsDragging(e){if(!this.startWorkspace_)throw Error("Cannot update dragging because the start workspace is undefined");if(this.calledUpdateIsDragging)throw Error("updateIsDragging_ should only be called once per gesture.");this.calledUpdateIsDragging=!0,this.flyout&&this.updateIsDraggingFromFlyout();const t=F();t&&ri(t)&&t.isMovable()?(this.dragging=!0,this.dragger=this.createDragger(t,this.startWorkspace_),this.dragger.onDragStart(e),this.dragger.onDrag(e,this.currentDragDeltaXY)):this.updateIsDraggingWorkspace()}createDragger(e,t){return new(y($e.BLOCK_DRAGGER,this.creatorWorkspace.options,!0))(e,t)}doStart(e){if(!this.startWorkspace_)throw Error("Cannot start the touch gesture becauase the start workspace is undefined");this.isPinchZoomEnabled=this.startWorkspace_.options.zoomOptions&&this.startWorkspace_.options.zoomOptions.pinch,be(e)?this.cancel():(this.gestureHasStarted=!0,Yi(),this.startWorkspace_.updateScreenCalculationsIfScrolled(),this.startWorkspace_.isMutator&&this.startWorkspace_.resize(),this.currentDropdownOwner=Lu(),this.startWorkspace_.hideChaff(!!this.flyout),this.startWorkspace_.markFocused(),this.mostRecentEvent=e,td(),pe(e)?this.handleRightClick(e):(e.type.toLowerCase()==="pointerdown"&&e.pointerType!=="mouse"&&k(e,this),this.mouseDownXY=new ye(e.clientX,e.clientY),this.bindMouseEvents(e),this.isEnding_||this.handleTouchStart(e)))}bindMouseEvents(e){this.boundEvents.push(W(document,"pointerdown",null,this.handleStart.bind(this),!0)),this.boundEvents.push(W(document,"pointermove",null,this.handleMove.bind(this),!0)),this.boundEvents.push(W(document,"pointerup",null,this.handleUp.bind(this),!0)),e.preventDefault(),e.stopPropagation()}handleStart(e){this.isDragging()||(this.handleTouchStart(e),this.isMultiTouch()&&q())}handleMove(e){this.isDragging()&&O(e)||!this.isMultiTouch()?(this.updateFromEvent(e),this.workspaceDragger?this.workspaceDragger.drag(this.currentDragDeltaXY):this.dragger&&this.dragger.onDrag(this.mostRecentEvent,this.currentDragDeltaXY),e.preventDefault(),e.stopPropagation()):this.isMultiTouch()&&(this.handleTouchMove(e),q())}handleUp(e){if(this.isDragging()||this.handleTouchEnd(e),!this.isMultiTouch()||this.isDragging()){if(!O(e))return;if(this.updateFromEvent(e),q(),this.isEnding_){console.log("Trying to end a gesture recursively.");return}this.isEnding_=!0,this.dragger?this.dragger.onDragEnd(e,this.currentDragDeltaXY):this.workspaceDragger?this.workspaceDragger.endDrag(this.currentDragDeltaXY):this.isBubbleClick()||this.isCommentClick()||(this.isFieldClick()?this.doFieldClick():this.isIconClick()?this.doIconClick():this.isBlockClick()?this.doBlockClick():this.isWorkspaceClick()&&this.doWorkspaceClick(e))}e.preventDefault(),e.stopPropagation(),this.dispose()}handleTouchStart(e){var t=A(e);this.cachedPoints.set(t,this.getTouchPoint(e));var o=Array.from(this.cachedPoints.keys());o.length===2&&(t=this.cachedPoints.get(o[0]),o=this.cachedPoints.get(o[1]),this.startDistance=ye.distance(t,o),this.multiTouch=!0,e.preventDefault())}handleTouchMove(e){const t=A(e);this.cachedPoints.set(t,this.getTouchPoint(e)),this.isPinchZoomEnabled&&this.cachedPoints.size===2?this.handlePinch(e):(this.updateFromEvent(e),this.workspaceDragger?this.workspaceDragger.drag(this.currentDragDeltaXY):this.dragger&&this.dragger.onDrag(this.mostRecentEvent,this.currentDragDeltaXY),e.preventDefault(),e.stopPropagation())}handlePinch(e){var t=Array.from(this.cachedPoints.keys()),o=this.cachedPoints.get(t[0]);if(t=this.cachedPoints.get(t[1]),o=ye.distance(o,t)/this.startDistance,0this.previousScale){if(t=o-this.previousScale,t=0this.cachedPoints.size&&(this.cachedPoints.clear(),this.previousScale=0)}getTouchPoint(e){return this.startWorkspace_?new ye(e.pageX,e.pageY):null}isMultiTouch(){return this.multiTouch}cancel(){this.isEnding_||(q(),this.dragger?this.dragger.onDragEnd(this.mostRecentEvent,this.currentDragDeltaXY):this.workspaceDragger&&this.workspaceDragger.endDrag(this.currentDragDeltaXY),this.dispose())}handleRightClick(e){this.targetBlock?(this.bringBlockToFront(),this.targetBlock.workspace.hideChaff(!!this.flyout),this.targetBlock.showContextMenu(e)):this.startBubble?this.startBubble.showContextMenu(e):this.startComment?(this.startComment.workspace.hideChaff(),this.startComment.showContextMenu(e)):this.startWorkspace_&&!this.flyout&&(this.startWorkspace_.hideChaff(),this.startWorkspace_.showContextMenu(e)),e.preventDefault(),e.stopPropagation(),this.dispose()}handleWsStart(e,t){if(this.gestureHasStarted)throw Error("Tried to call gesture.handleWsStart, but the gesture had already been started.");this.setStartWorkspace(t),this.mostRecentEvent=e,this.startBlock||this.startBubble||this.startComment||i.setSelected$$module$build$src$core$common(null),this.doStart(e)}fireWorkspaceClick(e){z(new(ne(ee.CLICK))(null,e.id,"workspace"))}handleFlyoutStart(e,t){if(this.gestureHasStarted)throw Error("Tried to call gesture.handleFlyoutStart, but the gesture had already been started.");this.setStartFlyout(t),this.handleWsStart(e,t.getWorkspace())}handleBlockStart(e,t){if(this.gestureHasStarted)throw Error("Tried to call gesture.handleBlockStart, but the gesture had already been started.");this.setStartBlock(t),this.mostRecentEvent=e}handleBubbleStart(e,t){if(this.gestureHasStarted)throw Error("Tried to call gesture.handleBubbleStart, but the gesture had already been started.");this.setStartBubble(t),this.mostRecentEvent=e}handleCommentStart(e,t){if(this.gestureHasStarted)throw Error("Tried to call gesture.handleCommentStart, but the gesture had already been started.");this.setStartComment(t),this.mostRecentEvent=e}doFieldClick(){if(!this.startField)throw Error("Cannot do a field click because the start field is undefined");this.currentDropdownOwner!==this.startField&&this.startField.showEditor(this.mostRecentEvent),this.bringBlockToFront()}doIconClick(){if(!this.startIcon)throw Error("Cannot do an icon click because the start icon is undefined");this.bringBlockToFront(),this.startIcon.onClick()}doBlockClick(){if(this.flyout&&this.flyout.autoClose){if(!this.targetBlock)throw Error("Cannot do a block click because the target block is undefined");if(this.targetBlock.isEnabled()){i.getGroup$$module$build$src$core$events$utils()||i.setGroup$$module$build$src$core$events$utils(!0);var e=this.flyout.createBlock(this.targetBlock);e.snapToGrid(),e.bumpNeighbours()}}else{if(!this.startWorkspace_)throw Error("Cannot do a block click because the start workspace is undefined");e=new(ne(ee.CLICK))(this.startBlock,this.startWorkspace_.id,"block"),z(e)}this.bringBlockToFront(),i.setGroup$$module$build$src$core$events$utils(!1)}doWorkspaceClick(e){e=this.creatorWorkspace,F()&&F().unselect(),this.fireWorkspaceClick(this.startWorkspace_||e)}bringBlockToFront(){this.targetBlock&&!this.flyout&&this.targetBlock.bringToFront()}setStartField(e){if(this.gestureHasStarted)throw Error("Tried to call gesture.setStartField, but the gesture had already been started.");this.startField||(this.startField=e)}setStartIcon(e){if(this.gestureHasStarted)throw Error("Tried to call gesture.setStartIcon, but the gesture had already been started.");this.startIcon||(this.startIcon=e)}setStartBubble(e){this.startBubble||(this.startBubble=e)}setStartComment(e){this.startComment||(this.startComment=e)}setStartBlock(e){this.startBlock||this.startBubble||(this.startBlock=e,i.setSelected$$module$build$src$core$common(this.startBlock),e.isInFlyout&&e!==e.getRootBlock()?this.setTargetBlock(e.getRootBlock()):this.setTargetBlock(e))}setTargetBlock(e){e.isShadow()?this.setTargetBlock(e.getParent()):this.targetBlock=e}setStartWorkspace(e){this.startWorkspace_||(this.startWorkspace_=e)}setStartFlyout(e){this.flyout||(this.flyout=e)}isBubbleClick(){return!!this.startBubble&&!this.hasExceededDragRadius}isCommentClick(){return!!this.startComment&&!this.hasExceededDragRadius}isBlockClick(){return!!this.startBlock&&!this.hasExceededDragRadius&&!this.isFieldClick()&&!this.isIconClick()}isFieldClick(){return this.startField?this.startField.isClickable()&&!this.hasExceededDragRadius&&(!this.flyout||this.startField.isClickableInFlyout(this.flyout.autoClose)):!1}isIconClick(){if(!this.startIcon)return!1;const e=!this.flyout||!this.startIcon.isClickableInFlyout||this.startIcon.isClickableInFlyout(this.flyout.autoClose);return!this.hasExceededDragRadius&&e}isWorkspaceClick(){return!this.startBlock&&!this.startBubble&&!this.startField&&!this.hasExceededDragRadius}getCurrentDragger(){let e,t;return(t=(e=this.workspaceDragger)!=null?e:this.dragger)!=null?t:null}isDragging(){return this.dragging}hasStarted(){return this.gestureHasStarted}static inProgress(){const e=B();for(let t=0,o;o=e[t];t++)if(o.currentGesture_)return!0;return!1}},op=class{constructor(e,t){this.pattern=e,this.scale=1;let o;this.spacing=(o=t.spacing)!=null?o:0;let n;this.length=(n=t.length)!=null?n:1,this.line2=(this.line1=e.firstChild)&&this.line1.nextSibling;let u;this.snapToGrid=(u=t.snap)!=null?u:!1}setSpacing(e){this.spacing=e,this.update(this.scale)}getSpacing(){return this.spacing}setLength(e){this.length=e,this.update(this.scale)}getLength(){return this.length}setSnapToGrid(e){this.snapToGrid=e}shouldSnap(){return this.snapToGrid}getPatternId(){return this.pattern.id}update(e){this.scale=e;var t=this.spacing*e;this.pattern.setAttribute("width",`${t}`),this.pattern.setAttribute("height",`${t}`),t=Math.floor(this.spacing/2)+.5;let o=t-this.length/2,n=t+this.length/2;t*=e,o*=e,n*=e,this.setLineAttributes(this.line1,e,o,n,t,t),this.setLineAttributes(this.line2,e,t,t,o,n)}setLineAttributes(e,t,o,n,u,g){e&&(e.setAttribute("stroke-width",`${t}`),e.setAttribute("x1",`${o}`),e.setAttribute("y1",`${u}`),e.setAttribute("x2",`${n}`),e.setAttribute("y2",`${g}`))}moveTo(e,t){this.pattern.setAttribute("x",`${e}`),this.pattern.setAttribute("y",`${t}`)}alignXY(e){var t=this.getSpacing();const o=t/2,n=Math.round(Math.round((e.x-o)/t)*t+o);return t=Math.round(Math.round((e.y-o)/t)*t+o),n===e.x&&t===e.y?e:new ye(n,t)}static createDom(e,t,o){e=ie(J.PATTERN,{id:"blocklyGridPattern"+e,patternUnits:"userSpaceOnUse"},o);let n,u;if(0<((n=t.length)!=null?n:1)&&0<((u=t.spacing)!=null?u:0)){ie(J.LINE,{stroke:t.colour},e);let g;(g=t.length)!=null&&g&&ie(J.LINE,{stroke:t.colour},e)}else ie(J.LINE,{},e);return e}},qC=class{constructor(e){this.workspace=e,this.layers=new Map,(e=e.getInjectionDiv())&&(this.dragLayer=this.createDragLayer(e),this.animationLayer=this.createAnimationLayer(e)),e=this.createLayer(jo),Oe(e,"blocklyBlockCanvas"),e=this.createLayer(El),Oe(e,"blocklyBubbleCanvas")}createDragLayer(e){const t=ie(J.SVG,{class:"blocklyBlockDragSurface",xmlns:pr,"xmlns:html":Gs,"xmlns:xlink":is,version:"1.1"});return e.append(t),ie(J.G,{},t)}createAnimationLayer(e){const t=ie(J.SVG,{class:"blocklyAnimationLayer",xmlns:pr,"xmlns:html":Gs,"xmlns:xlink":is,version:"1.1"});return e.append(t),ie(J.G,{},t)}appendToAnimationLayer(e){let t;const o=(t=this.dragLayer)==null?void 0:t.getAttribute("transform");if(o){let u;(u=this.animationLayer)==null||u.setAttribute("transform",o)}let n;(n=this.animationLayer)==null||n.appendChild(e.getSvgRoot())}translateLayers(e,t){e=`translate(${e.x}, ${e.y}) scale(${t})`;let o;(o=this.dragLayer)==null||o.setAttribute("transform",e);for(const[,n]of this.layers)n.setAttribute("transform",e)}moveToDragLayer(e){let t;(t=this.dragLayer)==null||t.appendChild(e.getSvgRoot())}moveOffDragLayer(e,t){this.append(e,t)}append(e,t){this.layers.has(t)||this.createLayer(t);let o;(o=this.layers.get(t))==null||o.appendChild(e.getSvgRoot())}createLayer(e){const t=this.workspace.getSvgGroup(),o=ie(J.G,{});let n=!1;const u=[...this.layers].sort((g,I)=>g[0]-I[0]);for(const[g,I]of u)if(et[1]===e)?e:(this.sourceBlock_&&console.warn("Cannot set the dropdown's value to an unavailable option. Block type: "+this.sourceBlock_.type+", Field name: "+this.name+", Value: "+e),null)}doValueUpdate_(e){super.doValueUpdate_(e),e=this.getOptions(!0);for(let t=0,o;o=e[t];t++)o[1]===this.value_&&(this.selectedOption=o)}applyColour(){const e=this.sourceBlock_;this.borderRect_&&(this.borderRect_.setAttribute("stroke",e.getColourTertiary()),this.menu_?this.borderRect_.setAttribute("fill",e.getColourTertiary()):this.borderRect_.setAttribute("fill","transparent")),e&&this.arrow&&(e.isShadow()?this.arrow.style.fill=e.getColourSecondary():this.arrow.style.fill=e.getColour())}render_(){this.getTextContent().nodeValue="",this.imageElement.style.display="none";const e=this.selectedOption&&this.selectedOption[0];e&&typeof e=="object"?this.renderSelectedImage(e):this.renderSelectedText(),this.positionBorderRect_()}renderSelectedImage(e){const t=this.getSourceBlock();if(!t)throw new _t;this.imageElement.style.display="",this.imageElement.setAttributeNS(is,"xlink:href",e.src),this.imageElement.setAttribute("height",String(e.height)),this.imageElement.setAttribute("width",String(e.width));const o=Number(e.height);e=Number(e.width);var n=!!this.borderRect_;const u=Math.max(n?this.getConstants().FIELD_DROPDOWN_BORDER_RECT_HEIGHT:0,o+es.IMAGE_Y_PADDING);n=n?this.getConstants().FIELD_BORDER_RECT_X_PADDING:0;let g;g=this.svgArrow?this.positionSVGArrow(e+n,u/2-this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE/2):Io(this.arrow,this.getConstants().FIELD_TEXT_FONTSIZE,this.getConstants().FIELD_TEXT_FONTWEIGHT,this.getConstants().FIELD_TEXT_FONTFAMILY),this.size_.width=e+g+2*n,this.size_.height=u;let I=0;t.RTL?this.imageElement.setAttribute("x",`${n+g}`):(I=e+g,this.getTextElement().setAttribute("text-anchor","end"),this.imageElement.setAttribute("x",`${n}`)),this.imageElement.setAttribute("y",String(u/2-o/2)),this.positionTextElement_(I+n,e+g)}renderSelectedText(){this.getTextContent().nodeValue=this.getDisplayText_();var e=this.getTextElement();Oe(e,"blocklyDropdownText"),e.setAttribute("text-anchor","start");var t=!!this.borderRect_;e=Math.max(t?this.getConstants().FIELD_DROPDOWN_BORDER_RECT_HEIGHT:0,this.getConstants().FIELD_TEXT_HEIGHT);const o=Io(this.getTextElement(),this.getConstants().FIELD_TEXT_FONTSIZE,this.getConstants().FIELD_TEXT_FONTWEIGHT,this.getConstants().FIELD_TEXT_FONTFAMILY);t=t?this.getConstants().FIELD_BORDER_RECT_X_PADDING:0;let n=0;this.svgArrow&&(n=this.positionSVGArrow(o+t,e/2-this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE/2)),this.size_.width=o+n+2*t,this.size_.height=e,this.positionTextElement_(t,o)}positionSVGArrow(e,t){if(!this.svgArrow)return 0;const o=this.getSourceBlock();if(!o)throw new _t;const n=this.borderRect_?this.getConstants().FIELD_BORDER_RECT_X_PADDING:0,u=this.getConstants().FIELD_DROPDOWN_SVG_ARROW_PADDING,g=this.getConstants().FIELD_DROPDOWN_SVG_ARROW_SIZE;return this.svgArrow.setAttribute("transform","translate("+(o.RTL?n:e+u)+","+t+")"),g+u}getText_(){if(!this.selectedOption)return null;const e=this.selectedOption[0];return typeof e=="object"?e.alt:e}static fromJson(e){if(!e.options)throw Error("options are required for the dropdown field. The options property must be assigned an array of [humanReadableValue, languageNeutralValue] tuples.");return new this(e.options,void 0,e)}trimOptions(e){let t=!1;const o=e.map(([I,P])=>typeof I=="string"?[bt(I),P]:(t=!0,[I.alt!==null?Object.assign({},I,{alt:bt(I.alt)}):Object.assign({},I),P]));if(t||2>e.length)return{options:o};var n=o.map(([I])=>I),u=Qn(n);e=Ku(n,u);const g=Ju(n,u);return!e&&!g||u<=e+g?{options:o}:(u=e?n[0].substring(0,e-1):void 0,n=g?n[0].substr(1-g):void 0,{options:this.applyTrim(o,e,g),prefix:u,suffix:n})}applyTrim(e,t,o){return e.map(([n,u])=>[n.substring(t,n.length-o),u])}validateOptions(e){if(!Array.isArray(e))throw TypeError("FieldDropdown options must be an array.");if(!e.length)throw TypeError("FieldDropdown options must not be an empty array.");let t=!1;for(let o=0;oe.width)return t;if(e=this.getWorkspaceViewRect(e),this.workspace.RTL){var o=this.anchor.x-t;o-this.size.widthe.right&&(t=-(e.right-this.anchor.x))}else{o=t+this.anchor.x;const n=o+this.size.width;oe.right&&(t=e.right-this.anchor.x-this.size.width)}return t}getOptimalRelativeTop(e){let t=-this.size.height/4;if(this.size.height>e.height)return t;const o=this.anchor.y+t,n=o+this.size.height;return e=this.getWorkspaceViewRect(e),oe.bottom&&(t=e.bottom-this.anchor.y-this.size.height),t}getWorkspaceViewRect(e){const t=e.top;let o=e.top+e.height,n=e.left;return e=e.left+e.width,o-=this.getScrollbarThickness(),this.workspace.RTL?n-=this.getScrollbarThickness():e-=this.getScrollbarThickness(),new rt(t,o,n,e)}getScrollbarThickness(){return yt.scrollbarThickness/this.workspace.scale}renderTail(){const e=[];var t=this.size.width/2,o=this.size.height/2,n=-this.relativeLeft,u=-this.relativeTop;if(t===n&&o===u)e.push("M "+t+","+o);else{u-=o,n-=t,this.workspace.RTL&&(n*=-1);var g=Math.sqrt(u*u+n*n),I=Math.acos(n/g);0>u&&(I=2*Math.PI-I);var L=I+Math.PI/2;L>2*Math.PI&&(L-=2*Math.PI);var le=Math.sin(L);const dt=Math.cos(L);let ut=(this.size.width+this.size.height)/rs.TAIL_THICKNESS;ut=Math.min(ut,this.size.width,this.size.height)/4,L=1-rs.ANCHOR_RADIUS/g,n=t+L*n,u=o+L*u,L=t+ut*dt;const ts=o+ut*le;t-=ut*dt,o-=ut*le,le=Aa(this.workspace.RTL?-rs.TAIL_ANGLE:rs.TAIL_ANGLE),le=I+le,le>2*Math.PI&&(le-=2*Math.PI),I=Math.sin(le)*g/rs.TAIL_BEND,g=Math.cos(le)*g/rs.TAIL_BEND,e.push("M"+L+","+ts),e.push("C"+(L+g)+","+(ts+I)+" "+n+","+u+" "+n+","+u),e.push("C"+n+","+u+" "+(t+g)+","+(o+I)+" "+t+","+o)}e.push("z");let Ee;(Ee=this.tail)==null||Ee.setAttribute("d",e.join(" "))}bringToFront(){let e;const t=(e=this.svgRoot)==null?void 0:e.parentNode;return this.svgRoot&&(t==null?void 0:t.lastChild)!==this.svgRoot?(t==null||t.appendChild(this.svgRoot),!0):!1}getRelativeToSurfaceXY(){return new ye(this.workspace.RTL?-this.relativeLeft+this.anchor.x-this.size.width:this.anchor.x+this.relativeLeft,this.anchor.y+this.relativeTop)}getSvgRoot(){return this.svgRoot}moveDuringDrag(e){this.moveTo(e.x,e.y),this.relativeLeft=this.workspace.RTL?this.anchor.x-e.x-this.size.width:e.x-this.anchor.x,this.relativeTop=e.y-this.anchor.y,this.renderTail()}setDragging(e){}setDeleteStyle(e){}isDeletable(){return!1}showContextMenu(e){}isMovable(){return!0}startDrag(){this.dragStrategy.startDrag()}drag(e){this.dragStrategy.drag(e)}endDrag(){this.dragStrategy.endDrag()}revertDrag(){this.dragStrategy.revertDrag()}select(){}unselect(){}};rs=nt,nt.BORDER_WIDTH=6,nt.DOUBLE_BORDER=2*rs.BORDER_WIDTH,nt.MIN_SIZE=rs.DOUBLE_BORDER,nt.TAIL_THICKNESS=1,nt.TAIL_ANGLE=20,nt.TAIL_BEND=4,nt.ANCHOR_RADIUS=8;var vo=class extends nt{constructor(e,t,o,n){super(t,o,n),this.workspace=t,this.anchor=o,this.ownerRect=n,this.autoLayout=!0,t=new gs(e),this.validateWorkspaceOptions(t),this.svgDialog=ie(J.SVG,{x:nt.BORDER_WIDTH,y:nt.BORDER_WIDTH},this.contentContainer),e.parentWorkspace=this.workspace,this.miniWorkspace=this.newWorkspaceSvg(new gs(e)),this.miniWorkspace.internalIsMutator=!0,e=this.miniWorkspace.createDom("blocklyMutatorBackground"),this.svgDialog.appendChild(e),t.languageTree&&(e.insertBefore(this.miniWorkspace.addFlyout(J.G),this.miniWorkspace.getCanvas()),e=this.miniWorkspace.getFlyout(),e==null||e.init(this.miniWorkspace),e==null||e.show(t.languageTree)),this.miniWorkspace.addChangeListener(this.onWorkspaceChange.bind(this));let u,g;(u=this.miniWorkspace.getFlyout())==null||(g=u.getWorkspace())==null||g.addChangeListener(this.onWorkspaceChange.bind(this)),this.updateBubbleSize()}dispose(){this.miniWorkspace.dispose(),super.dispose()}getWorkspace(){return this.miniWorkspace}addWorkspaceChangeListener(e){this.miniWorkspace.addChangeListener(e)}validateWorkspaceOptions(e){if(e.hasCategories)throw Error("The miniworkspace bubble does not support toolboxes with categories");if(e.hasTrashcan)throw Error("The miniworkspace bubble does not support trashcans");if(e.zoomOptions.controls||e.zoomOptions.wheel||e.zoomOptions.pinch)throw Error("The miniworkspace bubble does not support zooming");if(e.moveOptions.scrollbars||e.moveOptions.wheel||e.moveOptions.drag)throw Error("The miniworkspace bubble does not scrolling/moving the workspace");if(e.horizontalLayout)throw Error("The miniworkspace bubble does not support horizontal layouts")}onWorkspaceChange(){this.bumpBlocksIntoBounds(),this.updateBubbleSize()}bumpBlocksIntoBounds(){if(!this.miniWorkspace.isDragging())for(const e of this.miniWorkspace.getTopBlocks(!1)){const t=e.getRelativeToSurfaceXY();if(20>t.y&&e.moveBy(0,20-t.y),e.RTL){let o=-20;const n=this.miniWorkspace.getFlyout();n&&(o-=n.getWidth()),t.x>o&&e.moveBy(o-t.x,0)}else 20>t.x&&e.moveBy(20-t.x,0)}}updateBubbleSize(){if(!this.miniWorkspace.isDragging()){var e=this.getSize(),t=this.calculateWorkspaceSize();Math.abs(e.width-t.width)({kind:"block",type:o}))}),t}getAnchorLocation(){const e=Ol/2;return ye.sum(this.workspaceLocation,new ye(e,e))}getBubbleOwnerRect(){const e=this.sourceBlock.getSvgRoot().getBBox();return new rt(e.y,e.y+e.height,e.x,e.x+e.width)}createRootBlock(){if(!this.sourceBlock.decompose)throw Error("Blocks with mutator icons must include a decompose method");this.rootBlock=this.sourceBlock.decompose(this.miniWorkspaceBubble.getWorkspace());for(var e of this.rootBlock.getDescendants(!1))e.queueRender();this.rootBlock.setMovable(!1),this.rootBlock.setDeletable(!1);let t,o,n,u;e=(u=(t=this.miniWorkspaceBubble)==null||(o=t.getWorkspace())==null||(n=o.getFlyout())==null?void 0:n.getWidth())!=null?u:0,this.rootBlock.moveBy(this.rootBlock.RTL?-(e+Nl):Nl,Nl)}addSaveConnectionsListener(){this.sourceBlock.saveConnections&&this.rootBlock&&(this.saveConnectionsListener=()=>{this.sourceBlock.saveConnections&&this.rootBlock&&this.sourceBlock.saveConnections(this.rootBlock)},this.saveConnectionsListener(),this.sourceBlock.workspace.addChangeListener(this.saveConnectionsListener))}createMiniWorkspaceChangeListener(){return e=>{i.MutatorIcon$$module$build$src$core$icons$mutator_icon.isIgnorableMutatorEvent(e)||this.updateWorkspacePid||(this.updateWorkspacePid=setTimeout(()=>{this.updateWorkspacePid=null,this.recomposeSourceBlock()},0))}}static isIgnorableMutatorEvent(e){return e.isUiEvent||$(e)||T(e)&&e.element==="disabled"}recomposeSourceBlock(){if(this.rootBlock){if(!this.sourceBlock.compose)throw Error("Blocks with mutator icons must include a compose method");var e=i.getGroup$$module$build$src$core$events$utils();e||i.setGroup$$module$build$src$core$events$utils(!0);var t=mi.getExtraBlockState_(this.sourceBlock);this.sourceBlock.compose(this.rootBlock);var o=mi.getExtraBlockState_(this.sourceBlock);t!==o&&z(new(ne(ee.BLOCK_CHANGE))(this.sourceBlock,"mutation",null,t,o)),i.setGroup$$module$build$src$core$events$utils(e)}}getWorkspace(){let e;return(e=this.miniWorkspaceBubble)==null?void 0:e.getWorkspace()}},i.MutatorIcon$$module$build$src$core$icons$mutator_icon.TYPE=Ct.MUTATOR,i.MutatorIcon$$module$build$src$core$icons$mutator_icon.WEIGHT=1,i.MutatorIcon$$module$build$src$core$icons$mutator_icon;var dn=Object.create(null),QC={allExtensions:dn};i.register$$module$build$src$core$extensions("parent_tooltip_when_inline",R$);var As={TEST_ONLY:QC};As.apply=Va,As.buildTooltipForDropdown=i.buildTooltipForDropdown$$module$build$src$core$extensions,As.buildTooltipWithFieldText=i.buildTooltipWithFieldText$$module$build$src$core$extensions,As.isRegistered=kd,As.register=i.register$$module$build$src$core$extensions,As.registerMixin=i.registerMixin$$module$build$src$core$extensions,As.registerMutator=i.registerMutator$$module$build$src$core$extensions,As.runAfterPageLoad=D$,As.unregister=T$;var Ye;(function(e){e[e.WIN_KEY_FF_LINUX=0]="WIN_KEY_FF_LINUX",e[e.MAC_ENTER=3]="MAC_ENTER",e[e.BACKSPACE=8]="BACKSPACE",e[e.TAB=9]="TAB",e[e.NUM_CENTER=12]="NUM_CENTER",e[e.ENTER=13]="ENTER",e[e.SHIFT=16]="SHIFT",e[e.CTRL=17]="CTRL",e[e.ALT=18]="ALT",e[e.PAUSE=19]="PAUSE",e[e.CAPS_LOCK=20]="CAPS_LOCK",e[e.ESC=27]="ESC",e[e.SPACE=32]="SPACE",e[e.PAGE_UP=33]="PAGE_UP",e[e.PAGE_DOWN=34]="PAGE_DOWN",e[e.END=35]="END",e[e.HOME=36]="HOME",e[e.LEFT=37]="LEFT",e[e.UP=38]="UP",e[e.RIGHT=39]="RIGHT",e[e.DOWN=40]="DOWN",e[e.PLUS_SIGN=43]="PLUS_SIGN",e[e.PRINT_SCREEN=44]="PRINT_SCREEN",e[e.INSERT=45]="INSERT",e[e.DELETE=46]="DELETE",e[e.ZERO=48]="ZERO",e[e.ONE=49]="ONE",e[e.TWO=50]="TWO",e[e.THREE=51]="THREE",e[e.FOUR=52]="FOUR",e[e.FIVE=53]="FIVE",e[e.SIX=54]="SIX",e[e.SEVEN=55]="SEVEN",e[e.EIGHT=56]="EIGHT",e[e.NINE=57]="NINE",e[e.FF_SEMICOLON=59]="FF_SEMICOLON",e[e.FF_EQUALS=61]="FF_EQUALS",e[e.FF_DASH=173]="FF_DASH",e[e.FF_HASH=163]="FF_HASH",e[e.QUESTION_MARK=63]="QUESTION_MARK",e[e.AT_SIGN=64]="AT_SIGN",e[e.A=65]="A",e[e.B=66]="B",e[e.C=67]="C",e[e.D=68]="D",e[e.E=69]="E",e[e.F=70]="F",e[e.G=71]="G",e[e.H=72]="H",e[e.I=73]="I",e[e.J=74]="J",e[e.K=75]="K",e[e.L=76]="L",e[e.M=77]="M",e[e.N=78]="N",e[e.O=79]="O",e[e.P=80]="P",e[e.Q=81]="Q",e[e.R=82]="R",e[e.S=83]="S",e[e.T=84]="T",e[e.U=85]="U",e[e.V=86]="V",e[e.W=87]="W",e[e.X=88]="X",e[e.Y=89]="Y",e[e.Z=90]="Z",e[e.META=91]="META",e[e.WIN_KEY_RIGHT=92]="WIN_KEY_RIGHT",e[e.CONTEXT_MENU=93]="CONTEXT_MENU",e[e.NUM_ZERO=96]="NUM_ZERO",e[e.NUM_ONE=97]="NUM_ONE",e[e.NUM_TWO=98]="NUM_TWO",e[e.NUM_THREE=99]="NUM_THREE",e[e.NUM_FOUR=100]="NUM_FOUR",e[e.NUM_FIVE=101]="NUM_FIVE",e[e.NUM_SIX=102]="NUM_SIX",e[e.NUM_SEVEN=103]="NUM_SEVEN",e[e.NUM_EIGHT=104]="NUM_EIGHT",e[e.NUM_NINE=105]="NUM_NINE",e[e.NUM_MULTIPLY=106]="NUM_MULTIPLY",e[e.NUM_PLUS=107]="NUM_PLUS",e[e.NUM_MINUS=109]="NUM_MINUS",e[e.NUM_PERIOD=110]="NUM_PERIOD",e[e.NUM_DIVISION=111]="NUM_DIVISION",e[e.F1=112]="F1",e[e.F2=113]="F2",e[e.F3=114]="F3",e[e.F4=115]="F4",e[e.F5=116]="F5",e[e.F6=117]="F6",e[e.F7=118]="F7",e[e.F8=119]="F8",e[e.F9=120]="F9",e[e.F10=121]="F10",e[e.F11=122]="F11",e[e.F12=123]="F12",e[e.NUMLOCK=144]="NUMLOCK",e[e.SCROLL_LOCK=145]="SCROLL_LOCK",e[e.FIRST_MEDIA_KEY=166]="FIRST_MEDIA_KEY",e[e.LAST_MEDIA_KEY=183]="LAST_MEDIA_KEY",e[e.SEMICOLON=186]="SEMICOLON",e[e.DASH=189]="DASH",e[e.EQUALS=187]="EQUALS",e[e.COMMA=188]="COMMA",e[e.PERIOD=190]="PERIOD",e[e.SLASH=191]="SLASH",e[e.APOSTROPHE=192]="APOSTROPHE",e[e.TILDE=192]="TILDE",e[e.SINGLE_QUOTE=222]="SINGLE_QUOTE",e[e.OPEN_SQUARE_BRACKET=219]="OPEN_SQUARE_BRACKET",e[e.BACKSLASH=220]="BACKSLASH",e[e.CLOSE_SQUARE_BRACKET=221]="CLOSE_SQUARE_BRACKET",e[e.WIN_KEY=224]="WIN_KEY",e[e.MAC_FF_META=224]="MAC_FF_META",e[e.MAC_WK_CMD_LEFT=91]="MAC_WK_CMD_LEFT",e[e.MAC_WK_CMD_RIGHT=93]="MAC_WK_CMD_RIGHT",e[e.WIN_IME=229]="WIN_IME",e[e.VK_NONAME=252]="VK_NONAME",e[e.PHANTOM=255]="PHANTOM"})(Ye||(Ye={}));var yo={};yo.arc=vt,yo.curve=Zt,yo.line=Yi,yo.lineOnAxis=De,yo.lineTo=Hs,yo.moveBy=pt,yo.moveTo=St,yo.point=Me;var mt={};mt.Coordinate=ye,mt.KeyCodes=Ye,mt.Rect=rt,mt.Size=Xe,mt.Svg=J,mt.aria=fr,mt.array=Lb,mt.browserEvents=go,mt.colour=ps,mt.deprecation=mb,mt.dom=Dt,mt.extensions=As,mt.idGenerator=mh,mt.math=$l,mt.object=yv,mt.parsing=Tr,mt.string=nn,mt.style=Mo,mt.svgMath=ui,mt.svgPaths=yo,mt.toolbox=Lo,mt.userAgent=jC,mt.xml=Xi;var kv=class extends nt{constructor(e,t,o){super(e,t,o),this.workspace=e,this.anchor=t,this.ownerRect=o,this.resizePointerMoveListener=this.resizePointerUpListener=null,this.textChangeListeners=[],this.sizeChangeListeners=[],this.text="",this.DEFAULT_SIZE=new Xe(160+nt.DOUBLE_BORDER,80+nt.DOUBLE_BORDER),this.MIN_SIZE=new Xe(45+nt.DOUBLE_BORDER,20+nt.DOUBLE_BORDER),this.editable=!0,Re(this.svgRoot,"blocklyTextInputBubble"),{inputRoot:this.inputRoot,textArea:this.textArea}=this.createEditor(this.contentContainer),this.resizeGroup=this.createResizeHandle(this.svgRoot,e),this.setSize(this.DEFAULT_SIZE,!0)}getText(){return this.text}setText(e){this.text=e,this.textArea.value=e,this.onTextChange()}setEditable(e){(this.editable=e)?this.textArea.removeAttribute("readonly"):this.textArea.setAttribute("readonly","")}isEditable(){return this.editable}addTextChangeListener(e){this.textChangeListeners.push(e)}addSizeChangeListener(e){this.sizeChangeListeners.push(e)}createEditor(e){e=ie(J.FOREIGNOBJECT,{x:nt.BORDER_WIDTH,y:nt.BORDER_WIDTH},e);const t=document.createElementNS(Gs,"body");t.setAttribute("xmlns",Gs),t.className="blocklyMinimalBody";const o=document.createElementNS(Gs,"textarea");return o.className="blocklyTextarea blocklyText",o.setAttribute("dir",this.workspace.RTL?"RTL":"LTR"),t.appendChild(o),e.appendChild(t),this.bindTextAreaEvents(o),setTimeout(()=>{o.focus()},0),{inputRoot:e,textArea:o}}bindTextAreaEvents(e){H(e,"wheel",this,t=>{t.stopPropagation()}),H(e,"focus",this,this.onStartEdit,!0),H(e,"change",this,this.onTextChange)}createResizeHandle(e,t){return e=ie(J.IMAGE,{class:"blocklyResizeHandle",href:`${t.options.pathToMedia}resize-handle.svg`},e),H(e,"pointerdown",this,this.onResizePointerDown),e}setSize(e,t=!1){e.width=Math.max(e.width,this.MIN_SIZE.width),e.height=Math.max(e.height,this.MIN_SIZE.height);const o=e.width-nt.DOUBLE_BORDER,n=e.height-nt.DOUBLE_BORDER;this.inputRoot.setAttribute("width",`${o}`),this.inputRoot.setAttribute("height",`${n}`),this.resizeGroup.setAttribute("y",`${n}`),this.workspace.RTL?this.resizeGroup.setAttribute("x",`${-nt.DOUBLE_BORDER}`):this.resizeGroup.setAttribute("x",`${o}`),super.setSize(e,t),this.onSizeChange()}getSize(){return super.getSize()}onResizePointerDown(e){this.bringToFront(),pe(e)||(za(this.workspace,e,new ye(this.workspace.RTL?-this.getSize().width:this.getSize().width,this.getSize().height)),this.resizePointerUpListener=H(document,"pointerup",this,this.onResizePointerUp),this.resizePointerMoveListener=H(document,"pointermove",this,this.onResizePointerMove),this.workspace.hideChaff()),e.stopPropagation()}onResizePointerUp(e){Y(),this.resizePointerUpListener&&(V(this.resizePointerUpListener),this.resizePointerUpListener=null),this.resizePointerMoveListener&&(V(this.resizePointerMoveListener),this.resizePointerMoveListener=null)}onResizePointerMove(e){e=Ua(this.workspace,e),this.setSize(new Xe(this.workspace.RTL?-e.x:e.x,e.y),!1),this.onSizeChange()}onStartEdit(){this.bringToFront()&&this.textArea.focus()}onTextChange(){this.text=this.textArea.value;for(const e of this.textChangeListeners)e()}onSizeChange(){for(const e of this.sizeChangeListeners)e()}};Be(` + Found: ${n}`))}if(t)throw TypeError("Found invalid FieldDropdown options.")}};es.CHECKMARK_OVERHANG=25,es.MAX_MENU_HEIGHT_VH=.45,es.ARROW_CHAR="▾",es.IMAGE_Y_OFFSET=5,es.IMAGE_Y_PADDING=2*es.IMAGE_Y_OFFSET,Us("field_dropdown",es);var Cv=class{constructor(e,t){this.bubble=e,this.workspace=t,this.startLoc=null,this.inGroup=!1}isMovable(){return!0}startDrag(){(this.inGroup=!!i.getGroup$$module$build$src$core$events$utils())||i.setGroup$$module$build$src$core$events$utils(!0),this.startLoc=this.bubble.getRelativeToSurfaceXY(),this.workspace.setResizesEnabled(!1);let e;(e=this.workspace.getLayerManager())==null||e.moveToDragLayer(this.bubble),this.bubble.setDragging&&this.bubble.setDragging(!0)}drag(e){this.bubble.moveDuringDrag(e)}endDrag(){this.workspace.setResizesEnabled(!0),this.inGroup||i.setGroup$$module$build$src$core$events$utils(!1);let e;(e=this.workspace.getLayerManager())==null||e.moveOffDragLayer(this.bubble,El),this.bubble.setDragging(!1)}revertDrag(){this.startLoc&&this.bubble.moveDuringDrag(this.startLoc)}},rs,nt=class{constructor(e,t,o){this.workspace=e,this.anchor=t,this.ownerRect=o,this.size=new Ze(0,0),this.colour="#ffffff",this.disposed=!1,this.relativeLeft=this.relativeTop=0,this.dragStrategy=new Cv(this,this.workspace),this.id=v(),this.svgRoot=ie(J.G,{class:"blocklyBubble"},e.getBubbleCanvas()),e=ie(J.G,{filter:`url(#${this.workspace.getRenderer().getConstants().embossFilterId})`},this.svgRoot),this.tail=ie(J.PATH,{class:"blocklyBubbleTail"},e),this.background=ie(J.RECT,{class:"blocklyDraggable",x:0,y:0,rx:rs.BORDER_WIDTH,ry:rs.BORDER_WIDTH},e),this.contentContainer=ie(J.G,{},this.svgRoot),W(this.background,"pointerdown",this,this.onMouseDown)}dispose(){Qe(this.svgRoot),this.disposed=!0}setAnchorLocation(e,t=!1){this.anchor=e,t?this.positionByRect(this.ownerRect):this.positionRelativeToAnchor(),this.renderTail()}setPositionRelativeToAnchor(e,t){this.relativeLeft=e,this.relativeTop=t,this.positionRelativeToAnchor(),this.renderTail()}getSize(){return this.size}setSize(e,t=!1){e.width=Math.max(e.width,rs.MIN_SIZE),e.height=Math.max(e.height,rs.MIN_SIZE),this.size=e,this.background.setAttribute("width",`${e.width}`),this.background.setAttribute("height",`${e.height}`),t?this.positionByRect(this.ownerRect):this.positionRelativeToAnchor(),this.renderTail()}getColour(){return this.colour}setColour(e){this.colour=e,this.tail.setAttribute("fill",e),this.background.setAttribute("fill",e)}onMouseDown(e){let t;(t=this.workspace.getGesture(e))==null||t.handleBubbleStart(e,this),this.bringToFront(),i.setSelected$$module$build$src$core$common(this)}positionRelativeToAnchor(){let e=this.anchor.x;e=this.workspace.RTL?e-(this.relativeLeft+this.size.width):e+this.relativeLeft,this.moveTo(e,this.relativeTop+this.anchor.y)}moveTo(e,t){this.svgRoot.setAttribute("transform",`translate(${e}, ${t})`)}positionByRect(e=new rt(0,0,0,0)){var t=this.workspace.getMetricsManager().getViewMetrics(!0),o=this.getOptimalRelativeLeft(t),n=this.getOptimalRelativeTop(t);const u={x:o,y:-this.size.height-this.workspace.getRenderer().getConstants().MIN_BLOCK_HEIGHT},g={x:-this.size.width-30,y:n};n={x:e.getWidth(),y:n};var I={x:o,y:e.getHeight()};o=e.getWidth()e.width)return t;if(e=this.getWorkspaceViewRect(e),this.workspace.RTL){var o=this.anchor.x-t;o-this.size.widthe.right&&(t=-(e.right-this.anchor.x))}else{o=t+this.anchor.x;const n=o+this.size.width;oe.right&&(t=e.right-this.anchor.x-this.size.width)}return t}getOptimalRelativeTop(e){let t=-this.size.height/4;if(this.size.height>e.height)return t;const o=this.anchor.y+t,n=o+this.size.height;return e=this.getWorkspaceViewRect(e),oe.bottom&&(t=e.bottom-this.anchor.y-this.size.height),t}getWorkspaceViewRect(e){const t=e.top;let o=e.top+e.height,n=e.left;return e=e.left+e.width,o-=this.getScrollbarThickness(),this.workspace.RTL?n-=this.getScrollbarThickness():e-=this.getScrollbarThickness(),new rt(t,o,n,e)}getScrollbarThickness(){return yt.scrollbarThickness/this.workspace.scale}renderTail(){const e=[];var t=this.size.width/2,o=this.size.height/2,n=-this.relativeLeft,u=-this.relativeTop;if(t===n&&o===u)e.push("M "+t+","+o);else{u-=o,n-=t,this.workspace.RTL&&(n*=-1);var g=Math.sqrt(u*u+n*n),I=Math.acos(n/g);0>u&&(I=2*Math.PI-I);var P=I+Math.PI/2;P>2*Math.PI&&(P-=2*Math.PI);var le=Math.sin(P);const dt=Math.cos(P);let ut=(this.size.width+this.size.height)/rs.TAIL_THICKNESS;ut=Math.min(ut,this.size.width,this.size.height)/4,P=1-rs.ANCHOR_RADIUS/g,n=t+P*n,u=o+P*u,P=t+ut*dt;const ts=o+ut*le;t-=ut*dt,o-=ut*le,le=Oa(this.workspace.RTL?-rs.TAIL_ANGLE:rs.TAIL_ANGLE),le=I+le,le>2*Math.PI&&(le-=2*Math.PI),I=Math.sin(le)*g/rs.TAIL_BEND,g=Math.cos(le)*g/rs.TAIL_BEND,e.push("M"+P+","+ts),e.push("C"+(P+g)+","+(ts+I)+" "+n+","+u+" "+n+","+u),e.push("C"+n+","+u+" "+(t+g)+","+(o+I)+" "+t+","+o)}e.push("z");let Ee;(Ee=this.tail)==null||Ee.setAttribute("d",e.join(" "))}bringToFront(){let e;const t=(e=this.svgRoot)==null?void 0:e.parentNode;return this.svgRoot&&(t==null?void 0:t.lastChild)!==this.svgRoot?(t==null||t.appendChild(this.svgRoot),!0):!1}getRelativeToSurfaceXY(){return new ye(this.workspace.RTL?-this.relativeLeft+this.anchor.x-this.size.width:this.anchor.x+this.relativeLeft,this.anchor.y+this.relativeTop)}getSvgRoot(){return this.svgRoot}moveDuringDrag(e){this.moveTo(e.x,e.y),this.relativeLeft=this.workspace.RTL?this.anchor.x-e.x-this.size.width:e.x-this.anchor.x,this.relativeTop=e.y-this.anchor.y,this.renderTail()}setDragging(e){}setDeleteStyle(e){}isDeletable(){return!1}showContextMenu(e){}isMovable(){return!0}startDrag(){this.dragStrategy.startDrag()}drag(e){this.dragStrategy.drag(e)}endDrag(){this.dragStrategy.endDrag()}revertDrag(){this.dragStrategy.revertDrag()}select(){}unselect(){}};rs=nt,nt.BORDER_WIDTH=6,nt.DOUBLE_BORDER=2*rs.BORDER_WIDTH,nt.MIN_SIZE=rs.DOUBLE_BORDER,nt.TAIL_THICKNESS=1,nt.TAIL_ANGLE=20,nt.TAIL_BEND=4,nt.ANCHOR_RADIUS=8;var vo=class extends nt{constructor(e,t,o,n){super(t,o,n),this.workspace=t,this.anchor=o,this.ownerRect=n,this.autoLayout=!0,t=new gs(e),this.validateWorkspaceOptions(t),this.svgDialog=ie(J.SVG,{x:nt.BORDER_WIDTH,y:nt.BORDER_WIDTH},this.contentContainer),e.parentWorkspace=this.workspace,this.miniWorkspace=this.newWorkspaceSvg(new gs(e)),this.miniWorkspace.internalIsMutator=!0,e=this.miniWorkspace.createDom("blocklyMutatorBackground"),this.svgDialog.appendChild(e),t.languageTree&&(e.insertBefore(this.miniWorkspace.addFlyout(J.G),this.miniWorkspace.getCanvas()),e=this.miniWorkspace.getFlyout(),e==null||e.init(this.miniWorkspace),e==null||e.show(t.languageTree)),this.miniWorkspace.addChangeListener(this.onWorkspaceChange.bind(this));let u,g;(u=this.miniWorkspace.getFlyout())==null||(g=u.getWorkspace())==null||g.addChangeListener(this.onWorkspaceChange.bind(this)),this.updateBubbleSize()}dispose(){this.miniWorkspace.dispose(),super.dispose()}getWorkspace(){return this.miniWorkspace}addWorkspaceChangeListener(e){this.miniWorkspace.addChangeListener(e)}validateWorkspaceOptions(e){if(e.hasCategories)throw Error("The miniworkspace bubble does not support toolboxes with categories");if(e.hasTrashcan)throw Error("The miniworkspace bubble does not support trashcans");if(e.zoomOptions.controls||e.zoomOptions.wheel||e.zoomOptions.pinch)throw Error("The miniworkspace bubble does not support zooming");if(e.moveOptions.scrollbars||e.moveOptions.wheel||e.moveOptions.drag)throw Error("The miniworkspace bubble does not scrolling/moving the workspace");if(e.horizontalLayout)throw Error("The miniworkspace bubble does not support horizontal layouts")}onWorkspaceChange(){this.bumpBlocksIntoBounds(),this.updateBubbleSize()}bumpBlocksIntoBounds(){if(!this.miniWorkspace.isDragging())for(const e of this.miniWorkspace.getTopBlocks(!1)){const t=e.getRelativeToSurfaceXY();if(20>t.y&&e.moveBy(0,20-t.y),e.RTL){let o=-20;const n=this.miniWorkspace.getFlyout();n&&(o-=n.getWidth()),t.x>o&&e.moveBy(o-t.x,0)}else 20>t.x&&e.moveBy(20-t.x,0)}}updateBubbleSize(){if(!this.miniWorkspace.isDragging()){var e=this.getSize(),t=this.calculateWorkspaceSize();Math.abs(e.width-t.width)({kind:"block",type:o}))}),t}getAnchorLocation(){const e=Ml/2;return ye.sum(this.workspaceLocation,new ye(e,e))}getBubbleOwnerRect(){const e=this.sourceBlock.getSvgRoot().getBBox();return new rt(e.y,e.y+e.height,e.x,e.x+e.width)}createRootBlock(){if(!this.sourceBlock.decompose)throw Error("Blocks with mutator icons must include a decompose method");this.rootBlock=this.sourceBlock.decompose(this.miniWorkspaceBubble.getWorkspace());for(var e of this.rootBlock.getDescendants(!1))e.queueRender();this.rootBlock.setMovable(!1),this.rootBlock.setDeletable(!1);let t,o,n,u;e=(u=(t=this.miniWorkspaceBubble)==null||(o=t.getWorkspace())==null||(n=o.getFlyout())==null?void 0:n.getWidth())!=null?u:0,this.rootBlock.moveBy(this.rootBlock.RTL?-(e+Nl):Nl,Nl)}addSaveConnectionsListener(){this.sourceBlock.saveConnections&&this.rootBlock&&(this.saveConnectionsListener=()=>{this.sourceBlock.saveConnections&&this.rootBlock&&this.sourceBlock.saveConnections(this.rootBlock)},this.saveConnectionsListener(),this.sourceBlock.workspace.addChangeListener(this.saveConnectionsListener))}createMiniWorkspaceChangeListener(){return e=>{i.MutatorIcon$$module$build$src$core$icons$mutator_icon.isIgnorableMutatorEvent(e)||this.updateWorkspacePid||(this.updateWorkspacePid=setTimeout(()=>{this.updateWorkspacePid=null,this.recomposeSourceBlock()},0))}}static isIgnorableMutatorEvent(e){return e.isUiEvent||$(e)||S(e)&&e.element==="disabled"}recomposeSourceBlock(){if(this.rootBlock){if(!this.sourceBlock.compose)throw Error("Blocks with mutator icons must include a compose method");var e=i.getGroup$$module$build$src$core$events$utils();e||i.setGroup$$module$build$src$core$events$utils(!0);var t=mi.getExtraBlockState_(this.sourceBlock);this.sourceBlock.compose(this.rootBlock);var o=mi.getExtraBlockState_(this.sourceBlock);t!==o&&z(new(ne(ee.BLOCK_CHANGE))(this.sourceBlock,"mutation",null,t,o)),i.setGroup$$module$build$src$core$events$utils(e)}}getWorkspace(){let e;return(e=this.miniWorkspaceBubble)==null?void 0:e.getWorkspace()}},i.MutatorIcon$$module$build$src$core$icons$mutator_icon.TYPE=Ct.MUTATOR,i.MutatorIcon$$module$build$src$core$icons$mutator_icon.WEIGHT=1,i.MutatorIcon$$module$build$src$core$icons$mutator_icon;var dn=Object.create(null),eT={allExtensions:dn};i.register$$module$build$src$core$extensions("parent_tooltip_when_inline",M$);var As={TEST_ONLY:eT};As.apply=Ya,As.buildTooltipForDropdown=i.buildTooltipForDropdown$$module$build$src$core$extensions,As.buildTooltipWithFieldText=i.buildTooltipWithFieldText$$module$build$src$core$extensions,As.isRegistered=Cd,As.register=i.register$$module$build$src$core$extensions,As.registerMixin=i.registerMixin$$module$build$src$core$extensions,As.registerMutator=i.registerMutator$$module$build$src$core$extensions,As.runAfterPageLoad=O$,As.unregister=E$;var Ke;(function(e){e[e.WIN_KEY_FF_LINUX=0]="WIN_KEY_FF_LINUX",e[e.MAC_ENTER=3]="MAC_ENTER",e[e.BACKSPACE=8]="BACKSPACE",e[e.TAB=9]="TAB",e[e.NUM_CENTER=12]="NUM_CENTER",e[e.ENTER=13]="ENTER",e[e.SHIFT=16]="SHIFT",e[e.CTRL=17]="CTRL",e[e.ALT=18]="ALT",e[e.PAUSE=19]="PAUSE",e[e.CAPS_LOCK=20]="CAPS_LOCK",e[e.ESC=27]="ESC",e[e.SPACE=32]="SPACE",e[e.PAGE_UP=33]="PAGE_UP",e[e.PAGE_DOWN=34]="PAGE_DOWN",e[e.END=35]="END",e[e.HOME=36]="HOME",e[e.LEFT=37]="LEFT",e[e.UP=38]="UP",e[e.RIGHT=39]="RIGHT",e[e.DOWN=40]="DOWN",e[e.PLUS_SIGN=43]="PLUS_SIGN",e[e.PRINT_SCREEN=44]="PRINT_SCREEN",e[e.INSERT=45]="INSERT",e[e.DELETE=46]="DELETE",e[e.ZERO=48]="ZERO",e[e.ONE=49]="ONE",e[e.TWO=50]="TWO",e[e.THREE=51]="THREE",e[e.FOUR=52]="FOUR",e[e.FIVE=53]="FIVE",e[e.SIX=54]="SIX",e[e.SEVEN=55]="SEVEN",e[e.EIGHT=56]="EIGHT",e[e.NINE=57]="NINE",e[e.FF_SEMICOLON=59]="FF_SEMICOLON",e[e.FF_EQUALS=61]="FF_EQUALS",e[e.FF_DASH=173]="FF_DASH",e[e.FF_HASH=163]="FF_HASH",e[e.QUESTION_MARK=63]="QUESTION_MARK",e[e.AT_SIGN=64]="AT_SIGN",e[e.A=65]="A",e[e.B=66]="B",e[e.C=67]="C",e[e.D=68]="D",e[e.E=69]="E",e[e.F=70]="F",e[e.G=71]="G",e[e.H=72]="H",e[e.I=73]="I",e[e.J=74]="J",e[e.K=75]="K",e[e.L=76]="L",e[e.M=77]="M",e[e.N=78]="N",e[e.O=79]="O",e[e.P=80]="P",e[e.Q=81]="Q",e[e.R=82]="R",e[e.S=83]="S",e[e.T=84]="T",e[e.U=85]="U",e[e.V=86]="V",e[e.W=87]="W",e[e.X=88]="X",e[e.Y=89]="Y",e[e.Z=90]="Z",e[e.META=91]="META",e[e.WIN_KEY_RIGHT=92]="WIN_KEY_RIGHT",e[e.CONTEXT_MENU=93]="CONTEXT_MENU",e[e.NUM_ZERO=96]="NUM_ZERO",e[e.NUM_ONE=97]="NUM_ONE",e[e.NUM_TWO=98]="NUM_TWO",e[e.NUM_THREE=99]="NUM_THREE",e[e.NUM_FOUR=100]="NUM_FOUR",e[e.NUM_FIVE=101]="NUM_FIVE",e[e.NUM_SIX=102]="NUM_SIX",e[e.NUM_SEVEN=103]="NUM_SEVEN",e[e.NUM_EIGHT=104]="NUM_EIGHT",e[e.NUM_NINE=105]="NUM_NINE",e[e.NUM_MULTIPLY=106]="NUM_MULTIPLY",e[e.NUM_PLUS=107]="NUM_PLUS",e[e.NUM_MINUS=109]="NUM_MINUS",e[e.NUM_PERIOD=110]="NUM_PERIOD",e[e.NUM_DIVISION=111]="NUM_DIVISION",e[e.F1=112]="F1",e[e.F2=113]="F2",e[e.F3=114]="F3",e[e.F4=115]="F4",e[e.F5=116]="F5",e[e.F6=117]="F6",e[e.F7=118]="F7",e[e.F8=119]="F8",e[e.F9=120]="F9",e[e.F10=121]="F10",e[e.F11=122]="F11",e[e.F12=123]="F12",e[e.NUMLOCK=144]="NUMLOCK",e[e.SCROLL_LOCK=145]="SCROLL_LOCK",e[e.FIRST_MEDIA_KEY=166]="FIRST_MEDIA_KEY",e[e.LAST_MEDIA_KEY=183]="LAST_MEDIA_KEY",e[e.SEMICOLON=186]="SEMICOLON",e[e.DASH=189]="DASH",e[e.EQUALS=187]="EQUALS",e[e.COMMA=188]="COMMA",e[e.PERIOD=190]="PERIOD",e[e.SLASH=191]="SLASH",e[e.APOSTROPHE=192]="APOSTROPHE",e[e.TILDE=192]="TILDE",e[e.SINGLE_QUOTE=222]="SINGLE_QUOTE",e[e.OPEN_SQUARE_BRACKET=219]="OPEN_SQUARE_BRACKET",e[e.BACKSLASH=220]="BACKSLASH",e[e.CLOSE_SQUARE_BRACKET=221]="CLOSE_SQUARE_BRACKET",e[e.WIN_KEY=224]="WIN_KEY",e[e.MAC_FF_META=224]="MAC_FF_META",e[e.MAC_WK_CMD_LEFT=91]="MAC_WK_CMD_LEFT",e[e.MAC_WK_CMD_RIGHT=93]="MAC_WK_CMD_RIGHT",e[e.WIN_IME=229]="WIN_IME",e[e.VK_NONAME=252]="VK_NONAME",e[e.PHANTOM=255]="PHANTOM"})(Ke||(Ke={}));var yo={};yo.arc=vt,yo.curve=Zt,yo.line=Ki,yo.lineOnAxis=De,yo.lineTo=Hs,yo.moveBy=pt,yo.moveTo=St,yo.point=Ne;var mt={};mt.Coordinate=ye,mt.KeyCodes=Ke,mt.Rect=rt,mt.Size=Ze,mt.Svg=J,mt.aria=fr,mt.array=Bb,mt.browserEvents=go,mt.colour=ps,mt.deprecation=$b,mt.dom=Dt,mt.extensions=As,mt.idGenerator=fh,mt.math=bl,mt.object=wv,mt.parsing=Tr,mt.string=nn,mt.style=No,mt.svgMath=ui,mt.svgPaths=yo,mt.toolbox=Lo,mt.userAgent=FC,mt.xml=qi;var Tv=class extends nt{constructor(e,t,o){super(e,t,o),this.workspace=e,this.anchor=t,this.ownerRect=o,this.resizePointerMoveListener=this.resizePointerUpListener=null,this.textChangeListeners=[],this.sizeChangeListeners=[],this.text="",this.DEFAULT_SIZE=new Ze(160+nt.DOUBLE_BORDER,80+nt.DOUBLE_BORDER),this.MIN_SIZE=new Ze(45+nt.DOUBLE_BORDER,20+nt.DOUBLE_BORDER),this.editable=!0,Oe(this.svgRoot,"blocklyTextInputBubble"),{inputRoot:this.inputRoot,textArea:this.textArea}=this.createEditor(this.contentContainer),this.resizeGroup=this.createResizeHandle(this.svgRoot,e),this.setSize(this.DEFAULT_SIZE,!0)}getText(){return this.text}setText(e){this.text=e,this.textArea.value=e,this.onTextChange()}setEditable(e){(this.editable=e)?this.textArea.removeAttribute("readonly"):this.textArea.setAttribute("readonly","")}isEditable(){return this.editable}addTextChangeListener(e){this.textChangeListeners.push(e)}addSizeChangeListener(e){this.sizeChangeListeners.push(e)}createEditor(e){e=ie(J.FOREIGNOBJECT,{x:nt.BORDER_WIDTH,y:nt.BORDER_WIDTH},e);const t=document.createElementNS(Gs,"body");t.setAttribute("xmlns",Gs),t.className="blocklyMinimalBody";const o=document.createElementNS(Gs,"textarea");return o.className="blocklyTextarea blocklyText",o.setAttribute("dir",this.workspace.RTL?"RTL":"LTR"),t.appendChild(o),e.appendChild(t),this.bindTextAreaEvents(o),setTimeout(()=>{o.focus()},0),{inputRoot:e,textArea:o}}bindTextAreaEvents(e){W(e,"wheel",this,t=>{t.stopPropagation()}),W(e,"focus",this,this.onStartEdit,!0),W(e,"change",this,this.onTextChange)}createResizeHandle(e,t){return e=ie(J.IMAGE,{class:"blocklyResizeHandle",href:`${t.options.pathToMedia}resize-handle.svg`},e),W(e,"pointerdown",this,this.onResizePointerDown),e}setSize(e,t=!1){e.width=Math.max(e.width,this.MIN_SIZE.width),e.height=Math.max(e.height,this.MIN_SIZE.height);const o=e.width-nt.DOUBLE_BORDER,n=e.height-nt.DOUBLE_BORDER;this.inputRoot.setAttribute("width",`${o}`),this.inputRoot.setAttribute("height",`${n}`),this.resizeGroup.setAttribute("y",`${n}`),this.workspace.RTL?this.resizeGroup.setAttribute("x",`${-nt.DOUBLE_BORDER}`):this.resizeGroup.setAttribute("x",`${o}`),super.setSize(e,t),this.onSizeChange()}getSize(){return super.getSize()}onResizePointerDown(e){this.bringToFront(),pe(e)||(Ua(this.workspace,e,new ye(this.workspace.RTL?-this.getSize().width:this.getSize().width,this.getSize().height)),this.resizePointerUpListener=W(document,"pointerup",this,this.onResizePointerUp),this.resizePointerMoveListener=W(document,"pointermove",this,this.onResizePointerMove),this.workspace.hideChaff()),e.stopPropagation()}onResizePointerUp(e){K(),this.resizePointerUpListener&&(V(this.resizePointerUpListener),this.resizePointerUpListener=null),this.resizePointerMoveListener&&(V(this.resizePointerMoveListener),this.resizePointerMoveListener=null)}onResizePointerMove(e){e=Ha(this.workspace,e),this.setSize(new Ze(this.workspace.RTL?-e.x:e.x,e.y),!1),this.onSizeChange()}onStartEdit(){this.bringToFront()&&this.textArea.focus()}onTextChange(){this.text=this.textArea.value;for(const e of this.textChangeListeners)e()}onSizeChange(){for(const e of this.sizeChangeListeners)e()}};Be(` .blocklyTextInputBubble .blocklyTextarea { background-color: var(--commentFillColour); border: 0; @@ -855,13 +855,13 @@ children`),this.state=e}},nv=class extends en{constructor(e,t,o){super(`Cannot a width: 100%; height: 100%; } -`);var op={};op.register=Sd,op.unregister=O$;var ip=17,Cv=160,Tv=80,_o=class extends Rl{constructor(e){super(e),this.sourceBlock=e,this.textInputBubble=null,this.text="",this.bubbleSize=new Xe(Cv,Tv),this.bubbleVisiblity=!1}getType(){return _o.TYPE}initView(e){this.svgRoot||(super.initView(e),ie(J.CIRCLE,{class:"blocklyIconShape",r:"8",cx:"8",cy:"8"},this.svgRoot),ie(J.PATH,{class:"blocklyIconSymbol",d:"m6.8,10h2c0.003,-0.617 0.271,-0.962 0.633,-1.266 2.875,-2.4050.607,-5.534 -3.765,-3.874v1.7c3.12,-1.657 3.698,0.118 2.336,1.25-1.201,0.998 -1.201,1.528 -1.204,2.19z"},this.svgRoot),ie(J.RECT,{class:"blocklyIconSymbol",x:"6.8",y:"10.78",height:"2",width:"2"},this.svgRoot),Re(this.svgRoot,"blockly-icon-comment"))}dispose(){super.dispose();let e;(e=this.textInputBubble)==null||e.dispose()}getWeight(){return _o.WEIGHT}getSize(){return new Xe(ip,ip)}applyColour(){super.applyColour();const e=this.sourceBlock.getColour();let t;(t=this.textInputBubble)==null||t.setColour(e)}updateEditable(){const e=this,t=()=>super.updateEditable;return ge.asyncExecutePromiseGeneratorFunction(function*(){t().call(e),e.bubbleIsVisible()&&(yield e.setBubbleVisible(!1),yield e.setBubbleVisible(!0))})}onLocationChange(e){super.onLocationChange(e),e=this.getAnchorLocation();let t;(t=this.textInputBubble)==null||t.setAnchorLocation(e)}setText(e){const t=this.text;z(new(ne(ee.BLOCK_CHANGE))(this.sourceBlock,"comment",null,t,e)),this.text=e;let o;(o=this.textInputBubble)==null||o.setText(this.text)}getText(){return this.text}setBubbleSize(e){this.bubbleSize=e;let t;(t=this.textInputBubble)==null||t.setSize(this.bubbleSize,!0)}getBubbleSize(){return this.bubbleSize}saveState(){return this.text?{text:this.text,pinned:this.bubbleIsVisible(),height:this.bubbleSize.height,width:this.bubbleSize.width}:null}loadState(e){let t;this.text=(t=e.text)!=null?t:"";let o,n;this.bubbleSize=new Xe((o=e.width)!=null?o:Cv,(n=e.height)!=null?n:Tv);let u;this.bubbleVisiblity=(u=e.pinned)!=null?u:!1,this.setBubbleVisible(this.bubbleVisiblity)}onClick(){super.onClick(),this.setBubbleVisible(!this.bubbleIsVisible())}isClickableInFlyout(){return!1}onTextChange(){if(this.textInputBubble){var e=this.textInputBubble.getText();this.text!==e&&(z(new(ne(ee.BLOCK_CHANGE))(this.sourceBlock,"comment",null,this.text,e)),this.text=e)}}onSizeChange(){this.textInputBubble&&(this.bubbleSize=this.textInputBubble.getSize())}bubbleIsVisible(){return this.bubbleVisiblity}setBubbleVisible(e){const t=this;return ge.asyncExecutePromiseGeneratorFunction(function*(){t.bubbleVisiblity!==e&&(t.bubbleVisiblity=e,yield Ts(),!t.sourceBlock.rendered||t.sourceBlock.isInFlyout||t.sourceBlock.isInsertionMarker()||(e?(t.sourceBlock.isEditable()?t.showEditableBubble():t.showNonEditableBubble(),t.applyColour()):t.hideBubble(),z(new(ne(ee.BUBBLE_OPEN))(t.sourceBlock,e,"comment"))))})}showEditableBubble(){this.createBubble();let e;(e=this.textInputBubble)==null||e.addTextChangeListener(()=>this.onTextChange());let t;(t=this.textInputBubble)==null||t.addSizeChangeListener(()=>this.onSizeChange())}showNonEditableBubble(){this.createBubble();let e;(e=this.textInputBubble)==null||e.setEditable(!1)}createBubble(){this.textInputBubble=new kv(this.sourceBlock.workspace,this.getAnchorLocation(),this.getBubbleOwnerRect()),this.textInputBubble.setText(this.getText()),this.textInputBubble.setSize(this.bubbleSize,!0)}hideBubble(){let e;(e=this.textInputBubble)==null||e.dispose(),this.textInputBubble=null}getAnchorLocation(){const e=ip/2;return ye.sum(this.workspaceLocation,new ye(e,e))}getBubbleOwnerRect(){return this.sourceBlock.getBoundingRectangleWithoutChildren()}};_o.TYPE=Ct.COMMENT,_o.WEIGHT=3,Sd(_o.TYPE,_o);var Sv=class extends Error{constructor(e){super(`Tried to append an icon of type ${e.getType()} when an icon of that type already exists on the block. Use getIcon to access the existing icon.`),this.icon=e}},Ev={};Ev.DuplicateIconType=Sv;var Iv=class extends nt{constructor(e,t,o,n){super(t,o,n),this.text=e,this.workspace=t,this.anchor=o,this.ownerRect=n,this.paragraph=this.stringToSvg(e,this.contentContainer),this.updateBubbleSize()}getText(){return this.text}setText(e){this.text=e,Ze(this.paragraph),this.paragraph=this.stringToSvg(e,this.contentContainer),this.updateBubbleSize()}stringToSvg(e,t){return t=this.createParagraph(t),e=this.createTextFragments(t,e),this.workspace.RTL&&this.rightAlignTextFragments(t.getBBox().width,e),t}createParagraph(e){return ie(J.G,{class:"blocklyText blocklyBubbleText blocklyNoPointerEvents",transform:`translate(0,${nt.BORDER_WIDTH})`,style:`direction: ${this.workspace.RTL?"rtl":"ltr"}`},e)}createTextFragments(e,t){let o=1;return t.split(` -`).map(n=>{const u=ie(J.TEXT,{y:`${o}em`,x:nt.BORDER_WIDTH},e);return n=document.createTextNode(n),u.appendChild(n),o+=1,u})}rightAlignTextFragments(e,t){for(const o of t)o.setAttribute("text-anchor","start"),o.setAttribute("x",`${e+nt.BORDER_WIDTH}`)}updateBubbleSize(){const e=this.paragraph.getBBox();this.setSize(new Xe(e.width+2*nt.BORDER_WIDTH,e.height+2*nt.BORDER_WIDTH),!0)}},np=17,wo=class extends Rl{constructor(e){super(e),this.sourceBlock=e,this.textMap=new Map,this.textBubble=null}getType(){return wo.TYPE}initView(e){this.svgRoot||(super.initView(e),ie(J.PATH,{class:"blocklyIconShape",d:"M2,15Q-1,15 0.5,12L6.5,1.7Q8,-1 9.5,1.7L15.5,12Q17,15 14,15z"},this.svgRoot),ie(J.PATH,{class:"blocklyIconSymbol",d:"m7,4.8v3.16l0.27,2.27h1.46l0.27,-2.27v-3.16z"},this.svgRoot),ie(J.RECT,{class:"blocklyIconSymbol",x:"7",y:"11",height:"2",width:"2"},this.svgRoot),Re(this.svgRoot,"blockly-icon-warning"))}dispose(){super.dispose();let e;(e=this.textBubble)==null||e.dispose()}getWeight(){return wo.WEIGHT}getSize(){return new Xe(np,np)}applyColour(){super.applyColour();let e;(e=this.textBubble)==null||e.setColour(this.sourceBlock.getColour())}updateCollapsed(){}isShownWhenCollapsed(){return!0}onLocationChange(e){super.onLocationChange(e);let t;(t=this.textBubble)==null||t.setAnchorLocation(this.getAnchorLocation())}addMessage(e,t){if(this.textMap.get(t)===e)return this;e?this.textMap.set(t,e):this.textMap.delete(t);let o;return(o=this.textBubble)==null||o.setText(this.getText()),this}getText(){return[...this.textMap.values()].join(` -`)}onClick(){super.onClick(),this.setBubbleVisible(!this.bubbleIsVisible())}isClickableInFlyout(){return!1}bubbleIsVisible(){return!!this.textBubble}setBubbleVisible(e){const t=this;return ge.asyncExecutePromiseGeneratorFunction(function*(){if(t.bubbleIsVisible()!==e){if(yield Ts(),e)t.textBubble=new Iv(t.getText(),t.sourceBlock.workspace,t.getAnchorLocation(),t.getBubbleOwnerRect()),t.applyColour();else{let o;(o=t.textBubble)==null||o.dispose(),t.textBubble=null}z(new(ne(ee.BUBBLE_OPEN))(t.sourceBlock,e,"warning"))}})}getAnchorLocation(){const e=np/2;return ye.sum(this.workspaceLocation,new ye(e,e))}getBubbleOwnerRect(){const e=this.sourceBlock.getSvgRoot().getBBox();return new rt(e.y,e.y+e.height,e.x,e.x+e.width)}};wo.TYPE=Ct.WARNING,wo.WEIGHT=2;var Fo={};Fo.CommentIcon=_o,Fo.Icon=Rl,Fo.IconType=Ct,Fo.MutatorIcon=i.MutatorIcon$$module$build$src$core$icons$mutator_icon,Fo.WarningIcon=wo,Fo.exceptions=Ev,Fo.registry=op,i.Names$$module$build$src$core$names=class{constructor(e,t){this.db=new Map,this.dbReverse=new Set,this.variableMap=null,this.variablePrefix=t||"",this.reservedWords=new Set(e?e.split(","):[])}reset(){this.db.clear(),this.dbReverse.clear(),this.variableMap=null}setVariableMap(e){this.variableMap=e}getNameForUserVariable(e){return this.variableMap?(e=this.variableMap.getVariableById(e))?e.name:null:(console.warn(`Deprecated call to Names.prototype.getName without defining a variable map. To fix, add the following code in your generator's init() function: -Blockly.YourGeneratorName.nameDB_.setVariableMap(workspace.getVariableMap());`),null)}populateVariables(e){e=i.allUsedVarModels$$module$build$src$core$variables(e);for(let t=0;trect,`,`${e} .blocklyEditableText>rect {`,`fill: ${this.FIELD_BORDER_RECT_COLOUR};`,"fill-opacity: .6;","stroke: none;","}",`${e} .blocklyNonEditableText>text,`,`${e} .blocklyEditableText>text {`,"fill: #000;","}",`${e} .blocklyFlyoutLabelText {`,"fill: #000;","}",`${e} .blocklyText.blocklyBubbleText {`,"fill: #000;","}",`${e} .blocklyEditableText:not(.editing):hover>rect {`,"stroke: #fff;","stroke-width: 2;","}",`${e} .blocklyHtmlInput {`,`font-family: ${this.FIELD_TEXT_FONTFAMILY};`,`font-weight: ${this.FIELD_TEXT_FONTWEIGHT};`,"}",`${e} .blocklySelected>.blocklyPath {`,"stroke: #fc3;","stroke-width: 3px;","}",`${e} .blocklyHighlightedConnectionPath {`,"stroke: #fc3;","}",`${e} .blocklyReplaceable .blocklyPath {`,"fill-opacity: .5;","}",`${e} .blocklyReplaceable .blocklyPathLight,`,`${e} .blocklyReplaceable .blocklyPathDark {`,"display: none;","}",`${e} .blocklyInsertionMarker>.blocklyPath {`,`fill-opacity: ${this.INSERTION_MARKER_OPACITY};`,"stroke: none;","}"]}},Bl=class{constructor(e,t){this.inlinePath_=this.outlinePath_="",this.block_=e,this.info_=t,this.topLeft_=e.getRelativeToSurfaceXY(),this.constants_=t.getRenderer().getConstants()}draw(){this.drawOutline_(),this.drawInternals_(),this.updateConnectionHighlights(),this.block_.pathObject.setPath(this.outlinePath_+` -`+this.inlinePath_),this.info_.RTL&&this.block_.pathObject.flipRTL(),this.recordSizeOnBlock_()}recordSizeOnBlock_(){this.block_.height=this.info_.height,this.block_.width=this.info_.widthWithChildren,this.block_.childlessWidth=this.info_.width}drawOutline_(){this.drawTop_();for(let e=1;ee||e>this.fieldRow.length)throw Error("index "+e+" out of bounds.");return(t||t===""&&o)&&(typeof t=="string"&&(t=i.fromJson$$module$build$src$core$field_registry({type:"field_label",text:t})),t.setSourceBlock(this.sourceBlock),this.sourceBlock.initialized&&this.initField(t),t.name=o,t.setVisible(this.isVisible()),t.prefixField&&(e=this.insertFieldAt(e,t.prefixField)),this.fieldRow.splice(e,0,t),e++,t.suffixField&&(e=this.insertFieldAt(e,t.suffixField)),this.sourceBlock.rendered&&this.sourceBlock.queueRender()),e}removeField(e,t){for(let o=0,n;n=this.fieldRow[o];o++)if(n.name===e)return n.dispose(),this.fieldRow.splice(o,1),this.sourceBlock.rendered&&this.sourceBlock.queueRender(),!0;if(t)return!1;throw Error('Field "'+e+'" not found.')}isVisible(){return this.visible}setVisible(e){let t=[];if(this.visible===e)return t;this.visible=e;for(let n=0,u;u=this.fieldRow[n];n++)u.setVisible(e);if(this.connection){var o=this.connection;e?t=o.startTrackingAll():o.stopTrackingAll(),(o=o.targetBlock())&&(o.getSvgRoot().style.display=e?"block":"none")}return t}markDirty(){for(let e=0,t;t=this.fieldRow[e];e++)t.markDirty()}setCheck(e){if(!this.connection)throw Error("This input does not have a connection.");return this.connection.setCheck(e),this}setAlign(e){return this.align=e,this.sourceBlock.rendered&&this.sourceBlock.queueRender(),this}setShadowDom(e){if(!this.connection)throw Error("This input does not have a connection.");return this.connection.setShadowDom(e),this}getShadowDom(){if(!this.connection)throw Error("This input does not have a connection.");return this.connection.getShadowDom()}init(){for(const e of this.fieldRow)e.init()}initModel(){for(const e of this.fieldRow)e.initModel()}initField(e){this.sourceBlock.rendered?e.init():e.initModel()}dispose(){for(let e=0,t;t=this.fieldRow[e];e++)t.dispose();this.connection&&this.connection.dispose()}makeConnection(e){return this.sourceBlock.makeConnection_(e)}},Ks=class extends pn{constructor(e,t){super(e,t),this.name=e,this.type=i.inputTypes$$module$build$src$core$inputs$input_types.DUMMY}},Co=class extends pn{constructor(e,t){super(e,t),this.name=e,this.type=i.inputTypes$$module$build$src$core$inputs$input_types.END_ROW}},ls=class extends pn{constructor(e,t){if(!e)throw Error("Statement inputs must have a non-empty name");super(e,t),this.name=e,this.type=i.inputTypes$$module$build$src$core$inputs$input_types.STATEMENT,this.connection=this.makeConnection(xe.NEXT_STATEMENT)}},Mv;i.ValueInput$$module$build$src$core$inputs$value_input=class extends pn{constructor(e,t){if(!e)throw Error("Value inputs must have a non-empty name");super(e,t),this.name=e,this.type=i.inputTypes$$module$build$src$core$inputs$input_types.VALUE,this.connection=this.makeConnection(xe.INPUT_VALUE)}},Mv={},Mv.ValueInput=i.ValueInput$$module$build$src$core$inputs$value_input;var Rr=class{constructor(e,t){this.statementEdge=this.width=this.widthWithChildren=this.height=0,this.rows=[],this.inputRows=[],this.startY=this.startX=0,this.renderer_=e,this.block_=t,this.constants_=this.renderer_.getConstants(),this.outputConnection=t.outputConnection?new Ov(this.constants_,t.outputConnection):null,this.isInline=t.getInputsInline()&&!t.isCollapsed(),this.isCollapsed=t.isCollapsed(),this.isInsertionMarker=t.isInsertionMarker(),this.RTL=t.RTL,this.topRow=new dp(this.constants_),this.bottomRow=new rp(this.constants_)}getRenderer(){return this.renderer_}measure(){this.createRows_(),this.addElemSpacing_(),this.addRowSpacing_(),this.computeBounds_(),this.alignRowElements_(),this.finalize_()}createRows_(){this.populateTopRow_(),this.rows.push(this.topRow);let e=new cp(this.constants_);this.inputRows.push(e);var t=this.block_.getIcons();for(let o=0,n;n=t[o];o++){const u=new Dv(this.constants_,n);this.isCollapsed&&!n.isShownWhenCollapsed()||e.elements.push(u)}t=void 0;for(let o=0,n;n=this.block_.inputList[o];o++)if(n.isVisible()){this.shouldStartNewRow_(n,t)&&(this.rows.push(e),e=new cp(this.constants_),this.inputRows.push(e));for(let u=0,g;g=n.fieldRow[u];u++)e.elements.push(new hn(this.constants_,g,n));this.addInput_(n,e),t=n}this.isCollapsed&&(e.hasJaggedEdge=!0,e.elements.push(new Av(this.constants_))),(e.elements.length||e.hasDummyInput)&&this.rows.push(e),this.populateBottomRow_(),this.rows.push(this.bottomRow)}populateTopRow_(){var e=!!this.block_.previousConnection;const t=(this.block_.hat?this.block_.hat==="cap":this.constants_.ADD_START_HATS)&&!this.outputConnection&&!e;let o=this.topRow.hasLeftSquareCorner(this.block_)?Ar:Dr;this.topRow.elements.push(new o(this.constants_)),t?(e=new ap(this.constants_),this.topRow.elements.push(e),this.topRow.capline=e.ascenderHeight):e&&(this.topRow.hasPreviousConnection=!0,this.topRow.connection=new Nv(this.constants_,this.block_.previousConnection),this.topRow.elements.push(this.topRow.connection)),this.block_.inputList.length&&this.block_.inputList[0]instanceof ls&&!this.block_.isCollapsed()?this.topRow.minHeight=this.constants_.TOP_ROW_PRECEDES_STATEMENT_MIN_HEIGHT:this.topRow.minHeight=this.constants_.TOP_ROW_MIN_HEIGHT,o=this.topRow.hasRightSquareCorner(this.block_)?Ar:Dr,this.topRow.elements.push(new o(this.constants_,"right"))}populateBottomRow_(){this.bottomRow.hasNextConnection=!!this.block_.nextConnection,this.bottomRow.minHeight=this.block_.inputList.length&&this.block_.inputList[this.block_.inputList.length-1]instanceof ls?this.constants_.BOTTOM_ROW_AFTER_STATEMENT_MIN_HEIGHT:this.constants_.BOTTOM_ROW_MIN_HEIGHT,this.bottomRow.hasLeftSquareCorner(this.block_)?this.bottomRow.elements.push(new Ar(this.constants_)):this.bottomRow.elements.push(new Dr(this.constants_)),this.bottomRow.hasNextConnection&&(this.bottomRow.connection=new Rv(this.constants_,this.block_.nextConnection),this.bottomRow.elements.push(this.bottomRow.connection)),this.bottomRow.hasRightSquareCorner(this.block_)?this.bottomRow.elements.push(new Ar(this.constants_,"right")):this.bottomRow.elements.push(new Dr(this.constants_,"right"))}addInput_(e,t){this.isInline&&e instanceof i.ValueInput$$module$build$src$core$inputs$value_input?(t.elements.push(new lp(this.constants_,e)),t.hasInlineInput=!0):e instanceof ls?(t.elements.push(new xr(this.constants_,e)),t.hasStatement=!0):e instanceof i.ValueInput$$module$build$src$core$inputs$value_input?(t.elements.push(new Ll(this.constants_,e)),t.hasExternalInput=!0):(e instanceof Ks||e instanceof Co)&&(t.minHeight=Math.max(t.minHeight,e.getSourceBlock()&&e.getSourceBlock().isShadow()?this.constants_.DUMMY_INPUT_SHADOW_MIN_HEIGHT:this.constants_.DUMMY_INPUT_MIN_HEIGHT),t.hasDummyInput=!0),t.align===null&&(t.align=e.align)}shouldStartNewRow_(e,t){return t?t instanceof Co||e instanceof ls||t instanceof ls?!0:e instanceof i.ValueInput$$module$build$src$core$inputs$value_input||e instanceof Ks||t instanceof i.ValueInput$$module$build$src$core$inputs$value_input?!this.isInline:!1:!1}addElemSpacing_(){for(let e=0,t;t=this.rows[e];e++){const o=t.elements;if(t.elements=[],t.startsWithElemSpacer()&&t.elements.push(new as(this.constants_,this.getInRowSpacing_(null,o[0]))),o.length){for(let n=0;ne.disposeInternal()),this.inputList.forEach(e=>e.dispose()),this.inputList.length=0,this.getConnections_(!0).forEach(e=>e.dispose()),this.disposed=!0}isDeadOrDying(){return this.disposing||this.disposed}initModel(){if(!this.initialized){for(const e of this.inputList)e.initModel();this.initialized=!0}}unplug(e){this.outputConnection&&this.unplugFromRow(e),this.previousConnection&&this.unplugFromStack(e)}unplugFromRow(e){let t=null,o;(o=this.outputConnection)!=null&&o.isConnected()&&(t=this.outputConnection.targetConnection,this.outputConnection.disconnect()),t&&e&&(e=this.getOnlyValueConnection())&&e.isConnected()&&!e.targetBlock().isShadow()&&(e=e.targetConnection,e==null||e.disconnect(),this.workspace.connectionChecker.canConnect(e,t,!1)?t.connect(e):e==null||e.onFailedConnect(t))}getOnlyValueConnection(){let e=null;for(let t=0;t(n=n+(o==="("||u===")"?"":" ")+u,o=u[u.length-1],n),""),t=t.trim()||"???",e&&t.length>e&&(t=t.substring(0,e-3)+"..."),t}toTokens(e="?"){const t=[];for(const n of this.inputList)if(n.name!=$r){for(const u of n.fieldRow)t.push(u.getText());if(n.connection){const u=n.connection.targetBlock();if(u){var o=n.connection;let g=o.getCheck();!g&&o.targetConnection&&(g=o.targetConnection.getCheck()),(o=!!g&&(g.includes("Boolean")||g.includes("Number")))&&t.push("("),t.push(...u.toTokens(e)),o&&t.push(")")}else t.push(e)}}return t}appendValueInput(e){return this.appendInput(new i.ValueInput$$module$build$src$core$inputs$value_input(e,this))}appendStatementInput(e){return this.statementInputCount++,this.appendInput(new ls(e,this))}appendDummyInput(e=""){return this.appendInput(new Ks(e,this))}appendEndRowInput(e=""){return this.appendInput(new Co(e,this))}appendInput(e){return this.inputList.push(e),e}appendInputFromRegistry(e,t){return(e=p($e.INPUT,e,!1))?this.appendInput(new e(t,this)):null}jsonInit(e){var t=e.type?'Block "'+e.type+'": ':"";if(e.output&&e.previousStatement)throw Error(t+"Must not have both an output and a previousStatement.");for(var o=0;e["args"+o];){if(e["message"+o]===void 0)throw Error(t+`args${o} must have a corresponding message (message${o}).`);o++}if(e.style&&e.style.hat&&(this.hat=e.style.hat,e.style=null),e.style&&e.colour)throw Error(t+"Must not have both a colour and a style.");for(e.style?this.jsonInitStyle(e,t):this.jsonInitColour(e,t),o=0;e["message"+o]!==void 0;)this.interpolate(e["message"+o],e["args"+o]||[],e["implicitAlign"+o]||e["lastDummyAlign"+o],t),o++;if(e.inputsInline!==void 0&&(i.disable$$module$build$src$core$events$utils(),this.setInputsInline(e.inputsInline),i.enable$$module$build$src$core$events$utils()),e.output!==void 0&&this.setOutput(!0,e.output),e.outputShape!==void 0&&this.setOutputShape(e.outputShape),e.previousStatement!==void 0&&this.setPreviousStatement(!0,e.previousStatement),e.nextStatement!==void 0&&this.setNextStatement(!0,e.nextStatement),e.tooltip!==void 0&&(o=bt(e.tooltip),this.setTooltip(o)),e.enableContextMenu!==void 0&&(this.contextMenu=!!e.enableContextMenu),e.suppressPrefixSuffix!==void 0&&(this.suppressPrefixSuffix=!!e.suppressPrefixSuffix),e.helpUrl!==void 0&&(o=bt(e.helpUrl),this.setHelpUrl(o)),typeof e.extensions=="string"&&(console.warn(t+"JSON attribute 'extensions' should be an array of strings. Found raw string in JSON for '"+e.type+"' block."),e.extensions=[e.extensions]),e.mutator!==void 0&&Va(e.mutator,this,!0),e=e.extensions,Array.isArray(e))for(t=0;tg||g>t)throw Error('Block "'+this.type+'": Message index %'+g+" out of range.");if(o[g])throw Error('Block "'+this.type+'": Message index %'+g+" duplicated.");o[g]=!0,n++}}if(n!==t)throw Error('Block "'+this.type+'": Message does not reference all '+t+" arg(s).")}interpolateArguments(e,t,o){const n=[];for(let g=0;g=this.inputList.length)throw RangeError("Input index "+e+" out of bounds.");if(t>this.inputList.length)throw RangeError("Reference input "+t+" out of bounds.");const o=this.inputList[e];this.inputList.splice(e,1),et.getWeight()-o.getWeight()),e}removeIcon(e){if(!this.hasIcon(e))return!1;let t;return(t=this.getIcon(e))==null||t.dispose(),this.icons=this.icons.filter(o=>!o.getType().equals(e)),!0}hasIcon(e){return this.icons.some(t=>t.getType().equals(e))}getIcon(e){return e instanceof Ct?this.icons.find(t=>t.getType().equals(e)):this.icons.find(t=>t.getType().toString()===e)}getIcons(){return[...this.icons]}getRelativeToSurfaceXY(){return this.xy}moveBy(e,t,o){if(this.parentBlock_)throw Error("Block has parent");const n=new(ne(ee.BLOCK_MOVE))(this);o&&n.setReason(o),this.xy.translate(e,t),n.recordNew(),z(n)}makeConnection_(e){return new Qe(this,e)}allInputsFilled(e){if(e===void 0&&(e=!0),!e&&this.isShadow())return!1;for(let o=0,n;n=this.inputList[o];o++)if(n.connection){var t=n.connection.targetBlock();if(!t||!t.allInputsFilled(e))return!1}return(t=this.getNextBlock())?t.allInputsFilled(e):!0}toDevString(){let e=this.type?'"'+this.type+'" block':"Block";return this.id&&(e+=' (id="'+this.id+'")'),e}};Uo.COLLAPSED_INPUT_NAME=$r,Uo.COLLAPSED_FIELD_NAME=gl;var ms=class{constructor(e,t,o,n){this.workspace=e,this.targetWorkspace=t,this.isFlyoutLabel=n,this.onMouseUpWrapper=null,this.height=this.width=0,this.cursorSvg=this.svgText=this.svgGroup=null,this.text=o.text,this.position=new ye(0,0),this.callbackKey=o.callbackKey||o.callbackkey,this.cssClass=o["web-class"]||null,this.info=o}createDom(){var e=this.isFlyoutLabel?"blocklyFlyoutLabel":"blocklyFlyoutButton";this.cssClass&&(e+=" "+this.cssClass),this.svgGroup=ie(J.G,{class:e},this.workspace.getCanvas());let t;this.isFlyoutLabel||(t=ie(J.RECT,{class:"blocklyFlyoutButtonShadow",rx:ms.BORDER_RADIUS,ry:ms.BORDER_RADIUS,x:1,y:1},this.svgGroup)),e=ie(J.RECT,{class:this.isFlyoutLabel?"blocklyFlyoutLabelBackground":"blocklyFlyoutButtonBackground",rx:ms.BORDER_RADIUS,ry:ms.BORDER_RADIUS},this.svgGroup);const o=ie(J.TEXT,{class:this.isFlyoutLabel?"blocklyFlyoutLabelText":"blocklyText",x:0,y:0,"text-anchor":"middle"},this.svgGroup);var n=bt(this.text);this.workspace.RTL&&(n+="‏"),o.textContent=n,this.isFlyoutLabel&&(this.svgText=o,this.workspace.getThemeManager().subscribe(this.svgText,"flyoutForegroundColour","fill"));const u=js(o,"fontSize"),g=js(o,"fontWeight"),I=js(o,"fontFamily");if(this.width=Bs(o,u,g,I),n=ro(n,u,g,I),this.height=n.height,!this.isFlyoutLabel){this.width+=2*ms.TEXT_MARGIN_X,this.height+=2*ms.TEXT_MARGIN_Y;let L;(L=t)==null||L.setAttribute("width",String(this.width));let le;(le=t)==null||le.setAttribute("height",String(this.height))}return e.setAttribute("width",String(this.width)),e.setAttribute("height",String(this.height)),o.setAttribute("x",String(this.width/2)),o.setAttribute("y",String(this.height/2-n.height/2+n.baseline)),this.updateTransform(),this.onMouseUpWrapper=H(this.svgGroup,"pointerup",this,this.onMouseUp),this.svgGroup}show(){this.updateTransform(),this.svgGroup.setAttribute("display","block")}updateTransform(){this.svgGroup.setAttribute("transform","translate("+this.position.x+","+this.position.y+")")}moveTo(e,t){this.position.x=e,this.position.y=t,this.updateTransform()}isLabel(){return this.isFlyoutLabel}getPosition(){return this.position}getButtonText(){return this.text}getTargetWorkspace(){return this.targetWorkspace}getWorkspace(){return this.workspace}dispose(){this.onMouseUpWrapper&&V(this.onMouseUpWrapper),this.svgGroup&&Ze(this.svgGroup),this.svgText&&this.workspace.getThemeManager().unsubscribe(this.svgText)}setCursorSvg(e){e?this.svgGroup&&(this.svgGroup.appendChild(e),this.cursorSvg=e):this.cursorSvg=null}setMarkerSvg(){throw Error("Attempted to set a marker on a button.")}onMouseUp(e){(e=this.targetWorkspace.getGesture(e))&&e.cancel(),this.isFlyoutLabel&&this.callbackKey?console.warn("Labels should not have callbacks. Label text: "+this.text):this.isFlyoutLabel||this.callbackKey&&this.targetWorkspace.getButtonCallback(this.callbackKey)?this.isFlyoutLabel||(e=this.targetWorkspace.getButtonCallback(this.callbackKey))&&e(this):console.warn("Buttons should have callbacks. Button text: "+this.text)}};ms.TEXT_MARGIN_X=5,ms.TEXT_MARGIN_Y=2,ms.BORDER_RADIUS=4,Be(` +`);var ip={};ip.register=Ed,ip.unregister=N$;var np=17,Sv=160,Ev=80,_o=class extends Rl{constructor(e){super(e),this.sourceBlock=e,this.textInputBubble=null,this.text="",this.bubbleSize=new Ze(Sv,Ev),this.bubbleVisiblity=!1}getType(){return _o.TYPE}initView(e){this.svgRoot||(super.initView(e),ie(J.CIRCLE,{class:"blocklyIconShape",r:"8",cx:"8",cy:"8"},this.svgRoot),ie(J.PATH,{class:"blocklyIconSymbol",d:"m6.8,10h2c0.003,-0.617 0.271,-0.962 0.633,-1.266 2.875,-2.4050.607,-5.534 -3.765,-3.874v1.7c3.12,-1.657 3.698,0.118 2.336,1.25-1.201,0.998 -1.201,1.528 -1.204,2.19z"},this.svgRoot),ie(J.RECT,{class:"blocklyIconSymbol",x:"6.8",y:"10.78",height:"2",width:"2"},this.svgRoot),Oe(this.svgRoot,"blockly-icon-comment"))}dispose(){super.dispose();let e;(e=this.textInputBubble)==null||e.dispose()}getWeight(){return _o.WEIGHT}getSize(){return new Ze(np,np)}applyColour(){super.applyColour();const e=this.sourceBlock.getColour();let t;(t=this.textInputBubble)==null||t.setColour(e)}updateEditable(){const e=this,t=()=>super.updateEditable;return ge.asyncExecutePromiseGeneratorFunction(function*(){t().call(e),e.bubbleIsVisible()&&(yield e.setBubbleVisible(!1),yield e.setBubbleVisible(!0))})}onLocationChange(e){super.onLocationChange(e),e=this.getAnchorLocation();let t;(t=this.textInputBubble)==null||t.setAnchorLocation(e)}setText(e){const t=this.text;z(new(ne(ee.BLOCK_CHANGE))(this.sourceBlock,"comment",null,t,e)),this.text=e;let o;(o=this.textInputBubble)==null||o.setText(this.text)}getText(){return this.text}setBubbleSize(e){this.bubbleSize=e;let t;(t=this.textInputBubble)==null||t.setSize(this.bubbleSize,!0)}getBubbleSize(){return this.bubbleSize}saveState(){return this.text?{text:this.text,pinned:this.bubbleIsVisible(),height:this.bubbleSize.height,width:this.bubbleSize.width}:null}loadState(e){let t;this.text=(t=e.text)!=null?t:"";let o,n;this.bubbleSize=new Ze((o=e.width)!=null?o:Sv,(n=e.height)!=null?n:Ev);let u;this.bubbleVisiblity=(u=e.pinned)!=null?u:!1,this.setBubbleVisible(this.bubbleVisiblity)}onClick(){super.onClick(),this.setBubbleVisible(!this.bubbleIsVisible())}isClickableInFlyout(){return!1}onTextChange(){if(this.textInputBubble){var e=this.textInputBubble.getText();this.text!==e&&(z(new(ne(ee.BLOCK_CHANGE))(this.sourceBlock,"comment",null,this.text,e)),this.text=e)}}onSizeChange(){this.textInputBubble&&(this.bubbleSize=this.textInputBubble.getSize())}bubbleIsVisible(){return this.bubbleVisiblity}setBubbleVisible(e){const t=this;return ge.asyncExecutePromiseGeneratorFunction(function*(){t.bubbleVisiblity!==e&&(t.bubbleVisiblity=e,yield Ts(),!t.sourceBlock.rendered||t.sourceBlock.isInFlyout||t.sourceBlock.isInsertionMarker()||(e?(t.sourceBlock.isEditable()?t.showEditableBubble():t.showNonEditableBubble(),t.applyColour()):t.hideBubble(),z(new(ne(ee.BUBBLE_OPEN))(t.sourceBlock,e,"comment"))))})}showEditableBubble(){this.createBubble();let e;(e=this.textInputBubble)==null||e.addTextChangeListener(()=>this.onTextChange());let t;(t=this.textInputBubble)==null||t.addSizeChangeListener(()=>this.onSizeChange())}showNonEditableBubble(){this.createBubble();let e;(e=this.textInputBubble)==null||e.setEditable(!1)}createBubble(){this.textInputBubble=new Tv(this.sourceBlock.workspace,this.getAnchorLocation(),this.getBubbleOwnerRect()),this.textInputBubble.setText(this.getText()),this.textInputBubble.setSize(this.bubbleSize,!0)}hideBubble(){let e;(e=this.textInputBubble)==null||e.dispose(),this.textInputBubble=null}getAnchorLocation(){const e=np/2;return ye.sum(this.workspaceLocation,new ye(e,e))}getBubbleOwnerRect(){return this.sourceBlock.getBoundingRectangleWithoutChildren()}};_o.TYPE=Ct.COMMENT,_o.WEIGHT=3,Ed(_o.TYPE,_o);var Iv=class extends Error{constructor(e){super(`Tried to append an icon of type ${e.getType()} when an icon of that type already exists on the block. Use getIcon to access the existing icon.`),this.icon=e}},xv={};xv.DuplicateIconType=Iv;var Dv=class extends nt{constructor(e,t,o,n){super(t,o,n),this.text=e,this.workspace=t,this.anchor=o,this.ownerRect=n,this.paragraph=this.stringToSvg(e,this.contentContainer),this.updateBubbleSize()}getText(){return this.text}setText(e){this.text=e,Qe(this.paragraph),this.paragraph=this.stringToSvg(e,this.contentContainer),this.updateBubbleSize()}stringToSvg(e,t){return t=this.createParagraph(t),e=this.createTextFragments(t,e),this.workspace.RTL&&this.rightAlignTextFragments(t.getBBox().width,e),t}createParagraph(e){return ie(J.G,{class:"blocklyText blocklyBubbleText blocklyNoPointerEvents",transform:`translate(0,${nt.BORDER_WIDTH})`,style:`direction: ${this.workspace.RTL?"rtl":"ltr"}`},e)}createTextFragments(e,t){let o=1;return t.split(` +`).map(n=>{const u=ie(J.TEXT,{y:`${o}em`,x:nt.BORDER_WIDTH},e);return n=document.createTextNode(n),u.appendChild(n),o+=1,u})}rightAlignTextFragments(e,t){for(const o of t)o.setAttribute("text-anchor","start"),o.setAttribute("x",`${e+nt.BORDER_WIDTH}`)}updateBubbleSize(){const e=this.paragraph.getBBox();this.setSize(new Ze(e.width+2*nt.BORDER_WIDTH,e.height+2*nt.BORDER_WIDTH),!0)}},rp=17,wo=class extends Rl{constructor(e){super(e),this.sourceBlock=e,this.textMap=new Map,this.textBubble=null}getType(){return wo.TYPE}initView(e){this.svgRoot||(super.initView(e),ie(J.PATH,{class:"blocklyIconShape",d:"M2,15Q-1,15 0.5,12L6.5,1.7Q8,-1 9.5,1.7L15.5,12Q17,15 14,15z"},this.svgRoot),ie(J.PATH,{class:"blocklyIconSymbol",d:"m7,4.8v3.16l0.27,2.27h1.46l0.27,-2.27v-3.16z"},this.svgRoot),ie(J.RECT,{class:"blocklyIconSymbol",x:"7",y:"11",height:"2",width:"2"},this.svgRoot),Oe(this.svgRoot,"blockly-icon-warning"))}dispose(){super.dispose();let e;(e=this.textBubble)==null||e.dispose()}getWeight(){return wo.WEIGHT}getSize(){return new Ze(rp,rp)}applyColour(){super.applyColour();let e;(e=this.textBubble)==null||e.setColour(this.sourceBlock.getColour())}updateCollapsed(){}isShownWhenCollapsed(){return!0}onLocationChange(e){super.onLocationChange(e);let t;(t=this.textBubble)==null||t.setAnchorLocation(this.getAnchorLocation())}addMessage(e,t){if(this.textMap.get(t)===e)return this;e?this.textMap.set(t,e):this.textMap.delete(t);let o;return(o=this.textBubble)==null||o.setText(this.getText()),this}getText(){return[...this.textMap.values()].join(` +`)}onClick(){super.onClick(),this.setBubbleVisible(!this.bubbleIsVisible())}isClickableInFlyout(){return!1}bubbleIsVisible(){return!!this.textBubble}setBubbleVisible(e){const t=this;return ge.asyncExecutePromiseGeneratorFunction(function*(){if(t.bubbleIsVisible()!==e){if(yield Ts(),e)t.textBubble=new Dv(t.getText(),t.sourceBlock.workspace,t.getAnchorLocation(),t.getBubbleOwnerRect()),t.applyColour();else{let o;(o=t.textBubble)==null||o.dispose(),t.textBubble=null}z(new(ne(ee.BUBBLE_OPEN))(t.sourceBlock,e,"warning"))}})}getAnchorLocation(){const e=rp/2;return ye.sum(this.workspaceLocation,new ye(e,e))}getBubbleOwnerRect(){const e=this.sourceBlock.getSvgRoot().getBBox();return new rt(e.y,e.y+e.height,e.x,e.x+e.width)}};wo.TYPE=Ct.WARNING,wo.WEIGHT=2;var Fo={};Fo.CommentIcon=_o,Fo.Icon=Rl,Fo.IconType=Ct,Fo.MutatorIcon=i.MutatorIcon$$module$build$src$core$icons$mutator_icon,Fo.WarningIcon=wo,Fo.exceptions=xv,Fo.registry=ip,i.Names$$module$build$src$core$names=class{constructor(e,t){this.db=new Map,this.dbReverse=new Set,this.variableMap=null,this.variablePrefix=t||"",this.reservedWords=new Set(e?e.split(","):[])}reset(){this.db.clear(),this.dbReverse.clear(),this.variableMap=null}setVariableMap(e){this.variableMap=e}getNameForUserVariable(e){return this.variableMap?(e=this.variableMap.getVariableById(e))?e.name:null:(console.warn(`Deprecated call to Names.prototype.getName without defining a variable map. To fix, add the following code in your generator's init() function: +Blockly.YourGeneratorName.nameDB_.setVariableMap(workspace.getVariableMap());`),null)}populateVariables(e){e=i.allUsedVarModels$$module$build$src$core$variables(e);for(let t=0;trect,`,`${e} .blocklyEditableText>rect {`,`fill: ${this.FIELD_BORDER_RECT_COLOUR};`,"fill-opacity: .6;","stroke: none;","}",`${e} .blocklyNonEditableText>text,`,`${e} .blocklyEditableText>text {`,"fill: #000;","}",`${e} .blocklyFlyoutLabelText {`,"fill: #000;","}",`${e} .blocklyText.blocklyBubbleText {`,"fill: #000;","}",`${e} .blocklyEditableText:not(.editing):hover>rect {`,"stroke: #fff;","stroke-width: 2;","}",`${e} .blocklyHtmlInput {`,`font-family: ${this.FIELD_TEXT_FONTFAMILY};`,`font-weight: ${this.FIELD_TEXT_FONTWEIGHT};`,"}",`${e} .blocklySelected>.blocklyPath {`,"stroke: #fc3;","stroke-width: 3px;","}",`${e} .blocklyHighlightedConnectionPath {`,"stroke: #fc3;","}",`${e} .blocklyReplaceable .blocklyPath {`,"fill-opacity: .5;","}",`${e} .blocklyReplaceable .blocklyPathLight,`,`${e} .blocklyReplaceable .blocklyPathDark {`,"display: none;","}",`${e} .blocklyInsertionMarker>.blocklyPath {`,`fill-opacity: ${this.INSERTION_MARKER_OPACITY};`,"stroke: none;","}"]}},jl=class{constructor(e,t){this.inlinePath_=this.outlinePath_="",this.block_=e,this.info_=t,this.topLeft_=e.getRelativeToSurfaceXY(),this.constants_=t.getRenderer().getConstants()}draw(){this.drawOutline_(),this.drawInternals_(),this.updateConnectionHighlights(),this.block_.pathObject.setPath(this.outlinePath_+` +`+this.inlinePath_),this.info_.RTL&&this.block_.pathObject.flipRTL(),this.recordSizeOnBlock_()}recordSizeOnBlock_(){this.block_.height=this.info_.height,this.block_.width=this.info_.widthWithChildren,this.block_.childlessWidth=this.info_.width}drawOutline_(){this.drawTop_();for(let e=1;ee||e>this.fieldRow.length)throw Error("index "+e+" out of bounds.");return(t||t===""&&o)&&(typeof t=="string"&&(t=i.fromJson$$module$build$src$core$field_registry({type:"field_label",text:t})),t.setSourceBlock(this.sourceBlock),this.sourceBlock.initialized&&this.initField(t),t.name=o,t.setVisible(this.isVisible()),t.prefixField&&(e=this.insertFieldAt(e,t.prefixField)),this.fieldRow.splice(e,0,t),e++,t.suffixField&&(e=this.insertFieldAt(e,t.suffixField)),this.sourceBlock.rendered&&this.sourceBlock.queueRender()),e}removeField(e,t){for(let o=0,n;n=this.fieldRow[o];o++)if(n.name===e)return n.dispose(),this.fieldRow.splice(o,1),this.sourceBlock.rendered&&this.sourceBlock.queueRender(),!0;if(t)return!1;throw Error('Field "'+e+'" not found.')}isVisible(){return this.visible}setVisible(e){let t=[];if(this.visible===e)return t;this.visible=e;for(let n=0,u;u=this.fieldRow[n];n++)u.setVisible(e);if(this.connection){var o=this.connection;e?t=o.startTrackingAll():o.stopTrackingAll(),(o=o.targetBlock())&&(o.getSvgRoot().style.display=e?"block":"none")}return t}markDirty(){for(let e=0,t;t=this.fieldRow[e];e++)t.markDirty()}setCheck(e){if(!this.connection)throw Error("This input does not have a connection.");return this.connection.setCheck(e),this}setAlign(e){return this.align=e,this.sourceBlock.rendered&&this.sourceBlock.queueRender(),this}setShadowDom(e){if(!this.connection)throw Error("This input does not have a connection.");return this.connection.setShadowDom(e),this}getShadowDom(){if(!this.connection)throw Error("This input does not have a connection.");return this.connection.getShadowDom()}init(){for(const e of this.fieldRow)e.init()}initModel(){for(const e of this.fieldRow)e.initModel()}initField(e){this.sourceBlock.rendered?e.init():e.initModel()}dispose(){for(let e=0,t;t=this.fieldRow[e];e++)t.dispose();this.connection&&this.connection.dispose()}makeConnection(e){return this.sourceBlock.makeConnection_(e)}},Ys=class extends pn{constructor(e,t){super(e,t),this.name=e,this.type=i.inputTypes$$module$build$src$core$inputs$input_types.DUMMY}},Co=class extends pn{constructor(e,t){super(e,t),this.name=e,this.type=i.inputTypes$$module$build$src$core$inputs$input_types.END_ROW}},ls=class extends pn{constructor(e,t){if(!e)throw Error("Statement inputs must have a non-empty name");super(e,t),this.name=e,this.type=i.inputTypes$$module$build$src$core$inputs$input_types.STATEMENT,this.connection=this.makeConnection(xe.NEXT_STATEMENT)}},Pv;i.ValueInput$$module$build$src$core$inputs$value_input=class extends pn{constructor(e,t){if(!e)throw Error("Value inputs must have a non-empty name");super(e,t),this.name=e,this.type=i.inputTypes$$module$build$src$core$inputs$input_types.VALUE,this.connection=this.makeConnection(xe.INPUT_VALUE)}},Pv={},Pv.ValueInput=i.ValueInput$$module$build$src$core$inputs$value_input;var Or=class{constructor(e,t){this.statementEdge=this.width=this.widthWithChildren=this.height=0,this.rows=[],this.inputRows=[],this.startY=this.startX=0,this.renderer_=e,this.block_=t,this.constants_=this.renderer_.getConstants(),this.outputConnection=t.outputConnection?new Nv(this.constants_,t.outputConnection):null,this.isInline=t.getInputsInline()&&!t.isCollapsed(),this.isCollapsed=t.isCollapsed(),this.isInsertionMarker=t.isInsertionMarker(),this.RTL=t.RTL,this.topRow=new hp(this.constants_),this.bottomRow=new ap(this.constants_)}getRenderer(){return this.renderer_}measure(){this.createRows_(),this.addElemSpacing_(),this.addRowSpacing_(),this.computeBounds_(),this.alignRowElements_(),this.finalize_()}createRows_(){this.populateTopRow_(),this.rows.push(this.topRow);let e=new up(this.constants_);this.inputRows.push(e);var t=this.block_.getIcons();for(let o=0,n;n=t[o];o++){const u=new Ov(this.constants_,n);this.isCollapsed&&!n.isShownWhenCollapsed()||e.elements.push(u)}t=void 0;for(let o=0,n;n=this.block_.inputList[o];o++)if(n.isVisible()){this.shouldStartNewRow_(n,t)&&(this.rows.push(e),e=new up(this.constants_),this.inputRows.push(e));for(let u=0,g;g=n.fieldRow[u];u++)e.elements.push(new hn(this.constants_,g,n));this.addInput_(n,e),t=n}this.isCollapsed&&(e.hasJaggedEdge=!0,e.elements.push(new Rv(this.constants_))),(e.elements.length||e.hasDummyInput)&&this.rows.push(e),this.populateBottomRow_(),this.rows.push(this.bottomRow)}populateTopRow_(){var e=!!this.block_.previousConnection;const t=(this.block_.hat?this.block_.hat==="cap":this.constants_.ADD_START_HATS)&&!this.outputConnection&&!e;let o=this.topRow.hasLeftSquareCorner(this.block_)?Ar:Dr;this.topRow.elements.push(new o(this.constants_)),t?(e=new lp(this.constants_),this.topRow.elements.push(e),this.topRow.capline=e.ascenderHeight):e&&(this.topRow.hasPreviousConnection=!0,this.topRow.connection=new Lv(this.constants_,this.block_.previousConnection),this.topRow.elements.push(this.topRow.connection)),this.block_.inputList.length&&this.block_.inputList[0]instanceof ls&&!this.block_.isCollapsed()?this.topRow.minHeight=this.constants_.TOP_ROW_PRECEDES_STATEMENT_MIN_HEIGHT:this.topRow.minHeight=this.constants_.TOP_ROW_MIN_HEIGHT,o=this.topRow.hasRightSquareCorner(this.block_)?Ar:Dr,this.topRow.elements.push(new o(this.constants_,"right"))}populateBottomRow_(){this.bottomRow.hasNextConnection=!!this.block_.nextConnection,this.bottomRow.minHeight=this.block_.inputList.length&&this.block_.inputList[this.block_.inputList.length-1]instanceof ls?this.constants_.BOTTOM_ROW_AFTER_STATEMENT_MIN_HEIGHT:this.constants_.BOTTOM_ROW_MIN_HEIGHT,this.bottomRow.hasLeftSquareCorner(this.block_)?this.bottomRow.elements.push(new Ar(this.constants_)):this.bottomRow.elements.push(new Dr(this.constants_)),this.bottomRow.hasNextConnection&&(this.bottomRow.connection=new Mv(this.constants_,this.block_.nextConnection),this.bottomRow.elements.push(this.bottomRow.connection)),this.bottomRow.hasRightSquareCorner(this.block_)?this.bottomRow.elements.push(new Ar(this.constants_,"right")):this.bottomRow.elements.push(new Dr(this.constants_,"right"))}addInput_(e,t){this.isInline&&e instanceof i.ValueInput$$module$build$src$core$inputs$value_input?(t.elements.push(new cp(this.constants_,e)),t.hasInlineInput=!0):e instanceof ls?(t.elements.push(new xr(this.constants_,e)),t.hasStatement=!0):e instanceof i.ValueInput$$module$build$src$core$inputs$value_input?(t.elements.push(new Pl(this.constants_,e)),t.hasExternalInput=!0):(e instanceof Ys||e instanceof Co)&&(t.minHeight=Math.max(t.minHeight,e.getSourceBlock()&&e.getSourceBlock().isShadow()?this.constants_.DUMMY_INPUT_SHADOW_MIN_HEIGHT:this.constants_.DUMMY_INPUT_MIN_HEIGHT),t.hasDummyInput=!0),t.align===null&&(t.align=e.align)}shouldStartNewRow_(e,t){return t?t instanceof Co||e instanceof ls||t instanceof ls?!0:e instanceof i.ValueInput$$module$build$src$core$inputs$value_input||e instanceof Ys||t instanceof i.ValueInput$$module$build$src$core$inputs$value_input?!this.isInline:!1:!1}addElemSpacing_(){for(let e=0,t;t=this.rows[e];e++){const o=t.elements;if(t.elements=[],t.startsWithElemSpacer()&&t.elements.push(new as(this.constants_,this.getInRowSpacing_(null,o[0]))),o.length){for(let n=0;ne.disposeInternal()),this.inputList.forEach(e=>e.dispose()),this.inputList.length=0,this.getConnections_(!0).forEach(e=>e.dispose()),this.disposed=!0}isDeadOrDying(){return this.disposing||this.disposed}initModel(){if(!this.initialized){for(const e of this.inputList)e.initModel();this.initialized=!0}}unplug(e){this.outputConnection&&this.unplugFromRow(e),this.previousConnection&&this.unplugFromStack(e)}unplugFromRow(e){let t=null,o;(o=this.outputConnection)!=null&&o.isConnected()&&(t=this.outputConnection.targetConnection,this.outputConnection.disconnect()),t&&e&&(e=this.getOnlyValueConnection())&&e.isConnected()&&!e.targetBlock().isShadow()&&(e=e.targetConnection,e==null||e.disconnect(),this.workspace.connectionChecker.canConnect(e,t,!1)?t.connect(e):e==null||e.onFailedConnect(t))}getOnlyValueConnection(){let e=null;for(let t=0;t(n=n+(o==="("||u===")"?"":" ")+u,o=u[u.length-1],n),""),t=t.trim()||"???",e&&t.length>e&&(t=t.substring(0,e-3)+"..."),t}toTokens(e="?"){const t=[];for(const n of this.inputList)if(n.name!=$r){for(const u of n.fieldRow)t.push(u.getText());if(n.connection){const u=n.connection.targetBlock();if(u){var o=n.connection;let g=o.getCheck();!g&&o.targetConnection&&(g=o.targetConnection.getCheck()),(o=!!g&&(g.includes("Boolean")||g.includes("Number")))&&t.push("("),t.push(...u.toTokens(e)),o&&t.push(")")}else t.push(e)}}return t}appendValueInput(e){return this.appendInput(new i.ValueInput$$module$build$src$core$inputs$value_input(e,this))}appendStatementInput(e){return this.statementInputCount++,this.appendInput(new ls(e,this))}appendDummyInput(e=""){return this.appendInput(new Ys(e,this))}appendEndRowInput(e=""){return this.appendInput(new Co(e,this))}appendInput(e){return this.inputList.push(e),e}appendInputFromRegistry(e,t){return(e=p($e.INPUT,e,!1))?this.appendInput(new e(t,this)):null}jsonInit(e){var t=e.type?'Block "'+e.type+'": ':"";if(e.output&&e.previousStatement)throw Error(t+"Must not have both an output and a previousStatement.");for(var o=0;e["args"+o];){if(e["message"+o]===void 0)throw Error(t+`args${o} must have a corresponding message (message${o}).`);o++}if(e.style&&e.style.hat&&(this.hat=e.style.hat,e.style=null),e.style&&e.colour)throw Error(t+"Must not have both a colour and a style.");for(e.style?this.jsonInitStyle(e,t):this.jsonInitColour(e,t),o=0;e["message"+o]!==void 0;)this.interpolate(e["message"+o],e["args"+o]||[],e["implicitAlign"+o]||e["lastDummyAlign"+o],t),o++;if(e.inputsInline!==void 0&&(i.disable$$module$build$src$core$events$utils(),this.setInputsInline(e.inputsInline),i.enable$$module$build$src$core$events$utils()),e.output!==void 0&&this.setOutput(!0,e.output),e.outputShape!==void 0&&this.setOutputShape(e.outputShape),e.previousStatement!==void 0&&this.setPreviousStatement(!0,e.previousStatement),e.nextStatement!==void 0&&this.setNextStatement(!0,e.nextStatement),e.tooltip!==void 0&&(o=bt(e.tooltip),this.setTooltip(o)),e.enableContextMenu!==void 0&&(this.contextMenu=!!e.enableContextMenu),e.suppressPrefixSuffix!==void 0&&(this.suppressPrefixSuffix=!!e.suppressPrefixSuffix),e.helpUrl!==void 0&&(o=bt(e.helpUrl),this.setHelpUrl(o)),typeof e.extensions=="string"&&(console.warn(t+"JSON attribute 'extensions' should be an array of strings. Found raw string in JSON for '"+e.type+"' block."),e.extensions=[e.extensions]),e.mutator!==void 0&&Ya(e.mutator,this,!0),e=e.extensions,Array.isArray(e))for(t=0;tg||g>t)throw Error('Block "'+this.type+'": Message index %'+g+" out of range.");if(o[g])throw Error('Block "'+this.type+'": Message index %'+g+" duplicated.");o[g]=!0,n++}}if(n!==t)throw Error('Block "'+this.type+'": Message does not reference all '+t+" arg(s).")}interpolateArguments(e,t,o){const n=[];for(let g=0;g=this.inputList.length)throw RangeError("Input index "+e+" out of bounds.");if(t>this.inputList.length)throw RangeError("Reference input "+t+" out of bounds.");const o=this.inputList[e];this.inputList.splice(e,1),et.getWeight()-o.getWeight()),e}removeIcon(e){if(!this.hasIcon(e))return!1;let t;return(t=this.getIcon(e))==null||t.dispose(),this.icons=this.icons.filter(o=>!o.getType().equals(e)),!0}hasIcon(e){return this.icons.some(t=>t.getType().equals(e))}getIcon(e){return e instanceof Ct?this.icons.find(t=>t.getType().equals(e)):this.icons.find(t=>t.getType().toString()===e)}getIcons(){return[...this.icons]}getRelativeToSurfaceXY(){return this.xy}moveBy(e,t,o){if(this.parentBlock_)throw Error("Block has parent");const n=new(ne(ee.BLOCK_MOVE))(this);o&&n.setReason(o),this.xy.translate(e,t),n.recordNew(),z(n)}makeConnection_(e){return new et(this,e)}allInputsFilled(e){if(e===void 0&&(e=!0),!e&&this.isShadow())return!1;for(let o=0,n;n=this.inputList[o];o++)if(n.connection){var t=n.connection.targetBlock();if(!t||!t.allInputsFilled(e))return!1}return(t=this.getNextBlock())?t.allInputsFilled(e):!0}toDevString(){let e=this.type?'"'+this.type+'" block':"Block";return this.id&&(e+=' (id="'+this.id+'")'),e}};Uo.COLLAPSED_INPUT_NAME=$r,Uo.COLLAPSED_FIELD_NAME=ml;var ms=class{constructor(e,t,o,n){this.workspace=e,this.targetWorkspace=t,this.isFlyoutLabel=n,this.onMouseUpWrapper=null,this.height=this.width=0,this.cursorSvg=this.svgText=this.svgGroup=null,this.text=o.text,this.position=new ye(0,0),this.callbackKey=o.callbackKey||o.callbackkey,this.cssClass=o["web-class"]||null,this.info=o}createDom(){var e=this.isFlyoutLabel?"blocklyFlyoutLabel":"blocklyFlyoutButton";this.cssClass&&(e+=" "+this.cssClass),this.svgGroup=ie(J.G,{class:e},this.workspace.getCanvas());let t;this.isFlyoutLabel||(t=ie(J.RECT,{class:"blocklyFlyoutButtonShadow",rx:ms.BORDER_RADIUS,ry:ms.BORDER_RADIUS,x:1,y:1},this.svgGroup)),e=ie(J.RECT,{class:this.isFlyoutLabel?"blocklyFlyoutLabelBackground":"blocklyFlyoutButtonBackground",rx:ms.BORDER_RADIUS,ry:ms.BORDER_RADIUS},this.svgGroup);const o=ie(J.TEXT,{class:this.isFlyoutLabel?"blocklyFlyoutLabelText":"blocklyText",x:0,y:0,"text-anchor":"middle"},this.svgGroup);var n=bt(this.text);this.workspace.RTL&&(n+="‏"),o.textContent=n,this.isFlyoutLabel&&(this.svgText=o,this.workspace.getThemeManager().subscribe(this.svgText,"flyoutForegroundColour","fill"));const u=js(o,"fontSize"),g=js(o,"fontWeight"),I=js(o,"fontFamily");if(this.width=Bs(o,u,g,I),n=ro(n,u,g,I),this.height=n.height,!this.isFlyoutLabel){this.width+=2*ms.TEXT_MARGIN_X,this.height+=2*ms.TEXT_MARGIN_Y;let P;(P=t)==null||P.setAttribute("width",String(this.width));let le;(le=t)==null||le.setAttribute("height",String(this.height))}return e.setAttribute("width",String(this.width)),e.setAttribute("height",String(this.height)),o.setAttribute("x",String(this.width/2)),o.setAttribute("y",String(this.height/2-n.height/2+n.baseline)),this.updateTransform(),this.onMouseUpWrapper=W(this.svgGroup,"pointerup",this,this.onMouseUp),this.svgGroup}show(){this.updateTransform(),this.svgGroup.setAttribute("display","block")}updateTransform(){this.svgGroup.setAttribute("transform","translate("+this.position.x+","+this.position.y+")")}moveTo(e,t){this.position.x=e,this.position.y=t,this.updateTransform()}isLabel(){return this.isFlyoutLabel}getPosition(){return this.position}getButtonText(){return this.text}getTargetWorkspace(){return this.targetWorkspace}getWorkspace(){return this.workspace}dispose(){this.onMouseUpWrapper&&V(this.onMouseUpWrapper),this.svgGroup&&Qe(this.svgGroup),this.svgText&&this.workspace.getThemeManager().unsubscribe(this.svgText)}setCursorSvg(e){e?this.svgGroup&&(this.svgGroup.appendChild(e),this.cursorSvg=e):this.cursorSvg=null}setMarkerSvg(){throw Error("Attempted to set a marker on a button.")}onMouseUp(e){(e=this.targetWorkspace.getGesture(e))&&e.cancel(),this.isFlyoutLabel&&this.callbackKey?console.warn("Labels should not have callbacks. Label text: "+this.text):this.isFlyoutLabel||this.callbackKey&&this.targetWorkspace.getButtonCallback(this.callbackKey)?this.isFlyoutLabel||(e=this.targetWorkspace.getButtonCallback(this.callbackKey))&&e(this):console.warn("Buttons should have callbacks. Button text: "+this.text)}};ms.TEXT_MARGIN_X=5,ms.TEXT_MARGIN_Y=2,ms.BORDER_RADIUS=4,Be(` .blocklyFlyoutButton { fill: #888; cursor: default; @@ -882,16 +882,16 @@ Blockly.YourGeneratorName.nameDB_.setVariableMap(workspace.getVariableMap());`), .blocklyFlyoutLabelBackground { opacity: 0; } -`);var de=class{constructor(e,t,o){if(this.wsCoordinate=null,!t)throw Error("Cannot create a node without a location.");this.type=e,this.isConnectionLocation=de.isConnectionType(e),this.location=t,this.processParams(o||null)}processParams(e){e&&e.wsCoordinate&&(this.wsCoordinate=e.wsCoordinate)}getLocation(){return this.location}getType(){return this.type}getWsCoordinate(){return this.wsCoordinate}isConnection(){return this.isConnectionLocation}findNextForInput(){var e=this.location.getParentInput();const t=e.getSourceBlock();for(e=t.inputList.indexOf(e),e+=1;et instanceof Uo&&u.block===t||t instanceof ms&&u.button===t);return 0>n?null:(o=o?n+1:n-1,o===-1||o===e.length?null:e[o])}findTopASTNodeForBlock(e){const t=rr(e);return t?de.createConnectionNode(t):de.createBlockNode(e)}getOutAstNodeForBlock(e){if(!e)return null;e=e.getTopStackBlock();const t=rr(e);return t&&t.targetConnection&&t.targetConnection.getParentInput()?de.createInputNode(t.targetConnection.getParentInput()):de.createStackNode(e)}findFirstFieldOrInput(e){e=e.inputList;for(let t=0;t{Ga(o.getSourceBlock()),setTimeout(()=>{n.bringToFront()},0)})}}update(e,t){const o=this.getCandidate(e);((this.wouldDeleteBlock=this.shouldDelete(!!o,t))||this.shouldUpdatePreviews(o,e))&&(i.disable$$module$build$src$core$events$utils(),this.maybeHidePreview(o),this.maybeShowPreview(o),i.enable$$module$build$src$core$events$utils())}createMarkerBlock(e){i.disable$$module$build$src$core$events$utils();let t;try{const o=os(e,{addCoordinates:!1,addInputBlocks:!1,addNextBlocks:!1,doFullSerialization:!1});if(!o)throw Error(`Failed to serialize source block. ${e.toDevString()}`);t=lo(o,this.workspace);for(const n of t.getDescendants(!1))n.setInsertionMarker(!0);t.initSvg(),t.getSvgRoot().setAttribute("visibility","hidden")}finally{i.enable$$module$build$src$core$events$utils()}return t}initAvailableConnections(){const e=this.topBlock.getConnections_(!1),t=this.topBlock.lastConnectionInStack(!0);return t&&t!==this.topBlock.nextConnection&&(e.push(t),this.lastOnStack=t),e}shouldUpdatePreviews(e,t){if(!e)return!!this.activeCandidate;if(!this.activeCandidate)return!0;const{local:o,closest:n}=this.activeCandidate;if(n===e.closest&&o===e.local)return!1;const u=o.x+t.x-n.x;return t=o.y+t.y-n.y,e.radius{let le;(le=n)==null||le.positionNearConnection(L,g,I);let Ee;(Ee=n)==null||Ee.getSvgRoot().setAttribute("visibility","visible")}),this.markerConnection=u}hideInsertionMarker(){if(this.markerConnection){var e=this.markerConnection,t=e.getSourceBlock(),o=t.outputConnection,n;if((n=t.previousConnection)!=null&&n.targetConnection||o!=null&&o.targetConnection)t.unplug(!0);else{let u;(u=e.targetBlock())==null||u.unplug(!1)}if(e.targetConnection)throw Error("markerConnection still connected at the end of disconnectInsertionMarker");this.markerConnection=null,(e=t.getSvgRoot())&&e.setAttribute("visibility","hidden")}}showInsertionInputOutline(e){e=e.closest,this.highlightedBlock=e.getSourceBlock(),this.highlightedBlock.highlightShapeForInput(e,!0)}hideInsertionInputOutline(){if(this.highlightedBlock){if(!this.activeCandidate)throw Error("Cannot hide the insertion marker outline because there is no active candidate");this.highlightedBlock.highlightShapeForInput(this.activeCandidate.closest,!1),this.highlightedBlock=null}}showReplacementFade(e){if(this.fadedBlock=e.closest.targetBlock(),!this.fadedBlock)throw Error("Cannot show the replacement fade because the closest connection does not have a target block");this.fadedBlock.fadeForReplacement(!0)}hideReplacementFade(){this.fadedBlock&&(this.fadedBlock.fadeForReplacement(!1),this.fadedBlock=null)}getInsertionMarkers(){const e=[];return this.firstMarker&&e.push(this.firstMarker),this.lastMarker&&e.push(this.lastMarker),e}disposeInsertionMarker(e){if(e){i.disable$$module$build$src$core$events$utils();try{e.dispose()}finally{i.enable$$module$build$src$core$events$utils()}}}};(function(e){e=e.PREVIEW_TYPE||(e.PREVIEW_TYPE={}),e[e.INSERTION_MARKER=0]="INSERTION_MARKER",e[e.INPUT_OUTLINE=1]="INPUT_OUTLINE",e[e.REPLACEMENT_FADE=2]="REPLACEMENT_FADE"})(fs||(fs={})),fs.PREVIEW_TYPE;var Fl=class{constructor(e){this.overrides=null,this.name=e}getClassName(){return this.name+"-renderer"}init(e,t){this.constants_=this.makeConstants_(),t&&(this.overrides=t,Object.assign(this.constants_,t)),this.constants_.setTheme(e),this.constants_.init()}createDom(e,t){this.constants_.createDom(e,this.name+"-"+t.name,"."+this.getClassName()+"."+t.getClassName())}refreshDom(e,t){const o=this.getConstants();o.dispose(),this.constants_=this.makeConstants_(),this.overrides&&Object.assign(this.constants_,this.overrides),this.constants_.randomIdentifier=o.randomIdentifier,this.constants_.setTheme(t),this.constants_.init(),this.createDom(e,t)}dispose(){this.constants_&&this.constants_.dispose()}makeConstants_(){return new Pl}makeRenderInfo_(e){return new Rr(this,e)}makeDrawer_(e,t){return new Bl(e,t)}makeMarkerDrawer(e,t){return new gp(e,this.getConstants(),t)}makePathObject(e,t){return new jl(e,t,this.constants_)}getConstants(){return this.constants_}shouldHighlightConnection(e){return!0}orphanCanConnectAtEnd(e,t,o){return!!Qe.getConnectionForOrphanedConnection(e,o===xe.OUTPUT_VALUE?t.outputConnection:t.previousConnection)}getConnectionPreviewMethod(e,t,o){return w("getConnectionPreviewMethod","v10","v12","an IConnectionPreviewer, if it fulfills your use case."),t.type===xe.OUTPUT_VALUE||t.type===xe.PREVIOUS_STATEMENT?!e.isConnected()||this.orphanCanConnectAtEnd(o,e.targetBlock(),t.type)?fs.PREVIEW_TYPE.INSERTION_MARKER:fs.PREVIEW_TYPE.REPLACEMENT_FADE:fs.PREVIEW_TYPE.INSERTION_MARKER}render(e){const t=this.makeRenderInfo_(e);t.measure(),this.makeDrawer_(e,t).draw()}},ot={};ot.BottomRow=rp,ot.Connection=ko,ot.ConstantProvider=Pl,ot.Drawer=Bl,ot.ExternalValueInput=Ll,ot.Field=hn,ot.Hat=ap,ot.Icon=Dv,ot.InRowSpacer=as,ot.InlineInput=lp,ot.InputConnection=zo,ot.InputRow=cp,ot.JaggedEdge=Av,ot.MarkerSvg=gp,ot.Measurable=Vs,ot.NextConnection=Rv,ot.OutputConnection=Ov,ot.PathObject=jl,ot.PreviousConnection=Nv,ot.RenderInfo=Rr,ot.Renderer=Fl,ot.RoundCorner=Dr,ot.Row=Ir,ot.SpacerRow=up,ot.SquareCorner=Ar,ot.StatementInput=xr,ot.TopRow=dp,ot.Types=j,ot.init=Od,ot.register=ar,ot.unregister=H$;var Lv=class{constructor(e,t){this.workspace=e,this.theme=t,this.subscribedWorkspaces=[],this.componentDB=new Map}getTheme(){return this.theme}setTheme(e){var t=this.theme;this.theme=e,(e=this.workspace.getInjectionDiv())&&(t&&(t=t.getClassName())&&ze(e,t),(t=this.theme.getClassName())&&Re(e,t));for(let o=0,n;n=this.subscribedWorkspaces[o];o++)n.refreshTheme();for(const[o,n]of this.componentDB)for(const u of n){e=u.element,t=u.propertyName;const g=this.theme&&this.theme.getComponentStyle(o);e.style.setProperty(t,g||"")}for(const o of this.subscribedWorkspaces)o.hideChaff()}subscribeWorkspace(e){this.subscribedWorkspaces.push(e)}unsubscribeWorkspace(e){if(!He(this.subscribedWorkspaces,e))throw Error("Cannot unsubscribe a workspace that hasn't been subscribed.")}subscribe(e,t,o){this.componentDB.has(t)||this.componentDB.set(t,[]),this.componentDB.get(t).push({element:e,propertyName:o}),t=this.theme&&this.theme.getComponentStyle(t),e.style.setProperty(o,t||"")}unsubscribe(e){if(e)for(const[t,o]of this.componentDB){for(let n=o.length-1;0<=n;n--)o[n].element===e&&o.splice(n,1);o.length||this.componentDB.delete(t)}}dispose(){this.subscribedWorkspaces.length=0,this.componentDB.clear()}},mp="VARIABLE_DYNAMIC",wi={CATEGORY_NAME:mp};wi.flyoutCategory=Qa,wi.flyoutCategoryBlocks=Pd,wi.onCreateVariableButtonClick_Colour=Ld,wi.onCreateVariableButtonClick_Number=Md,wi.onCreateVariableButtonClick_String=Nd;var Pv=30,ki=[];ki[xe.INPUT_VALUE]=xe.OUTPUT_VALUE,ki[xe.OUTPUT_VALUE]=xe.INPUT_VALUE,ki[xe.NEXT_STATEMENT]=xe.PREVIOUS_STATEMENT,ki[xe.PREVIOUS_STATEMENT]=xe.NEXT_STATEMENT;var fp="RENAME_VARIABLE_ID",$p="DELETE_VARIABLE_ID",Bv=class{canConnect(e,t,o,n){return this.canConnectWithReason(e,t,o,n)===Qe.CAN_CONNECT}canConnectWithReason(e,t,o,n){const u=this.doSafetyChecks(e,t);return u!==Qe.CAN_CONNECT?u:this.doTypeChecks(e,t)?o&&!this.doDragChecks(e,t,n||0)?Qe.REASON_DRAG_CHECKS_FAILED:Qe.CAN_CONNECT:Qe.REASON_CHECKS_FAILED}getErrorMessage(e,t,o){switch(e){case Qe.REASON_SELF_CONNECTION:return"Attempted to connect a block to itself.";case Qe.REASON_DIFFERENT_WORKSPACES:return"Blocks not on same workspace.";case Qe.REASON_WRONG_TYPE:return"Attempt to connect incompatible types.";case Qe.REASON_TARGET_NULL:return"Target connection is null.";case Qe.REASON_CHECKS_FAILED:return"Connection checks failed. "+(t+" expected "+t.getCheck()+", found "+o.getCheck());case Qe.REASON_SHADOW_PARENT:return"Connecting non-shadow to shadow block.";case Qe.REASON_DRAG_CHECKS_FAILED:return"Drag checks failed.";case Qe.REASON_PREVIOUS_AND_OUTPUT:return"Block would have an output and a previous connection.";default:return"Unknown connection failure: this should never happen!"}}doSafetyChecks(e,t){if(!e||!t)return Qe.REASON_TARGET_NULL;let o,n,u;return e.isSuperior()?(o=e.getSourceBlock(),n=t.getSourceBlock(),u=t):(n=e.getSourceBlock(),o=t.getSourceBlock(),u=e,e=t),o===n?Qe.REASON_SELF_CONNECTION:u.type!==ki[e.type]?Qe.REASON_WRONG_TYPE:o.workspace!==n.workspace?Qe.REASON_DIFFERENT_WORKSPACES:o.isShadow()&&!n.isShadow()?Qe.REASON_SHADOW_PARENT:u.type===xe.OUTPUT_VALUE&&n.previousConnection&&n.previousConnection.isConnected()||u.type===xe.PREVIOUS_STATEMENT&&n.outputConnection&&n.outputConnection.isConnected()?Qe.REASON_PREVIOUS_AND_OUTPUT:Qe.CAN_CONNECT}doTypeChecks(e,t){if(e=e.getCheck(),t=t.getCheck(),!e||!t)return!0;for(let o=0;oo||t.getSourceBlock().isInsertionMarker())return!1;switch(t.type){case xe.PREVIOUS_STATEMENT:return this.canConnectToPrevious_(e,t);case xe.OUTPUT_VALUE:if(t.isConnected()&&!t.targetBlock().isInsertionMarker()||e.isConnected())return!1;break;case xe.INPUT_VALUE:if(t.isConnected()&&!t.targetBlock().isMovable()&&!t.targetBlock().isShadow())return!1;break;case xe.NEXT_STATEMENT:if(t.isConnected()&&!e.getSourceBlock().nextConnection&&!t.targetBlock().isShadow()&&t.targetBlock().nextConnection||t.targetBlock()&&!t.targetBlock().isMovable()&&!t.targetBlock().isShadow())return!1;break;default:return!1}return!hr.includes(t)}canConnectToPrevious_(e,t){return e.targetConnection||hr.includes(t)?!1:t.targetConnection?(e=t.targetBlock(),e.isInsertionMarker()?!e.getPreviousBlock():!1):!0}};r($e.CONNECTION_CHECKER,Ws,Bv);var bp=class extends br{constructor(e){super(e),this.type=ee.VAR_DELETE,e&&(this.varType=e.type,this.varName=e.name)}toJson(){const e=super.toJson();if(this.varType===void 0)throw Error("The var type is undefined. Either pass a variable to the constructor, or call fromJson");if(!this.varName)throw Error("The var name is undefined. Either pass a variable to the constructor, or call fromJson");return e.varType=this.varType,e.varName=this.varName,e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new bp),t.varType=e.varType,t.varName=e.varName,t}run(e){const t=this.getEventWorkspace_();if(!this.varId)throw Error("The var ID is undefined. Either pass a variable to the constructor, or call fromJson");if(!this.varName)throw Error("The var name is undefined. Either pass a variable to the constructor, or call fromJson");e?t.deleteVariableById(this.varId):t.createVariable(this.varName,this.varType,this.varId)}};r($e.EVENT,ee.VAR_DELETE,bp);var vp=class extends br{constructor(e,t){super(e),this.type=ee.VAR_RENAME,e&&(this.oldName=e.name,this.newName=typeof t>"u"?"":t)}toJson(){const e=super.toJson();if(!this.oldName)throw Error("The old var name is undefined. Either pass a variable to the constructor, or call fromJson");if(!this.newName)throw Error("The new var name is undefined. Either pass a value to the constructor, or call fromJson");return e.oldName=this.oldName,e.newName=this.newName,e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new vp),t.oldName=e.oldName,t.newName=e.newName,t}run(e){const t=this.getEventWorkspace_();if(!this.varId)throw Error("The var ID is undefined. Either pass a variable to the constructor, or call fromJson");if(!this.oldName)throw Error("The old var name is undefined. Either pass a variable to the constructor, or call fromJson");if(!this.newName)throw Error("The new var name is undefined. Either pass a value to the constructor, or call fromJson");e?t.renameVariableById(this.varId,this.newName):t.renameVariableById(this.varId,this.oldName)}};r($e.EVENT,ee.VAR_RENAME,vp);var yp=class{constructor(e){this.workspace=e,this.variableMap=new Map}clear(){for(const e of this.variableMap.values())for(;0{u&&t&&this.deleteVariableInternal(t,n)})):this.deleteVariableInternal(t,n)}else console.warn("Can't delete non-existent variable: "+e)}deleteVariableInternal(e,t){const o=i.getGroup$$module$build$src$core$events$utils();o||i.setGroup$$module$build$src$core$events$utils(!0);try{for(let n=0;ne.name)}getVariableUsesById(e){const t=[],o=this.workspace.getAllBlocks(!1);for(let n=0;n!o.isInsertionMarker())):[]}addTopComment(e){this.topComments.push(e),this.commentDB.has(e.id)&&console.warn('Overriding an existing comment on this workspace, with id "'+e.id+'"'),this.commentDB.set(e.id,e)}removeTopComment(e){if(!He(this.topComments,e))throw Error("Comment not present in workspace's list of top-most comments.");this.commentDB.delete(e.id)}getTopComments(e=!1){const t=[].concat(this.topComments);return e&&1!o.isInsertionMarker())}clear(){this.isClearing=!0;try{const e=i.getGroup$$module$build$src$core$events$utils();for(e||i.setGroup$$module$build$src$core$events$utils(!0);this.topBlocks.length;)this.topBlocks[0].dispose(!1);for(;this.topComments.length;)this.topComments[this.topComments.length-1].dispose();i.setGroup$$module$build$src$core$events$utils(e),this.variableMap.clear(),this.potentialVariableMap&&this.potentialVariableMap.clear()}finally{this.isClearing=!1}}renameVariableById(e,t){this.variableMap.renameVariableById(e,t)}createVariable(e,t,o){return this.variableMap.createVariable(e,t,o)}getVariableUsesById(e){return this.variableMap.getVariableUsesById(e)}deleteVariableById(e){this.variableMap.deleteVariableById(e)}getVariable(e,t){return this.variableMap.getVariable(e,t)}getVariableById(e){return this.variableMap.getVariableById(e)}getVariablesOfType(e){return this.variableMap.getVariablesOfType(e)}getVariableTypes(){return this.variableMap.getVariableTypes(this)}getAllVariables(){return this.variableMap.getAllVariables()}getAllVariableNames(){return this.variableMap.getAllVariableNames()}getWidth(){return 0}newBlock(e,t){throw Error("The implementation of newBlock should be monkey-patched in by blockly.ts")}newComment(e){throw Error("The implementation of newComment should be monkey-patched in by blockly.ts")}remainingCapacity(){return isNaN(this.options.maxBlocks)?1/0:this.options.maxBlocks-this.getAllBlocks(!1).length}remainingCapacityOfType(e){return this.options.maxInstances?(this.options.maxInstances[e]!==void 0?this.options.maxInstances[e]:1/0)-this.getBlocksByType(e,!1).length:1/0}isCapacityAvailable(e){if(!this.hasBlockLimits())return!0;let t=0;for(const o in e){if(e[o]>this.remainingCapacityOfType(o))return!1;t+=e[o]}return!(t>this.remainingCapacity())}hasBlockLimits(){return this.options.maxBlocks!==1/0||!!this.options.maxInstances}getUndoStack(){return this.undoStack_}getRedoStack(){return this.redoStack_}undo(e){var t=e?this.redoStack_:this.undoStack_,o=e?this.undoStack_:this.redoStack_;const n=t.pop();if(n){for(var u=[n];t.length&&n.group&&n.group===t[t.length-1].group;){const g=t.pop();g&&u.push(g)}for(t=0;tthis.MAX_UNDO&&0<=this.MAX_UNDO;)this.undoStack_.shift();for(let t=0;t!!t.getStyleName())),this.refreshToolboxSelection(),this.toolbox&&this.toolbox.refreshTheme(),this.isVisible()&&this.setVisible(!0);const e=new(ne(ee.THEME_CHANGE))(this.getTheme().name,this.id);z(e)}updateBlockStyles(e){for(let t=0,o;o=e[t];t++){const n=o.getStyleName();n&&o.setStyle(n)}}getInverseScreenCTM(){if(this.inverseScreenCTMDirty){const e=this.getParentSvg().getScreenCTM();e&&(this.inverseScreenCTM=e.inverse(),this.inverseScreenCTMDirty=!1)}return this.inverseScreenCTM}updateInverseScreenCTM(){this.inverseScreenCTMDirty=!0}isVisible(){return this.visible}getSvgXY(e){let t=0,o=0,n=1;(this.getCanvas().contains(e)||this.getBubbleCanvas().contains(e))&&(n=this.scale);do{const u=Wn(e);(e===this.getCanvas()||e===this.getBubbleCanvas())&&(n=1),t+=u.x*n,o+=u.y*n,e=e.parentNode}while(e&&e!==this.getParentSvg()&&e!==this.getInjectionDiv());return new ye(t,o)}getCachedParentSvgSize(){const e=this.cachedParentSvgSize;return new Xe(e.width,e.height)}getOriginOffsetInPixels(){return fa(this.getCanvas())}getInjectionDiv(){if(!this.injectionDiv){let e=this.svgGroup_;for(;e;){if((" "+(e.getAttribute("class")||"")+" ").includes(" injectionDiv ")){this.injectionDiv=e;break}e=e.parentNode}}return this.injectionDiv}getSvgGroup(){return this.svgGroup_}getBlockCanvas(){return this.getCanvas()}setResizeHandlerWrapper(e){this.resizeHandlerWrapper=e}createDom(e,t){return this.injectionDiv||(this.injectionDiv=t??null),this.svgGroup_=ie(J.G,{class:"blocklyWorkspace"}),e&&(this.svgBackground_=ie(J.RECT,{height:"100%",width:"100%",class:e},this.svgGroup_),e==="blocklyMainBackground"&&this.grid?this.svgBackground_.style.fill="url(#"+this.grid.getPatternId()+")":this.themeManager_.subscribe(this.svgBackground_,"workspaceBackgroundColour","fill")),this.layerManager=new qC(this),this.svgBlockCanvas_=this.layerManager.getBlockLayer(),this.svgBubbleCanvas_=this.layerManager.getBubbleLayer(),this.isFlyout||(H(this.svgGroup_,"pointerdown",this,this.onMouseDown,!1),this.dummyWheelListener=()=>{},document.body.addEventListener("wheel",this.dummyWheelListener),H(this.svgGroup_,"wheel",this,this.onMouseWheel)),this.options.hasCategories&&(this.toolbox=new(y($e.TOOLBOX,this.options,!0))(this)),this.grid&&this.grid.update(this.scale),this.recordDragTargets(),(e=y($e.CURSOR,this.options))&&this.markerManager.setCursor(new e),this.renderer.createDom(this.svgGroup_,this.getTheme()),this.svgGroup_}dispose(){if(this.rendered=!1,this.currentGesture_&&this.currentGesture_.cancel(),this.svgGroup_&&Ze(this.svgGroup_),this.toolbox&&(this.toolbox.dispose(),this.toolbox=null),this.flyout&&(this.flyout.dispose(),this.flyout=null),this.trashcan&&(this.trashcan.dispose(),this.trashcan=null),this.scrollbar&&(this.scrollbar.dispose(),this.scrollbar=null),this.zoomControls_&&this.zoomControls_.dispose(),this.audioManager&&this.audioManager.dispose(),this.grid&&(this.grid=null),this.renderer.dispose(),this.markerManager&&this.markerManager.dispose(),super.dispose(),this.themeManager_&&(this.themeManager_.unsubscribeWorkspace(this),this.themeManager_.unsubscribe(this.svgBackground_),this.options.parentWorkspace||this.themeManager_.dispose()),this.connectionDBList.length=0,this.toolboxCategoryCallbacks.clear(),this.flyoutButtonCallbacks.clear(),!this.options.parentWorkspace){const e=this.getParentSvg();e&&e.parentNode&&Ze(e.parentNode)}this.resizeHandlerWrapper&&(V(this.resizeHandlerWrapper),this.resizeHandlerWrapper=null),this.dummyWheelListener&&(document.body.removeEventListener("wheel",this.dummyWheelListener),this.dummyWheelListener=null)}addTrashcan(){this.trashcan=cs.newTrashcan(this);const e=this.trashcan.createDom();this.svgGroup_.insertBefore(e,this.getCanvas())}static newTrashcan(e){throw Error("The implementation of newTrashcan should be monkey-patched in by blockly.ts")}addZoomControls(){this.zoomControls_=new Hb(this);const e=this.zoomControls_.createDom();this.svgGroup_.appendChild(e)}addFlyout(e){const t=new gs({parentWorkspace:this,rtl:this.RTL,oneBasedIndex:this.options.oneBasedIndex,horizontalLayout:this.horizontalLayout,renderer:this.options.renderer,rendererOverrides:this.options.rendererOverrides,move:{scrollbars:!0}});return t.toolboxPosition=this.options.toolboxPosition,this.flyout=this.horizontalLayout?new(y($e.FLYOUTS_HORIZONTAL_TOOLBOX,this.options,!0))(t):new(y($e.FLYOUTS_VERTICAL_TOOLBOX,this.options,!0))(t),this.flyout.autoClose=!1,this.flyout.getWorkspace().setVisible(!0),this.flyout.createDom(e)}getFlyout(e){return this.flyout||e?this.flyout:this.toolbox?this.toolbox.getFlyout():null}getToolbox(){return this.toolbox}updateScreenCalculations(){this.updateInverseScreenCTM(),this.recordDragTargets()}resizeContents(){this.resizesEnabled&&this.rendered&&(this.scrollbar&&this.scrollbar.resize(),this.updateInverseScreenCTM())}resize(){this.toolbox&&this.toolbox.position(),this.flyout&&this.flyout.position();const e=this.componentManager.getComponents(gt.Capability.POSITIONABLE,!0),t=this.getMetricsManager().getUiMetrics(),o=[];for(let n=0,u;u=e[n];n++){u.position(t,o);const g=u.getBoundingRectangle();g&&o.push(g)}this.scrollbar&&this.scrollbar.resize(),this.updateScreenCalculations()}updateScreenCalculationsIfScrolled(){const e=bu();ye.equals(this.lastRecordedPageScroll,e)||(this.lastRecordedPageScroll=e,this.updateScreenCalculations())}getLayerManager(){return this.layerManager}getCanvas(){return this.layerManager.getBlockLayer()}setCachedParentSvgSize(e,t){const o=this.getParentSvg();e!=null&&(this.cachedParentSvgSize.width=e,o.setAttribute("data-cached-width",`${e}`)),t!=null&&(this.cachedParentSvgSize.height=t,o.setAttribute("data-cached-height",`${t}`))}getBubbleCanvas(){return this.layerManager.getBubbleLayer()}getParentSvg(){if(!this.cachedParentSvg){let e=this.svgGroup_;for(;e;){if(e.tagName==="svg"){this.cachedParentSvg=e;break}e=e.parentNode}}return this.cachedParentSvg}maybeFireViewportChangeEvent(){if(C()){var e=this.scale,t=-this.scrollY,o=-this.scrollX;if(!(e===this.oldScale&&1>Math.abs(t-this.oldTop)&&1>Math.abs(o-this.oldLeft))){var n=new(ne(ee.VIEWPORT_CHANGE))(t,o,e,this.id,this.oldScale);this.oldScale=e,this.oldTop=t,this.oldLeft=o,z(n)}}}translate(e,t){let o;(o=this.layerManager)==null||o.translateLayers(new ye(e,t),this.scale);let n;(n=this.grid)==null||n.moveTo(e,t),this.maybeFireViewportChangeEvent()}getWidth(){const e=this.getMetrics();return e?e.viewWidth/this.scale:0}setVisible(e){this.visible=e,this.svgGroup_&&(this.scrollbar&&this.scrollbar.setContainerVisible(e),this.getFlyout()&&this.getFlyout().setContainerVisible(e),this.getParentSvg().style.display=e?"block":"none",this.toolbox&&this.toolbox.setVisible(e),e||this.hideChaff(!0))}render(){const e=this.getAllBlocks(!1);for(let t=e.length-1;0<=t;t--)e[t].queueRender();this.getTopBlocks().flatMap(t=>t.getDescendants(!1)).filter(t=>t.isInsertionMarker()).forEach(t=>t.queueRender()),Ts().then(()=>{this.markerManager.updateMarkers()})}highlightBlock(e,t){if(t===void 0){for(let o=0,n;n=this.highlightedBlocks[o];o++)n.setHighlighted(!1);this.highlightedBlocks.length=0}(e=e?this.getBlockById(e):null)&&((t=t===void 0||t)?this.highlightedBlocks.includes(e)||this.highlightedBlocks.push(e):He(this.highlightedBlocks,e),e.setHighlighted(t))}refreshToolboxSelection(){const e=this.isFlyout?this.targetWorkspace:this;e&&!e.currentGesture_&&e.toolbox&&e.toolbox.getFlyout()&&e.toolbox.refreshSelection()}renameVariableById(e,t){super.renameVariableById(e,t),this.refreshToolboxSelection()}deleteVariableById(e){super.deleteVariableById(e),this.refreshToolboxSelection()}createVariable(e,t,o){return e=super.createVariable(e,t,o),this.refreshToolboxSelection(),e}recordDragTargets(){const e=this.componentManager.getComponents(gt.Capability.DRAG_TARGET,!0);this.dragTargetAreas=[];for(let t=0,o;o=e[t];t++){const n=o.getClientRect();n&&this.dragTargetAreas.push({component:o,clientRect:n})}}newBlock(e,t){throw Error("The implementation of newBlock should be monkey-patched in by blockly.ts")}newComment(e){throw Error("The implementation of newComment should be monkey-patched in by blockly.ts")}getDragTarget(e){for(let t=0,o;o=this.dragTargetAreas[t];t++)if(o.clientRect.contains(e.clientX,e.clientY))return o.component;return null}onMouseDown(e){const t=this.getGesture(e);t&&t.handleWsStart(e,this)}startDrag(e,t){za(this,e,t)}moveDrag(e){return Ua(this,e)}isDragging(){return this.currentGesture_!==null&&this.currentGesture_.isDragging()}isDraggable(){return this.options.moveOptions&&this.options.moveOptions.drag}isMovable(){return this.options.moveOptions&&!!this.options.moveOptions.scrollbars||this.options.moveOptions&&this.options.moveOptions.wheel||this.options.moveOptions&&this.options.moveOptions.drag||this.options.zoomOptions&&this.options.zoomOptions.wheel||this.options.zoomOptions&&this.options.zoomOptions.pinch}isMovableHorizontally(){const e=!!this.scrollbar;return this.isMovable()&&(!e||e&&this.scrollbar.canScrollHorizontally())}isMovableVertically(){const e=!!this.scrollbar;return this.isMovable()&&(!e||e&&this.scrollbar.canScrollVertically())}onMouseWheel(e){if(bo.inProgress())e.preventDefault(),e.stopPropagation();else{var t=this.options.zoomOptions&&this.options.zoomOptions.wheel,o=this.options.moveOptions&&this.options.moveOptions.wheel;if(t||o){var n=Le(e);if(kh)var u=e.metaKey;t&&(e.ctrlKey||u||!o)?(n=-n.y/50,t=fe(e,this.getParentSvg(),this.getInverseScreenCTM()),this.zoom(t.x,t.y,n)):(t=this.scrollX-n.x,o=this.scrollY-n.y,e.shiftKey&&!n.x&&(t=this.scrollX-n.y,o=this.scrollY),this.scroll(t,o)),e.preventDefault()}}}getBlocksBoundingBox(){const e=this.getTopBoundedElements();if(!e.length)return new rt(0,0,0,0);const t=e[0].getBoundingRectangle();for(let n=1;nt.bottom&&(t.bottom=o.bottom),o.leftt.right&&(t.right=o.right))}return t}cleanUp(){this.setResizesEnabled(!1),i.setGroup$$module$build$src$core$events$utils(!0);var e=this.getTopBlocks(!0),t=e.filter(g=>g.isMovable());const o=e.filter(g=>!g.isMovable()).map(g=>g.getBoundingRectangle());e=function(g){for(const I of o)if(g.intersects(I))return I;return null};var n=0;const u=this.renderer.getConstants().MIN_BLOCK_HEIGHT;for(const g of t){for(t=g.getBoundingRectangle(),g.moveBy(-t.left,n-t.top,["cleanup"]),g.snapToGrid(),t=g.getBoundingRectangle(),n=e(t);n!=null;)n=n.top+n.getHeight()+u,g.moveBy(0,n-t.top,["cleanup"]),g.snapToGrid(),t=g.getBoundingRectangle(),n=e(t);n=g.getRelativeToSurfaceXY().y+g.getHeightWidth().height+u}i.setGroup$$module$build$src$core$events$utils(!1),this.setResizesEnabled(!0)}showContextMenu(e){if(!this.options.readOnly&&!this.isFlyout){var t=Ke.registry.getContextMenuOptions(Ke.ScopeType.WORKSPACE,{workspace:this});this.configureContextMenu&&this.configureContextMenu(t,e),sr(e,t,this.RTL,this)}}updateToolbox(e){if(e=$a(e)){if(!this.options.languageTree)throw Error("Existing toolbox is null. Can't create new toolbox.");if(ba(e)){if(!this.toolbox)throw Error("Existing toolbox has no categories. Can't change mode.");this.options.languageTree=e,this.toolbox.render(e)}else{if(!this.flyout)throw Error("Existing toolbox has categories. Can't change mode.");this.options.languageTree=e,this.flyout.show(e)}}else if(this.options.languageTree)throw Error("Can't nullify an existing toolbox.")}markFocused(){this.options.parentWorkspace?this.options.parentWorkspace.markFocused():(se(this),this.getParentSvg().focus({preventScroll:!0}))}zoom(e,t,o){o=Math.pow(this.options.zoomOptions.scaleSpeed,o);const n=this.scale*o;if(this.scale!==n){n>this.options.zoomOptions.maxScale?o=this.options.zoomOptions.maxScale/this.scale:nthis.options.zoomOptions.maxScale?e=this.options.zoomOptions.maxScale:this.options.zoomOptions.minScale&&et.autoHide(e))}static setTopLevelWorkspaceMetrics(e){const t=this.getMetrics();typeof e.x=="number"&&(this.scrollX=-(t.scrollLeft+(t.scrollWidth-t.viewWidth)*e.x)),typeof e.y=="number"&&(this.scrollY=-(t.scrollTop+(t.scrollHeight-t.viewHeight)*e.y)),this.translate(this.scrollX+t.absoluteLeft,this.scrollY+t.absoluteTop)}},_p=class extends Ss{constructor(e,t,o){super(o),this.type=ee.SELECTED,this.oldElementId=e??void 0,this.newElementId=t??void 0}toJson(){const e=super.toJson();return e.oldElementId=this.oldElementId,e.newElementId=this.newElementId,e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new _p),t.oldElementId=e.oldElementId,t.newElementId=e.newElementId,t}};r($e.EVENT,ee.SELECTED,_p);var Or=class{paste(e,t,o){if(!t.isCapacityAvailable(e.typeCounts))return null;o&&(e.blockState.x=o.x,e.blockState.y=o.y),o=o||new ye(e.blockState.x||0,e.blockState.y||0),i.disable$$module$build$src$core$events$utils();let n;try{n=lo(e.blockState,t),W$(n,o)}finally{i.enable$$module$build$src$core$events$utils()}return n&&(C()&&!n.isShadow()&&z(new(ne(ee.BLOCK_CREATE))(n)),i.setSelected$$module$build$src$core$common(n),n)}};Or.TYPE="block",Ca(Or.TYPE,new Or);var zl={};zl.bumpIntoBounds=Ji,zl.bumpIntoBoundsHandler=Bd,zl.bumpTopObjectsIntoBounds=el;var Fv=class{constructor(e){this.block=e,this.connectionPreviewer=this.connectionCandidate=this.startLoc=this.startChildConn=this.startParentConn=null,this.dragging=!1,this.dragOffset=new ye(0,0),this.inGroup=!1,this.workspace=e.workspace}isMovable(){if(this.block.isShadow()){let e,t;return(t=(e=this.block.getParent())==null?void 0:e.isMovable())!=null?t:!1}return this.block.isOwnMovable()&&!this.block.isDeadOrDying()&&!this.workspace.options.readOnly&&!this.block.isInFlyout}startDrag(e){if(this.block.isShadow())this.startDraggingShadow(e);else{this.dragging=!0,(this.inGroup=!!i.getGroup$$module$build$src$core$events$utils())||i.setGroup$$module$build$src$core$events$utils(!0),this.fireDragStartEvent(),this.startLoc=this.block.getRelativeToSurfaceXY(),this.connectionCandidate=null,this.connectionPreviewer=new(y($e.CONNECTION_PREVIEWER,this.workspace.options))(this.block),io(),this.workspace.setResizesEnabled(!1),Ki(),e=!!e&&(e.altKey||e.ctrlKey||e.metaKey),this.shouldDisconnect(e)&&this.disconnectBlock(e),this.block.setDragging(!0);var t;(t=this.workspace.getLayerManager())==null||t.moveToDragLayer(this.block)}}startDraggingShadow(e){const t=this.block.getParent();if(!t)throw Error("Tried to drag a shadow block with no parent. Shadow blocks should always have parents.");this.dragOffset=ye.difference(t.getRelativeToSurfaceXY(),this.block.getRelativeToSurfaceXY()),t.startDrag(e)}shouldDisconnect(e){return!!(this.block.getParent()||e&&this.block.nextConnection&&this.block.nextConnection.targetBlock())}disconnectBlock(e){let t,o,n;if(this.startParentConn=(n=(t=this.block.outputConnection)==null?void 0:t.targetConnection)!=null?n:(o=this.block.previousConnection)==null?void 0:o.targetConnection,e){let u;this.startChildConn=(u=this.block.nextConnection)==null?void 0:u.targetConnection}this.block.unplug(e),_d(this.block)}fireDragStartEvent(){const e=new(ne(ee.BLOCK_DRAG))(this.block,!0,this.block.getDescendants(!1));z(e)}fireDragEndEvent(){const e=new(ne(ee.BLOCK_DRAG))(this.block,!1,this.block.getDescendants(!1));z(e)}fireMoveEvent(){if(!this.block.isDeadOrDying()){var e=new(ne(ee.BLOCK_MOVE))(this.block);e.setReason(["drag"]),e.oldCoordinate=this.startLoc,e.recordNew(),z(e)}}drag(e){if(this.block.isShadow()){let t;(t=this.block.getParent())==null||t.drag(ye.sum(e,this.dragOffset))}else this.block.moveDuringDrag(e),this.updateConnectionPreview(this.block,ye.difference(e,this.startLoc))}updateConnectionPreview(e,t){var o=this.connectionCandidate;const n=this.getConnectionCandidate(e,t);if(n){this.connectionCandidate=t=o&&this.currCandidateIsBetter(o,t,n)?o:n;var{local:u,neighbour:g}=t;t=u.type===xe.OUTPUT_VALUE||u.type===xe.PREVIOUS_STATEMENT,o=g.isConnected()&&!g.targetBlock().isInsertionMarker(),t&&o&&!this.orphanCanConnectAtEnd(e,g.targetBlock(),u.type)?this.connectionPreviewer.previewReplacement(u,g,g.targetBlock()):this.connectionPreviewer.previewConnection(u,g)}else this.connectionPreviewer.hidePreview(),this.connectionCandidate=null}orphanCanConnectAtEnd(e,t,o){return!!Qe.getConnectionForOrphanedConnection(e,o===xe.OUTPUT_VALUE?t.outputConnection:t.previousConnection)}currCandidateIsBetter(e,t,o){const{local:n,neighbour:u}=e;e=new ye(n.x,n.y);const g=new ye(u.x,u.y);return t=ye.distance(ye.sum(e,t),g),o.distance>t-i.config$$module$build$src$core$config.currentConnectionPreference}getConnectionCandidate(e,t){e=this.getLocalConnections(e);let o=this.connectionCandidate?i.config$$module$build$src$core$config.connectingSnapRadius:i.config$$module$build$src$core$config.snapRadius,n=null;for(const u of e){const{connection:g,radius:I}=u.closest(o,t);g&&(n={local:u,neighbour:g,distance:I},o=I)}return n}getLocalConnections(e){const t=e.getConnections_(!1),o=e.lastConnectionInStack(!0);return o&&o!==e.nextConnection&&t.push(o),t}endDrag(e){if(this.block.isShadow()){let t;(t=this.block.getParent())==null||t.endDrag(e)}else{if(this.fireDragEndEvent(),this.fireMoveEvent(),no(),Ki(),this.connectionPreviewer.hidePreview(),!this.block.isDeadOrDying()&&this.dragging){let t;(t=this.workspace.getLayerManager())==null||t.moveOffDragLayer(this.block,jo),this.block.setDragging(!1)}this.connectionCandidate?(this.applyConnections(this.connectionCandidate),this.disposeStep()):this.block.queueRender().then(()=>this.disposeStep()),this.inGroup||i.setGroup$$module$build$src$core$events$utils(!1)}}disposeStep(){this.block.snapToGrid(),this.connectionPreviewer.dispose(),this.workspace.setResizesEnabled(!0)}applyConnections(e){const{local:t,neighbour:o}=e;t.connect(o);const n=t.isSuperior()?o:t,u=this.block.getRootBlock();Ts().then(()=>{Ga(n.getSourceBlock()),setTimeout(()=>{u.bringToFront()},0)})}revertDrag(){if(this.block.isShadow()){let t;(t=this.block.getParent())==null||t.revertDrag()}else{var e;if((e=this.startChildConn)==null||e.connect(this.block.nextConnection),this.startParentConn)switch(this.startParentConn.type){case xe.INPUT_VALUE:this.startParentConn.connect(this.block.outputConnection);break;case xe.NEXT_STATEMENT:this.startParentConn.connect(this.block.previousConnection)}else{this.block.moveTo(this.startLoc,["drag"]);let t;(t=this.workspace.getLayerManager())==null||t.moveOffDragLayer(this.block,jo),Ji(this.workspace,this.workspace.getMetricsManager().getScrollMetrics(!0),this.block)}this.startParentConn=this.startChildConn=null,this.connectionPreviewer.hidePreview(),this.connectionCandidate=null,this.block.setDragging(!1),this.dragging=!1}}},zv=class{constructor(){this.drawer=this.curNode=this.colour=null,this.type="marker"}setDrawer(e){this.drawer=e}getDrawer(){return this.drawer}getCurNode(){return this.curNode}setCurNode(e){const t=this.curNode;this.curNode=e,this.drawer&&this.drawer.draw(t,this.curNode)}draw(){this.drawer&&this.drawer.draw(this.curNode,this.curNode)}hide(){this.drawer&&this.drawer.hide()}dispose(){this.getDrawer()&&this.getDrawer().dispose()}},wp=class extends zv{constructor(){super(),this.type="cursor"}next(){var e=this.getCurNode();if(!e)return null;for(e=e.next();e&&e.next()&&(e.getType()===de.types.NEXT||e.getType()===de.types.BLOCK);)e=e.next();return e&&this.setCurNode(e),e}in(){var e=this.getCurNode();if(!e)return null;(e.getType()===de.types.PREVIOUS||e.getType()===de.types.OUTPUT)&&(e=e.next());let t,o;return(e=(o=(t=e)==null?void 0:t.in())!=null?o:null)&&this.setCurNode(e),e}prev(){var e=this.getCurNode();if(!e)return null;for(e=e.prev();e&&e.prev()&&(e.getType()===de.types.NEXT||e.getType()===de.types.BLOCK);)e=e.prev();return e&&this.setCurNode(e),e}out(){var e=this.getCurNode();return e?((e=e.out())&&e.getType()===de.types.BLOCK&&(e=e.prev()||e),e&&this.setCurNode(e),e):null}};r($e.CURSOR,Ws,wp);var Nr=class extends wp{constructor(){super()}next(){var e=this.getCurNode();return e?((e=this.getNextNode_(e,this.validNode_))&&this.setCurNode(e),e):null}in(){return this.next()}prev(){var e=this.getCurNode();return e?((e=this.getPreviousNode_(e,this.validNode_))&&this.setCurNode(e),e):null}out(){return this.prev()}getNextNode_(e,t){if(!e)return null;const o=e.in()||e.next();return t(o)?o:o?this.getNextNode_(o,t):(e=this.findSiblingOrParent(e.out()),t(e)?e:e?this.getNextNode_(e,t):null)}getPreviousNode_(e,t){if(!e)return null;let o=e.prev();return o=o?this.getRightMostChild(o):e.out(),t(o)?o:o?this.getPreviousNode_(o,t):null}validNode_(e){let t=!1;return e=e&&e.getType(),(e===de.types.OUTPUT||e===de.types.INPUT||e===de.types.FIELD||e===de.types.NEXT||e===de.types.PREVIOUS||e===de.types.WORKSPACE)&&(t=!0),t}findSiblingOrParent(e){if(!e)return null;const t=e.next();return t||this.findSiblingOrParent(e.out())}getRightMostChild(e){if(!e.in())return e;for(e=e.in();e&&e.next();)e=e.next();return this.getRightMostChild(e)}};Nr.registrationName="basicCursor",r($e.CURSOR,Nr.registrationName,Nr);var Uv=class extends Nr{validNode_(e){let t=!1;const o=e&&e.getType();return e&&(e=e.getLocation(),o===de.types.FIELD&&e&&e.isTabNavigable()&&e.isClickable()&&(t=!0)),t}},Hv=10,Yt=class extends Qe{constructor(e,t){super(e,t),this.highlighted=!1,this.targetConnection=null,this.db=e.workspace.connectionDBList[t],this.dbOpposite=e.workspace.connectionDBList[ki[t]],this.offsetInBlock=new ye(0,0),this.trackedState=Yt.TrackedState.WILL_TRACK}dispose(){super.dispose(),this.trackedState===Yt.TrackedState.TRACKED&&this.db.removeConnection(this,this.y);let e,t;(t=(e=this.sourceBlock_.pathObject).removeConnectionHighlight)==null||t.call(e,this)}getSourceBlock(){return super.getSourceBlock()}targetBlock(){return super.targetBlock()}distanceFrom(e){const t=this.x-e.x;return e=this.y-e.y,Math.sqrt(t*t+e*e)}bumpAwayFrom(e,t=!1){if(!this.sourceBlock_.workspace.isDragging()){var o=i.config$$module$build$src$core$config.snapRadius+Math.floor(Math.random()*Hv),n=i.config$$module$build$src$core$config.snapRadius+Math.floor(Math.random()*Hv),u=e.sourceBlock_.getRootBlock(),g=this.sourceBlock_.getRootBlock();if(!u.isInFlyout&&!g.isInFlyout){var I=!0;if(g.isMovable())u.isMovable()&&t&&(n=-n);else if(u.isMovable())I=!1,o=-o,n=-n;else return;t=I?e:this,e=I?this:e,u=I?g:u,(g=F()===u)||u.addSelect(),u.RTL&&(o=-o),u.moveBy(t.x+o-e.x,t.y+n-e.y,["bump"]),g||u.removeSelect()}}}moveTo(e,t){let o=!1;return this.trackedState===Yt.TrackedState.WILL_TRACK?(this.db.addConnection(this,t),this.trackedState=Yt.TrackedState.TRACKED,o=!0):this.trackedState===Yt.TrackedState.TRACKED&&(this.db.removeConnection(this,this.y),this.db.addConnection(this,t),o=!0),this.x=e,this.y=t,o}moveBy(e,t){return this.moveTo(this.x+e,this.y+t)}moveToOffset(e){return this.moveTo(e.x+this.offsetInBlock.x,e.y+this.offsetInBlock.y)}setOffsetInBlock(e,t){this.offsetInBlock.x=e,this.offsetInBlock.y=t}getOffsetInBlock(){return this.offsetInBlock}tightenEfficiently(){var e=this.targetConnection;const t=this.targetBlock();e&&t&&(e=ye.difference(this.offsetInBlock,e.offsetInBlock),t.translate(e.x,e.y))}closest(e,t){return this.dbOpposite.searchForClosest(this,e,t)}highlight(){this.highlighted=!0,this.getSourceBlock().queueRender()}unhighlight(){this.highlighted=!1,this.getSourceBlock().queueRender()}isHighlighted(){return this.highlighted}setTracking(e){e&&this.trackedState===Yt.TrackedState.TRACKED||!e&&this.trackedState===Yt.TrackedState.UNTRACKED||this.sourceBlock_.isInFlyout||(e?(this.db.addConnection(this,this.y),this.trackedState=Yt.TrackedState.TRACKED):(this.trackedState===Yt.TrackedState.TRACKED&&this.db.removeConnection(this,this.y),this.trackedState=Yt.TrackedState.UNTRACKED))}stopTrackingAll(){if(this.setTracking(!1),this.targetConnection){const e=this.targetBlock().getDescendants(!1);for(let t=0;tclearTimeout(e)),this.warningTextDb.clear(),this.getIcons().forEach(e=>e.dispose())}checkAndDelete(){this.workspace.isFlyout||(i.setGroup$$module$build$src$core$events$utils(!0),this.workspace.hideChaff(),this.outputConnection?this.dispose(!1,!0):this.dispose(!0,!0),i.setGroup$$module$build$src$core$events$utils(!1))}toCopyData(){return this.isInsertionMarker_?null:{paster:Or.TYPE,blockState:os(this,{addCoordinates:!0,addNextBlocks:!1}),typeCounts:Ie(this,!0)}}applyColour(){this.pathObject.applyColour(this);const e=this.getIcons();for(let t=0;t{this.isDeadOrDying()||(this.warningTextDb.delete(t),this.setWarningText(e,t))},100));else if(this.isInFlyout&&(e=null),o=this.getIcon(wo.TYPE),e){let n=this.getSurroundParent(),u=null;for(;n;)n.isCollapsed()&&(u=n),n=n.getSurroundParent();u&&u.setWarningText(i.Msg$$module$build$src$core$msg.COLLAPSED_WARNINGS_WARNING,$s.COLLAPSED_WARNING_ID),o?o.addMessage(e,t):this.addIcon(new wo(this).addMessage(e,t))}else o&&(t?(o.addMessage("",t),o.getText()||this.removeIcon(wo.TYPE)):this.removeIcon(wo.TYPE))}setMutator(e){this.removeIcon(i.MutatorIcon$$module$build$src$core$icons$mutator_icon.TYPE),e&&this.addIcon(e)}addIcon(e){return super.addIcon(e),e instanceof i.MutatorIcon$$module$build$src$core$icons$mutator_icon&&(this.mutator=e),e.initView(this.createIconPointerDownListener(e)),e.applyColour(),e.updateEditable(),this.queueRender(),e}createIconPointerDownListener(e){return t=>{this.isDeadOrDying()||(t=this.workspace.getGesture(t))&&t.setStartIcon(e)}}removeIcon(e){const t=super.removeIcon(e);return e.equals(i.MutatorIcon$$module$build$src$core$icons$mutator_icon.TYPE)&&(this.mutator=null),this.queueRender(),t}setEnabled(e){w("setEnabled","v11","v12","the setDisabledReason method of BlockSvg");const t=this.isEnabled();super.setEnabled(e),this.isEnabled()===t||this.getInheritedDisabled()||this.updateDisabled()}setDisabledReason(e,t){const o=this.isEnabled();super.setDisabledReason(e,t),this.isEnabled()===o||this.getInheritedDisabled()||this.updateDisabled()}setHighlighted(e){this.pathObject.updateHighlighted(e)}addSelect(){this.pathObject.updateSelected(!0)}removeSelect(){this.pathObject.updateSelected(!1)}setDeleteStyle(e){this.pathObject.updateDraggingDelete(e)}getColour(){return this.style.colourPrimary}setColour(e){super.setColour(e),e=this.workspace.getRenderer().getConstants().getBlockStyleForColour(this.colour_),this.pathObject.setStyle(e.style),this.style=e.style,this.styleName_=e.name,this.applyColour()}setStyle(e){const t=this.workspace.getRenderer().getConstants().getBlockStyle(e);if(this.styleName_=e,t)this.hat=t.hat,this.pathObject.setStyle(t),this.colour_=t.colourPrimary,this.style=t,this.applyColour();else throw Error("Invalid style name: "+e)}getStyle(){return this.style}bringToFront(e=!1){let t=this;if(!t.isDeadOrDying())do{const o=t.getSvgRoot(),n=o.parentNode,u=n.childNodes;if(u[u.length-1]!==o&&n.appendChild(o),e)break;t=t.getParent()}while(t)}setPreviousStatement(e,t){super.setPreviousStatement(e,t),this.queueRender()}setNextStatement(e,t){super.setNextStatement(e,t),this.queueRender()}setOutput(e,t){super.setOutput(e,t),this.queueRender()}setInputsInline(e){super.setInputsInline(e),this.queueRender()}removeInput(e,t){return e=super.removeInput(e,t),this.queueRender(),e}moveNumberedInputBefore(e,t){super.moveNumberedInputBefore(e,t),this.queueRender()}appendInput(e){return super.appendInput(e),this.queueRender(),e}setConnectionTracking(e){if(this.previousConnection&&this.previousConnection.setTracking(e),this.outputConnection&&this.outputConnection.setTracking(e),this.nextConnection){this.nextConnection.setTracking(e);var t=this.nextConnection.targetBlock();t&&t.setConnectionTracking(e)}if(!this.collapsed_)for(t=0;t=this.workspace.options.maxTrashcanContents||(e=new gs({scrollbars:!0,parentWorkspace:this.workspace,rtl:this.workspace.RTL,oneBasedIndex:this.workspace.options.oneBasedIndex,renderer:this.workspace.options.renderer,rendererOverrides:this.workspace.options.rendererOverrides,move:{scrollbars:!0}}),this.workspace.horizontalLayout?(e.toolboxPosition=this.workspace.toolboxPosition===Ge.TOP?Ge.BOTTOM:Ge.TOP,this.flyout=new(y($e.FLYOUTS_HORIZONTAL_TOOLBOX,this.workspace.options,!0))(e)):(e.toolboxPosition=this.workspace.toolboxPosition===Ge.RIGHT?Ge.LEFT:Ge.RIGHT,this.flyout=new(y($e.FLYOUTS_VERTICAL_TOOLBOX,this.workspace.options,!0))(e)),this.workspace.addChangeListener(this.onDelete.bind(this)))}createDom(){this.svgGroup=ie(J.G,{class:"blocklyTrash"});let e;const t=String(Math.random()).substring(2);e=ie(J.CLIPPATH,{id:"blocklyTrashBodyClipPath"+t},this.svgGroup),ie(J.RECT,{width:mn,height:Hl,y:fn},e);const o=ie(J.IMAGE,{width:Gt.width,x:-Cp,height:Gt.height,y:-Tp,"clip-path":"url(#blocklyTrashBodyClipPath"+t+")"},this.svgGroup);return o.setAttributeNS(is,"xlink:href",this.workspace.options.pathToMedia+Gt.url),e=ie(J.CLIPPATH,{id:"blocklyTrashLidClipPath"+t},this.svgGroup),ie(J.RECT,{width:mn,height:fn},e),this.svgLid=ie(J.IMAGE,{width:Gt.width,x:-Cp,height:Gt.height,y:-Tp,"clip-path":"url(#blocklyTrashLidClipPath"+t+")"},this.svgGroup),this.svgLid.setAttributeNS(is,"xlink:href",this.workspace.options.pathToMedia+Gt.url),ue(this.svgGroup,"pointerdown",this,this.blockMouseDownWhenOpenable),ue(this.svgGroup,"pointerup",this,this.click),ue(o,"pointerover",this,this.mouseOver),ue(o,"pointerout",this,this.mouseOut),this.animateLid(),this.svgGroup}init(){0{let o;(o=this.flyout)==null||o.show(e),t.cursor="";let n;(n=this.workspace.scrollbar)==null||n.setVisible(!1)},10),this.fireUiEvent(!0)}}closeFlyout(){if(this.contentsIsOpen()){var e;(e=this.flyout)==null||e.hide();var t;(t=this.workspace.scrollbar)==null||t.setVisible(!0),this.fireUiEvent(!1),this.workspace.recordDragTargets()}}autoHide(e){!e&&this.flyout&&this.closeFlyout()}emptyContents(){this.hasContents()&&(this.contents.length=0,this.setMinOpenness(0),this.closeFlyout())}position(e,t){if(this.initialized){var o=wa(this.workspace,e);e=_a(o,new Xe(mn,Hl+fn),rT,Vv,e,this.workspace),t=ka(e,Vv,o.vertical===$o.TOP?Po.DOWN:Po.UP,t),this.top=t.top,this.left=t.left;var n;(n=this.svgGroup)==null||n.setAttribute("transform","translate("+this.left+","+this.top+")");var u;(u=this.flyout)==null||u.position()}}getBoundingRectangle(){return new rt(this.top,this.top+Hl+fn,this.left,this.left+mn)}getClientRect(){if(!this.svgGroup)return null;var e=this.svgGroup.getBoundingClientRect();const t=e.top+Tp-Wl;return e=e.left+Cp-Wl,new rt(t,t+fn+Hl+2*Wl,e,e+mn+2*Wl)}onDragOver(e){this.setLidOpen(this.wouldDelete_)}onDragExit(e){this.setLidOpen(!1)}onDrop(e){setTimeout(this.setLidOpen.bind(this,!1),100)}setLidOpen(e){this.isLidOpen!==e&&(this.lidTask&&clearTimeout(this.lidTask),this.isLidOpen=e,this.animateLid())}animateLid(){const e=cT;var t=1/(e+1);this.lidOpen+=this.isLidOpen?t:-t,this.lidOpen=Math.min(Math.max(this.lidOpen,this.minOpenness),1),this.setLidAngle(this.lidOpen*Yv),t=Kv+this.lidOpen*(uT-Kv),this.svgGroup&&(this.svgGroup.style.opacity=`${t}`),this.lidOpen>this.minOpenness&&1>this.lidOpen&&(this.lidTask=setTimeout(this.animateLid.bind(this),lT/e))}setLidAngle(e){const t=this.workspace.toolboxPosition===Ge.RIGHT||this.workspace.horizontalLayout&&this.workspace.RTL;let o;(o=this.svgLid)==null||o.setAttribute("transform","rotate("+(t?-e:e)+","+(t?4:mn-4)+","+(fn-2)+")")}setMinOpenness(e){this.minOpenness=e,this.isLidOpen||this.setLidAngle(e*Yv)}closeLid(){this.setLidOpen(!1)}click(){this.hasContents()&&!this.workspace.isDragging()&&this.openFlyout()}fireUiEvent(e){e=new(ne(ee.TRASHCAN_OPEN))(e,this.workspace.id),z(e)}blockMouseDownWhenOpenable(e){!this.contentsIsOpen()&&this.hasContents()&&e.stopPropagation()}mouseOver(){this.hasContents()&&this.setLidOpen(!0)}mouseOut(){this.setLidOpen(!1)}onDelete(e){if(!(0>=this.workspace.options.maxTrashcanContents||!S(e)||e.wasShadow)){if(!e.oldJson)throw Error("Encountered a delete event without proper oldJson");if(e=JSON.stringify(this.cleanBlockJson(e.oldJson)),!this.contents.includes(e)){for(this.contents.unshift(e);this.contents.length>this.workspace.options.maxTrashcanContents;)this.contents.pop();this.setMinOpenness(aT)}}}cleanBlockJson(e){function t(o){if(o){if(delete o.id,delete o.x,delete o.y,delete o.enabled,delete o.disabledReasons,o.icons&&o.icons.comment){var n=o.icons.comment;delete n.height,delete n.width,delete n.pinned}n=o.inputs;for(var u in n){var g=n[u];const I=g.block;g=g.shadow,I&&t(I),g&&t(g)}o.next&&(u=o.next,o=u.block,u=u.shadow,o&&t(o),u&&t(u))}}return e=JSON.parse(JSON.stringify(e)),t(e),Object.assign({},{kind:"BLOCK"},e)}},mn=47,Hl=44,fn=16,Vv=20,rT=20,Wl=10,Cp=0,Tp=32,aT=.1,lT=80,cT=4,Kv=.4,uT=.8,Yv=45,st=class{constructor(){this.shortcuts=new Map,this.keyMap=new Map,this.reset()}reset(){this.shortcuts.clear(),this.keyMap.clear()}register(e,t){if(this.shortcuts.get(e.name)&&!t)throw Error(`Shortcut named "${e.name}" already exists.`);if(this.shortcuts.set(e.name,e),t=e.keyCodes,t!=null&&t.length)for(const o of t)this.addKeyMapping(o,e.name,!!e.allowCollision)}unregister(e){return this.shortcuts.get(e)?(this.removeAllKeyMappings(e),this.shortcuts.delete(e),!0):(console.warn(`Keyboard shortcut named "${e}" not found.`),!1)}addKeyMapping(e,t,o){e=`${e}`;const n=this.keyMap.get(e);if(n&&!o)throw Error(`Shortcut named "${t}" collides with shortcuts "${n}"`);n&&o?n.unshift(t):this.keyMap.set(e,[t])}removeKeyMapping(e,t,o){const n=this.keyMap.get(e);if(!n)return o||console.warn(`No keyboard shortcut named "${t}" registered with key code "${e}"`),!1;const u=n.indexOf(t);return-1Yd(t)),e.length?e:null}load(e,t){const o=t.getProcedureMap();for(const n of e)o.add(Jd(this.procedureModelClass,this.parameterModelClass,n,t))}clear(e){e.getProcedureMap().clear()}},Gl={};Gl.ProcedureSerializer=hT,Gl.loadProcedure=Jd,Gl.saveProcedure=Yd;var Jv=class{constructor(){this.priority=Wb}save(e){const t=[];for(const o of e.getAllVariables())e={name:o.name,id:o.getId()},o.type&&(e.type=o.type),t.push(e);return t.length?t:null}load(e,t){for(const o of e)t.createVariable(o.name,o.type,o.id)}clear(e){e.getVariableMap().clear()}};Vn("variables",new Jv);var qv={};qv.VariableSerializer=Jv;var Ip={};Ip.load=X$,Ip.save=q$;var pT={blocks:_r,exceptions:pi,priorities:UC,procedures:Gl,registry:Dh,variables:qv,workspaceComments:hl,workspaces:Ip},xp=class{constructor(e,t,o,n,u){this.workspace=e,this.oldHostMetrics=this.corner_=this.vScroll=this.hScroll=null,t=t===void 0?!0:t,o=o===void 0?!0:o;const g=t&&o;t&&(this.hScroll=new yt(e,!0,g,n,u)),o&&(this.vScroll=new yt(e,!1,g,n,u)),g&&(this.corner_=ie(J.RECT,{height:yt.scrollbarThickness,width:yt.scrollbarThickness,class:"blocklyScrollbarBackground"}),At(this.corner_,e.getBubbleCanvas()))}dispose(){Ze(this.corner_),this.oldHostMetrics=this.corner_=null,this.hScroll&&(this.hScroll.dispose(),this.hScroll=null),this.vScroll&&(this.vScroll.dispose(),this.vScroll=null)}resize(){const e=this.workspace.getMetrics();if(e){var t=!1,o=!1;if(this.oldHostMetrics&&this.oldHostMetrics.viewWidth===e.viewWidth&&this.oldHostMetrics.viewHeight===e.viewHeight&&this.oldHostMetrics.absoluteTop===e.absoluteTop&&this.oldHostMetrics.absoluteLeft===e.absoluteLeft?(this.oldHostMetrics&&this.oldHostMetrics.scrollWidth===e.scrollWidth&&this.oldHostMetrics.viewLeft===e.viewLeft&&this.oldHostMetrics.scrollLeft===e.scrollLeft||(t=!0),this.oldHostMetrics&&this.oldHostMetrics.scrollHeight===e.scrollHeight&&this.oldHostMetrics.viewTop===e.viewTop&&this.oldHostMetrics.scrollTop===e.scrollTop||(o=!0)):o=t=!0,t||o){try{i.disable$$module$build$src$core$events$utils(),this.hScroll&&t&&this.hScroll.resize(e),this.vScroll&&o&&this.vScroll.resize(e)}finally{i.enable$$module$build$src$core$events$utils()}this.workspace.maybeFireViewportChangeEvent()}if(this.hScroll&&this.vScroll){if(!this.oldHostMetrics||this.oldHostMetrics.viewWidth!==e.viewWidth||this.oldHostMetrics.absoluteLeft!==e.absoluteLeft){let n;(n=this.corner_)==null||n.setAttribute("x",String(this.vScroll.position.x))}if(!this.oldHostMetrics||this.oldHostMetrics.viewHeight!==e.viewHeight||this.oldHostMetrics.absoluteTop!==e.absoluteTop){let n;(n=this.corner_)==null||n.setAttribute("y",String(this.hScroll.position.y))}}this.oldHostMetrics=e}}canScrollHorizontally(){return!!this.hScroll}canScrollVertically(){return!!this.vScroll}setOrigin(e,t){this.hScroll&&this.hScroll.setOrigin(e,t),this.vScroll&&this.vScroll.setOrigin(e,t)}set(e,t,o){this.hScroll&&this.hScroll.set(e,!1),this.vScroll&&this.vScroll.set(t,!1),(o||o===void 0)&&(e={},this.hScroll&&(e.x=this.hScroll.getRatio_()),this.vScroll&&(e.y=this.vScroll.getRatio_()),this.workspace.setMetrics(e))}setX(e){this.hScroll&&this.hScroll.set(e,!0)}setY(e){this.vScroll&&this.vScroll.set(e,!0)}setContainerVisible(e){this.hScroll&&this.hScroll.setContainerVisible(e),this.vScroll&&this.vScroll.setContainerVisible(e)}isVisible(){let e=!1;return this.hScroll&&(e=this.hScroll.isVisible()),this.vScroll&&(e=e||this.vScroll.isVisible()),e}setVisible(e){this.hScroll&&this.hScroll.setVisibleInternal(e),this.vScroll&&this.vScroll.setVisibleInternal(e)}resizeContent(e){this.hScroll&&this.hScroll.resizeContentHorizontal(e),this.vScroll&&this.vScroll.resizeContentVertical(e)}resizeView(e){this.hScroll&&this.hScroll.resizeViewHorizontal(e),this.vScroll&&this.vScroll.resizeViewVertical(e)}},Dp=class{constructor(e){this.workspace_=e}getDimensionsPx_(e){let t=0,o=0;return e&&(t=e.getWidth(),o=e.getHeight()),new Xe(t,o)}getFlyoutMetrics(e){return e=this.getDimensionsPx_(this.workspace_.getFlyout(e)),{width:e.width,height:e.height,position:this.workspace_.toolboxPosition}}getToolboxMetrics(){const e=this.getDimensionsPx_(this.workspace_.getToolbox());return{width:e.width,height:e.height,position:this.workspace_.toolboxPosition}}getSvgMetrics(){return this.workspace_.getCachedParentSvgSize()}getAbsoluteMetrics(){let e=0,t=0;const o=this.getToolboxMetrics(),n=this.getFlyoutMetrics(),u=!!this.workspace_.getToolbox();var g;const I=!((g=this.workspace_.getFlyout())!=null&&g.autoClose);g=u?o.position:n.position;const L=g===Ge.TOP;return g===Ge.LEFT&&(u&&(e+=o.width),I&&(e+=n.width)),L&&(u&&(t+=o.height),I&&(t+=n.height)),{top:t,left:e}}getViewMetrics(e){e=e?this.workspace_.scale:1;const t=this.getSvgMetrics(),o=this.getToolboxMetrics(),n=this.getFlyoutMetrics(),u=!!this.workspace_.getToolbox();var g;const I=!((g=this.workspace_.getFlyout())!=null&&g.autoClose);g=u?o.position:n.position;const L=g===Ge.LEFT||g===Ge.RIGHT;return(g===Ge.TOP||g===Ge.BOTTOM)&&(u&&(t.height-=o.height),I&&(t.height-=n.height)),L&&(u&&(t.width-=o.width),I&&(t.width-=n.width)),{height:t.height/e,width:t.width/e,top:-this.workspace_.scrollY/e,left:-this.workspace_.scrollX/e}}getContentMetrics(e){e=e?1:this.workspace_.scale;const t=this.workspace_.getBlocksBoundingBox();return{height:(t.bottom-t.top)*e,width:(t.right-t.left)*e,top:t.top*e,left:t.left*e}}hasFixedEdges(){return!this.workspace_.isMovableHorizontally()||!this.workspace_.isMovableVertically()}getComputedFixedEdges_(e){if(!this.hasFixedEdges())return{};const t=this.workspace_.isMovableHorizontally(),o=this.workspace_.isMovableVertically();e=e||this.getViewMetrics(!1);const n={};return o||(n.top=e.top,n.bottom=e.top+e.height),t||(n.left=e.left,n.right=e.left+e.width),n}getPaddedContent_(e,t){const o=t.top+t.height,n=t.left+t.width,u=e.width;e=e.height;const g=u/2,I=e/2;return{top:Math.min(t.top-I,o-e),bottom:Math.max(o+I,t.top+e),left:Math.min(t.left-g,n-u),right:Math.max(n+g,t.left+u)}}getScrollMetrics(e,t,o){e=e?this.workspace_.scale:1,t=t||this.getViewMetrics(!1);var n=o||this.getContentMetrics();o=this.getComputedFixedEdges_(t),t=this.getPaddedContent_(t,n),n=o.top!==void 0?o.top:t.top;const u=o.left!==void 0?o.left:t.left;return{top:n/e,left:u/e,width:((o.right!==void 0?o.right:t.right)-u)/e,height:((o.bottom!==void 0?o.bottom:t.bottom)-n)/e}}getUiMetrics(){return{viewMetrics:this.getViewMetrics(),absoluteMetrics:this.getAbsoluteMetrics(),toolboxMetrics:this.getToolboxMetrics()}}getMetrics(){const e=this.getToolboxMetrics(),t=this.getFlyoutMetrics(!0),o=this.getSvgMetrics(),n=this.getAbsoluteMetrics(),u=this.getViewMetrics(),g=this.getContentMetrics(),I=this.getScrollMetrics(!1,u,g);return{contentHeight:g.height,contentWidth:g.width,contentTop:g.top,contentLeft:g.left,scrollHeight:I.height,scrollWidth:I.width,scrollTop:I.top,scrollLeft:I.left,viewHeight:u.height,viewWidth:u.width,viewTop:u.top,viewLeft:u.left,absoluteTop:n.top,absoluteLeft:n.left,svgHeight:o.height,svgWidth:o.width,toolboxWidth:e.width,toolboxHeight:e.height,toolboxPosition:e.position,flyoutWidth:t.width,flyoutHeight:t.height}}};r($e.METRICS_MANAGER,Ws,Dp),"Blockly"in globalThis||(globalThis.Blockly={Msg:ev});var Xv=class extends Pl{constructor(){super(),this.GRID_UNIT=4,this.CURSOR_COLOUR="#ffa200",this.CURSOR_RADIUS=5,this.JAGGED_TEETH_WIDTH=this.JAGGED_TEETH_HEIGHT=0,this.START_HAT_HEIGHT=22,this.START_HAT_WIDTH=96,this.SHAPES={HEXAGONAL:1,ROUND:2,SQUARE:3,PUZZLE:4,NOTCH:5},this.SHAPE_IN_SHAPE_PADDING={1:{0:5*this.GRID_UNIT,1:2*this.GRID_UNIT,2:5*this.GRID_UNIT,3:5*this.GRID_UNIT},2:{0:3*this.GRID_UNIT,1:3*this.GRID_UNIT,2:1*this.GRID_UNIT,3:2*this.GRID_UNIT},3:{0:2*this.GRID_UNIT,1:2*this.GRID_UNIT,2:2*this.GRID_UNIT,3:2*this.GRID_UNIT}},this.FULL_BLOCK_FIELDS=!0,this.FIELD_TEXT_FONTWEIGHT="bold",this.FIELD_TEXT_FONTFAMILY='"Helvetica Neue", "Segoe UI", Helvetica, sans-serif',this.FIELD_COLOUR_FULL_BLOCK=this.FIELD_TEXTINPUT_BOX_SHADOW=this.FIELD_DROPDOWN_SVG_ARROW=this.FIELD_DROPDOWN_COLOURED_DIV=this.FIELD_DROPDOWN_NO_BORDER_RECT_SHADOW=!0,this.SELECTED_GLOW_COLOUR="#fff200",this.SELECTED_GLOW_SIZE=.5,this.REPLACEMENT_GLOW_COLOUR="#fff200",this.REPLACEMENT_GLOW_SIZE=2,this.selectedGlowFilterId="",this.selectedGlowFilter=null,this.replacementGlowFilterId="",this.SQUARED=this.ROUNDED=this.HEXAGONAL=this.replacementGlowFilter=null,this.SMALL_PADDING=this.GRID_UNIT,this.MEDIUM_PADDING=2*this.GRID_UNIT,this.MEDIUM_LARGE_PADDING=3*this.GRID_UNIT,this.LARGE_PADDING=4*this.GRID_UNIT,this.CORNER_RADIUS=1*this.GRID_UNIT,this.NOTCH_WIDTH=9*this.GRID_UNIT,this.NOTCH_HEIGHT=2*this.GRID_UNIT,this.STATEMENT_INPUT_NOTCH_OFFSET=this.NOTCH_OFFSET_LEFT=3*this.GRID_UNIT,this.MIN_BLOCK_WIDTH=2*this.GRID_UNIT,this.MIN_BLOCK_HEIGHT=12*this.GRID_UNIT,this.EMPTY_STATEMENT_INPUT_HEIGHT=6*this.GRID_UNIT,this.TOP_ROW_MIN_HEIGHT=this.CORNER_RADIUS,this.TOP_ROW_PRECEDES_STATEMENT_MIN_HEIGHT=this.LARGE_PADDING,this.BOTTOM_ROW_MIN_HEIGHT=this.CORNER_RADIUS,this.BOTTOM_ROW_AFTER_STATEMENT_MIN_HEIGHT=6*this.GRID_UNIT,this.STATEMENT_BOTTOM_SPACER=-this.NOTCH_HEIGHT,this.STATEMENT_INPUT_SPACER_MIN_WIDTH=40*this.GRID_UNIT,this.STATEMENT_INPUT_PADDING_LEFT=4*this.GRID_UNIT,this.EMPTY_INLINE_INPUT_PADDING=4*this.GRID_UNIT,this.EMPTY_INLINE_INPUT_HEIGHT=8*this.GRID_UNIT,this.DUMMY_INPUT_MIN_HEIGHT=8*this.GRID_UNIT,this.DUMMY_INPUT_SHADOW_MIN_HEIGHT=6*this.GRID_UNIT,this.CURSOR_WS_WIDTH=20*this.GRID_UNIT,this.FIELD_TEXT_FONTSIZE=3*this.GRID_UNIT,this.FIELD_BORDER_RECT_RADIUS=this.CORNER_RADIUS,this.FIELD_BORDER_RECT_X_PADDING=2*this.GRID_UNIT,this.FIELD_BORDER_RECT_Y_PADDING=1.625*this.GRID_UNIT,this.FIELD_BORDER_RECT_HEIGHT=8*this.GRID_UNIT,this.FIELD_DROPDOWN_BORDER_RECT_HEIGHT=8*this.GRID_UNIT,this.FIELD_DROPDOWN_SVG_ARROW_PADDING=this.FIELD_BORDER_RECT_X_PADDING,this.FIELD_COLOUR_DEFAULT_WIDTH=6*this.GRID_UNIT,this.FIELD_COLOUR_DEFAULT_HEIGHT=8*this.GRID_UNIT,this.FIELD_CHECKBOX_X_OFFSET=1*this.GRID_UNIT,this.MAX_DYNAMIC_CONNECTION_SHAPE_WIDTH=12*this.GRID_UNIT}setFontConstants_(e){super.setFontConstants_(e),this.FIELD_DROPDOWN_BORDER_RECT_HEIGHT=this.FIELD_BORDER_RECT_HEIGHT=this.FIELD_TEXT_HEIGHT+2*this.FIELD_BORDER_RECT_Y_PADDING}init(){super.init(),this.HEXAGONAL=this.makeHexagonal(),this.ROUNDED=this.makeRounded(),this.SQUARED=this.makeSquared(),this.STATEMENT_INPUT_NOTCH_OFFSET=this.NOTCH_OFFSET_LEFT+this.INSIDE_CORNERS.rightWidth}setDynamicProperties_(e){super.setDynamicProperties_(e),this.SELECTED_GLOW_COLOUR=e.getComponentStyle("selectedGlowColour")||this.SELECTED_GLOW_COLOUR;const t=Number(e.getComponentStyle("selectedGlowSize"));this.SELECTED_GLOW_SIZE=t&&!isNaN(t)?t:this.SELECTED_GLOW_SIZE,this.REPLACEMENT_GLOW_COLOUR=e.getComponentStyle("replacementGlowColour")||this.REPLACEMENT_GLOW_COLOUR,this.REPLACEMENT_GLOW_SIZE=(e=Number(e.getComponentStyle("replacementGlowSize")))&&!isNaN(e)?e:this.REPLACEMENT_GLOW_SIZE}dispose(){super.dispose(),this.selectedGlowFilter&&Ze(this.selectedGlowFilter),this.replacementGlowFilter&&Ze(this.replacementGlowFilter)}makeStartHat(){const e=this.START_HAT_HEIGHT,t=this.START_HAT_WIDTH,o=Zt("c",[Me(25,-e),Me(71,-e),Me(t,0)]);return{height:e,width:t,path:o}}makeHexagonal(){function e(o,n,u){var g=o/2;return g=g>t?t:g,u=u?-1:1,o=(n?-1:1)*o/2,Hs(-u*g,o)+Hs(u*g,o)}const t=this.MAX_DYNAMIC_CONNECTION_SHAPE_WIDTH;return{type:this.SHAPES.HEXAGONAL,isDynamic:!0,width(o){return o/=2,o>t?t:o},height(o){return o},connectionOffsetY(o){return o/2},connectionOffsetX(o){return-o},pathDown(o){return e(o,!1,!1)},pathUp(o){return e(o,!0,!1)},pathRightDown(o){return e(o,!1,!0)},pathRightUp(o){return e(o,!1,!0)}}}makeRounded(){function e(n,u,g){const I=n>o?n-o:0;n=(n>o?o:n)/2;const L=g===u?"0":"1";return vt("a","0 0,"+L,n,Me((g?1:-1)*n,(u?-1:1)*n))+De("v",(u?-1:1)*I)+vt("a","0 0,"+L,n,Me((g?-1:1)*n,(u?-1:1)*n))}const t=this.MAX_DYNAMIC_CONNECTION_SHAPE_WIDTH,o=2*t;return{type:this.SHAPES.ROUND,isDynamic:!0,width(n){return n/=2,n>t?t:n},height(n){return n},connectionOffsetY(n){return n/2},connectionOffsetX(n){return-n},pathDown(n){return e(n,!1,!1)},pathUp(n){return e(n,!0,!1)},pathRightDown(n){return e(n,!1,!0)},pathRightUp(n){return e(n,!1,!0)}}}makeSquared(){function e(o,n,u){o-=2*t;const g=u===n?"0":"1";return vt("a","0 0,"+g,t,Me((u?1:-1)*t,(n?-1:1)*t))+De("v",(n?-1:1)*o)+vt("a","0 0,"+g,t,Me((u?-1:1)*t,(n?-1:1)*t))}const t=this.CORNER_RADIUS;return{type:this.SHAPES.SQUARE,isDynamic:!0,width(o){return t},height(o){return o},connectionOffsetY(o){return o/2},connectionOffsetX(o){return-o},pathDown(o){return e(o,!1,!1)},pathUp(o){return e(o,!0,!1)},pathRightDown(o){return e(o,!1,!0)},pathRightUp(o){return e(o,!1,!0)}}}shapeFor(e){let t=e.getCheck();switch(!t&&e.targetConnection&&(t=e.targetConnection.getCheck()),e.type){case xe.INPUT_VALUE:case xe.OUTPUT_VALUE:if(e=e.getSourceBlock().getOutputShape(),e!==null)switch(e){case this.SHAPES.HEXAGONAL:return this.HEXAGONAL;case this.SHAPES.ROUND:return this.ROUNDED;case this.SHAPES.SQUARE:return this.SQUARED}return t&&t.includes("Boolean")?this.HEXAGONAL:t&&t.includes("Number")?this.ROUNDED:(t&&t.includes("String"),this.ROUNDED);case xe.PREVIOUS_STATEMENT:case xe.NEXT_STATEMENT:return this.NOTCH;default:throw Error("Unknown type")}}makeNotch(){function e(Ee){return Zt("c",[Me(Ee*u/2,0),Me(Ee*u*3/4,I/2),Me(Ee*u,I)])+Yi([Me(Ee*u,g)])+Zt("c",[Me(Ee*u/4,I/2),Me(Ee*u/2,I),Me(Ee*u,I)])+De("h",Ee*n)+Zt("c",[Me(Ee*u/2,0),Me(Ee*u*3/4,-(I/2)),Me(Ee*u,-I)])+Yi([Me(Ee*u,-g)])+Zt("c",[Me(Ee*u/4,-(I/2)),Me(Ee*u/2,-I),Me(Ee*u,-I)])}const t=this.NOTCH_WIDTH,o=this.NOTCH_HEIGHT,n=t/3,u=n/3,g=o/2,I=g/2,L=e(1),le=e(-1);return{type:this.SHAPES.NOTCH,width:t,height:o,pathLeft:L,pathRight:le}}makeInsideCorners(){const e=this.CORNER_RADIUS,t=vt("a","0 0,0",e,Me(-e,e)),o=vt("a","0 0,1",e,Me(-e,e)),n=vt("a","0 0,0",e,Me(e,e)),u=vt("a","0 0,1",e,Me(e,e));return{width:e,height:e,pathTop:t,pathBottom:n,rightWidth:e,rightHeight:e,pathTopRight:o,pathBottomRight:u}}generateSecondaryColour_(e){return si("#000",e,.15)||e}generateTertiaryColour_(e){return si("#000",e,.25)||e}createDom(e,t,o){super.createDom(e,t,o),e=ie(J.DEFS,{},e),t=ie(J.FILTER,{id:"blocklySelectedGlowFilter"+this.randomIdentifier,height:"160%",width:"180%",y:"-30%",x:"-40%"},e),ie(J.FEGAUSSIANBLUR,{in:"SourceGraphic",stdDeviation:this.SELECTED_GLOW_SIZE},t),o=ie(J.FECOMPONENTTRANSFER,{result:"outBlur"},t),ie(J.FEFUNCA,{type:"table",tableValues:"0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"},o),ie(J.FEFLOOD,{"flood-color":this.SELECTED_GLOW_COLOUR,"flood-opacity":1,result:"outColor"},t),ie(J.FECOMPOSITE,{in:"outColor",in2:"outBlur",operator:"in",result:"outGlow"},t),this.selectedGlowFilterId=t.id,this.selectedGlowFilter=t,e=ie(J.FILTER,{id:"blocklyReplacementGlowFilter"+this.randomIdentifier,height:"160%",width:"180%",y:"-30%",x:"-40%"},e),ie(J.FEGAUSSIANBLUR,{in:"SourceGraphic",stdDeviation:this.REPLACEMENT_GLOW_SIZE},e),t=ie(J.FECOMPONENTTRANSFER,{result:"outBlur"},e),ie(J.FEFUNCA,{type:"table",tableValues:"0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"},t),ie(J.FEFLOOD,{"flood-color":this.REPLACEMENT_GLOW_COLOUR,"flood-opacity":1,result:"outColor"},e),ie(J.FECOMPOSITE,{in:"outColor",in2:"outBlur",operator:"in",result:"outGlow"},e),ie(J.FECOMPOSITE,{in:"SourceGraphic",in2:"outGlow",operator:"over"},e),this.replacementGlowFilterId=e.id,this.replacementGlowFilter=e}getCSS_(e){return[`${e} .blocklyText,`,`${e} .blocklyFlyoutLabelText {`,`font: ${this.FIELD_TEXT_FONTWEIGHT} ${this.FIELD_TEXT_FONTSIZE}pt ${this.FIELD_TEXT_FONTFAMILY};`,"}",`${e} .blocklyTextInputBubble textarea {`,"font-weight: normal;","}",`${e} .blocklyText {`,"fill: #fff;","}",`${e} .blocklyNonEditableText>rect:not(.blocklyDropdownRect),`,`${e} .blocklyEditableText>rect:not(.blocklyDropdownRect) {`,`fill: ${this.FIELD_BORDER_RECT_COLOUR};`,"}",`${e} .blocklyNonEditableText>text,`,`${e} .blocklyEditableText>text,`,`${e} .blocklyNonEditableText>g>text,`,`${e} .blocklyEditableText>g>text {`,"fill: #575E75;","}",`${e} .blocklyFlyoutLabelText {`,"fill: #575E75;","}",`${e} .blocklyText.blocklyBubbleText {`,"fill: #575E75;","}",`${e} .blocklyDraggable:not(.blocklyDisabled)`," .blocklyEditableText:not(.editing):hover>rect,",`${e} .blocklyDraggable:not(.blocklyDisabled)`," .blocklyEditableText:not(.editing):hover>.blocklyPath {","stroke: #fff;","stroke-width: 2;","}",`${e} .blocklyHtmlInput {`,`font-family: ${this.FIELD_TEXT_FONTFAMILY};`,`font-weight: ${this.FIELD_TEXT_FONTWEIGHT};`,"color: #575E75;","}",`${e} .blocklyDropdownText {`,"fill: #fff !important;","}",`${e}.blocklyWidgetDiv .blocklyMenuItem,`,`${e}.blocklyDropDownDiv .blocklyMenuItem {`,`font-family: ${this.FIELD_TEXT_FONTFAMILY};`,"}",`${e}.blocklyDropDownDiv .blocklyMenuItemContent {`,"color: #fff;","}",`${e} .blocklyHighlightedConnectionPath {`,`stroke: ${this.SELECTED_GLOW_COLOUR};`,"}",`${e} .blocklyDisabled > .blocklyOutlinePath {`,`fill: url(#blocklyDisabledPattern${this.randomIdentifier})`,"}",`${e} .blocklyInsertionMarker>.blocklyPath {`,`fill-opacity: ${this.INSERTION_MARKER_OPACITY};`,"stroke: none;","}"]}},Zv=class extends Bl{constructor(e,t){super(e,t)}draw(){const e=this.block_.pathObject;e.beginDrawing(),this.drawOutline_(),this.drawInternals_(),this.updateConnectionHighlights(),e.setPath(this.outlinePath_+` -`+this.inlinePath_),this.info_.RTL&&e.flipRTL(),this.recordSizeOnBlock_(),this.info_.outputConnection&&(e.outputShapeType=this.info_.outputConnection.shape.type),e.endDrawing()}drawOutline_(){this.info_.outputConnection&&this.info_.outputConnection.isDynamicShape&&!this.info_.hasStatementInput&&!this.info_.bottomRow.hasNextConnection?(this.drawFlatTop_(),this.drawRightDynamicConnection_(),this.drawFlatBottom_(),this.drawLeftDynamicConnection_()):super.drawOutline_()}drawLeft_(){this.info_.outputConnection&&this.info_.outputConnection.isDynamicShape?this.drawLeftDynamicConnection_():super.drawLeft_()}drawRightSideRow_(e){if(!(0>=e.height)){if(j.isSpacer(e)){const n=e.precedesStatement;var t=e.followsStatement;if(n||t){const u=this.constants_.INSIDE_CORNERS;var o=u.rightHeight;o=e.height-(n?o:0),t=t?u.pathBottomRight:"",e=0=o||0>=t)throw Error("Height and width values of an image field must be greater than 0.");this.size_=new Xe(t,o+Ci.Y_PADDING),this.imageHeight=o,typeof u=="function"&&(this.clickHandler=u),e!==lt.SKIP_SETUP&&(I?this.configure_(I):(this.flipRtl=!!g,this.altText=bt(n)||""),this.setValue(bt(e)))}configure_(e){super.configure_(e),e.flipRtl&&(this.flipRtl=e.flipRtl),e.alt&&(this.altText=bt(e.alt))}initView(){this.imageElement=ie(J.IMAGE,{height:this.imageHeight+"px",width:this.size_.width+"px",alt:this.altText},this.fieldGroup_),this.imageElement.setAttributeNS(is,"xlink:href",this.value_),this.clickHandler&&(this.imageElement.style.cursor="pointer")}updateSize_(){}doClassValidation_(e){return typeof e!="string"?null:e}doValueUpdate_(e){this.value_=e,this.imageElement&&this.imageElement.setAttributeNS(is,"xlink:href",this.value_)}getFlipRtl(){return this.flipRtl}setAlt(e){e!==this.altText&&(this.altText=e||"",this.imageElement&&this.imageElement.setAttribute("alt",this.altText))}showEditor_(){this.clickHandler&&this.clickHandler(this)}setOnClickHandler(e){this.clickHandler=e}getText_(){return this.altText}static fromJson(e){if(!e.src||!e.width||!e.height)throw Error("src, width, and height values for an image field arerequired. The width and height must be non-zero.");return new this(e.src,e.width,e.height,void 0,void 0,void 0,e)}};Ci.Y_PADDING=1,Us("field_image",Ci),Ci.prototype.DEFAULT_VALUE="";var Vl=class extends lt{constructor(e,t,o){super(lt.SKIP_SETUP),this.spellcheck_=!0,this.htmlInput_=null,this.isTextValid_=this.isBeingEdited_=!1,this.onKeyInputWrapper=this.onKeyDownWrapper=this.valueWhenEditorWasOpened_=null,this.fullBlockClickTarget_=!1,this.workspace_=null,this.SERIALIZABLE=!0,this.CURSOR="text",e!==lt.SKIP_SETUP&&(o&&this.configure_(o),this.setValue(e),t&&this.setValidator(t))}configure_(e){super.configure_(e),e.spellcheck!==void 0&&(this.spellcheck_=e.spellcheck)}initView(){if(!this.getSourceBlock())throw new _t;super.initView(),this.isFullBlockField()&&(this.clickTarget_=this.sourceBlock_.getSvgRoot())}isFullBlockField(){const e=this.getSourceBlock();if(!e)throw new _t;let t;return this.fullBlockClickTarget_=!((t=this.getConstants())==null||!t.FULL_BLOCK_FIELDS)&&e.isSimpleReporter()}doValueInvalid_(e,t=!0){this.isBeingEdited_&&(this.isDirty_=!0,this.isTextValid_=!1,e=this.value_,this.value_=this.valueWhenEditorWasOpened_,this.sourceBlock_&&C()&&this.value_!==e&&t&&z(new(ne(ee.BLOCK_CHANGE))(this.sourceBlock_,"field",this.name||null,e,this.value_)))}doValueUpdate_(e){this.isTextValid_=this.isDirty_=!0,this.value_=e}applyColour(){const e=this.getSourceBlock();if(!e)throw new _t;this.getConstants().FULL_BLOCK_FIELDS&&this.fieldGroup_&&(!this.isFullBlockField()&&this.borderRect_?(this.borderRect_.style.display="block",this.borderRect_.setAttribute("stroke",e.getColourTertiary())):(this.borderRect_.style.display="none",e.pathObject.svgPath.setAttribute("fill",this.getConstants().FIELD_BORDER_RECT_COLOUR)))}getSize(){let e;return(e=this.getConstants())!=null&&e.FULL_BLOCK_FIELDS&&(this.render_(),this.isDirty_=!1),super.getSize()}onLocationChange(){this.isBeingEdited_&&this.resizeEditor_()}render_(){if(super.render_(),this.isBeingEdited_){var e=this.htmlInput_;this.isTextValid_?(ze(e,"blocklyInvalidInput"),xt(e,Et.INVALID,!1)):(Re(e,"blocklyInvalidInput"),xt(e,Et.INVALID,!0))}if(e=this.getSourceBlock(),!e)throw new _t;this.getConstants().FULL_BLOCK_FIELDS&&e.applyColour()}setSpellcheck(e){e!==this.spellcheck_&&(this.spellcheck_=e,this.htmlInput_&&this.htmlInput_.setAttribute("spellcheck",this.spellcheck_))}showEditor_(e,t=!1){this.workspace_=this.sourceBlock_.workspace,!t&&this.workspace_.options.modalInputs&&(Ob||wh||ll)?this.showPromptEditor():this.showInlineEditor(t)}showPromptEditor(){Ea(i.Msg$$module$build$src$core$msg.CHANGE_VALUE_TITLE,this.getText(),e=>{e!==null&&this.setValue(this.getValueFromEditorText_(e)),this.onFinishEditing_(this.value_)})}showInlineEditor(e){const t=this.getSourceBlock();if(!t)throw new _t;Fa(this,t.RTL,this.widgetDispose_.bind(this),this.workspace_),this.htmlInput_=this.widgetCreate_(),this.isBeingEdited_=!0,this.valueWhenEditorWasOpened_=this.value_,e||(this.htmlInput_.focus({preventScroll:!0}),this.htmlInput_.select())}widgetCreate_(){var e=this.getSourceBlock();if(!e)throw new _t;i.setGroup$$module$build$src$core$events$utils(!0);const t=oi();var o=this.getClickTarget_();if(!o)throw Error("A click target has not been set.");Re(o,"editing"),o=document.createElement("input"),o.className="blocklyHtmlInput",o.setAttribute("spellcheck",this.spellcheck_);const n=this.workspace_.getScale();var u=this.getConstants().FIELD_TEXT_FONTSIZE*n+"pt";return t.style.fontSize=u,o.style.fontSize=u,u=Vl.BORDERRADIUS*n+"px",this.isFullBlockField()&&(u=this.getScaledBBox(),u=(u.bottom-u.top)/2+"px",e=e.getParent()?e.getParent().getColourTertiary():this.sourceBlock_.getColourTertiary(),o.style.border=1*n+"px solid "+e,t.style.borderRadius=u,t.style.transition="box-shadow 0.25s ease 0s",this.getConstants().FIELD_TEXTINPUT_BOX_SHADOW&&(t.style.boxShadow="rgba(255, 255, 255, 0.3) 0 0 0 "+4*n+"px")),o.style.borderRadius=u,t.appendChild(o),o.value=o.defaultValue=this.getEditorText_(this.value_),o.setAttribute("data-untyped-default-value",String(this.value_)),this.resizeEditor_(),this.bindInputEvents_(o),o}widgetDispose_(){this.isBeingEdited_=!1,this.isTextValid_=!0,this.forceRerender(),this.onFinishEditing_(this.value_),this.sourceBlock_&&C()&&this.valueWhenEditorWasOpened_!==null&&this.valueWhenEditorWasOpened_!==this.value_&&(z(new(ne(ee.BLOCK_CHANGE))(this.sourceBlock_,"field",this.name||null,this.valueWhenEditorWasOpened_,this.value_)),this.valueWhenEditorWasOpened_=null),i.setGroup$$module$build$src$core$events$utils(!1),this.unbindInputEvents_();var e=oi().style;if(e.width="auto",e.height="auto",e.fontSize="",e.transition="",e.boxShadow="",this.htmlInput_=null,e=this.getClickTarget_(),!e)throw Error("A click target has not been set.");ze(e,"editing")}onFinishEditing_(e){}bindInputEvents_(e){this.onKeyDownWrapper=H(e,"keydown",this,this.onHtmlInputKeyDown_),this.onKeyInputWrapper=H(e,"input",this,this.onHtmlInputChange)}unbindInputEvents_(){this.onKeyDownWrapper&&(V(this.onKeyDownWrapper),this.onKeyDownWrapper=null),this.onKeyInputWrapper&&(V(this.onKeyInputWrapper),this.onKeyInputWrapper=null)}onHtmlInputKeyDown_(e){e.key==="Enter"?(ii(this),Fs()):e.key==="Escape"?(this.setValue(this.htmlInput_.getAttribute("data-untyped-default-value"),!1),ii(this),Fs()):e.key==="Tab"&&(ii(this),Fs(),this.sourceBlock_.tab(this,!e.shiftKey),e.preventDefault())}onHtmlInputChange(e){e=this.value_,this.setValue(this.getValueFromEditorText_(this.htmlInput_.value),!1),this.sourceBlock_&&C()&&this.value_!==e&&z(new(ne(ee.BLOCK_FIELD_INTERMEDIATE_CHANGE))(this.sourceBlock_,this.name||null,e,this.value_))}setEditorValue_(e,t=!0){this.isDirty_=!0,this.isBeingEdited_&&(this.htmlInput_.value=this.getEditorText_(e)),this.setValue(e,t)}resizeEditor_(){Ts().then(()=>{const e=this.getSourceBlock();if(!e)throw new _t;const t=oi(),o=this.getScaledBBox();t.style.width=o.right-o.left+"px",t.style.height=o.bottom-o.top+"px";const n=o.top;t.style.left=`${e.RTL?o.right-t.offsetWidth:o.left}px`,t.style.top=`${n}px`})}repositionForWindowResize(){let e;const t=(e=this.getSourceBlock())==null?void 0:e.getRootBlock();return t instanceof $s?(Ji(this.workspace_,this.workspace_.getMetricsManager().getViewMetrics(!0),t)||this.resizeEditor_(),!0):!1}isTabNavigable(){return!0}getText_(){return this.isBeingEdited_&&this.htmlInput_?this.htmlInput_.value:null}getEditorText_(e){return`${e}`}getValueFromEditorText_(e){return e}};Vl.BORDERRADIUS=4;var Kl=class extends Vl{constructor(e,t,o){super(e,t,o)}doClassValidation_(e){return e===void 0?null:`${e}`}static fromJson(e){return new this(bt(e.text),void 0,e)}};Us("field_input",Kl),Kl.prototype.DEFAULT_VALUE="";var Qv=class extends rp{constructor(e){super(e)}endsWithElemSpacer(){return!1}hasLeftSquareCorner(e){return!!e.outputConnection}hasRightSquareCorner(e){return!!e.outputConnection&&!e.statementInputCount&&!e.nextConnection}},Yl=class extends xr{constructor(e,t){if(super(e,t),this.connectedBottomNextConnection=!1,this.connectedBlock){for(e=this.connectedBlock;t=e.getNextBlock();)e=t;e.nextConnection||(this.height=this.connectedBlockHeight,this.connectedBottomNextConnection=!0)}}},ey=class extends Vs{constructor(e){super(e),this.width=this.height=0,this.type|=j.getType("RIGHT_CONNECTION")}},ty=class extends dp{constructor(e){super(e)}endsWithElemSpacer(){return!1}hasLeftSquareCorner(e){const t=(e.hat?e.hat==="cap":this.constants_.ADD_START_HATS)&&!e.outputConnection&&!e.previousConnection;return!!e.outputConnection||t}hasRightSquareCorner(e){return!!e.outputConnection&&!e.statementInputCount&&!e.nextConnection}},sy=class extends Rr{constructor(e,t){super(e,t),this.isInline=!0,this.renderer_=e,this.constants_=this.renderer_.getConstants(),this.topRow=new ty(this.constants_),this.bottomRow=new Qv(this.constants_),this.isMultiRow=!t.getInputsInline()||t.isCollapsed(),this.hasStatementInput=0=this.rows.length-1?!!this.bottomRow.hasNextConnection:!!n.precedesStatement,j.isInputRow(g)&&g.hasStatement){g.measure();let I,L;t=g.width-((L=(I=g.getLastInput())==null?void 0:I.width)!=null?L:0)+e}else if(o&&(u===2||n)&&j.isInputRow(g)&&!g.hasStatement){n=g.xPos,o=null;for(let I=0;Io?o:this.height/2,t-o*(1-Math.sin(Math.acos((o-this.constants_.SMALL_PADDING)/o)))):0;if(j.isInlineInput(e)&&e instanceof zo){const u=e.connectedBlock;return e=u?u.pathObject.outputShapeType:e.shape.type,e==null||u&&u.outputConnection&&(u.statementInputCount||u.nextConnection)||o===n.SHAPES.HEXAGONAL&&o!==e?0:t-this.constants_.SHAPE_IN_SHAPE_PADDING[o][e]}return j.isField(e)&&e instanceof hn?o===n.SHAPES.ROUND&&e.field instanceof Kl?t-2.75*n.GRID_UNIT:t-this.constants_.SHAPE_IN_SHAPE_PADDING[o][0]:j.isIcon(e)?this.constants_.SMALL_PADDING:0}finalizeVerticalAlignment_(){if(!this.outputConnection)for(let n=2;n=this.rows.length-1?!!this.bottomRow.hasNextConnection:!!I.precedesStatement;if(e?this.topRow.hasPreviousConnection:u.followsStatement){var o=g.elements[1];if(o=g.elements.length===3&&o instanceof hn&&(o.field instanceof _i||o.field instanceof Ci),!e&&o)u.height-=this.constants_.SMALL_PADDING,I.height-=this.constants_.SMALL_PADDING,g.height-=this.constants_.MEDIUM_PADDING;else if(!e&&!t)u.height+=this.constants_.SMALL_PADDING;else if(t){for(e=!1,t=0;t{if(!n.isDeadOrDying()){i.disable$$module$build$src$core$events$utils();try{n==null||n.positionNearConnection(u,g,I),n==null||n.getSvgRoot().setAttribute("visibility","visible")}finally{i.enable$$module$build$src$core$events$utils()}}}),u}createInsertionMarker(e){const t=os(e,{addCoordinates:!1,addInputBlocks:!1,addNextBlocks:!1,doFullSerialization:!1});if(!t)throw Error(`Failed to serialize source block. ${e.toDevString()}`);e=lo(t,this.workspace);for(const o of e.getDescendants(!1))o.setInsertionMarker(!0);return e.initSvg(),e.getSvgRoot().setAttribute("visibility","hidden"),e}getMatchingConnection(e,t,o){if(e=e.getConnections_(!0),t=t.getConnections_(!0),e.length!==t.length)return null;for(let n=0;nt instanceof Uo&&u.block===t||t instanceof ms&&u.button===t);return 0>n?null:(o=o?n+1:n-1,o===-1||o===e.length?null:e[o])}findTopASTNodeForBlock(e){const t=rr(e);return t?de.createConnectionNode(t):de.createBlockNode(e)}getOutAstNodeForBlock(e){if(!e)return null;e=e.getTopStackBlock();const t=rr(e);return t&&t.targetConnection&&t.targetConnection.getParentInput()?de.createInputNode(t.targetConnection.getParentInput()):de.createStackNode(e)}findFirstFieldOrInput(e){e=e.inputList;for(let t=0;t{Va(o.getSourceBlock()),setTimeout(()=>{n.bringToFront()},0)})}}update(e,t){const o=this.getCandidate(e);((this.wouldDeleteBlock=this.shouldDelete(!!o,t))||this.shouldUpdatePreviews(o,e))&&(i.disable$$module$build$src$core$events$utils(),this.maybeHidePreview(o),this.maybeShowPreview(o),i.enable$$module$build$src$core$events$utils())}createMarkerBlock(e){i.disable$$module$build$src$core$events$utils();let t;try{const o=os(e,{addCoordinates:!1,addInputBlocks:!1,addNextBlocks:!1,doFullSerialization:!1});if(!o)throw Error(`Failed to serialize source block. ${e.toDevString()}`);t=lo(o,this.workspace);for(const n of t.getDescendants(!1))n.setInsertionMarker(!0);t.initSvg(),t.getSvgRoot().setAttribute("visibility","hidden")}finally{i.enable$$module$build$src$core$events$utils()}return t}initAvailableConnections(){const e=this.topBlock.getConnections_(!1),t=this.topBlock.lastConnectionInStack(!0);return t&&t!==this.topBlock.nextConnection&&(e.push(t),this.lastOnStack=t),e}shouldUpdatePreviews(e,t){if(!e)return!!this.activeCandidate;if(!this.activeCandidate)return!0;const{local:o,closest:n}=this.activeCandidate;if(n===e.closest&&o===e.local)return!1;const u=o.x+t.x-n.x;return t=o.y+t.y-n.y,e.radius{let le;(le=n)==null||le.positionNearConnection(P,g,I);let Ee;(Ee=n)==null||Ee.getSvgRoot().setAttribute("visibility","visible")}),this.markerConnection=u}hideInsertionMarker(){if(this.markerConnection){var e=this.markerConnection,t=e.getSourceBlock(),o=t.outputConnection,n;if((n=t.previousConnection)!=null&&n.targetConnection||o!=null&&o.targetConnection)t.unplug(!0);else{let u;(u=e.targetBlock())==null||u.unplug(!1)}if(e.targetConnection)throw Error("markerConnection still connected at the end of disconnectInsertionMarker");this.markerConnection=null,(e=t.getSvgRoot())&&e.setAttribute("visibility","hidden")}}showInsertionInputOutline(e){e=e.closest,this.highlightedBlock=e.getSourceBlock(),this.highlightedBlock.highlightShapeForInput(e,!0)}hideInsertionInputOutline(){if(this.highlightedBlock){if(!this.activeCandidate)throw Error("Cannot hide the insertion marker outline because there is no active candidate");this.highlightedBlock.highlightShapeForInput(this.activeCandidate.closest,!1),this.highlightedBlock=null}}showReplacementFade(e){if(this.fadedBlock=e.closest.targetBlock(),!this.fadedBlock)throw Error("Cannot show the replacement fade because the closest connection does not have a target block");this.fadedBlock.fadeForReplacement(!0)}hideReplacementFade(){this.fadedBlock&&(this.fadedBlock.fadeForReplacement(!1),this.fadedBlock=null)}getInsertionMarkers(){const e=[];return this.firstMarker&&e.push(this.firstMarker),this.lastMarker&&e.push(this.lastMarker),e}disposeInsertionMarker(e){if(e){i.disable$$module$build$src$core$events$utils();try{e.dispose()}finally{i.enable$$module$build$src$core$events$utils()}}}};(function(e){e=e.PREVIEW_TYPE||(e.PREVIEW_TYPE={}),e[e.INSERTION_MARKER=0]="INSERTION_MARKER",e[e.INPUT_OUTLINE=1]="INPUT_OUTLINE",e[e.REPLACEMENT_FADE=2]="REPLACEMENT_FADE"})(fs||(fs={})),fs.PREVIEW_TYPE;var zl=class{constructor(e){this.overrides=null,this.name=e}getClassName(){return this.name+"-renderer"}init(e,t){this.constants_=this.makeConstants_(),t&&(this.overrides=t,Object.assign(this.constants_,t)),this.constants_.setTheme(e),this.constants_.init()}createDom(e,t){this.constants_.createDom(e,this.name+"-"+t.name,"."+this.getClassName()+"."+t.getClassName())}refreshDom(e,t){const o=this.getConstants();o.dispose(),this.constants_=this.makeConstants_(),this.overrides&&Object.assign(this.constants_,this.overrides),this.constants_.randomIdentifier=o.randomIdentifier,this.constants_.setTheme(t),this.constants_.init(),this.createDom(e,t)}dispose(){this.constants_&&this.constants_.dispose()}makeConstants_(){return new Bl}makeRenderInfo_(e){return new Or(this,e)}makeDrawer_(e,t){return new jl(e,t)}makeMarkerDrawer(e,t){return new mp(e,this.getConstants(),t)}makePathObject(e,t){return new Fl(e,t,this.constants_)}getConstants(){return this.constants_}shouldHighlightConnection(e){return!0}orphanCanConnectAtEnd(e,t,o){return!!et.getConnectionForOrphanedConnection(e,o===xe.OUTPUT_VALUE?t.outputConnection:t.previousConnection)}getConnectionPreviewMethod(e,t,o){return w("getConnectionPreviewMethod","v10","v12","an IConnectionPreviewer, if it fulfills your use case."),t.type===xe.OUTPUT_VALUE||t.type===xe.PREVIOUS_STATEMENT?!e.isConnected()||this.orphanCanConnectAtEnd(o,e.targetBlock(),t.type)?fs.PREVIEW_TYPE.INSERTION_MARKER:fs.PREVIEW_TYPE.REPLACEMENT_FADE:fs.PREVIEW_TYPE.INSERTION_MARKER}render(e){const t=this.makeRenderInfo_(e);t.measure(),this.makeDrawer_(e,t).draw()}},it={};it.BottomRow=ap,it.Connection=ko,it.ConstantProvider=Bl,it.Drawer=jl,it.ExternalValueInput=Pl,it.Field=hn,it.Hat=lp,it.Icon=Ov,it.InRowSpacer=as,it.InlineInput=cp,it.InputConnection=zo,it.InputRow=up,it.JaggedEdge=Rv,it.MarkerSvg=mp,it.Measurable=Vs,it.NextConnection=Mv,it.OutputConnection=Nv,it.PathObject=Fl,it.PreviousConnection=Lv,it.RenderInfo=Or,it.Renderer=zl,it.RoundCorner=Dr,it.Row=Ir,it.SpacerRow=dp,it.SquareCorner=Ar,it.StatementInput=xr,it.TopRow=hp,it.Types=j,it.init=Md,it.register=ar,it.unregister=G$;var Bv=class{constructor(e,t){this.workspace=e,this.theme=t,this.subscribedWorkspaces=[],this.componentDB=new Map}getTheme(){return this.theme}setTheme(e){var t=this.theme;this.theme=e,(e=this.workspace.getInjectionDiv())&&(t&&(t=t.getClassName())&&ze(e,t),(t=this.theme.getClassName())&&Oe(e,t));for(let o=0,n;n=this.subscribedWorkspaces[o];o++)n.refreshTheme();for(const[o,n]of this.componentDB)for(const u of n){e=u.element,t=u.propertyName;const g=this.theme&&this.theme.getComponentStyle(o);e.style.setProperty(t,g||"")}for(const o of this.subscribedWorkspaces)o.hideChaff()}subscribeWorkspace(e){this.subscribedWorkspaces.push(e)}unsubscribeWorkspace(e){if(!He(this.subscribedWorkspaces,e))throw Error("Cannot unsubscribe a workspace that hasn't been subscribed.")}subscribe(e,t,o){this.componentDB.has(t)||this.componentDB.set(t,[]),this.componentDB.get(t).push({element:e,propertyName:o}),t=this.theme&&this.theme.getComponentStyle(t),e.style.setProperty(o,t||"")}unsubscribe(e){if(e)for(const[t,o]of this.componentDB){for(let n=o.length-1;0<=n;n--)o[n].element===e&&o.splice(n,1);o.length||this.componentDB.delete(t)}}dispose(){this.subscribedWorkspaces.length=0,this.componentDB.clear()}},fp="VARIABLE_DYNAMIC",wi={CATEGORY_NAME:fp};wi.flyoutCategory=el,wi.flyoutCategoryBlocks=Bd,wi.onCreateVariableButtonClick_Colour=Pd,wi.onCreateVariableButtonClick_Number=Ld,wi.onCreateVariableButtonClick_String=Nd;var jv=30,ki=[];ki[xe.INPUT_VALUE]=xe.OUTPUT_VALUE,ki[xe.OUTPUT_VALUE]=xe.INPUT_VALUE,ki[xe.NEXT_STATEMENT]=xe.PREVIOUS_STATEMENT,ki[xe.PREVIOUS_STATEMENT]=xe.NEXT_STATEMENT;var $p="RENAME_VARIABLE_ID",bp="DELETE_VARIABLE_ID",Fv=class{canConnect(e,t,o,n){return this.canConnectWithReason(e,t,o,n)===et.CAN_CONNECT}canConnectWithReason(e,t,o,n){const u=this.doSafetyChecks(e,t);return u!==et.CAN_CONNECT?u:this.doTypeChecks(e,t)?o&&!this.doDragChecks(e,t,n||0)?et.REASON_DRAG_CHECKS_FAILED:et.CAN_CONNECT:et.REASON_CHECKS_FAILED}getErrorMessage(e,t,o){switch(e){case et.REASON_SELF_CONNECTION:return"Attempted to connect a block to itself.";case et.REASON_DIFFERENT_WORKSPACES:return"Blocks not on same workspace.";case et.REASON_WRONG_TYPE:return"Attempt to connect incompatible types.";case et.REASON_TARGET_NULL:return"Target connection is null.";case et.REASON_CHECKS_FAILED:return"Connection checks failed. "+(t+" expected "+t.getCheck()+", found "+o.getCheck());case et.REASON_SHADOW_PARENT:return"Connecting non-shadow to shadow block.";case et.REASON_DRAG_CHECKS_FAILED:return"Drag checks failed.";case et.REASON_PREVIOUS_AND_OUTPUT:return"Block would have an output and a previous connection.";default:return"Unknown connection failure: this should never happen!"}}doSafetyChecks(e,t){if(!e||!t)return et.REASON_TARGET_NULL;let o,n,u;return e.isSuperior()?(o=e.getSourceBlock(),n=t.getSourceBlock(),u=t):(n=e.getSourceBlock(),o=t.getSourceBlock(),u=e,e=t),o===n?et.REASON_SELF_CONNECTION:u.type!==ki[e.type]?et.REASON_WRONG_TYPE:o.workspace!==n.workspace?et.REASON_DIFFERENT_WORKSPACES:o.isShadow()&&!n.isShadow()?et.REASON_SHADOW_PARENT:u.type===xe.OUTPUT_VALUE&&n.previousConnection&&n.previousConnection.isConnected()||u.type===xe.PREVIOUS_STATEMENT&&n.outputConnection&&n.outputConnection.isConnected()?et.REASON_PREVIOUS_AND_OUTPUT:et.CAN_CONNECT}doTypeChecks(e,t){if(e=e.getCheck(),t=t.getCheck(),!e||!t)return!0;for(let o=0;oo||t.getSourceBlock().isInsertionMarker())return!1;switch(t.type){case xe.PREVIOUS_STATEMENT:return this.canConnectToPrevious_(e,t);case xe.OUTPUT_VALUE:if(t.isConnected()&&!t.targetBlock().isInsertionMarker()||e.isConnected())return!1;break;case xe.INPUT_VALUE:if(t.isConnected()&&!t.targetBlock().isMovable()&&!t.targetBlock().isShadow())return!1;break;case xe.NEXT_STATEMENT:if(t.isConnected()&&!e.getSourceBlock().nextConnection&&!t.targetBlock().isShadow()&&t.targetBlock().nextConnection||t.targetBlock()&&!t.targetBlock().isMovable()&&!t.targetBlock().isShadow())return!1;break;default:return!1}return!hr.includes(t)}canConnectToPrevious_(e,t){return e.targetConnection||hr.includes(t)?!1:t.targetConnection?(e=t.targetBlock(),e.isInsertionMarker()?!e.getPreviousBlock():!1):!0}};r($e.CONNECTION_CHECKER,Ws,Fv);var vp=class extends br{constructor(e){super(e),this.type=ee.VAR_DELETE,e&&(this.varType=e.type,this.varName=e.name)}toJson(){const e=super.toJson();if(this.varType===void 0)throw Error("The var type is undefined. Either pass a variable to the constructor, or call fromJson");if(!this.varName)throw Error("The var name is undefined. Either pass a variable to the constructor, or call fromJson");return e.varType=this.varType,e.varName=this.varName,e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new vp),t.varType=e.varType,t.varName=e.varName,t}run(e){const t=this.getEventWorkspace_();if(!this.varId)throw Error("The var ID is undefined. Either pass a variable to the constructor, or call fromJson");if(!this.varName)throw Error("The var name is undefined. Either pass a variable to the constructor, or call fromJson");e?t.deleteVariableById(this.varId):t.createVariable(this.varName,this.varType,this.varId)}};r($e.EVENT,ee.VAR_DELETE,vp);var yp=class extends br{constructor(e,t){super(e),this.type=ee.VAR_RENAME,e&&(this.oldName=e.name,this.newName=typeof t>"u"?"":t)}toJson(){const e=super.toJson();if(!this.oldName)throw Error("The old var name is undefined. Either pass a variable to the constructor, or call fromJson");if(!this.newName)throw Error("The new var name is undefined. Either pass a value to the constructor, or call fromJson");return e.oldName=this.oldName,e.newName=this.newName,e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new yp),t.oldName=e.oldName,t.newName=e.newName,t}run(e){const t=this.getEventWorkspace_();if(!this.varId)throw Error("The var ID is undefined. Either pass a variable to the constructor, or call fromJson");if(!this.oldName)throw Error("The old var name is undefined. Either pass a variable to the constructor, or call fromJson");if(!this.newName)throw Error("The new var name is undefined. Either pass a value to the constructor, or call fromJson");e?t.renameVariableById(this.varId,this.newName):t.renameVariableById(this.varId,this.oldName)}};r($e.EVENT,ee.VAR_RENAME,yp);var _p=class{constructor(e){this.workspace=e,this.variableMap=new Map}clear(){for(const e of this.variableMap.values())for(;0{u&&t&&this.deleteVariableInternal(t,n)})):this.deleteVariableInternal(t,n)}else console.warn("Can't delete non-existent variable: "+e)}deleteVariableInternal(e,t){const o=i.getGroup$$module$build$src$core$events$utils();o||i.setGroup$$module$build$src$core$events$utils(!0);try{for(let n=0;ne.name)}getVariableUsesById(e){const t=[],o=this.workspace.getAllBlocks(!1);for(let n=0;n!o.isInsertionMarker())):[]}addTopComment(e){this.topComments.push(e),this.commentDB.has(e.id)&&console.warn('Overriding an existing comment on this workspace, with id "'+e.id+'"'),this.commentDB.set(e.id,e)}removeTopComment(e){if(!He(this.topComments,e))throw Error("Comment not present in workspace's list of top-most comments.");this.commentDB.delete(e.id)}getTopComments(e=!1){const t=[].concat(this.topComments);return e&&1!o.isInsertionMarker())}clear(){this.isClearing=!0;try{const e=i.getGroup$$module$build$src$core$events$utils();for(e||i.setGroup$$module$build$src$core$events$utils(!0);this.topBlocks.length;)this.topBlocks[0].dispose(!1);for(;this.topComments.length;)this.topComments[this.topComments.length-1].dispose();i.setGroup$$module$build$src$core$events$utils(e),this.variableMap.clear(),this.potentialVariableMap&&this.potentialVariableMap.clear()}finally{this.isClearing=!1}}renameVariableById(e,t){this.variableMap.renameVariableById(e,t)}createVariable(e,t,o){return this.variableMap.createVariable(e,t,o)}getVariableUsesById(e){return this.variableMap.getVariableUsesById(e)}deleteVariableById(e){this.variableMap.deleteVariableById(e)}getVariable(e,t){return this.variableMap.getVariable(e,t)}getVariableById(e){return this.variableMap.getVariableById(e)}getVariablesOfType(e){return this.variableMap.getVariablesOfType(e)}getVariableTypes(){return this.variableMap.getVariableTypes(this)}getAllVariables(){return this.variableMap.getAllVariables()}getAllVariableNames(){return this.variableMap.getAllVariableNames()}getWidth(){return 0}newBlock(e,t){throw Error("The implementation of newBlock should be monkey-patched in by blockly.ts")}newComment(e){throw Error("The implementation of newComment should be monkey-patched in by blockly.ts")}remainingCapacity(){return isNaN(this.options.maxBlocks)?1/0:this.options.maxBlocks-this.getAllBlocks(!1).length}remainingCapacityOfType(e){return this.options.maxInstances?(this.options.maxInstances[e]!==void 0?this.options.maxInstances[e]:1/0)-this.getBlocksByType(e,!1).length:1/0}isCapacityAvailable(e){if(!this.hasBlockLimits())return!0;let t=0;for(const o in e){if(e[o]>this.remainingCapacityOfType(o))return!1;t+=e[o]}return!(t>this.remainingCapacity())}hasBlockLimits(){return this.options.maxBlocks!==1/0||!!this.options.maxInstances}getUndoStack(){return this.undoStack_}getRedoStack(){return this.redoStack_}undo(e){var t=e?this.redoStack_:this.undoStack_,o=e?this.undoStack_:this.redoStack_;const n=t.pop();if(n){for(var u=[n];t.length&&n.group&&n.group===t[t.length-1].group;){const g=t.pop();g&&u.push(g)}for(t=0;tthis.MAX_UNDO&&0<=this.MAX_UNDO;)this.undoStack_.shift();for(let t=0;t!!t.getStyleName())),this.refreshToolboxSelection(),this.toolbox&&this.toolbox.refreshTheme(),this.isVisible()&&this.setVisible(!0);const e=new(ne(ee.THEME_CHANGE))(this.getTheme().name,this.id);z(e)}updateBlockStyles(e){for(let t=0,o;o=e[t];t++){const n=o.getStyleName();n&&o.setStyle(n)}}getInverseScreenCTM(){if(this.inverseScreenCTMDirty){const e=this.getParentSvg().getScreenCTM();e&&(this.inverseScreenCTM=e.inverse(),this.inverseScreenCTMDirty=!1)}return this.inverseScreenCTM}updateInverseScreenCTM(){this.inverseScreenCTMDirty=!0}isVisible(){return this.visible}getSvgXY(e){let t=0,o=0,n=1;(this.getCanvas().contains(e)||this.getBubbleCanvas().contains(e))&&(n=this.scale);do{const u=Wn(e);(e===this.getCanvas()||e===this.getBubbleCanvas())&&(n=1),t+=u.x*n,o+=u.y*n,e=e.parentNode}while(e&&e!==this.getParentSvg()&&e!==this.getInjectionDiv());return new ye(t,o)}getCachedParentSvgSize(){const e=this.cachedParentSvgSize;return new Ze(e.width,e.height)}getOriginOffsetInPixels(){return $a(this.getCanvas())}getInjectionDiv(){if(!this.injectionDiv){let e=this.svgGroup_;for(;e;){if((" "+(e.getAttribute("class")||"")+" ").includes(" injectionDiv ")){this.injectionDiv=e;break}e=e.parentNode}}return this.injectionDiv}getSvgGroup(){return this.svgGroup_}getBlockCanvas(){return this.getCanvas()}setResizeHandlerWrapper(e){this.resizeHandlerWrapper=e}createDom(e,t){return this.injectionDiv||(this.injectionDiv=t??null),this.svgGroup_=ie(J.G,{class:"blocklyWorkspace"}),e&&(this.svgBackground_=ie(J.RECT,{height:"100%",width:"100%",class:e},this.svgGroup_),e==="blocklyMainBackground"&&this.grid?this.svgBackground_.style.fill="url(#"+this.grid.getPatternId()+")":this.themeManager_.subscribe(this.svgBackground_,"workspaceBackgroundColour","fill")),this.layerManager=new qC(this),this.svgBlockCanvas_=this.layerManager.getBlockLayer(),this.svgBubbleCanvas_=this.layerManager.getBubbleLayer(),this.isFlyout||(W(this.svgGroup_,"pointerdown",this,this.onMouseDown,!1),this.dummyWheelListener=()=>{},document.body.addEventListener("wheel",this.dummyWheelListener),W(this.svgGroup_,"wheel",this,this.onMouseWheel)),this.options.hasCategories&&(this.toolbox=new(y($e.TOOLBOX,this.options,!0))(this)),this.grid&&this.grid.update(this.scale),this.recordDragTargets(),(e=y($e.CURSOR,this.options))&&this.markerManager.setCursor(new e),this.renderer.createDom(this.svgGroup_,this.getTheme()),this.svgGroup_}dispose(){if(this.rendered=!1,this.currentGesture_&&this.currentGesture_.cancel(),this.svgGroup_&&Qe(this.svgGroup_),this.toolbox&&(this.toolbox.dispose(),this.toolbox=null),this.flyout&&(this.flyout.dispose(),this.flyout=null),this.trashcan&&(this.trashcan.dispose(),this.trashcan=null),this.scrollbar&&(this.scrollbar.dispose(),this.scrollbar=null),this.zoomControls_&&this.zoomControls_.dispose(),this.audioManager&&this.audioManager.dispose(),this.grid&&(this.grid=null),this.renderer.dispose(),this.markerManager&&this.markerManager.dispose(),super.dispose(),this.themeManager_&&(this.themeManager_.unsubscribeWorkspace(this),this.themeManager_.unsubscribe(this.svgBackground_),this.options.parentWorkspace||this.themeManager_.dispose()),this.connectionDBList.length=0,this.toolboxCategoryCallbacks.clear(),this.flyoutButtonCallbacks.clear(),!this.options.parentWorkspace){const e=this.getParentSvg();e&&e.parentNode&&Qe(e.parentNode)}this.resizeHandlerWrapper&&(V(this.resizeHandlerWrapper),this.resizeHandlerWrapper=null),this.dummyWheelListener&&(document.body.removeEventListener("wheel",this.dummyWheelListener),this.dummyWheelListener=null)}addTrashcan(){this.trashcan=cs.newTrashcan(this);const e=this.trashcan.createDom();this.svgGroup_.insertBefore(e,this.getCanvas())}static newTrashcan(e){throw Error("The implementation of newTrashcan should be monkey-patched in by blockly.ts")}addZoomControls(){this.zoomControls_=new Gb(this);const e=this.zoomControls_.createDom();this.svgGroup_.appendChild(e)}addFlyout(e){const t=new gs({parentWorkspace:this,rtl:this.RTL,oneBasedIndex:this.options.oneBasedIndex,horizontalLayout:this.horizontalLayout,renderer:this.options.renderer,rendererOverrides:this.options.rendererOverrides,move:{scrollbars:!0}});return t.toolboxPosition=this.options.toolboxPosition,this.flyout=this.horizontalLayout?new(y($e.FLYOUTS_HORIZONTAL_TOOLBOX,this.options,!0))(t):new(y($e.FLYOUTS_VERTICAL_TOOLBOX,this.options,!0))(t),this.flyout.autoClose=!1,this.flyout.getWorkspace().setVisible(!0),this.flyout.createDom(e)}getFlyout(e){return this.flyout||e?this.flyout:this.toolbox?this.toolbox.getFlyout():null}getToolbox(){return this.toolbox}updateScreenCalculations(){this.updateInverseScreenCTM(),this.recordDragTargets()}resizeContents(){this.resizesEnabled&&this.rendered&&(this.scrollbar&&this.scrollbar.resize(),this.updateInverseScreenCTM())}resize(){this.toolbox&&this.toolbox.position(),this.flyout&&this.flyout.position();const e=this.componentManager.getComponents(gt.Capability.POSITIONABLE,!0),t=this.getMetricsManager().getUiMetrics(),o=[];for(let n=0,u;u=e[n];n++){u.position(t,o);const g=u.getBoundingRectangle();g&&o.push(g)}this.scrollbar&&this.scrollbar.resize(),this.updateScreenCalculations()}updateScreenCalculationsIfScrolled(){const e=vu();ye.equals(this.lastRecordedPageScroll,e)||(this.lastRecordedPageScroll=e,this.updateScreenCalculations())}getLayerManager(){return this.layerManager}getCanvas(){return this.layerManager.getBlockLayer()}setCachedParentSvgSize(e,t){const o=this.getParentSvg();e!=null&&(this.cachedParentSvgSize.width=e,o.setAttribute("data-cached-width",`${e}`)),t!=null&&(this.cachedParentSvgSize.height=t,o.setAttribute("data-cached-height",`${t}`))}getBubbleCanvas(){return this.layerManager.getBubbleLayer()}getParentSvg(){if(!this.cachedParentSvg){let e=this.svgGroup_;for(;e;){if(e.tagName==="svg"){this.cachedParentSvg=e;break}e=e.parentNode}}return this.cachedParentSvg}maybeFireViewportChangeEvent(){if(C()){var e=this.scale,t=-this.scrollY,o=-this.scrollX;if(!(e===this.oldScale&&1>Math.abs(t-this.oldTop)&&1>Math.abs(o-this.oldLeft))){var n=new(ne(ee.VIEWPORT_CHANGE))(t,o,e,this.id,this.oldScale);this.oldScale=e,this.oldTop=t,this.oldLeft=o,z(n)}}}translate(e,t){let o;(o=this.layerManager)==null||o.translateLayers(new ye(e,t),this.scale);let n;(n=this.grid)==null||n.moveTo(e,t),this.maybeFireViewportChangeEvent()}getWidth(){const e=this.getMetrics();return e?e.viewWidth/this.scale:0}setVisible(e){this.visible=e,this.svgGroup_&&(this.scrollbar&&this.scrollbar.setContainerVisible(e),this.getFlyout()&&this.getFlyout().setContainerVisible(e),this.getParentSvg().style.display=e?"block":"none",this.toolbox&&this.toolbox.setVisible(e),e||this.hideChaff(!0))}render(){const e=this.getAllBlocks(!1);for(let t=e.length-1;0<=t;t--)e[t].queueRender();this.getTopBlocks().flatMap(t=>t.getDescendants(!1)).filter(t=>t.isInsertionMarker()).forEach(t=>t.queueRender()),Ts().then(()=>{this.markerManager.updateMarkers()})}highlightBlock(e,t){if(t===void 0){for(let o=0,n;n=this.highlightedBlocks[o];o++)n.setHighlighted(!1);this.highlightedBlocks.length=0}(e=e?this.getBlockById(e):null)&&((t=t===void 0||t)?this.highlightedBlocks.includes(e)||this.highlightedBlocks.push(e):He(this.highlightedBlocks,e),e.setHighlighted(t))}refreshToolboxSelection(){const e=this.isFlyout?this.targetWorkspace:this;e&&!e.currentGesture_&&e.toolbox&&e.toolbox.getFlyout()&&e.toolbox.refreshSelection()}renameVariableById(e,t){super.renameVariableById(e,t),this.refreshToolboxSelection()}deleteVariableById(e){super.deleteVariableById(e),this.refreshToolboxSelection()}createVariable(e,t,o){return e=super.createVariable(e,t,o),this.refreshToolboxSelection(),e}recordDragTargets(){const e=this.componentManager.getComponents(gt.Capability.DRAG_TARGET,!0);this.dragTargetAreas=[];for(let t=0,o;o=e[t];t++){const n=o.getClientRect();n&&this.dragTargetAreas.push({component:o,clientRect:n})}}newBlock(e,t){throw Error("The implementation of newBlock should be monkey-patched in by blockly.ts")}newComment(e){throw Error("The implementation of newComment should be monkey-patched in by blockly.ts")}getDragTarget(e){for(let t=0,o;o=this.dragTargetAreas[t];t++)if(o.clientRect.contains(e.clientX,e.clientY))return o.component;return null}onMouseDown(e){const t=this.getGesture(e);t&&t.handleWsStart(e,this)}startDrag(e,t){Ua(this,e,t)}moveDrag(e){return Ha(this,e)}isDragging(){return this.currentGesture_!==null&&this.currentGesture_.isDragging()}isDraggable(){return this.options.moveOptions&&this.options.moveOptions.drag}isMovable(){return this.options.moveOptions&&!!this.options.moveOptions.scrollbars||this.options.moveOptions&&this.options.moveOptions.wheel||this.options.moveOptions&&this.options.moveOptions.drag||this.options.zoomOptions&&this.options.zoomOptions.wheel||this.options.zoomOptions&&this.options.zoomOptions.pinch}isMovableHorizontally(){const e=!!this.scrollbar;return this.isMovable()&&(!e||e&&this.scrollbar.canScrollHorizontally())}isMovableVertically(){const e=!!this.scrollbar;return this.isMovable()&&(!e||e&&this.scrollbar.canScrollVertically())}onMouseWheel(e){if(bo.inProgress())e.preventDefault(),e.stopPropagation();else{var t=this.options.zoomOptions&&this.options.zoomOptions.wheel,o=this.options.moveOptions&&this.options.moveOptions.wheel;if(t||o){var n=Le(e);if(Ch)var u=e.metaKey;t&&(e.ctrlKey||u||!o)?(n=-n.y/50,t=fe(e,this.getParentSvg(),this.getInverseScreenCTM()),this.zoom(t.x,t.y,n)):(t=this.scrollX-n.x,o=this.scrollY-n.y,e.shiftKey&&!n.x&&(t=this.scrollX-n.y,o=this.scrollY),this.scroll(t,o)),e.preventDefault()}}}getBlocksBoundingBox(){const e=this.getTopBoundedElements();if(!e.length)return new rt(0,0,0,0);const t=e[0].getBoundingRectangle();for(let n=1;nt.bottom&&(t.bottom=o.bottom),o.leftt.right&&(t.right=o.right))}return t}cleanUp(){this.setResizesEnabled(!1),i.setGroup$$module$build$src$core$events$utils(!0);var e=this.getTopBlocks(!0),t=e.filter(g=>g.isMovable());const o=e.filter(g=>!g.isMovable()).map(g=>g.getBoundingRectangle());e=function(g){for(const I of o)if(g.intersects(I))return I;return null};var n=0;const u=this.renderer.getConstants().MIN_BLOCK_HEIGHT;for(const g of t){for(t=g.getBoundingRectangle(),g.moveBy(-t.left,n-t.top,["cleanup"]),g.snapToGrid(),t=g.getBoundingRectangle(),n=e(t);n!=null;)n=n.top+n.getHeight()+u,g.moveBy(0,n-t.top,["cleanup"]),g.snapToGrid(),t=g.getBoundingRectangle(),n=e(t);n=g.getRelativeToSurfaceXY().y+g.getHeightWidth().height+u}i.setGroup$$module$build$src$core$events$utils(!1),this.setResizesEnabled(!0)}showContextMenu(e){if(!this.options.readOnly&&!this.isFlyout){var t=Ye.registry.getContextMenuOptions(Ye.ScopeType.WORKSPACE,{workspace:this});this.configureContextMenu&&this.configureContextMenu(t,e),sr(e,t,this.RTL,this)}}updateToolbox(e){if(e=ba(e)){if(!this.options.languageTree)throw Error("Existing toolbox is null. Can't create new toolbox.");if(va(e)){if(!this.toolbox)throw Error("Existing toolbox has no categories. Can't change mode.");this.options.languageTree=e,this.toolbox.render(e)}else{if(!this.flyout)throw Error("Existing toolbox has categories. Can't change mode.");this.options.languageTree=e,this.flyout.show(e)}}else if(this.options.languageTree)throw Error("Can't nullify an existing toolbox.")}markFocused(){this.options.parentWorkspace?this.options.parentWorkspace.markFocused():(se(this),this.getParentSvg().focus({preventScroll:!0}))}zoom(e,t,o){o=Math.pow(this.options.zoomOptions.scaleSpeed,o);const n=this.scale*o;if(this.scale!==n){n>this.options.zoomOptions.maxScale?o=this.options.zoomOptions.maxScale/this.scale:nthis.options.zoomOptions.maxScale?e=this.options.zoomOptions.maxScale:this.options.zoomOptions.minScale&&et.autoHide(e))}static setTopLevelWorkspaceMetrics(e){const t=this.getMetrics();typeof e.x=="number"&&(this.scrollX=-(t.scrollLeft+(t.scrollWidth-t.viewWidth)*e.x)),typeof e.y=="number"&&(this.scrollY=-(t.scrollTop+(t.scrollHeight-t.viewHeight)*e.y)),this.translate(this.scrollX+t.absoluteLeft,this.scrollY+t.absoluteTop)}},wp=class extends Ss{constructor(e,t,o){super(o),this.type=ee.SELECTED,this.oldElementId=e??void 0,this.newElementId=t??void 0}toJson(){const e=super.toJson();return e.oldElementId=this.oldElementId,e.newElementId=this.newElementId,e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new wp),t.oldElementId=e.oldElementId,t.newElementId=e.newElementId,t}};r($e.EVENT,ee.SELECTED,wp);var Rr=class{paste(e,t,o){if(!t.isCapacityAvailable(e.typeCounts))return null;o&&(e.blockState.x=o.x,e.blockState.y=o.y),o=o||new ye(e.blockState.x||0,e.blockState.y||0),i.disable$$module$build$src$core$events$utils();let n;try{n=lo(e.blockState,t),V$(n,o)}finally{i.enable$$module$build$src$core$events$utils()}return n&&(C()&&!n.isShadow()&&z(new(ne(ee.BLOCK_CREATE))(n)),i.setSelected$$module$build$src$core$common(n),n)}};Rr.TYPE="block",Ta(Rr.TYPE,new Rr);var Ul={};Ul.bumpIntoBounds=Ji,Ul.bumpIntoBoundsHandler=jd,Ul.bumpTopObjectsIntoBounds=tl;var Uv=class{constructor(e){this.block=e,this.connectionPreviewer=this.connectionCandidate=this.startLoc=this.startChildConn=this.startParentConn=null,this.dragging=!1,this.dragOffset=new ye(0,0),this.inGroup=!1,this.workspace=e.workspace}isMovable(){if(this.block.isShadow()){let e,t;return(t=(e=this.block.getParent())==null?void 0:e.isMovable())!=null?t:!1}return this.block.isOwnMovable()&&!this.block.isDeadOrDying()&&!this.workspace.options.readOnly&&!this.block.isInFlyout}startDrag(e){if(this.block.isShadow())this.startDraggingShadow(e);else{this.dragging=!0,(this.inGroup=!!i.getGroup$$module$build$src$core$events$utils())||i.setGroup$$module$build$src$core$events$utils(!0),this.fireDragStartEvent(),this.startLoc=this.block.getRelativeToSurfaceXY(),this.connectionCandidate=null,this.connectionPreviewer=new(y($e.CONNECTION_PREVIEWER,this.workspace.options))(this.block),io(),this.workspace.setResizesEnabled(!1),Yi(),e=!!e&&(e.altKey||e.ctrlKey||e.metaKey),this.shouldDisconnect(e)&&this.disconnectBlock(e),this.block.setDragging(!0);var t;(t=this.workspace.getLayerManager())==null||t.moveToDragLayer(this.block)}}startDraggingShadow(e){const t=this.block.getParent();if(!t)throw Error("Tried to drag a shadow block with no parent. Shadow blocks should always have parents.");this.dragOffset=ye.difference(t.getRelativeToSurfaceXY(),this.block.getRelativeToSurfaceXY()),t.startDrag(e)}shouldDisconnect(e){return!!(this.block.getParent()||e&&this.block.nextConnection&&this.block.nextConnection.targetBlock())}disconnectBlock(e){let t,o,n;if(this.startParentConn=(n=(t=this.block.outputConnection)==null?void 0:t.targetConnection)!=null?n:(o=this.block.previousConnection)==null?void 0:o.targetConnection,e){let u;this.startChildConn=(u=this.block.nextConnection)==null?void 0:u.targetConnection}this.block.unplug(e),wd(this.block)}fireDragStartEvent(){const e=new(ne(ee.BLOCK_DRAG))(this.block,!0,this.block.getDescendants(!1));z(e)}fireDragEndEvent(){const e=new(ne(ee.BLOCK_DRAG))(this.block,!1,this.block.getDescendants(!1));z(e)}fireMoveEvent(){if(!this.block.isDeadOrDying()){var e=new(ne(ee.BLOCK_MOVE))(this.block);e.setReason(["drag"]),e.oldCoordinate=this.startLoc,e.recordNew(),z(e)}}drag(e){if(this.block.isShadow()){let t;(t=this.block.getParent())==null||t.drag(ye.sum(e,this.dragOffset))}else this.block.moveDuringDrag(e),this.updateConnectionPreview(this.block,ye.difference(e,this.startLoc))}updateConnectionPreview(e,t){var o=this.connectionCandidate;const n=this.getConnectionCandidate(e,t);if(n){this.connectionCandidate=t=o&&this.currCandidateIsBetter(o,t,n)?o:n;var{local:u,neighbour:g}=t;t=u.type===xe.OUTPUT_VALUE||u.type===xe.PREVIOUS_STATEMENT,o=g.isConnected()&&!g.targetBlock().isInsertionMarker(),t&&o&&!this.orphanCanConnectAtEnd(e,g.targetBlock(),u.type)?this.connectionPreviewer.previewReplacement(u,g,g.targetBlock()):this.connectionPreviewer.previewConnection(u,g)}else this.connectionPreviewer.hidePreview(),this.connectionCandidate=null}orphanCanConnectAtEnd(e,t,o){return!!et.getConnectionForOrphanedConnection(e,o===xe.OUTPUT_VALUE?t.outputConnection:t.previousConnection)}currCandidateIsBetter(e,t,o){const{local:n,neighbour:u}=e;e=new ye(n.x,n.y);const g=new ye(u.x,u.y);return t=ye.distance(ye.sum(e,t),g),o.distance>t-i.config$$module$build$src$core$config.currentConnectionPreference}getConnectionCandidate(e,t){e=this.getLocalConnections(e);let o=this.connectionCandidate?i.config$$module$build$src$core$config.connectingSnapRadius:i.config$$module$build$src$core$config.snapRadius,n=null;for(const u of e){const{connection:g,radius:I}=u.closest(o,t);g&&(n={local:u,neighbour:g,distance:I},o=I)}return n}getLocalConnections(e){const t=e.getConnections_(!1),o=e.lastConnectionInStack(!0);return o&&o!==e.nextConnection&&t.push(o),t}endDrag(e){if(this.block.isShadow()){let t;(t=this.block.getParent())==null||t.endDrag(e)}else{if(this.fireDragEndEvent(),this.fireMoveEvent(),no(),Yi(),this.connectionPreviewer.hidePreview(),!this.block.isDeadOrDying()&&this.dragging){let t;(t=this.workspace.getLayerManager())==null||t.moveOffDragLayer(this.block,jo),this.block.setDragging(!1)}this.connectionCandidate?(this.applyConnections(this.connectionCandidate),this.disposeStep()):this.block.queueRender().then(()=>this.disposeStep()),this.inGroup||i.setGroup$$module$build$src$core$events$utils(!1)}}disposeStep(){this.block.snapToGrid(),this.connectionPreviewer.dispose(),this.workspace.setResizesEnabled(!0)}applyConnections(e){const{local:t,neighbour:o}=e;t.connect(o);const n=t.isSuperior()?o:t,u=this.block.getRootBlock();Ts().then(()=>{Va(n.getSourceBlock()),setTimeout(()=>{u.bringToFront()},0)})}revertDrag(){if(this.block.isShadow()){let t;(t=this.block.getParent())==null||t.revertDrag()}else{var e;if((e=this.startChildConn)==null||e.connect(this.block.nextConnection),this.startParentConn)switch(this.startParentConn.type){case xe.INPUT_VALUE:this.startParentConn.connect(this.block.outputConnection);break;case xe.NEXT_STATEMENT:this.startParentConn.connect(this.block.previousConnection)}else{this.block.moveTo(this.startLoc,["drag"]);let t;(t=this.workspace.getLayerManager())==null||t.moveOffDragLayer(this.block,jo),Ji(this.workspace,this.workspace.getMetricsManager().getScrollMetrics(!0),this.block)}this.startParentConn=this.startChildConn=null,this.connectionPreviewer.hidePreview(),this.connectionCandidate=null,this.block.setDragging(!1),this.dragging=!1}}},Hv=class{constructor(){this.drawer=this.curNode=this.colour=null,this.type="marker"}setDrawer(e){this.drawer=e}getDrawer(){return this.drawer}getCurNode(){return this.curNode}setCurNode(e){const t=this.curNode;this.curNode=e,this.drawer&&this.drawer.draw(t,this.curNode)}draw(){this.drawer&&this.drawer.draw(this.curNode,this.curNode)}hide(){this.drawer&&this.drawer.hide()}dispose(){this.getDrawer()&&this.getDrawer().dispose()}},kp=class extends Hv{constructor(){super(),this.type="cursor"}next(){var e=this.getCurNode();if(!e)return null;for(e=e.next();e&&e.next()&&(e.getType()===de.types.NEXT||e.getType()===de.types.BLOCK);)e=e.next();return e&&this.setCurNode(e),e}in(){var e=this.getCurNode();if(!e)return null;(e.getType()===de.types.PREVIOUS||e.getType()===de.types.OUTPUT)&&(e=e.next());let t,o;return(e=(o=(t=e)==null?void 0:t.in())!=null?o:null)&&this.setCurNode(e),e}prev(){var e=this.getCurNode();if(!e)return null;for(e=e.prev();e&&e.prev()&&(e.getType()===de.types.NEXT||e.getType()===de.types.BLOCK);)e=e.prev();return e&&this.setCurNode(e),e}out(){var e=this.getCurNode();return e?((e=e.out())&&e.getType()===de.types.BLOCK&&(e=e.prev()||e),e&&this.setCurNode(e),e):null}};r($e.CURSOR,Ws,kp);var Mr=class extends kp{constructor(){super()}next(){var e=this.getCurNode();return e?((e=this.getNextNode_(e,this.validNode_))&&this.setCurNode(e),e):null}in(){return this.next()}prev(){var e=this.getCurNode();return e?((e=this.getPreviousNode_(e,this.validNode_))&&this.setCurNode(e),e):null}out(){return this.prev()}getNextNode_(e,t){if(!e)return null;const o=e.in()||e.next();return t(o)?o:o?this.getNextNode_(o,t):(e=this.findSiblingOrParent(e.out()),t(e)?e:e?this.getNextNode_(e,t):null)}getPreviousNode_(e,t){if(!e)return null;let o=e.prev();return o=o?this.getRightMostChild(o):e.out(),t(o)?o:o?this.getPreviousNode_(o,t):null}validNode_(e){let t=!1;return e=e&&e.getType(),(e===de.types.OUTPUT||e===de.types.INPUT||e===de.types.FIELD||e===de.types.NEXT||e===de.types.PREVIOUS||e===de.types.WORKSPACE)&&(t=!0),t}findSiblingOrParent(e){if(!e)return null;const t=e.next();return t||this.findSiblingOrParent(e.out())}getRightMostChild(e){if(!e.in())return e;for(e=e.in();e&&e.next();)e=e.next();return this.getRightMostChild(e)}};Mr.registrationName="basicCursor",r($e.CURSOR,Mr.registrationName,Mr);var Wv=class extends Mr{validNode_(e){let t=!1;const o=e&&e.getType();return e&&(e=e.getLocation(),o===de.types.FIELD&&e&&e.isTabNavigable()&&e.isClickable()&&(t=!0)),t}},Gv=10,Kt=class extends et{constructor(e,t){super(e,t),this.highlighted=!1,this.targetConnection=null,this.db=e.workspace.connectionDBList[t],this.dbOpposite=e.workspace.connectionDBList[ki[t]],this.offsetInBlock=new ye(0,0),this.trackedState=Kt.TrackedState.WILL_TRACK}dispose(){super.dispose(),this.trackedState===Kt.TrackedState.TRACKED&&this.db.removeConnection(this,this.y);let e,t;(t=(e=this.sourceBlock_.pathObject).removeConnectionHighlight)==null||t.call(e,this)}getSourceBlock(){return super.getSourceBlock()}targetBlock(){return super.targetBlock()}distanceFrom(e){const t=this.x-e.x;return e=this.y-e.y,Math.sqrt(t*t+e*e)}bumpAwayFrom(e,t=!1){if(!this.sourceBlock_.workspace.isDragging()){var o=i.config$$module$build$src$core$config.snapRadius+Math.floor(Math.random()*Gv),n=i.config$$module$build$src$core$config.snapRadius+Math.floor(Math.random()*Gv),u=e.sourceBlock_.getRootBlock(),g=this.sourceBlock_.getRootBlock();if(!u.isInFlyout&&!g.isInFlyout){var I=!0;if(g.isMovable())u.isMovable()&&t&&(n=-n);else if(u.isMovable())I=!1,o=-o,n=-n;else return;t=I?e:this,e=I?this:e,u=I?g:u,(g=F()===u)||u.addSelect(),u.RTL&&(o=-o),u.moveBy(t.x+o-e.x,t.y+n-e.y,["bump"]),g||u.removeSelect()}}}moveTo(e,t){let o=!1;return this.trackedState===Kt.TrackedState.WILL_TRACK?(this.db.addConnection(this,t),this.trackedState=Kt.TrackedState.TRACKED,o=!0):this.trackedState===Kt.TrackedState.TRACKED&&(this.db.removeConnection(this,this.y),this.db.addConnection(this,t),o=!0),this.x=e,this.y=t,o}moveBy(e,t){return this.moveTo(this.x+e,this.y+t)}moveToOffset(e){return this.moveTo(e.x+this.offsetInBlock.x,e.y+this.offsetInBlock.y)}setOffsetInBlock(e,t){this.offsetInBlock.x=e,this.offsetInBlock.y=t}getOffsetInBlock(){return this.offsetInBlock}tightenEfficiently(){var e=this.targetConnection;const t=this.targetBlock();e&&t&&(e=ye.difference(this.offsetInBlock,e.offsetInBlock),t.translate(e.x,e.y))}closest(e,t){return this.dbOpposite.searchForClosest(this,e,t)}highlight(){this.highlighted=!0,this.getSourceBlock().queueRender()}unhighlight(){this.highlighted=!1,this.getSourceBlock().queueRender()}isHighlighted(){return this.highlighted}setTracking(e){e&&this.trackedState===Kt.TrackedState.TRACKED||!e&&this.trackedState===Kt.TrackedState.UNTRACKED||this.sourceBlock_.isInFlyout||(e?(this.db.addConnection(this,this.y),this.trackedState=Kt.TrackedState.TRACKED):(this.trackedState===Kt.TrackedState.TRACKED&&this.db.removeConnection(this,this.y),this.trackedState=Kt.TrackedState.UNTRACKED))}stopTrackingAll(){if(this.setTracking(!1),this.targetConnection){const e=this.targetBlock().getDescendants(!1);for(let t=0;tclearTimeout(e)),this.warningTextDb.clear(),this.getIcons().forEach(e=>e.dispose())}checkAndDelete(){this.workspace.isFlyout||(i.setGroup$$module$build$src$core$events$utils(!0),this.workspace.hideChaff(),this.outputConnection?this.dispose(!1,!0):this.dispose(!0,!0),i.setGroup$$module$build$src$core$events$utils(!1))}toCopyData(){return this.isInsertionMarker_?null:{paster:Rr.TYPE,blockState:os(this,{addCoordinates:!0,addNextBlocks:!1}),typeCounts:Ie(this,!0)}}applyColour(){this.pathObject.applyColour(this);const e=this.getIcons();for(let t=0;t{this.isDeadOrDying()||(this.warningTextDb.delete(t),this.setWarningText(e,t))},100));else if(this.isInFlyout&&(e=null),o=this.getIcon(wo.TYPE),e){let n=this.getSurroundParent(),u=null;for(;n;)n.isCollapsed()&&(u=n),n=n.getSurroundParent();u&&u.setWarningText(i.Msg$$module$build$src$core$msg.COLLAPSED_WARNINGS_WARNING,$s.COLLAPSED_WARNING_ID),o?o.addMessage(e,t):this.addIcon(new wo(this).addMessage(e,t))}else o&&(t?(o.addMessage("",t),o.getText()||this.removeIcon(wo.TYPE)):this.removeIcon(wo.TYPE))}setMutator(e){this.removeIcon(i.MutatorIcon$$module$build$src$core$icons$mutator_icon.TYPE),e&&this.addIcon(e)}addIcon(e){return super.addIcon(e),e instanceof i.MutatorIcon$$module$build$src$core$icons$mutator_icon&&(this.mutator=e),e.initView(this.createIconPointerDownListener(e)),e.applyColour(),e.updateEditable(),this.queueRender(),e}createIconPointerDownListener(e){return t=>{this.isDeadOrDying()||(t=this.workspace.getGesture(t))&&t.setStartIcon(e)}}removeIcon(e){const t=super.removeIcon(e);return e.equals(i.MutatorIcon$$module$build$src$core$icons$mutator_icon.TYPE)&&(this.mutator=null),this.queueRender(),t}setEnabled(e){w("setEnabled","v11","v12","the setDisabledReason method of BlockSvg");const t=this.isEnabled();super.setEnabled(e),this.isEnabled()===t||this.getInheritedDisabled()||this.updateDisabled()}setDisabledReason(e,t){const o=this.isEnabled();super.setDisabledReason(e,t),this.isEnabled()===o||this.getInheritedDisabled()||this.updateDisabled()}setHighlighted(e){this.pathObject.updateHighlighted(e)}addSelect(){this.pathObject.updateSelected(!0)}removeSelect(){this.pathObject.updateSelected(!1)}setDeleteStyle(e){this.pathObject.updateDraggingDelete(e)}getColour(){return this.style.colourPrimary}setColour(e){super.setColour(e),e=this.workspace.getRenderer().getConstants().getBlockStyleForColour(this.colour_),this.pathObject.setStyle(e.style),this.style=e.style,this.styleName_=e.name,this.applyColour()}setStyle(e){const t=this.workspace.getRenderer().getConstants().getBlockStyle(e);if(this.styleName_=e,t)this.hat=t.hat,this.pathObject.setStyle(t),this.colour_=t.colourPrimary,this.style=t,this.applyColour();else throw Error("Invalid style name: "+e)}getStyle(){return this.style}bringToFront(e=!1){let t=this;if(!t.isDeadOrDying())do{const o=t.getSvgRoot(),n=o.parentNode,u=n.childNodes;if(u[u.length-1]!==o&&n.appendChild(o),e)break;t=t.getParent()}while(t)}setPreviousStatement(e,t){super.setPreviousStatement(e,t),this.queueRender()}setNextStatement(e,t){super.setNextStatement(e,t),this.queueRender()}setOutput(e,t){super.setOutput(e,t),this.queueRender()}setInputsInline(e){super.setInputsInline(e),this.queueRender()}removeInput(e,t){return e=super.removeInput(e,t),this.queueRender(),e}moveNumberedInputBefore(e,t){super.moveNumberedInputBefore(e,t),this.queueRender()}appendInput(e){return super.appendInput(e),this.queueRender(),e}setConnectionTracking(e){if(this.previousConnection&&this.previousConnection.setTracking(e),this.outputConnection&&this.outputConnection.setTracking(e),this.nextConnection){this.nextConnection.setTracking(e);var t=this.nextConnection.targetBlock();t&&t.setConnectionTracking(e)}if(!this.collapsed_)for(t=0;t=this.workspace.options.maxTrashcanContents||(e=new gs({scrollbars:!0,parentWorkspace:this.workspace,rtl:this.workspace.RTL,oneBasedIndex:this.workspace.options.oneBasedIndex,renderer:this.workspace.options.renderer,rendererOverrides:this.workspace.options.rendererOverrides,move:{scrollbars:!0}}),this.workspace.horizontalLayout?(e.toolboxPosition=this.workspace.toolboxPosition===Ge.TOP?Ge.BOTTOM:Ge.TOP,this.flyout=new(y($e.FLYOUTS_HORIZONTAL_TOOLBOX,this.workspace.options,!0))(e)):(e.toolboxPosition=this.workspace.toolboxPosition===Ge.RIGHT?Ge.LEFT:Ge.RIGHT,this.flyout=new(y($e.FLYOUTS_VERTICAL_TOOLBOX,this.workspace.options,!0))(e)),this.workspace.addChangeListener(this.onDelete.bind(this)))}createDom(){this.svgGroup=ie(J.G,{class:"blocklyTrash"});let e;const t=String(Math.random()).substring(2);e=ie(J.CLIPPATH,{id:"blocklyTrashBodyClipPath"+t},this.svgGroup),ie(J.RECT,{width:mn,height:Wl,y:fn},e);const o=ie(J.IMAGE,{width:Gt.width,x:-Tp,height:Gt.height,y:-Sp,"clip-path":"url(#blocklyTrashBodyClipPath"+t+")"},this.svgGroup);return o.setAttributeNS(is,"xlink:href",this.workspace.options.pathToMedia+Gt.url),e=ie(J.CLIPPATH,{id:"blocklyTrashLidClipPath"+t},this.svgGroup),ie(J.RECT,{width:mn,height:fn},e),this.svgLid=ie(J.IMAGE,{width:Gt.width,x:-Tp,height:Gt.height,y:-Sp,"clip-path":"url(#blocklyTrashLidClipPath"+t+")"},this.svgGroup),this.svgLid.setAttributeNS(is,"xlink:href",this.workspace.options.pathToMedia+Gt.url),ue(this.svgGroup,"pointerdown",this,this.blockMouseDownWhenOpenable),ue(this.svgGroup,"pointerup",this,this.click),ue(o,"pointerover",this,this.mouseOver),ue(o,"pointerout",this,this.mouseOut),this.animateLid(),this.svgGroup}init(){0{let o;(o=this.flyout)==null||o.show(e),t.cursor="";let n;(n=this.workspace.scrollbar)==null||n.setVisible(!1)},10),this.fireUiEvent(!0)}}closeFlyout(){if(this.contentsIsOpen()){var e;(e=this.flyout)==null||e.hide();var t;(t=this.workspace.scrollbar)==null||t.setVisible(!0),this.fireUiEvent(!1),this.workspace.recordDragTargets()}}autoHide(e){!e&&this.flyout&&this.closeFlyout()}emptyContents(){this.hasContents()&&(this.contents.length=0,this.setMinOpenness(0),this.closeFlyout())}position(e,t){if(this.initialized){var o=ka(this.workspace,e);e=wa(o,new Ze(mn,Wl+fn),aT,Kv,e,this.workspace),t=Ca(e,Kv,o.vertical===$o.TOP?Po.DOWN:Po.UP,t),this.top=t.top,this.left=t.left;var n;(n=this.svgGroup)==null||n.setAttribute("transform","translate("+this.left+","+this.top+")");var u;(u=this.flyout)==null||u.position()}}getBoundingRectangle(){return new rt(this.top,this.top+Wl+fn,this.left,this.left+mn)}getClientRect(){if(!this.svgGroup)return null;var e=this.svgGroup.getBoundingClientRect();const t=e.top+Sp-Gl;return e=e.left+Tp-Gl,new rt(t,t+fn+Wl+2*Gl,e,e+mn+2*Gl)}onDragOver(e){this.setLidOpen(this.wouldDelete_)}onDragExit(e){this.setLidOpen(!1)}onDrop(e){setTimeout(this.setLidOpen.bind(this,!1),100)}setLidOpen(e){this.isLidOpen!==e&&(this.lidTask&&clearTimeout(this.lidTask),this.isLidOpen=e,this.animateLid())}animateLid(){const e=uT;var t=1/(e+1);this.lidOpen+=this.isLidOpen?t:-t,this.lidOpen=Math.min(Math.max(this.lidOpen,this.minOpenness),1),this.setLidAngle(this.lidOpen*Xv),t=Jv+this.lidOpen*(dT-Jv),this.svgGroup&&(this.svgGroup.style.opacity=`${t}`),this.lidOpen>this.minOpenness&&1>this.lidOpen&&(this.lidTask=setTimeout(this.animateLid.bind(this),cT/e))}setLidAngle(e){const t=this.workspace.toolboxPosition===Ge.RIGHT||this.workspace.horizontalLayout&&this.workspace.RTL;let o;(o=this.svgLid)==null||o.setAttribute("transform","rotate("+(t?-e:e)+","+(t?4:mn-4)+","+(fn-2)+")")}setMinOpenness(e){this.minOpenness=e,this.isLidOpen||this.setLidAngle(e*Xv)}closeLid(){this.setLidOpen(!1)}click(){this.hasContents()&&!this.workspace.isDragging()&&this.openFlyout()}fireUiEvent(e){e=new(ne(ee.TRASHCAN_OPEN))(e,this.workspace.id),z(e)}blockMouseDownWhenOpenable(e){!this.contentsIsOpen()&&this.hasContents()&&e.stopPropagation()}mouseOver(){this.hasContents()&&this.setLidOpen(!0)}mouseOut(){this.setLidOpen(!1)}onDelete(e){if(!(0>=this.workspace.options.maxTrashcanContents||!T(e)||e.wasShadow)){if(!e.oldJson)throw Error("Encountered a delete event without proper oldJson");if(e=JSON.stringify(this.cleanBlockJson(e.oldJson)),!this.contents.includes(e)){for(this.contents.unshift(e);this.contents.length>this.workspace.options.maxTrashcanContents;)this.contents.pop();this.setMinOpenness(lT)}}}cleanBlockJson(e){function t(o){if(o){if(delete o.id,delete o.x,delete o.y,delete o.enabled,delete o.disabledReasons,o.icons&&o.icons.comment){var n=o.icons.comment;delete n.height,delete n.width,delete n.pinned}n=o.inputs;for(var u in n){var g=n[u];const I=g.block;g=g.shadow,I&&t(I),g&&t(g)}o.next&&(u=o.next,o=u.block,u=u.shadow,o&&t(o),u&&t(u))}}return e=JSON.parse(JSON.stringify(e)),t(e),Object.assign({},{kind:"BLOCK"},e)}},mn=47,Wl=44,fn=16,Kv=20,aT=20,Gl=10,Tp=0,Sp=32,lT=.1,cT=80,uT=4,Jv=.4,dT=.8,Xv=45,ot=class{constructor(){this.shortcuts=new Map,this.keyMap=new Map,this.reset()}reset(){this.shortcuts.clear(),this.keyMap.clear()}register(e,t){if(this.shortcuts.get(e.name)&&!t)throw Error(`Shortcut named "${e.name}" already exists.`);if(this.shortcuts.set(e.name,e),t=e.keyCodes,t!=null&&t.length)for(const o of t)this.addKeyMapping(o,e.name,!!e.allowCollision)}unregister(e){return this.shortcuts.get(e)?(this.removeAllKeyMappings(e),this.shortcuts.delete(e),!0):(console.warn(`Keyboard shortcut named "${e}" not found.`),!1)}addKeyMapping(e,t,o){e=`${e}`;const n=this.keyMap.get(e);if(n&&!o)throw Error(`Shortcut named "${t}" collides with shortcuts "${n}"`);n&&o?n.unshift(t):this.keyMap.set(e,[t])}removeKeyMapping(e,t,o){const n=this.keyMap.get(e);if(!n)return o||console.warn(`No keyboard shortcut named "${t}" registered with key code "${e}"`),!1;const u=n.indexOf(t);return-1Jd(t)),e.length?e:null}load(e,t){const o=t.getProcedureMap();for(const n of e)o.add(Xd(this.procedureModelClass,this.parameterModelClass,n,t))}clear(e){e.getProcedureMap().clear()}},Vl={};Vl.ProcedureSerializer=pT,Vl.loadProcedure=Xd,Vl.saveProcedure=Jd;var qv=class{constructor(){this.priority=Vb}save(e){const t=[];for(const o of e.getAllVariables())e={name:o.name,id:o.getId()},o.type&&(e.type=o.type),t.push(e);return t.length?t:null}load(e,t){for(const o of e)t.createVariable(o.name,o.type,o.id)}clear(e){e.getVariableMap().clear()}};Vn("variables",new qv);var Zv={};Zv.VariableSerializer=qv;var xp={};xp.load=Q$,xp.save=Z$;var gT={blocks:_r,exceptions:pi,priorities:HC,procedures:Vl,registry:Ah,variables:Zv,workspaceComments:pl,workspaces:xp},Dp=class{constructor(e,t,o,n,u){this.workspace=e,this.oldHostMetrics=this.corner_=this.vScroll=this.hScroll=null,t=t===void 0?!0:t,o=o===void 0?!0:o;const g=t&&o;t&&(this.hScroll=new yt(e,!0,g,n,u)),o&&(this.vScroll=new yt(e,!1,g,n,u)),g&&(this.corner_=ie(J.RECT,{height:yt.scrollbarThickness,width:yt.scrollbarThickness,class:"blocklyScrollbarBackground"}),At(this.corner_,e.getBubbleCanvas()))}dispose(){Qe(this.corner_),this.oldHostMetrics=this.corner_=null,this.hScroll&&(this.hScroll.dispose(),this.hScroll=null),this.vScroll&&(this.vScroll.dispose(),this.vScroll=null)}resize(){const e=this.workspace.getMetrics();if(e){var t=!1,o=!1;if(this.oldHostMetrics&&this.oldHostMetrics.viewWidth===e.viewWidth&&this.oldHostMetrics.viewHeight===e.viewHeight&&this.oldHostMetrics.absoluteTop===e.absoluteTop&&this.oldHostMetrics.absoluteLeft===e.absoluteLeft?(this.oldHostMetrics&&this.oldHostMetrics.scrollWidth===e.scrollWidth&&this.oldHostMetrics.viewLeft===e.viewLeft&&this.oldHostMetrics.scrollLeft===e.scrollLeft||(t=!0),this.oldHostMetrics&&this.oldHostMetrics.scrollHeight===e.scrollHeight&&this.oldHostMetrics.viewTop===e.viewTop&&this.oldHostMetrics.scrollTop===e.scrollTop||(o=!0)):o=t=!0,t||o){try{i.disable$$module$build$src$core$events$utils(),this.hScroll&&t&&this.hScroll.resize(e),this.vScroll&&o&&this.vScroll.resize(e)}finally{i.enable$$module$build$src$core$events$utils()}this.workspace.maybeFireViewportChangeEvent()}if(this.hScroll&&this.vScroll){if(!this.oldHostMetrics||this.oldHostMetrics.viewWidth!==e.viewWidth||this.oldHostMetrics.absoluteLeft!==e.absoluteLeft){let n;(n=this.corner_)==null||n.setAttribute("x",String(this.vScroll.position.x))}if(!this.oldHostMetrics||this.oldHostMetrics.viewHeight!==e.viewHeight||this.oldHostMetrics.absoluteTop!==e.absoluteTop){let n;(n=this.corner_)==null||n.setAttribute("y",String(this.hScroll.position.y))}}this.oldHostMetrics=e}}canScrollHorizontally(){return!!this.hScroll}canScrollVertically(){return!!this.vScroll}setOrigin(e,t){this.hScroll&&this.hScroll.setOrigin(e,t),this.vScroll&&this.vScroll.setOrigin(e,t)}set(e,t,o){this.hScroll&&this.hScroll.set(e,!1),this.vScroll&&this.vScroll.set(t,!1),(o||o===void 0)&&(e={},this.hScroll&&(e.x=this.hScroll.getRatio_()),this.vScroll&&(e.y=this.vScroll.getRatio_()),this.workspace.setMetrics(e))}setX(e){this.hScroll&&this.hScroll.set(e,!0)}setY(e){this.vScroll&&this.vScroll.set(e,!0)}setContainerVisible(e){this.hScroll&&this.hScroll.setContainerVisible(e),this.vScroll&&this.vScroll.setContainerVisible(e)}isVisible(){let e=!1;return this.hScroll&&(e=this.hScroll.isVisible()),this.vScroll&&(e=e||this.vScroll.isVisible()),e}setVisible(e){this.hScroll&&this.hScroll.setVisibleInternal(e),this.vScroll&&this.vScroll.setVisibleInternal(e)}resizeContent(e){this.hScroll&&this.hScroll.resizeContentHorizontal(e),this.vScroll&&this.vScroll.resizeContentVertical(e)}resizeView(e){this.hScroll&&this.hScroll.resizeViewHorizontal(e),this.vScroll&&this.vScroll.resizeViewVertical(e)}},Ap=class{constructor(e){this.workspace_=e}getDimensionsPx_(e){let t=0,o=0;return e&&(t=e.getWidth(),o=e.getHeight()),new Ze(t,o)}getFlyoutMetrics(e){return e=this.getDimensionsPx_(this.workspace_.getFlyout(e)),{width:e.width,height:e.height,position:this.workspace_.toolboxPosition}}getToolboxMetrics(){const e=this.getDimensionsPx_(this.workspace_.getToolbox());return{width:e.width,height:e.height,position:this.workspace_.toolboxPosition}}getSvgMetrics(){return this.workspace_.getCachedParentSvgSize()}getAbsoluteMetrics(){let e=0,t=0;const o=this.getToolboxMetrics(),n=this.getFlyoutMetrics(),u=!!this.workspace_.getToolbox();var g;const I=!((g=this.workspace_.getFlyout())!=null&&g.autoClose);g=u?o.position:n.position;const P=g===Ge.TOP;return g===Ge.LEFT&&(u&&(e+=o.width),I&&(e+=n.width)),P&&(u&&(t+=o.height),I&&(t+=n.height)),{top:t,left:e}}getViewMetrics(e){e=e?this.workspace_.scale:1;const t=this.getSvgMetrics(),o=this.getToolboxMetrics(),n=this.getFlyoutMetrics(),u=!!this.workspace_.getToolbox();var g;const I=!((g=this.workspace_.getFlyout())!=null&&g.autoClose);g=u?o.position:n.position;const P=g===Ge.LEFT||g===Ge.RIGHT;return(g===Ge.TOP||g===Ge.BOTTOM)&&(u&&(t.height-=o.height),I&&(t.height-=n.height)),P&&(u&&(t.width-=o.width),I&&(t.width-=n.width)),{height:t.height/e,width:t.width/e,top:-this.workspace_.scrollY/e,left:-this.workspace_.scrollX/e}}getContentMetrics(e){e=e?1:this.workspace_.scale;const t=this.workspace_.getBlocksBoundingBox();return{height:(t.bottom-t.top)*e,width:(t.right-t.left)*e,top:t.top*e,left:t.left*e}}hasFixedEdges(){return!this.workspace_.isMovableHorizontally()||!this.workspace_.isMovableVertically()}getComputedFixedEdges_(e){if(!this.hasFixedEdges())return{};const t=this.workspace_.isMovableHorizontally(),o=this.workspace_.isMovableVertically();e=e||this.getViewMetrics(!1);const n={};return o||(n.top=e.top,n.bottom=e.top+e.height),t||(n.left=e.left,n.right=e.left+e.width),n}getPaddedContent_(e,t){const o=t.top+t.height,n=t.left+t.width,u=e.width;e=e.height;const g=u/2,I=e/2;return{top:Math.min(t.top-I,o-e),bottom:Math.max(o+I,t.top+e),left:Math.min(t.left-g,n-u),right:Math.max(n+g,t.left+u)}}getScrollMetrics(e,t,o){e=e?this.workspace_.scale:1,t=t||this.getViewMetrics(!1);var n=o||this.getContentMetrics();o=this.getComputedFixedEdges_(t),t=this.getPaddedContent_(t,n),n=o.top!==void 0?o.top:t.top;const u=o.left!==void 0?o.left:t.left;return{top:n/e,left:u/e,width:((o.right!==void 0?o.right:t.right)-u)/e,height:((o.bottom!==void 0?o.bottom:t.bottom)-n)/e}}getUiMetrics(){return{viewMetrics:this.getViewMetrics(),absoluteMetrics:this.getAbsoluteMetrics(),toolboxMetrics:this.getToolboxMetrics()}}getMetrics(){const e=this.getToolboxMetrics(),t=this.getFlyoutMetrics(!0),o=this.getSvgMetrics(),n=this.getAbsoluteMetrics(),u=this.getViewMetrics(),g=this.getContentMetrics(),I=this.getScrollMetrics(!1,u,g);return{contentHeight:g.height,contentWidth:g.width,contentTop:g.top,contentLeft:g.left,scrollHeight:I.height,scrollWidth:I.width,scrollTop:I.top,scrollLeft:I.left,viewHeight:u.height,viewWidth:u.width,viewTop:u.top,viewLeft:u.left,absoluteTop:n.top,absoluteLeft:n.left,svgHeight:o.height,svgWidth:o.width,toolboxWidth:e.width,toolboxHeight:e.height,toolboxPosition:e.position,flyoutWidth:t.width,flyoutHeight:t.height}}};r($e.METRICS_MANAGER,Ws,Ap),"Blockly"in globalThis||(globalThis.Blockly={Msg:sv});var Qv=class extends Bl{constructor(){super(),this.GRID_UNIT=4,this.CURSOR_COLOUR="#ffa200",this.CURSOR_RADIUS=5,this.JAGGED_TEETH_WIDTH=this.JAGGED_TEETH_HEIGHT=0,this.START_HAT_HEIGHT=22,this.START_HAT_WIDTH=96,this.SHAPES={HEXAGONAL:1,ROUND:2,SQUARE:3,PUZZLE:4,NOTCH:5},this.SHAPE_IN_SHAPE_PADDING={1:{0:5*this.GRID_UNIT,1:2*this.GRID_UNIT,2:5*this.GRID_UNIT,3:5*this.GRID_UNIT},2:{0:3*this.GRID_UNIT,1:3*this.GRID_UNIT,2:1*this.GRID_UNIT,3:2*this.GRID_UNIT},3:{0:2*this.GRID_UNIT,1:2*this.GRID_UNIT,2:2*this.GRID_UNIT,3:2*this.GRID_UNIT}},this.FULL_BLOCK_FIELDS=!0,this.FIELD_TEXT_FONTWEIGHT="bold",this.FIELD_TEXT_FONTFAMILY='"Helvetica Neue", "Segoe UI", Helvetica, sans-serif',this.FIELD_COLOUR_FULL_BLOCK=this.FIELD_TEXTINPUT_BOX_SHADOW=this.FIELD_DROPDOWN_SVG_ARROW=this.FIELD_DROPDOWN_COLOURED_DIV=this.FIELD_DROPDOWN_NO_BORDER_RECT_SHADOW=!0,this.SELECTED_GLOW_COLOUR="#fff200",this.SELECTED_GLOW_SIZE=.5,this.REPLACEMENT_GLOW_COLOUR="#fff200",this.REPLACEMENT_GLOW_SIZE=2,this.selectedGlowFilterId="",this.selectedGlowFilter=null,this.replacementGlowFilterId="",this.SQUARED=this.ROUNDED=this.HEXAGONAL=this.replacementGlowFilter=null,this.SMALL_PADDING=this.GRID_UNIT,this.MEDIUM_PADDING=2*this.GRID_UNIT,this.MEDIUM_LARGE_PADDING=3*this.GRID_UNIT,this.LARGE_PADDING=4*this.GRID_UNIT,this.CORNER_RADIUS=1*this.GRID_UNIT,this.NOTCH_WIDTH=9*this.GRID_UNIT,this.NOTCH_HEIGHT=2*this.GRID_UNIT,this.STATEMENT_INPUT_NOTCH_OFFSET=this.NOTCH_OFFSET_LEFT=3*this.GRID_UNIT,this.MIN_BLOCK_WIDTH=2*this.GRID_UNIT,this.MIN_BLOCK_HEIGHT=12*this.GRID_UNIT,this.EMPTY_STATEMENT_INPUT_HEIGHT=6*this.GRID_UNIT,this.TOP_ROW_MIN_HEIGHT=this.CORNER_RADIUS,this.TOP_ROW_PRECEDES_STATEMENT_MIN_HEIGHT=this.LARGE_PADDING,this.BOTTOM_ROW_MIN_HEIGHT=this.CORNER_RADIUS,this.BOTTOM_ROW_AFTER_STATEMENT_MIN_HEIGHT=6*this.GRID_UNIT,this.STATEMENT_BOTTOM_SPACER=-this.NOTCH_HEIGHT,this.STATEMENT_INPUT_SPACER_MIN_WIDTH=40*this.GRID_UNIT,this.STATEMENT_INPUT_PADDING_LEFT=4*this.GRID_UNIT,this.EMPTY_INLINE_INPUT_PADDING=4*this.GRID_UNIT,this.EMPTY_INLINE_INPUT_HEIGHT=8*this.GRID_UNIT,this.DUMMY_INPUT_MIN_HEIGHT=8*this.GRID_UNIT,this.DUMMY_INPUT_SHADOW_MIN_HEIGHT=6*this.GRID_UNIT,this.CURSOR_WS_WIDTH=20*this.GRID_UNIT,this.FIELD_TEXT_FONTSIZE=3*this.GRID_UNIT,this.FIELD_BORDER_RECT_RADIUS=this.CORNER_RADIUS,this.FIELD_BORDER_RECT_X_PADDING=2*this.GRID_UNIT,this.FIELD_BORDER_RECT_Y_PADDING=1.625*this.GRID_UNIT,this.FIELD_BORDER_RECT_HEIGHT=8*this.GRID_UNIT,this.FIELD_DROPDOWN_BORDER_RECT_HEIGHT=8*this.GRID_UNIT,this.FIELD_DROPDOWN_SVG_ARROW_PADDING=this.FIELD_BORDER_RECT_X_PADDING,this.FIELD_COLOUR_DEFAULT_WIDTH=6*this.GRID_UNIT,this.FIELD_COLOUR_DEFAULT_HEIGHT=8*this.GRID_UNIT,this.FIELD_CHECKBOX_X_OFFSET=1*this.GRID_UNIT,this.MAX_DYNAMIC_CONNECTION_SHAPE_WIDTH=12*this.GRID_UNIT}setFontConstants_(e){super.setFontConstants_(e),this.FIELD_DROPDOWN_BORDER_RECT_HEIGHT=this.FIELD_BORDER_RECT_HEIGHT=this.FIELD_TEXT_HEIGHT+2*this.FIELD_BORDER_RECT_Y_PADDING}init(){super.init(),this.HEXAGONAL=this.makeHexagonal(),this.ROUNDED=this.makeRounded(),this.SQUARED=this.makeSquared(),this.STATEMENT_INPUT_NOTCH_OFFSET=this.NOTCH_OFFSET_LEFT+this.INSIDE_CORNERS.rightWidth}setDynamicProperties_(e){super.setDynamicProperties_(e),this.SELECTED_GLOW_COLOUR=e.getComponentStyle("selectedGlowColour")||this.SELECTED_GLOW_COLOUR;const t=Number(e.getComponentStyle("selectedGlowSize"));this.SELECTED_GLOW_SIZE=t&&!isNaN(t)?t:this.SELECTED_GLOW_SIZE,this.REPLACEMENT_GLOW_COLOUR=e.getComponentStyle("replacementGlowColour")||this.REPLACEMENT_GLOW_COLOUR,this.REPLACEMENT_GLOW_SIZE=(e=Number(e.getComponentStyle("replacementGlowSize")))&&!isNaN(e)?e:this.REPLACEMENT_GLOW_SIZE}dispose(){super.dispose(),this.selectedGlowFilter&&Qe(this.selectedGlowFilter),this.replacementGlowFilter&&Qe(this.replacementGlowFilter)}makeStartHat(){const e=this.START_HAT_HEIGHT,t=this.START_HAT_WIDTH,o=Zt("c",[Ne(25,-e),Ne(71,-e),Ne(t,0)]);return{height:e,width:t,path:o}}makeHexagonal(){function e(o,n,u){var g=o/2;return g=g>t?t:g,u=u?-1:1,o=(n?-1:1)*o/2,Hs(-u*g,o)+Hs(u*g,o)}const t=this.MAX_DYNAMIC_CONNECTION_SHAPE_WIDTH;return{type:this.SHAPES.HEXAGONAL,isDynamic:!0,width(o){return o/=2,o>t?t:o},height(o){return o},connectionOffsetY(o){return o/2},connectionOffsetX(o){return-o},pathDown(o){return e(o,!1,!1)},pathUp(o){return e(o,!0,!1)},pathRightDown(o){return e(o,!1,!0)},pathRightUp(o){return e(o,!1,!0)}}}makeRounded(){function e(n,u,g){const I=n>o?n-o:0;n=(n>o?o:n)/2;const P=g===u?"0":"1";return vt("a","0 0,"+P,n,Ne((g?1:-1)*n,(u?-1:1)*n))+De("v",(u?-1:1)*I)+vt("a","0 0,"+P,n,Ne((g?-1:1)*n,(u?-1:1)*n))}const t=this.MAX_DYNAMIC_CONNECTION_SHAPE_WIDTH,o=2*t;return{type:this.SHAPES.ROUND,isDynamic:!0,width(n){return n/=2,n>t?t:n},height(n){return n},connectionOffsetY(n){return n/2},connectionOffsetX(n){return-n},pathDown(n){return e(n,!1,!1)},pathUp(n){return e(n,!0,!1)},pathRightDown(n){return e(n,!1,!0)},pathRightUp(n){return e(n,!1,!0)}}}makeSquared(){function e(o,n,u){o-=2*t;const g=u===n?"0":"1";return vt("a","0 0,"+g,t,Ne((u?1:-1)*t,(n?-1:1)*t))+De("v",(n?-1:1)*o)+vt("a","0 0,"+g,t,Ne((u?-1:1)*t,(n?-1:1)*t))}const t=this.CORNER_RADIUS;return{type:this.SHAPES.SQUARE,isDynamic:!0,width(o){return t},height(o){return o},connectionOffsetY(o){return o/2},connectionOffsetX(o){return-o},pathDown(o){return e(o,!1,!1)},pathUp(o){return e(o,!0,!1)},pathRightDown(o){return e(o,!1,!0)},pathRightUp(o){return e(o,!1,!0)}}}shapeFor(e){let t=e.getCheck();switch(!t&&e.targetConnection&&(t=e.targetConnection.getCheck()),e.type){case xe.INPUT_VALUE:case xe.OUTPUT_VALUE:if(e=e.getSourceBlock().getOutputShape(),e!==null)switch(e){case this.SHAPES.HEXAGONAL:return this.HEXAGONAL;case this.SHAPES.ROUND:return this.ROUNDED;case this.SHAPES.SQUARE:return this.SQUARED}return t&&t.includes("Boolean")?this.HEXAGONAL:t&&t.includes("Number")?this.ROUNDED:(t&&t.includes("String"),this.ROUNDED);case xe.PREVIOUS_STATEMENT:case xe.NEXT_STATEMENT:return this.NOTCH;default:throw Error("Unknown type")}}makeNotch(){function e(Ee){return Zt("c",[Ne(Ee*u/2,0),Ne(Ee*u*3/4,I/2),Ne(Ee*u,I)])+Ki([Ne(Ee*u,g)])+Zt("c",[Ne(Ee*u/4,I/2),Ne(Ee*u/2,I),Ne(Ee*u,I)])+De("h",Ee*n)+Zt("c",[Ne(Ee*u/2,0),Ne(Ee*u*3/4,-(I/2)),Ne(Ee*u,-I)])+Ki([Ne(Ee*u,-g)])+Zt("c",[Ne(Ee*u/4,-(I/2)),Ne(Ee*u/2,-I),Ne(Ee*u,-I)])}const t=this.NOTCH_WIDTH,o=this.NOTCH_HEIGHT,n=t/3,u=n/3,g=o/2,I=g/2,P=e(1),le=e(-1);return{type:this.SHAPES.NOTCH,width:t,height:o,pathLeft:P,pathRight:le}}makeInsideCorners(){const e=this.CORNER_RADIUS,t=vt("a","0 0,0",e,Ne(-e,e)),o=vt("a","0 0,1",e,Ne(-e,e)),n=vt("a","0 0,0",e,Ne(e,e)),u=vt("a","0 0,1",e,Ne(e,e));return{width:e,height:e,pathTop:t,pathBottom:n,rightWidth:e,rightHeight:e,pathTopRight:o,pathBottomRight:u}}generateSecondaryColour_(e){return si("#000",e,.15)||e}generateTertiaryColour_(e){return si("#000",e,.25)||e}createDom(e,t,o){super.createDom(e,t,o),e=ie(J.DEFS,{},e),t=ie(J.FILTER,{id:"blocklySelectedGlowFilter"+this.randomIdentifier,height:"160%",width:"180%",y:"-30%",x:"-40%"},e),ie(J.FEGAUSSIANBLUR,{in:"SourceGraphic",stdDeviation:this.SELECTED_GLOW_SIZE},t),o=ie(J.FECOMPONENTTRANSFER,{result:"outBlur"},t),ie(J.FEFUNCA,{type:"table",tableValues:"0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"},o),ie(J.FEFLOOD,{"flood-color":this.SELECTED_GLOW_COLOUR,"flood-opacity":1,result:"outColor"},t),ie(J.FECOMPOSITE,{in:"outColor",in2:"outBlur",operator:"in",result:"outGlow"},t),this.selectedGlowFilterId=t.id,this.selectedGlowFilter=t,e=ie(J.FILTER,{id:"blocklyReplacementGlowFilter"+this.randomIdentifier,height:"160%",width:"180%",y:"-30%",x:"-40%"},e),ie(J.FEGAUSSIANBLUR,{in:"SourceGraphic",stdDeviation:this.REPLACEMENT_GLOW_SIZE},e),t=ie(J.FECOMPONENTTRANSFER,{result:"outBlur"},e),ie(J.FEFUNCA,{type:"table",tableValues:"0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1"},t),ie(J.FEFLOOD,{"flood-color":this.REPLACEMENT_GLOW_COLOUR,"flood-opacity":1,result:"outColor"},e),ie(J.FECOMPOSITE,{in:"outColor",in2:"outBlur",operator:"in",result:"outGlow"},e),ie(J.FECOMPOSITE,{in:"SourceGraphic",in2:"outGlow",operator:"over"},e),this.replacementGlowFilterId=e.id,this.replacementGlowFilter=e}getCSS_(e){return[`${e} .blocklyText,`,`${e} .blocklyFlyoutLabelText {`,`font: ${this.FIELD_TEXT_FONTWEIGHT} ${this.FIELD_TEXT_FONTSIZE}pt ${this.FIELD_TEXT_FONTFAMILY};`,"}",`${e} .blocklyTextInputBubble textarea {`,"font-weight: normal;","}",`${e} .blocklyText {`,"fill: #fff;","}",`${e} .blocklyNonEditableText>rect:not(.blocklyDropdownRect),`,`${e} .blocklyEditableText>rect:not(.blocklyDropdownRect) {`,`fill: ${this.FIELD_BORDER_RECT_COLOUR};`,"}",`${e} .blocklyNonEditableText>text,`,`${e} .blocklyEditableText>text,`,`${e} .blocklyNonEditableText>g>text,`,`${e} .blocklyEditableText>g>text {`,"fill: #575E75;","}",`${e} .blocklyFlyoutLabelText {`,"fill: #575E75;","}",`${e} .blocklyText.blocklyBubbleText {`,"fill: #575E75;","}",`${e} .blocklyDraggable:not(.blocklyDisabled)`," .blocklyEditableText:not(.editing):hover>rect,",`${e} .blocklyDraggable:not(.blocklyDisabled)`," .blocklyEditableText:not(.editing):hover>.blocklyPath {","stroke: #fff;","stroke-width: 2;","}",`${e} .blocklyHtmlInput {`,`font-family: ${this.FIELD_TEXT_FONTFAMILY};`,`font-weight: ${this.FIELD_TEXT_FONTWEIGHT};`,"color: #575E75;","}",`${e} .blocklyDropdownText {`,"fill: #fff !important;","}",`${e}.blocklyWidgetDiv .blocklyMenuItem,`,`${e}.blocklyDropDownDiv .blocklyMenuItem {`,`font-family: ${this.FIELD_TEXT_FONTFAMILY};`,"}",`${e}.blocklyDropDownDiv .blocklyMenuItemContent {`,"color: #fff;","}",`${e} .blocklyHighlightedConnectionPath {`,`stroke: ${this.SELECTED_GLOW_COLOUR};`,"}",`${e} .blocklyDisabled > .blocklyOutlinePath {`,`fill: url(#blocklyDisabledPattern${this.randomIdentifier})`,"}",`${e} .blocklyInsertionMarker>.blocklyPath {`,`fill-opacity: ${this.INSERTION_MARKER_OPACITY};`,"stroke: none;","}"]}},ey=class extends jl{constructor(e,t){super(e,t)}draw(){const e=this.block_.pathObject;e.beginDrawing(),this.drawOutline_(),this.drawInternals_(),this.updateConnectionHighlights(),e.setPath(this.outlinePath_+` +`+this.inlinePath_),this.info_.RTL&&e.flipRTL(),this.recordSizeOnBlock_(),this.info_.outputConnection&&(e.outputShapeType=this.info_.outputConnection.shape.type),e.endDrawing()}drawOutline_(){this.info_.outputConnection&&this.info_.outputConnection.isDynamicShape&&!this.info_.hasStatementInput&&!this.info_.bottomRow.hasNextConnection?(this.drawFlatTop_(),this.drawRightDynamicConnection_(),this.drawFlatBottom_(),this.drawLeftDynamicConnection_()):super.drawOutline_()}drawLeft_(){this.info_.outputConnection&&this.info_.outputConnection.isDynamicShape?this.drawLeftDynamicConnection_():super.drawLeft_()}drawRightSideRow_(e){if(!(0>=e.height)){if(j.isSpacer(e)){const n=e.precedesStatement;var t=e.followsStatement;if(n||t){const u=this.constants_.INSIDE_CORNERS;var o=u.rightHeight;o=e.height-(n?o:0),t=t?u.pathBottomRight:"",e=0=o||0>=t)throw Error("Height and width values of an image field must be greater than 0.");this.size_=new Ze(t,o+Ci.Y_PADDING),this.imageHeight=o,typeof u=="function"&&(this.clickHandler=u),e!==lt.SKIP_SETUP&&(I?this.configure_(I):(this.flipRtl=!!g,this.altText=bt(n)||""),this.setValue(bt(e)))}configure_(e){super.configure_(e),e.flipRtl&&(this.flipRtl=e.flipRtl),e.alt&&(this.altText=bt(e.alt))}initView(){this.imageElement=ie(J.IMAGE,{height:this.imageHeight+"px",width:this.size_.width+"px",alt:this.altText},this.fieldGroup_),this.imageElement.setAttributeNS(is,"xlink:href",this.value_),this.clickHandler&&(this.imageElement.style.cursor="pointer")}updateSize_(){}doClassValidation_(e){return typeof e!="string"?null:e}doValueUpdate_(e){this.value_=e,this.imageElement&&this.imageElement.setAttributeNS(is,"xlink:href",this.value_)}getFlipRtl(){return this.flipRtl}setAlt(e){e!==this.altText&&(this.altText=e||"",this.imageElement&&this.imageElement.setAttribute("alt",this.altText))}showEditor_(){this.clickHandler&&this.clickHandler(this)}setOnClickHandler(e){this.clickHandler=e}getText_(){return this.altText}static fromJson(e){if(!e.src||!e.width||!e.height)throw Error("src, width, and height values for an image field arerequired. The width and height must be non-zero.");return new this(e.src,e.width,e.height,void 0,void 0,void 0,e)}};Ci.Y_PADDING=1,Us("field_image",Ci),Ci.prototype.DEFAULT_VALUE="";var Yl=class extends lt{constructor(e,t,o){super(lt.SKIP_SETUP),this.spellcheck_=!0,this.htmlInput_=null,this.isTextValid_=this.isBeingEdited_=!1,this.onKeyInputWrapper=this.onKeyDownWrapper=this.valueWhenEditorWasOpened_=null,this.fullBlockClickTarget_=!1,this.workspace_=null,this.SERIALIZABLE=!0,this.CURSOR="text",e!==lt.SKIP_SETUP&&(o&&this.configure_(o),this.setValue(e),t&&this.setValidator(t))}configure_(e){super.configure_(e),e.spellcheck!==void 0&&(this.spellcheck_=e.spellcheck)}initView(){if(!this.getSourceBlock())throw new _t;super.initView(),this.isFullBlockField()&&(this.clickTarget_=this.sourceBlock_.getSvgRoot())}isFullBlockField(){const e=this.getSourceBlock();if(!e)throw new _t;let t;return this.fullBlockClickTarget_=!((t=this.getConstants())==null||!t.FULL_BLOCK_FIELDS)&&e.isSimpleReporter()}doValueInvalid_(e,t=!0){this.isBeingEdited_&&(this.isDirty_=!0,this.isTextValid_=!1,e=this.value_,this.value_=this.valueWhenEditorWasOpened_,this.sourceBlock_&&C()&&this.value_!==e&&t&&z(new(ne(ee.BLOCK_CHANGE))(this.sourceBlock_,"field",this.name||null,e,this.value_)))}doValueUpdate_(e){this.isTextValid_=this.isDirty_=!0,this.value_=e}applyColour(){const e=this.getSourceBlock();if(!e)throw new _t;this.getConstants().FULL_BLOCK_FIELDS&&this.fieldGroup_&&(!this.isFullBlockField()&&this.borderRect_?(this.borderRect_.style.display="block",this.borderRect_.setAttribute("stroke",e.getColourTertiary())):(this.borderRect_.style.display="none",e.pathObject.svgPath.setAttribute("fill",this.getConstants().FIELD_BORDER_RECT_COLOUR)))}getSize(){let e;return(e=this.getConstants())!=null&&e.FULL_BLOCK_FIELDS&&(this.render_(),this.isDirty_=!1),super.getSize()}onLocationChange(){this.isBeingEdited_&&this.resizeEditor_()}render_(){if(super.render_(),this.isBeingEdited_){var e=this.htmlInput_;this.isTextValid_?(ze(e,"blocklyInvalidInput"),xt(e,Et.INVALID,!1)):(Oe(e,"blocklyInvalidInput"),xt(e,Et.INVALID,!0))}if(e=this.getSourceBlock(),!e)throw new _t;this.getConstants().FULL_BLOCK_FIELDS&&e.applyColour()}setSpellcheck(e){e!==this.spellcheck_&&(this.spellcheck_=e,this.htmlInput_&&this.htmlInput_.setAttribute("spellcheck",this.spellcheck_))}showEditor_(e,t=!1){this.workspace_=this.sourceBlock_.workspace,!t&&this.workspace_.options.modalInputs&&(Nb||kh||cl)?this.showPromptEditor():this.showInlineEditor(t)}showPromptEditor(){Ia(i.Msg$$module$build$src$core$msg.CHANGE_VALUE_TITLE,this.getText(),e=>{e!==null&&this.setValue(this.getValueFromEditorText_(e)),this.onFinishEditing_(this.value_)})}showInlineEditor(e){const t=this.getSourceBlock();if(!t)throw new _t;za(this,t.RTL,this.widgetDispose_.bind(this),this.workspace_),this.htmlInput_=this.widgetCreate_(),this.isBeingEdited_=!0,this.valueWhenEditorWasOpened_=this.value_,e||(this.htmlInput_.focus({preventScroll:!0}),this.htmlInput_.select())}widgetCreate_(){var e=this.getSourceBlock();if(!e)throw new _t;i.setGroup$$module$build$src$core$events$utils(!0);const t=oi();var o=this.getClickTarget_();if(!o)throw Error("A click target has not been set.");Oe(o,"editing"),o=document.createElement("input"),o.className="blocklyHtmlInput",o.setAttribute("spellcheck",this.spellcheck_);const n=this.workspace_.getScale();var u=this.getConstants().FIELD_TEXT_FONTSIZE*n+"pt";return t.style.fontSize=u,o.style.fontSize=u,u=Yl.BORDERRADIUS*n+"px",this.isFullBlockField()&&(u=this.getScaledBBox(),u=(u.bottom-u.top)/2+"px",e=e.getParent()?e.getParent().getColourTertiary():this.sourceBlock_.getColourTertiary(),o.style.border=1*n+"px solid "+e,t.style.borderRadius=u,t.style.transition="box-shadow 0.25s ease 0s",this.getConstants().FIELD_TEXTINPUT_BOX_SHADOW&&(t.style.boxShadow="rgba(255, 255, 255, 0.3) 0 0 0 "+4*n+"px")),o.style.borderRadius=u,t.appendChild(o),o.value=o.defaultValue=this.getEditorText_(this.value_),o.setAttribute("data-untyped-default-value",String(this.value_)),this.resizeEditor_(),this.bindInputEvents_(o),o}widgetDispose_(){this.isBeingEdited_=!1,this.isTextValid_=!0,this.forceRerender(),this.onFinishEditing_(this.value_),this.sourceBlock_&&C()&&this.valueWhenEditorWasOpened_!==null&&this.valueWhenEditorWasOpened_!==this.value_&&(z(new(ne(ee.BLOCK_CHANGE))(this.sourceBlock_,"field",this.name||null,this.valueWhenEditorWasOpened_,this.value_)),this.valueWhenEditorWasOpened_=null),i.setGroup$$module$build$src$core$events$utils(!1),this.unbindInputEvents_();var e=oi().style;if(e.width="auto",e.height="auto",e.fontSize="",e.transition="",e.boxShadow="",this.htmlInput_=null,e=this.getClickTarget_(),!e)throw Error("A click target has not been set.");ze(e,"editing")}onFinishEditing_(e){}bindInputEvents_(e){this.onKeyDownWrapper=W(e,"keydown",this,this.onHtmlInputKeyDown_),this.onKeyInputWrapper=W(e,"input",this,this.onHtmlInputChange)}unbindInputEvents_(){this.onKeyDownWrapper&&(V(this.onKeyDownWrapper),this.onKeyDownWrapper=null),this.onKeyInputWrapper&&(V(this.onKeyInputWrapper),this.onKeyInputWrapper=null)}onHtmlInputKeyDown_(e){e.key==="Enter"?(ii(this),Fs()):e.key==="Escape"?(this.setValue(this.htmlInput_.getAttribute("data-untyped-default-value"),!1),ii(this),Fs()):e.key==="Tab"&&(ii(this),Fs(),this.sourceBlock_.tab(this,!e.shiftKey),e.preventDefault())}onHtmlInputChange(e){e=this.value_,this.setValue(this.getValueFromEditorText_(this.htmlInput_.value),!1),this.sourceBlock_&&C()&&this.value_!==e&&z(new(ne(ee.BLOCK_FIELD_INTERMEDIATE_CHANGE))(this.sourceBlock_,this.name||null,e,this.value_))}setEditorValue_(e,t=!0){this.isDirty_=!0,this.isBeingEdited_&&(this.htmlInput_.value=this.getEditorText_(e)),this.setValue(e,t)}resizeEditor_(){Ts().then(()=>{const e=this.getSourceBlock();if(!e)throw new _t;const t=oi(),o=this.getScaledBBox();t.style.width=o.right-o.left+"px",t.style.height=o.bottom-o.top+"px";const n=o.top;t.style.left=`${e.RTL?o.right-t.offsetWidth:o.left}px`,t.style.top=`${n}px`})}repositionForWindowResize(){let e;const t=(e=this.getSourceBlock())==null?void 0:e.getRootBlock();return t instanceof $s?(Ji(this.workspace_,this.workspace_.getMetricsManager().getViewMetrics(!0),t)||this.resizeEditor_(),!0):!1}isTabNavigable(){return!0}getText_(){return this.isBeingEdited_&&this.htmlInput_?this.htmlInput_.value:null}getEditorText_(e){return`${e}`}getValueFromEditorText_(e){return e}};Yl.BORDERRADIUS=4;var Kl=class extends Yl{constructor(e,t,o){super(e,t,o)}doClassValidation_(e){return e===void 0?null:`${e}`}static fromJson(e){return new this(bt(e.text),void 0,e)}};Us("field_input",Kl),Kl.prototype.DEFAULT_VALUE="";var ty=class extends ap{constructor(e){super(e)}endsWithElemSpacer(){return!1}hasLeftSquareCorner(e){return!!e.outputConnection}hasRightSquareCorner(e){return!!e.outputConnection&&!e.statementInputCount&&!e.nextConnection}},Jl=class extends xr{constructor(e,t){if(super(e,t),this.connectedBottomNextConnection=!1,this.connectedBlock){for(e=this.connectedBlock;t=e.getNextBlock();)e=t;e.nextConnection||(this.height=this.connectedBlockHeight,this.connectedBottomNextConnection=!0)}}},sy=class extends Vs{constructor(e){super(e),this.width=this.height=0,this.type|=j.getType("RIGHT_CONNECTION")}},oy=class extends hp{constructor(e){super(e)}endsWithElemSpacer(){return!1}hasLeftSquareCorner(e){const t=(e.hat?e.hat==="cap":this.constants_.ADD_START_HATS)&&!e.outputConnection&&!e.previousConnection;return!!e.outputConnection||t}hasRightSquareCorner(e){return!!e.outputConnection&&!e.statementInputCount&&!e.nextConnection}},iy=class extends Or{constructor(e,t){super(e,t),this.isInline=!0,this.renderer_=e,this.constants_=this.renderer_.getConstants(),this.topRow=new oy(this.constants_),this.bottomRow=new ty(this.constants_),this.isMultiRow=!t.getInputsInline()||t.isCollapsed(),this.hasStatementInput=0=this.rows.length-1?!!this.bottomRow.hasNextConnection:!!n.precedesStatement,j.isInputRow(g)&&g.hasStatement){g.measure();let I,P;t=g.width-((P=(I=g.getLastInput())==null?void 0:I.width)!=null?P:0)+e}else if(o&&(u===2||n)&&j.isInputRow(g)&&!g.hasStatement){n=g.xPos,o=null;for(let I=0;Io?o:this.height/2,t-o*(1-Math.sin(Math.acos((o-this.constants_.SMALL_PADDING)/o)))):0;if(j.isInlineInput(e)&&e instanceof zo){const u=e.connectedBlock;return e=u?u.pathObject.outputShapeType:e.shape.type,e==null||u&&u.outputConnection&&(u.statementInputCount||u.nextConnection)||o===n.SHAPES.HEXAGONAL&&o!==e?0:t-this.constants_.SHAPE_IN_SHAPE_PADDING[o][e]}return j.isField(e)&&e instanceof hn?o===n.SHAPES.ROUND&&e.field instanceof Kl?t-2.75*n.GRID_UNIT:t-this.constants_.SHAPE_IN_SHAPE_PADDING[o][0]:j.isIcon(e)?this.constants_.SMALL_PADDING:0}finalizeVerticalAlignment_(){if(!this.outputConnection)for(let n=2;n=this.rows.length-1?!!this.bottomRow.hasNextConnection:!!I.precedesStatement;if(e?this.topRow.hasPreviousConnection:u.followsStatement){var o=g.elements[1];if(o=g.elements.length===3&&o instanceof hn&&(o.field instanceof _i||o.field instanceof Ci),!e&&o)u.height-=this.constants_.SMALL_PADDING,I.height-=this.constants_.SMALL_PADDING,g.height-=this.constants_.MEDIUM_PADDING;else if(!e&&!t)u.height+=this.constants_.SMALL_PADDING;else if(t){for(e=!1,t=0;t{if(!n.isDeadOrDying()){i.disable$$module$build$src$core$events$utils();try{n==null||n.positionNearConnection(u,g,I),n==null||n.getSvgRoot().setAttribute("visibility","visible")}finally{i.enable$$module$build$src$core$events$utils()}}}),u}createInsertionMarker(e){const t=os(e,{addCoordinates:!1,addInputBlocks:!1,addNextBlocks:!1,doFullSerialization:!1});if(!t)throw Error(`Failed to serialize source block. ${e.toDevString()}`);e=lo(t,this.workspace);for(const o of e.getDescendants(!1))o.setInsertionMarker(!0);return e.initSvg(),e.getSvgRoot().setAttribute("visibility","hidden"),e}getMatchingConnection(e,t,o){if(e=e.getConnections_(!0),t=t.getConnections_(!0),e.length!==t.length)return null;for(let n=0;n{this.targetWorkspace.isDragging()||t.addSelect()})),this.listeners.push(ue(e,"pointerleave",t,()=>{this.targetWorkspace.isDragging()||t.removeSelect()})),this.listeners.push(ue(o,"pointerenter",t,()=>{this.targetWorkspace.isDragging()||t.addSelect()})),this.listeners.push(ue(o,"pointerleave",t,()=>{this.targetWorkspace.isDragging()||t.removeSelect()}))}blockMouseDown(e){return t=>{const o=this.targetWorkspace.getGesture(t);o&&(o.setStartBlock(e),o.handleFlyoutStart(t,this))}}onMouseDown(e){const t=this.targetWorkspace.getGesture(e);t&&t.handleFlyoutStart(e,this)}isBlockCreatable(e){return e.isEnabled()}createBlock(e){let t=null;i.disable$$module$build$src$core$events$utils();var o=this.targetWorkspace.getAllVariables();this.targetWorkspace.setResizesEnabled(!1);try{t=this.placeNewBlock(e)}finally{i.enable$$module$build$src$core$events$utils()}if(this.targetWorkspace.hideChaff(),e=qn(this.targetWorkspace,o),C()){for(i.setGroup$$module$build$src$core$events$utils(!0),o=0;o-t||e<-180+t||e>180-t}getClientRect(){if(!this.svgGroup_||this.autoClose||!this.isVisible())return null;const e=this.svgGroup_.getBoundingClientRect(),t=e.left;return this.toolboxPosition_===Ge.LEFT?new rt(-1e9,1e9,-1e9,t+e.width):new rt(-1e9,1e9,t,1e9)}reflowInternal_(){this.workspace_.scale=this.getFlyoutScale();let e=0;var t=this.workspace_.getTopBlocks(!1);for(let n=0,u;u=t[n];n++){var o=u.getHeightWidth().width;u.outputConnection&&(o-=this.tabWidth_),e=Math.max(e,o)}for(let n=0,u;u=this.buttons_[n];n++)e=Math.max(e,u.width);if(e+=1.5*this.MARGIN+this.tabWidth_,e*=this.workspace_.scale,e+=yt.scrollbarThickness,this.width_!==e){for(let n=0,u;u=t[n];n++){if(this.RTL){o=u.getRelativeToSurfaceXY().x;let g=e/this.workspace_.scale-this.MARGIN;u.outputConnection||(g-=this.tabWidth_),u.moveBy(g-o,0)}this.rectMap_.has(u)&&this.moveRectToBlock_(this.rectMap_.get(u),u)}if(this.RTL)for(let n=0,u;u=this.buttons_[n];n++)t=u.getPosition().y,u.moveTo(e/this.workspace_.scale-u.width-this.MARGIN-this.tabWidth_,t);this.targetWorkspace.scrollbar||this.autoClose||this.targetWorkspace.getFlyout()!==this||this.toolboxPosition_!==Ge.LEFT||this.targetWorkspace.translate(this.targetWorkspace.scrollX+e,this.targetWorkspace.scrollY),this.width_=e,this.position(),this.targetWorkspace.resizeContents(),this.targetWorkspace.recordDragTargets()}}};Rp.registryName="verticalFlyout",r($e.FLYOUTS_VERTICAL_TOOLBOX,Ws,Rp);var cy=class extends Jl{constructor(e){super(e),this.horizontalLayout=!0}setMetrics_(e){if(this.isVisible()){var t=this.workspace_.getMetricsManager(),o=t.getScrollMetrics(),n=t.getViewMetrics();t=t.getAbsoluteMetrics(),typeof e.x=="number"&&(this.workspace_.scrollX=-(o.left+(o.width-n.width)*e.x)),this.workspace_.translate(this.workspace_.scrollX+t.left,this.workspace_.scrollY+t.top)}}getX(){return 0}getY(){if(!this.isVisible())return 0;var e=this.targetWorkspace.getMetricsManager();const t=e.getAbsoluteMetrics(),o=e.getViewMetrics();e=e.getToolboxMetrics();const n=this.toolboxPosition_===Ge.TOP;return this.targetWorkspace.toolboxPosition===this.toolboxPosition_?this.targetWorkspace.getToolbox()?n?e.height:o.height-this.height_:n?0:o.height:n?0:o.height+t.top-this.height_}position(){if(this.isVisible()&&this.targetWorkspace.isVisible()){var e=this.targetWorkspace.getMetricsManager().getViewMetrics();this.width_=e.width,this.setBackgroundPath(e.width-2*this.CORNER_RADIUS,this.height_-this.CORNER_RADIUS),e=this.getX();var t=this.getY();this.positionAt_(this.width_,this.height_,e,t)}}setBackgroundPath(e,t){const o=this.toolboxPosition_===Ge.TOP,n=["M 0,"+(o?0:this.CORNER_RADIUS)];o?(n.push("h",e+2*this.CORNER_RADIUS),n.push("v",t),n.push("a",this.CORNER_RADIUS,this.CORNER_RADIUS,0,0,1,-this.CORNER_RADIUS,this.CORNER_RADIUS),n.push("h",-e),n.push("a",this.CORNER_RADIUS,this.CORNER_RADIUS,0,0,1,-this.CORNER_RADIUS,-this.CORNER_RADIUS)):(n.push("a",this.CORNER_RADIUS,this.CORNER_RADIUS,0,0,1,this.CORNER_RADIUS,-this.CORNER_RADIUS),n.push("h",e),n.push("a",this.CORNER_RADIUS,this.CORNER_RADIUS,0,0,1,this.CORNER_RADIUS,this.CORNER_RADIUS),n.push("v",t),n.push("h",-e-2*this.CORNER_RADIUS)),n.push("z"),this.svgBackground_.setAttribute("d",n.join(" "))}scrollToStart(){let e;(e=this.workspace_.scrollbar)==null||e.setX(this.RTL?1/0:0)}wheel_(e){var t=Le(e);if(t=t.x||t.y){const o=this.workspace_.getMetricsManager(),n=o.getScrollMetrics();t=o.getViewMetrics().left-n.left+t;let u;(u=this.workspace_.scrollbar)==null||u.setX(t),tr(this.workspace_),Fs()}e.preventDefault(),e.stopPropagation()}layout_(e,t){this.workspace_.scale=this.targetWorkspace.scale;const o=this.MARGIN;let n=o+this.tabWidth_;this.RTL&&(e=e.reverse());for(let L=0,le;le=e[L];L++)if(le.type==="block"){var u=le.block;if(u==null)continue;var g=u.getDescendants(!1);for(let dt=0,ut;ut=g[dt];dt++)ut.isInFlyout=!0;g=u.getSvgRoot();const Ee=u.getHeightWidth();var I=u.outputConnection?this.tabWidth_:0;I=this.RTL?n+Ee.width:n-I,u.moveBy(I,o),I=this.createRect_(u,I,o,Ee,L),n+=Ee.width+t[L],this.addBlockListeners_(g,u,I)}else le.type==="button"&&(u=le.button,this.initFlyoutButton_(u,n,o),n+=u.width+t[L])}isDragTowardWorkspace(e){e=Math.atan2(e.y,e.x)/Math.PI*180;const t=this.dragAngleRange_;return e<90+t&&e>90-t||e>-90-t&&e<-90+t}getClientRect(){if(!this.svgGroup_||this.autoClose||!this.isVisible())return null;const e=this.svgGroup_.getBoundingClientRect(),t=e.top;return this.toolboxPosition_===Ge.TOP?new rt(-1e9,t+e.height,-1e9,1e9):new rt(t,1e9,-1e9,1e9)}reflowInternal_(){this.workspace_.scale=this.getFlyoutScale();let e=0;const t=this.workspace_.getTopBlocks(!1);for(let n=0,u;u=t[n];n++)e=Math.max(e,u.getHeightWidth().height);const o=this.buttons_;for(let n=0,u;u=o[n];n++)e=Math.max(e,u.height);if(e+=1.5*this.MARGIN,e*=this.workspace_.scale,e+=yt.scrollbarThickness,this.height_!==e){for(let n=0,u;u=t[n];n++)this.rectMap_.has(u)&&this.moveRectToBlock_(this.rectMap_.get(u),u);this.targetWorkspace.scrollbar||this.autoClose||this.targetWorkspace.getFlyout()!==this||this.toolboxPosition_!==Ge.TOP||this.targetWorkspace.translate(this.targetWorkspace.scrollX,this.targetWorkspace.scrollY+e),this.height_=e,this.position(),this.targetWorkspace.resizeContents(),this.targetWorkspace.recordDragTargets()}}};r($e.FLYOUTS_HORIZONTAL_TOOLBOX,Ws,cy);var Lr=class extends es{constructor(e,t,o,n,u){super(lt.SKIP_SETUP),this.defaultType="",this.variableTypes=[],this.variable=null,this.SERIALIZABLE=!0,this.menuGenerator_=Lr.dropdownCreate,this.defaultVariableName=typeof e=="string"?e:"",this.size_=new Xe(0,0),e!==lt.SKIP_SETUP&&(u?this.configure_(u):this.setTypes(o,n),t&&this.setValidator(t))}configure_(e){super.configure_(e),this.setTypes(e.variableTypes,e.defaultType)}initModel(){var e=this.getSourceBlock();if(!e)throw new _t;this.variable||(e=i.getOrCreateVariablePackage$$module$build$src$core$variables(e.workspace,null,this.defaultVariableName,this.defaultType),this.doValueUpdate_(e.getId()))}shouldAddBorderRect_(){const e=this.getSourceBlock();if(!e)throw new _t;return super.shouldAddBorderRect_()&&(!this.getConstants().FIELD_DROPDOWN_NO_BORDER_RECT_SHADOW||e.type!=="variables_get")}fromXml(e){var t=this.getSourceBlock();if(!t)throw new _t;const o=e.getAttribute("id"),n=e.textContent,u=e.getAttribute("variabletype")||e.getAttribute("variableType")||"";if(t=i.getOrCreateVariablePackage$$module$build$src$core$variables(t.workspace,o,n,u),u!==null&&u!==t.type)throw Error("Serialized variable type with id '"+t.getId()+"' had type "+t.type+", and does not match variable field that references it: "+zs(e)+".");this.setValue(t.getId())}toXml(e){return this.initModel(),e.id=this.variable.getId(),e.textContent=this.variable.name,this.variable.type&&e.setAttribute("variabletype",this.variable.type),e}saveState(e){var t=this.saveLegacyState(Lr);return t!==null||(this.initModel(),t={id:this.variable.getId()},e&&(t.name=this.variable.name,t.type=this.variable.type)),t}loadState(e){const t=this.getSourceBlock();if(!t)throw new _t;this.loadLegacyState(Lr,e)||(e=i.getOrCreateVariablePackage$$module$build$src$core$variables(t.workspace,e.id||null,e.name,e.type||""),this.setValue(e.getId()))}setSourceBlock(e){if(e.isShadow())throw Error("Variable fields are not allowed to exist on shadow blocks.");super.setSourceBlock(e)}getValue(){return this.variable?this.variable.getId():null}getText(){return this.variable?this.variable.name:""}getVariable(){return this.variable}getValidator(){return this.variable?this.validator_:null}doClassValidation_(e){if(e===null)return null;var t=this.getSourceBlock();if(!t)throw new _t;return t=i.getVariable$$module$build$src$core$variables(t.workspace,e),t?(t=t.type,this.typeIsAllowed(t)?e:(console.warn("Variable type doesn't match this field! Type was "+t),null)):(console.warn("Variable id doesn't point to a real variable! ID was "+e),null)}doValueUpdate_(e){const t=this.getSourceBlock();if(!t)throw new _t;this.variable=i.getVariable$$module$build$src$core$variables(t.workspace,e),super.doValueUpdate_(e)}typeIsAllowed(e){const t=this.getVariableTypes();if(!t)return!0;for(let o=0;othis.max_&&(e.max=`${this.max_}`,xt(e,Et.VALUEMAX,this.max_)),e}static fromJson(e){return new this(e.value,void 0,void 0,void 0,void 0,e)}};Us("field_number",Op),Op.prototype.DEFAULT_VALUE=0;var uy=class extends _i{constructor(e,t,o){super(String(e??""),t,o),this.EDITABLE=!1,this.SERIALIZABLE=!0}static fromJson(e){return new this(bt(e.text),void 0,e)}};Us("field_label_serializable",uy);var Ti=class extends lt{constructor(e,t,o){super(lt.SKIP_SETUP),this.SERIALIZABLE=!0,this.CURSOR="default",this.value_=this.value_,this.checkChar=Ti.CHECK_CHAR,e!==lt.SKIP_SETUP&&(o&&this.configure_(o),this.setValue(e),t&&this.setValidator(t))}configure_(e){super.configure_(e),e.checkCharacter&&(this.checkChar=e.checkCharacter)}saveState(){const e=this.saveLegacyState(Ti);return e!==null?e:this.getValueBoolean()}initView(){super.initView();const e=this.getTextElement();Re(e,"blocklyCheckbox"),e.style.display=this.value_?"block":"none"}render_(){this.textContent_&&(this.textContent_.nodeValue=this.getDisplayText_()),this.updateSize_(this.getConstants().FIELD_CHECKBOX_X_OFFSET)}getDisplayText_(){return this.checkChar}setCheckCharacter(e){this.checkChar=e||Ti.CHECK_CHAR,this.forceRerender()}showEditor_(){this.setValue(!this.value_)}doClassValidation_(e){return e===!0||e==="TRUE"?"TRUE":e===!1||e==="FALSE"?"FALSE":null}doValueUpdate_(e){this.value_=this.convertValueToBool(e),this.textElement_&&(this.textElement_.style.display=this.value_?"block":"none")}getValue(){return this.value_?"TRUE":"FALSE"}getValueBoolean(){return this.value_}getText(){return String(this.convertValueToBool(this.value_))}convertValueToBool(e){return typeof e=="string"?e==="TRUE":!!e}static fromJson(e){return new this(e.checked,void 0,e)}};Ti.CHECK_CHAR="✓",Us("field_checkbox",Ti),Ti.prototype.DEFAULT_VALUE=!1;var dy=class{constructor(e,t){this.draggable=e,this.workspace=t,this.dragTarget=null,this.startLoc=e.getRelativeToSurfaceXY()}onDragStart(e){this.draggable.startDrag(e)}onDrag(e,t){this.moveDraggable(e,t),t=this.getRoot(this.draggable),ds(t)&&t.setDeleteStyle(this.wouldDeleteDraggable(e,t)),this.updateDragTarget(e)}updateDragTarget(e){e=this.workspace.getDragTarget(e);const t=this.getRoot(this.draggable);if(this.dragTarget!==e){let o;(o=this.dragTarget)==null||o.onDragExit(t),e==null||e.onDragEnter(t)}e==null||e.onDragOver(t),this.dragTarget=e}moveDraggable(e,t){t=this.pixelsToWorkspaceUnits(t),t=ye.sum(this.startLoc,t),this.draggable.drag(t,e)}wouldDeleteDraggable(e,t){return(e=this.workspace.getDragTarget(e))&&this.workspace.getComponentManager().hasCapability(e.id,gt.Capability.DELETE_AREA)?e.wouldDelete(t):!1}onDragEnd(e){const t=i.getGroup$$module$build$src$core$events$utils();var o=this.workspace.getDragTarget(e);const n=this.getRoot(this.draggable);if(o){let u;(u=this.dragTarget)==null||u.onDrop(n)}this.shouldReturnToStart(e,n)&&this.draggable.revertDrag(),(o=ds(n)&&this.wouldDeleteDraggable(e,n))&&this.draggable instanceof $s&&Wa(this.draggable.getRootBlock()),this.draggable.endDrag(e),o&&ds(n)&&(e=i.getGroup$$module$build$src$core$events$utils(),i.setGroup$$module$build$src$core$events$utils(t),n.dispose(),i.setGroup$$module$build$src$core$events$utils(e))}getRoot(e){return e instanceof $s?e.getRootBlock():e}shouldReturnToStart(e,t){return(e=this.workspace.getDragTarget(e))?e.shouldPreventMove(t):!1}pixelsToWorkspaceUnits(e){return e=new ye(e.x/this.workspace.scale,e.y/this.workspace.scale),this.workspace.isMutator&&e.scale(1/this.workspace.options.parentWorkspace.scale),e}};r($e.BLOCK_DRAGGER,Ws,dy);var Pr={};Pr.BlockDragStrategy=Fv,Pr.BubbleDragStrategy=wv,Pr.CommentDragStrategy=fv,Pr.Dragger=dy;var Np=class extends Ss{constructor(e,t,o){super(e?e.workspace.id:void 0),this.type=ee.BLOCK_DRAG,e&&(this.blockId=e.id,this.isStart=t,this.blocks=o)}toJson(){const e=super.toJson();if(this.isStart===void 0)throw Error("Whether this event is the start of a drag is undefined. Either pass the value to the constructor, or call fromJson");if(this.blockId===void 0)throw Error("The block ID is undefined. Either pass a block to the constructor, or call fromJson");return e.isStart=this.isStart,e.blockId=this.blockId,e.blocks=this.blocks,e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new Np),t.isStart=e.isStart,t.blockId=e.blockId,t.blocks=e.blocks,t}};r($e.EVENT,ee.BLOCK_DRAG,Np);var Mp=class extends gi{constructor(e,t,o,n){super(e),this.type=ee.BLOCK_FIELD_INTERMEDIATE_CHANGE,this.recordUndo=!1,e&&(this.name=t,this.oldValue=o,this.newValue=n)}toJson(){const e=super.toJson();if(!this.name)throw Error("The changed field name is undefined. Either pass a name to the constructor, or call fromJson.");return e.name=this.name,e.oldValue=this.oldValue,e.newValue=this.newValue,e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new Mp),t.name=e.name,t.oldValue=e.oldValue,t.newValue=e.newValue,t}isNull(){return this.oldValue===this.newValue}run(e){var t=this.getEventWorkspace_();if(!this.blockId)throw Error("The block ID is undefined. Either pass a block to the constructor, or call fromJson");if(t=t.getBlockById(this.blockId),!t)throw Error("The associated block is undefined. Either pass a block to the constructor, or call fromJson");e=e?this.newValue:this.oldValue,(t=t.getField(this.name))?t.setValue(e):console.warn("Can't set non-existent field: "+this.name)}};r($e.EVENT,ee.BLOCK_FIELD_INTERMEDIATE_CHANGE,Mp);var Lp=class extends gi{constructor(e){super(e),this.type=ee.BLOCK_MOVE,e&&(e.isShadow()&&(this.recordUndo=!1),e=this.currentLocation(),this.oldParentId=e.parentId,this.oldInputName=e.inputName,this.oldCoordinate=e.coordinate)}toJson(){const e=super.toJson();return e.oldParentId=this.oldParentId,e.oldInputName=this.oldInputName,this.oldCoordinate&&(e.oldCoordinate=`${Math.round(this.oldCoordinate.x)}, ${Math.round(this.oldCoordinate.y)}`),e.newParentId=this.newParentId,e.newInputName=this.newInputName,this.newCoordinate&&(e.newCoordinate=`${Math.round(this.newCoordinate.x)}, ${Math.round(this.newCoordinate.y)}`),this.reason&&(e.reason=this.reason),this.recordUndo||(e.recordUndo=this.recordUndo),e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new Lp),t.oldParentId=e.oldParentId,t.oldInputName=e.oldInputName,e.oldCoordinate&&(o=e.oldCoordinate.split(","),t.oldCoordinate=new ye(Number(o[0]),Number(o[1]))),t.newParentId=e.newParentId,t.newInputName=e.newInputName,e.newCoordinate&&(o=e.newCoordinate.split(","),t.newCoordinate=new ye(Number(o[0]),Number(o[1]))),e.reason!==void 0&&(t.reason=e.reason),e.recordUndo!==void 0&&(t.recordUndo=e.recordUndo),t}recordNew(){const e=this.currentLocation();this.newParentId=e.parentId,this.newInputName=e.inputName,this.newCoordinate=e.coordinate}setReason(e){this.reason=e}currentLocation(){var e=this.getEventWorkspace_();if(!this.blockId)throw Error("The block ID is undefined. Either pass a block to the constructor, or call fromJson");var t=e.getBlockById(this.blockId);if(!t)throw Error("The block associated with the block move event could not be found");e={};const o=t.getParent();return o?(e.parentId=o.id,(t=o.getInputWithBlock(t))&&(e.inputName=t.name)):e.coordinate=t.getRelativeToSurfaceXY(),e}isNull(){return this.oldParentId===this.newParentId&&this.oldInputName===this.newInputName&&ye.equals(this.oldCoordinate,this.newCoordinate)}run(e){var t=this.getEventWorkspace_();if(!this.blockId)throw Error("The block ID is undefined. Either pass a block to the constructor, or call fromJson");var o=t.getBlockById(this.blockId);if(o){var n=e?this.newParentId:this.oldParentId,u=e?this.newInputName:this.oldInputName;if(e=e?this.newCoordinate:this.oldCoordinate,n){var g=t.getBlockById(n);if(!g){console.warn("Can't connect to non-existent block: "+n);return}}if(o.getParent()&&o.unplug(),e)u=o.getRelativeToSurfaceXY(),o.moveBy(e.x-u.x,e.y-u.y,this.reason);else{t=o.outputConnection,(!t||o.previousConnection&&o.previousConnection.isConnected())&&(t=o.previousConnection);let I,L;o=(L=t)==null?void 0:L.type,u?(o=g.getInput(u))&&(I=o.connection):o===xe.PREVIOUS_STATEMENT&&(I=g.nextConnection),I&&t?t.connect(I):console.warn("Can't connect to non-existent input: "+u)}}else console.warn("Can't move non-existent block: "+this.blockId)}};r($e.EVENT,ee.BLOCK_MOVE,Lp);var Pp=class extends Ss{constructor(e,t,o){super(e?e.workspace.id:void 0),this.type=ee.BUBBLE_OPEN,e&&(this.blockId=e.id,this.isOpen=t,this.bubbleType=o)}toJson(){const e=super.toJson();if(this.isOpen===void 0)throw Error("Whether this event is for opening the bubble is undefined. Either pass the value to the constructor, or call fromJson");if(!this.bubbleType)throw Error("The type of bubble is undefined. Either pass the value to the constructor, or call fromJson");return e.isOpen=this.isOpen,e.bubbleType=this.bubbleType,e.blockId=this.blockId||"",e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new Pp),t.isOpen=e.isOpen,t.bubbleType=e.bubbleType,t.blockId=e.blockId,t}},Bp;(function(e){e.MUTATOR="mutator",e.COMMENT="comment",e.WARNING="warning"})(Bp||(Bp={})),r($e.EVENT,ee.BUBBLE_OPEN,Pp);var qs=class extends qi{constructor(e){super(),this.isBlank=!e,e&&(this.commentId=e.id,this.workspaceId=e.workspace.id,this.group=i.getGroup$$module$build$src$core$events$utils(),this.recordUndo=G())}toJson(){const e=super.toJson();if(!this.commentId)throw Error("The comment ID is undefined. Either pass a comment to the constructor, or call fromJson");return e.commentId=this.commentId,e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new qs),t.commentId=e.commentId,t}static CommentCreateDeleteHelper(e,t){const o=e.getEventWorkspace_();if(t){if(!e.json)throw Error("Encountered a comment event without proper json");Kn(e.json,o)}else{if(!e.commentId)throw Error("The comment ID is undefined. Either pass a comment to the constructor, or call fromJson");(t=o.getCommentById(e.commentId))?t.dispose():console.warn("Can't delete non-existent comment: "+e.commentId)}}},jp=class extends qs{constructor(e,t,o){super(e),this.type=ee.COMMENT_CHANGE,e&&(this.oldContents_=typeof t>"u"?"":t,this.newContents_=typeof o>"u"?"":o)}toJson(){const e=super.toJson();if(!this.oldContents_)throw Error("The old contents is undefined. Either pass a value to the constructor, or call fromJson");if(!this.newContents_)throw Error("The new contents is undefined. Either pass a value to the constructor, or call fromJson");return e.oldContents=this.oldContents_,e.newContents=this.newContents_,e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new jp),t.oldContents_=e.oldContents,t.newContents_=e.newContents,t}isNull(){return this.oldContents_===this.newContents_}run(e){var t=this.getEventWorkspace_();if(!this.commentId)throw Error("The comment ID is undefined. Either pass a comment to the constructor, or call fromJson");if(t=t.getCommentById(this.commentId)){var o=e?this.newContents_:this.oldContents_;if(o===void 0)throw Error(e?"The new contents is undefined. Either pass a value to the constructor, or call fromJson":"The old contents is undefined. Either pass a value to the constructor, or call fromJson");t.setText(o)}else console.warn("Can't change non-existent comment: "+this.commentId)}};r($e.EVENT,ee.COMMENT_CHANGE,jp);var Fp=class extends qs{constructor(e,t){super(e),this.newCollapsed=t,this.type=ee.COMMENT_COLLAPSE}toJson(){const e=super.toJson();if(this.newCollapsed===void 0)throw Error("The new collapse value undefined. Either call recordNew, or call fromJson");return e.newCollapsed=this.newCollapsed,e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new Fp),t.newCollapsed=e.newCollapsed,t}run(e){var t=this.getEventWorkspace_();if(!this.commentId)throw Error("The comment ID is undefined. Either pass a comment to the constructor, or call fromJson");(t=t.getCommentById(this.commentId))?t.setCollapsed(e?!!this.newCollapsed:!this.newCollapsed):console.warn("Can't collapse or uncollapse non-existent comment: "+this.commentId)}};r($e.EVENT,ee.COMMENT_COLLAPSE,Fp);var zp=class extends qs{constructor(e){super(e),this.type=ee.COMMENT_CREATE,e&&(this.xml=ir(e),this.json=Pi(e,{addCoordinates:!0}))}toJson(){const e=super.toJson();if(!this.xml)throw Error("The comment XML is undefined. Either pass a comment to the constructor, or call fromJson");if(!this.json)throw Error("The comment JSON is undefined. Either pass a block to the constructor, or call fromJson");return e.xml=zs(this.xml),e.json=this.json,e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new zp),t.xml=i.textToDom$$module$build$src$core$utils$xml(e.xml),t.json=e.json,t}run(e){qs.CommentCreateDeleteHelper(this,e)}};r($e.EVENT,ee.COMMENT_CREATE,zp);var Up=class extends qs{constructor(e){super(e),this.type=ee.COMMENT_DELETE,e&&(this.xml=ir(e),this.json=Pi(e,{addCoordinates:!0}))}run(e){qs.CommentCreateDeleteHelper(this,!e)}toJson(){const e=super.toJson();if(!this.xml)throw Error("The comment XML is undefined. Either pass a comment to the constructor, or call fromJson");if(!this.json)throw Error("The comment JSON is undefined. Either pass a block to the constructor, or call fromJson");return e.xml=zs(this.xml),e.json=this.json,e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new Up),t.xml=i.textToDom$$module$build$src$core$utils$xml(e.xml),t.json=e.json,t}};r($e.EVENT,ee.COMMENT_DELETE,Up);var Hp=class extends Ss{constructor(e,t){super(e?e.workspace.id:void 0),this.type=ee.COMMENT_DRAG,e&&(this.commentId=e.id,this.isStart=t)}toJson(){const e=super.toJson();if(this.isStart===void 0)throw Error("Whether this event is the start of a drag is undefined. Either pass the value to the constructor, or call fromJson");if(this.commentId===void 0)throw Error("The comment ID is undefined. Either pass a comment to the constructor, or call fromJson");return e.isStart=this.isStart,e.commentId=this.commentId,e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new Hp),t.isStart=e.isStart,t.commentId=e.commentId,t}};r($e.EVENT,ee.COMMENT_DRAG,Hp);var Wp=class extends qs{constructor(e){super(e),this.type=ee.COMMENT_MOVE,e&&(this.comment_=e,this.oldCoordinate_=e.getRelativeToSurfaceXY())}recordNew(){if(this.newCoordinate_)throw Error("Tried to record the new position of a comment on the same event twice.");if(!this.comment_)throw Error("The comment is undefined. Pass a comment to the constructor if you want to use the record functionality");this.newCoordinate_=this.comment_.getRelativeToSurfaceXY()}setReason(e){this.reason=e}setOldCoordinate(e){this.oldCoordinate_=e}toJson(){const e=super.toJson();if(!this.oldCoordinate_)throw Error("The old comment position is undefined. Either pass a comment to the constructor, or call fromJson");if(!this.newCoordinate_)throw Error("The new comment position is undefined. Either call recordNew, or call fromJson");return e.oldCoordinate=`${Math.round(this.oldCoordinate_.x)}, ${Math.round(this.oldCoordinate_.y)}`,e.newCoordinate=Math.round(this.newCoordinate_.x)+","+Math.round(this.newCoordinate_.y),e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new Wp),o=e.oldCoordinate.split(","),t.oldCoordinate_=new ye(Number(o[0]),Number(o[1])),o=e.newCoordinate.split(","),t.newCoordinate_=new ye(Number(o[0]),Number(o[1])),t}isNull(){return ye.equals(this.oldCoordinate_,this.newCoordinate_)}run(e){var t=this.getEventWorkspace_();if(!this.commentId)throw Error("The comment ID is undefined. Either pass a comment to the constructor, or call fromJson");if(t=t.getCommentById(this.commentId)){if(e=e?this.newCoordinate_:this.oldCoordinate_,!e)throw Error("Either oldCoordinate_ or newCoordinate_ is undefined. Either pass a comment to the constructor and call recordNew, or call fromJson");t.moveTo(e)}else console.warn("Can't move non-existent comment: "+this.commentId)}};r($e.EVENT,ee.COMMENT_MOVE,Wp);var Gp=class extends qs{constructor(e){super(e),this.type=ee.COMMENT_RESIZE,e&&(this.oldSize=e.getSize())}recordCurrentSizeAsNewSize(){if(this.newSize)throw Error("Tried to record the new size of a comment on the same event twice.");var e=this.getEventWorkspace_();if(!this.commentId)throw Error("The comment ID is undefined. Either pass a comment to the constructor, or call fromJson");if(e=e.getCommentById(this.commentId),!e)throw Error("The comment associated with the comment resize event could not be found");this.newSize=e.getSize()}toJson(){const e=super.toJson();if(!this.oldSize)throw Error("The old comment size is undefined. Either pass a comment to the constructor, or call fromJson");if(!this.newSize)throw Error("The new comment size is undefined. Either call recordCurrentSizeAsNewSize, or call fromJson");return e.oldWidth=Math.round(this.oldSize.width),e.oldHeight=Math.round(this.oldSize.height),e.newWidth=Math.round(this.newSize.width),e.newHeight=Math.round(this.newSize.height),e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new Gp),t.oldSize=new Xe(e.oldWidth,e.oldHeight),t.newSize=new Xe(e.newWidth,e.newHeight),t}isNull(){return Xe.equals(this.oldSize,this.newSize)}run(e){var t=this.getEventWorkspace_();if(!this.commentId)throw Error("The comment ID is undefined. Either pass a comment to the constructor, or call fromJson");if(t=t.getCommentById(this.commentId)){if(e=e?this.newSize:this.oldSize,!e)throw Error("Either oldSize or newSize is undefined. Either pass a comment to the constructor and call recordCurrentSizeAsNewSize, or call fromJson");t.setSize(e)}else console.warn("Can't resize non-existent comment: "+this.commentId)}};r($e.EVENT,ee.COMMENT_RESIZE,Gp);var Vp=class extends Ss{constructor(e,t,o){super(o),this.type=ee.TOOLBOX_ITEM_SELECT,this.oldItem=e??void 0,this.newItem=t??void 0}toJson(){const e=super.toJson();return e.oldItem=this.oldItem,e.newItem=this.newItem,e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new Vp),t.oldItem=e.oldItem,t.newItem=e.newItem,t}};r($e.EVENT,ee.TOOLBOX_ITEM_SELECT,Vp);var hy=class extends qi{constructor(e){super(),this.isBlank=!0,this.recordUndo=!1,this.type=ee.FINISHED_LOADING,this.isBlank=!!e,e&&(this.workspaceId=e.id)}};r($e.EVENT,ee.FINISHED_LOADING,hy);var py,gy,my,fy,$y,by,vy,yy,_y,wy,ky,Cy,Ty,Sy,Ey,Iy,xy,Dy,Ay,Ry,Oy,Ny,My,Ly,Py,Se;i.BLOCK_CHANGE$$module$build$src$core$events$events=ee.BLOCK_CHANGE,i.BLOCK_CREATE$$module$build$src$core$events$events=ee.BLOCK_CREATE,i.BLOCK_DELETE$$module$build$src$core$events$events=ee.BLOCK_DELETE,py=ee.BLOCK_DRAG,i.BLOCK_MOVE$$module$build$src$core$events$events=ee.BLOCK_MOVE,gy=ee.BLOCK_FIELD_INTERMEDIATE_CHANGE,my=ee.BUBBLE_OPEN,fy=ee.BLOCK_CHANGE,$y=ee.CLICK,by=ee.COMMENT_CHANGE,vy=ee.COMMENT_CREATE,yy=ee.COMMENT_DELETE,_y=ee.COMMENT_MOVE,wy=ee.COMMENT_RESIZE,ky=ee.COMMENT_DRAG,Cy=ee.BLOCK_CREATE,Ty=ee.BLOCK_DELETE,Sy=ee.FINISHED_LOADING,Ey=ee.MARKER_MOVE,Iy=ee.BLOCK_MOVE,xy=ee.SELECTED,Dy=ee.THEME_CHANGE,Ay=ee.TOOLBOX_ITEM_SELECT,Ry=ee.TRASHCAN_OPEN,Oy=ee.UI,Ny=ee.VAR_CREATE,My=ee.VAR_DELETE,Ly=ee.VAR_RENAME,Py=ee.VIEWPORT_CHANGE,Se={},Se.Abstract=qi,Se.BLOCK_CHANGE=i.BLOCK_CHANGE$$module$build$src$core$events$events,Se.BLOCK_CREATE=i.BLOCK_CREATE$$module$build$src$core$events$events,Se.BLOCK_DELETE=i.BLOCK_DELETE$$module$build$src$core$events$events,Se.BLOCK_DRAG=py,Se.BLOCK_FIELD_INTERMEDIATE_CHANGE=gy,Se.BLOCK_MOVE=i.BLOCK_MOVE$$module$build$src$core$events$events,Se.BUBBLE_OPEN=my,Se.BUMP_EVENTS=pb,Se.BlockBase=gi,Se.BlockChange=mi,Se.BlockCreate=Qh,Se.BlockDelete=hp,Se.BlockDrag=Np,Se.BlockFieldIntermediateChange=Mp,Se.BlockMove=Lp,Se.BubbleOpen=Pp,Se.BubbleType=Bp,Se.CHANGE=fy,Se.CLICK=$y,Se.COMMENT_CHANGE=by,Se.COMMENT_CREATE=vy,Se.COMMENT_DELETE=yy,Se.COMMENT_DRAG=ky,Se.COMMENT_MOVE=_y,Se.COMMENT_RESIZE=wy,Se.CREATE=Cy,Se.Click=bh,Se.ClickTarget=vh,Se.CommentBase=qs,Se.CommentChange=jp,Se.CommentCollapse=Fp,Se.CommentCreate=zp,Se.CommentDelete=Up,Se.CommentDrag=Hp,Se.CommentMove=Wp,Se.CommentResize=Gp,Se.DELETE=Ty,Se.FINISHED_LOADING=Sy,Se.FinishedLoading=hy,Se.MARKER_MOVE=Ey,Se.MOVE=Iy,Se.MarkerMove=pp,Se.SELECTED=xy,Se.Selected=_p,Se.THEME_CHANGE=Dy,Se.TOOLBOX_ITEM_SELECT=Ay,Se.TRASHCAN_OPEN=Ry,Se.ThemeChange=ep,Se.ToolboxItemSelect=Vp,Se.TrashcanOpen=kp,Se.UI=Oy,Se.UiBase=Ss,Se.VAR_CREATE=Ny,Se.VAR_DELETE=My,Se.VAR_RENAME=Ly,Se.VIEWPORT_CHANGE=Py,Se.VarBase=br,Se.VarCreate=jh,Se.VarDelete=bp,Se.VarRename=vp,Se.ViewportChange=tp,Se.clearPendingUndo=K,Se.disable=i.disable$$module$build$src$core$events$utils,Se.disableOrphans=me,Se.enable=i.enable$$module$build$src$core$events$utils,Se.filter=O,Se.fire=z,Se.fromJson=ce,Se.get=ne,Se.getDescendantIds=ve,Se.getGroup=i.getGroup$$module$build$src$core$events$utils,Se.getRecordUndo=G,Se.isEnabled=C,Se.setGroup=i.setGroup$$module$build$src$core$events$utils,Se.setRecordUndo=i.setRecordUndo$$module$build$src$core$events$utils;var Rs={};Rs.BottomRow=Qv,Rs.ConstantProvider=Xv,Rs.Drawer=Zv,Rs.MarkerSvg=oy,Rs.PathObject=iy,Rs.RenderInfo=sy,Rs.Renderer=Ap,Rs.RightConnectionShape=ey,Rs.StatementInput=Yl,Rs.TopRow=ty,gh();var It={};It.registerCleanup=Zd,It.registerCollapse=eh,It.registerCollapseExpandBlock=ah,It.registerComment=nh,It.registerCommentCreate=ph,It.registerCommentDelete=dh,It.registerCommentDuplicate=hh,It.registerCommentOptions=ab,It.registerDefaultOptions=gh,It.registerDelete=ch,It.registerDeleteAll=oh,It.registerDisable=lh,It.registerDuplicate=ih,It.registerExpand=th,It.registerHelp=uh,It.registerInline=rh,It.registerRedo=Xd,It.registerUndo=qd;var ql={};ql.CommentView=bv,ql.RenderedWorkspaceComment=Il,ql.WorkspaceComment=El;var Br={};Br.Bubble=nt,Br.MiniWorkspaceBubble=vo,Br.TextBubble=Iv,Br.TextInputBubble=kv;var By=class extends Pl{constructor(){super(),this.FIELD_TEXT_BASELINE_CENTER=!1,this.DARK_PATH_OFFSET=1,this.MAX_BOTTOM_WIDTH=30,this.STATEMENT_BOTTOM_SPACER=-this.NOTCH_HEIGHT/2}getCSS_(e){return super.getCSS_(e).concat([`${e} .blocklyInsertionMarker>.blocklyPathLight,`,`${e} .blocklyInsertionMarker>.blocklyPathDark {`,`fill-opacity: ${this.INSERTION_MARKER_OPACITY};`,"stroke: none;","}"])}},jy=class{constructor(e){this.inlineSteps_=this.steps_="",this.info_=e,this.RTL_=this.info_.RTL,e=e.getRenderer(),this.constants_=e.getConstants(),this.highlightConstants_=e.getHighlightConstants(),this.highlightOffset=this.highlightConstants_.OFFSET,this.outsideCornerPaths_=this.highlightConstants_.OUTSIDE_CORNER,this.insideCornerPaths_=this.highlightConstants_.INSIDE_CORNER,this.puzzleTabPaths_=this.highlightConstants_.PUZZLE_TAB,this.notchPaths_=this.highlightConstants_.NOTCH,this.startPaths_=this.highlightConstants_.START_HAT,this.jaggedTeethPaths_=this.highlightConstants_.JAGGED_TEETH}getPath(){return this.steps_+` -`+this.inlineSteps_}drawTopCorner(e){this.steps_+=pt(e.xPos,this.info_.startY);for(let t=0,o;o=e.elements[t];t++)j.isLeftSquareCorner(o)?this.steps_+=this.highlightConstants_.START_POINT:j.isLeftRoundedCorner(o)?this.steps_+=this.outsideCornerPaths_.topLeft(this.RTL_):j.isPreviousConnection(o)?this.steps_+=this.notchPaths_.pathLeft:j.isHat(o)?this.steps_+=this.startPaths_.path(this.RTL_):j.isSpacer(o)&&o.width!==0&&(this.steps_+=De("H",o.xPos+o.width-this.highlightOffset));this.steps_+=De("H",e.xPos+e.width-this.highlightOffset)}drawJaggedEdge_(e){this.info_.RTL&&(this.steps_+=this.jaggedTeethPaths_.pathLeft+De("v",e.height-this.jaggedTeethPaths_.height-this.highlightOffset))}drawValueInput(e){const t=e.getLastInput();if(this.RTL_){const o=e.height-t.connectionHeight;this.steps_+=St(t.xPos+t.width-this.highlightOffset,e.yPos)+this.puzzleTabPaths_.pathDown(this.RTL_)+De("v",o)}else this.steps_+=St(t.xPos+t.width,e.yPos)+this.puzzleTabPaths_.pathDown(this.RTL_)}drawStatementInput(e){const t=e.getLastInput();if(t)if(this.RTL_){const o=e.height-2*this.insideCornerPaths_.height;this.steps_+=St(t.xPos,e.yPos)+this.insideCornerPaths_.pathTop(this.RTL_)+De("v",o)+this.insideCornerPaths_.pathBottom(this.RTL_)+Hs(e.width-t.xPos-this.insideCornerPaths_.width,0)}else this.steps_+=St(t.xPos,e.yPos+e.height)+this.insideCornerPaths_.pathBottom(this.RTL_)+Hs(e.width-t.xPos-this.insideCornerPaths_.width,0)}drawRightSideRow(e){const t=e.xPos+e.width-this.highlightOffset;e instanceof up&&e.followsStatement&&(this.steps_+=De("H",t)),this.RTL_&&(this.steps_+=De("H",t),e.height>this.highlightOffset&&(this.steps_+=De("V",e.yPos+e.height-this.highlightOffset)))}drawBottomRow(e){if(this.RTL_)this.steps_+=De("V",e.baseline-this.highlightOffset);else{const t=this.info_.bottomRow.elements[0];j.isLeftSquareCorner(t)?this.steps_+=St(e.xPos+this.highlightOffset,e.baseline-this.highlightOffset):j.isLeftRoundedCorner(t)&&(this.steps_+=St(e.xPos,e.baseline),this.steps_+=this.outsideCornerPaths_.bottomLeft())}}drawLeft(){var e=this.info_.outputConnection;e&&(e=e.connectionOffsetY+e.height,this.RTL_?this.steps_+=St(this.info_.startX,e):(this.steps_+=St(this.info_.startX+this.highlightOffset,this.info_.bottomRow.baseline-this.highlightOffset),this.steps_+=De("V",e)),this.steps_+=this.puzzleTabPaths_.pathUp(this.RTL_)),this.RTL_||(e=this.info_.topRow,j.isLeftRoundedCorner(e.elements[0])?this.steps_+=De("V",this.outsideCornerPaths_.height):this.steps_+=De("V",e.capline+this.highlightOffset))}drawInlineInput(e){const t=this.highlightOffset,o=e.xPos+e.connectionWidth;var n=e.centerline-e.height/2;const u=e.width-e.connectionWidth,g=n+t;this.RTL_?(n=e.connectionOffsetY-t,e=e.height-(e.connectionOffsetY+e.connectionHeight)+t,this.inlineSteps_+=St(o-t,g)+De("v",n)+this.puzzleTabPaths_.pathDown(this.RTL_)+De("v",e)+De("h",u)):this.inlineSteps_+=St(e.xPos+e.width+t,g)+De("v",e.height)+De("h",-u)+St(o,n+e.connectionOffsetY)+this.puzzleTabPaths_.pathDown(this.RTL_)}},Fy=class extends Bl{constructor(e,t){super(e,t),this.highlighter_=new jy(t)}draw(){this.drawOutline_(),this.drawInternals_(),this.updateConnectionHighlights();const e=this.block_.pathObject;e.setPath(this.outlinePath_+` -`+this.inlinePath_),e.setHighlightPath(this.highlighter_.getPath()),this.info_.RTL&&e.flipRTL(),this.recordSizeOnBlock_()}drawTop_(){this.highlighter_.drawTopCorner(this.info_.topRow),this.highlighter_.drawRightSideRow(this.info_.topRow),super.drawTop_()}drawJaggedEdge_(e){this.highlighter_.drawJaggedEdge_(e),super.drawJaggedEdge_(e)}drawValueInput_(e){this.highlighter_.drawValueInput(e),super.drawValueInput_(e)}drawStatementInput_(e){this.highlighter_.drawStatementInput(e),super.drawStatementInput_(e)}drawRightSideRow_(e){this.highlighter_.drawRightSideRow(e),this.outlinePath_+=De("H",e.xPos+e.width)+De("V",e.yPos+e.height)}drawBottom_(){this.highlighter_.drawBottomRow(this.info_.bottomRow),super.drawBottom_()}drawLeft_(){this.highlighter_.drawLeft(),super.drawLeft_()}drawInlineInput_(e){this.highlighter_.drawInlineInput(e),super.drawInlineInput_(e)}positionInlineInputConnection_(e){const t=e.centerline-e.height/2;if(e.connectionModel){let o=e.xPos+e.connectionWidth+this.constants_.DARK_PATH_OFFSET;this.info_.RTL&&(o*=-1),e.connectionModel.setOffsetInBlock(o,t+e.connectionOffsetY+this.constants_.DARK_PATH_OFFSET)}}positionStatementInputConnection_(e){const t=e.getLastInput();if(t!=null&&t.connectionModel){let o=e.xPos+e.statementEdge+t.notchOffset;o=this.info_.RTL?-1*o:o+this.constants_.DARK_PATH_OFFSET,t.connectionModel.setOffsetInBlock(o,e.yPos+this.constants_.DARK_PATH_OFFSET)}}positionExternalValueConnection_(e){const t=e.getLastInput();if(t&&t.connectionModel){let o=e.xPos+e.width+this.constants_.DARK_PATH_OFFSET;this.info_.RTL&&(o*=-1),t.connectionModel.setOffsetInBlock(o,e.yPos)}}positionNextConnection_(){const e=this.info_.bottomRow;if(e.connection){const t=e.connection,o=t.xPos;t.connectionModel.setOffsetInBlock((this.info_.RTL?-o:o)+this.constants_.DARK_PATH_OFFSET/2,e.baseline+this.constants_.DARK_PATH_OFFSET)}}},zy=class{constructor(e){this.OFFSET=.5,this.constantProvider=e,this.START_POINT=pt(this.OFFSET,this.OFFSET)}init(){this.INSIDE_CORNER=this.makeInsideCorner(),this.OUTSIDE_CORNER=this.makeOutsideCorner(),this.PUZZLE_TAB=this.makePuzzleTab(),this.NOTCH=this.makeNotch(),this.JAGGED_TEETH=this.makeJaggedTeeth(),this.START_HAT=this.makeStartHat()}makeInsideCorner(){const e=this.constantProvider.CORNER_RADIUS,t=this.OFFSET,o=(1-Math.SQRT1_2)*(e+t)-t,n=pt(o,o)+vt("a","0 0,0",e,Me(-o-t,e-o)),u=vt("a","0 0,0",e+t,Me(e+t,e+t)),g=pt(o,-o)+vt("a","0 0,0",e+t,Me(e-o,o+t));return{width:e+t,height:e,pathTop(I){return I?n:""},pathBottom(I){return I?u:g}}}makeOutsideCorner(){const e=this.constantProvider.CORNER_RADIUS,t=this.OFFSET,o=(1-Math.SQRT1_2)*(e-t)+t,n=pt(o,o)+vt("a","0 0,1",e-t,Me(e-o,-o+t)),u=pt(t,e)+vt("a","0 0,1",e-t,Me(e,-e+t)),g=-o,I=pt(o,g)+vt("a","0 0,1",e-t,Me(-o+t,-g-e));return{height:e,topLeft(L){return L?n:u},bottomLeft(){return I}}}makePuzzleTab(){const e=this.constantProvider.TAB_WIDTH,t=this.constantProvider.TAB_HEIGHT,o=pt(-2,-t+3.4)+Hs(-.45*e,-2.1),n=De("v",2.5)+pt(.97*-e,2.5)+Zt("q",[Me(.05*-e,10),Me(.3*e,9.5)])+pt(.67*e,-1.9)+De("v",2.5),u=De("v",-1.5)+pt(-.92*e,-.5)+Zt("q",[Me(-.19*e,-5.5),Me(0,-11)])+pt(.92*e,1),g=pt(-5,t-.7)+Hs(.46*e,-2.1);return{width:e,height:t,pathUp(I){return I?o:u},pathDown(I){return I?n:g}}}makeNotch(){return{pathLeft:De("h",this.OFFSET)+this.constantProvider.NOTCH.pathLeft}}makeJaggedTeeth(){return{pathLeft:Hs(5.1,2.6)+pt(-10.2,6.8)+Hs(5.1,2.6),height:12,width:10.2}}makeStartHat(){const e=this.constantProvider.START_HAT.height,t=pt(25,-8.7)+Zt("c",[Me(29.7,-6.2),Me(57.2,-.5),Me(75,8.7)]),o=Zt("c",[Me(17.8,-9.2),Me(45.3,-14.9),Me(75,-8.7)])+St(100.5,e+.5);return{path(n){return n?t:o}}}},Uy=class extends lp{constructor(e,t){super(e,t),this.constants_=e,this.connectedBlock&&(this.width+=this.constants_.DARK_PATH_OFFSET,this.height+=this.constants_.DARK_PATH_OFFSET)}},Hy=class extends xr{constructor(e,t){super(e,t),this.constants_=e,this.connectedBlock&&(this.height+=this.constants_.DARK_PATH_OFFSET)}},Wy=class extends Rr{constructor(e,t){super(e,t),this.renderer_=e}getRenderer(){return this.renderer_}populateBottomRow_(){super.populateBottomRow_(),this.block_.inputList.length&&this.block_.inputList[this.block_.inputList.length-1]instanceof ls||(this.bottomRow.minHeight=this.constants_.MEDIUM_PADDING-this.constants_.DARK_PATH_OFFSET)}addInput_(e,t){this.isInline&&e instanceof i.ValueInput$$module$build$src$core$inputs$value_input?(t.elements.push(new Uy(this.constants_,e)),t.hasInlineInput=!0):e instanceof ls?(t.elements.push(new Hy(this.constants_,e)),t.hasStatement=!0):e instanceof i.ValueInput$$module$build$src$core$inputs$value_input?(t.elements.push(new Ll(this.constants_,e)),t.hasExternalInput=!0):(e instanceof Ks||e instanceof Co)&&(t.minHeight=Math.max(t.minHeight,this.constants_.DUMMY_INPUT_MIN_HEIGHT),t.hasDummyInput=!0),this.isInline||t.align!==null||(t.align=e.align)}addElemSpacing_(){let e=!1;for(let o=0,n;n=this.rows[o];o++)n.hasExternalInput&&(e=!0);for(let o=0,n;n=this.rows[o];o++){var t=n.elements;if(n.elements=[],n.startsWithElemSpacer()&&n.elements.push(new as(this.constants_,this.getInRowSpacing_(null,t[0]))),t.length){for(let u=0;u{this.targetWorkspace.isDragging()||t.addSelect()})),this.listeners.push(ue(e,"pointerleave",t,()=>{this.targetWorkspace.isDragging()||t.removeSelect()})),this.listeners.push(ue(o,"pointerenter",t,()=>{this.targetWorkspace.isDragging()||t.addSelect()})),this.listeners.push(ue(o,"pointerleave",t,()=>{this.targetWorkspace.isDragging()||t.removeSelect()}))}blockMouseDown(e){return t=>{const o=this.targetWorkspace.getGesture(t);o&&(o.setStartBlock(e),o.handleFlyoutStart(t,this))}}onMouseDown(e){const t=this.targetWorkspace.getGesture(e);t&&t.handleFlyoutStart(e,this)}isBlockCreatable(e){return e.isEnabled()}createBlock(e){let t=null;i.disable$$module$build$src$core$events$utils();var o=this.targetWorkspace.getAllVariables();this.targetWorkspace.setResizesEnabled(!1);try{t=this.placeNewBlock(e)}finally{i.enable$$module$build$src$core$events$utils()}if(this.targetWorkspace.hideChaff(),e=Xn(this.targetWorkspace,o),C()){for(i.setGroup$$module$build$src$core$events$utils(!0),o=0;o-t||e<-180+t||e>180-t}getClientRect(){if(!this.svgGroup_||this.autoClose||!this.isVisible())return null;const e=this.svgGroup_.getBoundingClientRect(),t=e.left;return this.toolboxPosition_===Ge.LEFT?new rt(-1e9,1e9,-1e9,t+e.width):new rt(-1e9,1e9,t,1e9)}reflowInternal_(){this.workspace_.scale=this.getFlyoutScale();let e=0;var t=this.workspace_.getTopBlocks(!1);for(let n=0,u;u=t[n];n++){var o=u.getHeightWidth().width;u.outputConnection&&(o-=this.tabWidth_),e=Math.max(e,o)}for(let n=0,u;u=this.buttons_[n];n++)e=Math.max(e,u.width);if(e+=1.5*this.MARGIN+this.tabWidth_,e*=this.workspace_.scale,e+=yt.scrollbarThickness,this.width_!==e){for(let n=0,u;u=t[n];n++){if(this.RTL){o=u.getRelativeToSurfaceXY().x;let g=e/this.workspace_.scale-this.MARGIN;u.outputConnection||(g-=this.tabWidth_),u.moveBy(g-o,0)}this.rectMap_.has(u)&&this.moveRectToBlock_(this.rectMap_.get(u),u)}if(this.RTL)for(let n=0,u;u=this.buttons_[n];n++)t=u.getPosition().y,u.moveTo(e/this.workspace_.scale-u.width-this.MARGIN-this.tabWidth_,t);this.targetWorkspace.scrollbar||this.autoClose||this.targetWorkspace.getFlyout()!==this||this.toolboxPosition_!==Ge.LEFT||this.targetWorkspace.translate(this.targetWorkspace.scrollX+e,this.targetWorkspace.scrollY),this.width_=e,this.position(),this.targetWorkspace.resizeContents(),this.targetWorkspace.recordDragTargets()}}};Rp.registryName="verticalFlyout",r($e.FLYOUTS_VERTICAL_TOOLBOX,Ws,Rp);var dy=class extends Xl{constructor(e){super(e),this.horizontalLayout=!0}setMetrics_(e){if(this.isVisible()){var t=this.workspace_.getMetricsManager(),o=t.getScrollMetrics(),n=t.getViewMetrics();t=t.getAbsoluteMetrics(),typeof e.x=="number"&&(this.workspace_.scrollX=-(o.left+(o.width-n.width)*e.x)),this.workspace_.translate(this.workspace_.scrollX+t.left,this.workspace_.scrollY+t.top)}}getX(){return 0}getY(){if(!this.isVisible())return 0;var e=this.targetWorkspace.getMetricsManager();const t=e.getAbsoluteMetrics(),o=e.getViewMetrics();e=e.getToolboxMetrics();const n=this.toolboxPosition_===Ge.TOP;return this.targetWorkspace.toolboxPosition===this.toolboxPosition_?this.targetWorkspace.getToolbox()?n?e.height:o.height-this.height_:n?0:o.height:n?0:o.height+t.top-this.height_}position(){if(this.isVisible()&&this.targetWorkspace.isVisible()){var e=this.targetWorkspace.getMetricsManager().getViewMetrics();this.width_=e.width,this.setBackgroundPath(e.width-2*this.CORNER_RADIUS,this.height_-this.CORNER_RADIUS),e=this.getX();var t=this.getY();this.positionAt_(this.width_,this.height_,e,t)}}setBackgroundPath(e,t){const o=this.toolboxPosition_===Ge.TOP,n=["M 0,"+(o?0:this.CORNER_RADIUS)];o?(n.push("h",e+2*this.CORNER_RADIUS),n.push("v",t),n.push("a",this.CORNER_RADIUS,this.CORNER_RADIUS,0,0,1,-this.CORNER_RADIUS,this.CORNER_RADIUS),n.push("h",-e),n.push("a",this.CORNER_RADIUS,this.CORNER_RADIUS,0,0,1,-this.CORNER_RADIUS,-this.CORNER_RADIUS)):(n.push("a",this.CORNER_RADIUS,this.CORNER_RADIUS,0,0,1,this.CORNER_RADIUS,-this.CORNER_RADIUS),n.push("h",e),n.push("a",this.CORNER_RADIUS,this.CORNER_RADIUS,0,0,1,this.CORNER_RADIUS,this.CORNER_RADIUS),n.push("v",t),n.push("h",-e-2*this.CORNER_RADIUS)),n.push("z"),this.svgBackground_.setAttribute("d",n.join(" "))}scrollToStart(){let e;(e=this.workspace_.scrollbar)==null||e.setX(this.RTL?1/0:0)}wheel_(e){var t=Le(e);if(t=t.x||t.y){const o=this.workspace_.getMetricsManager(),n=o.getScrollMetrics();t=o.getViewMetrics().left-n.left+t;let u;(u=this.workspace_.scrollbar)==null||u.setX(t),tr(this.workspace_),Fs()}e.preventDefault(),e.stopPropagation()}layout_(e,t){this.workspace_.scale=this.targetWorkspace.scale;const o=this.MARGIN;let n=o+this.tabWidth_;this.RTL&&(e=e.reverse());for(let P=0,le;le=e[P];P++)if(le.type==="block"){var u=le.block;if(u==null)continue;var g=u.getDescendants(!1);for(let dt=0,ut;ut=g[dt];dt++)ut.isInFlyout=!0;g=u.getSvgRoot();const Ee=u.getHeightWidth();var I=u.outputConnection?this.tabWidth_:0;I=this.RTL?n+Ee.width:n-I,u.moveBy(I,o),I=this.createRect_(u,I,o,Ee,P),n+=Ee.width+t[P],this.addBlockListeners_(g,u,I)}else le.type==="button"&&(u=le.button,this.initFlyoutButton_(u,n,o),n+=u.width+t[P])}isDragTowardWorkspace(e){e=Math.atan2(e.y,e.x)/Math.PI*180;const t=this.dragAngleRange_;return e<90+t&&e>90-t||e>-90-t&&e<-90+t}getClientRect(){if(!this.svgGroup_||this.autoClose||!this.isVisible())return null;const e=this.svgGroup_.getBoundingClientRect(),t=e.top;return this.toolboxPosition_===Ge.TOP?new rt(-1e9,t+e.height,-1e9,1e9):new rt(t,1e9,-1e9,1e9)}reflowInternal_(){this.workspace_.scale=this.getFlyoutScale();let e=0;const t=this.workspace_.getTopBlocks(!1);for(let n=0,u;u=t[n];n++)e=Math.max(e,u.getHeightWidth().height);const o=this.buttons_;for(let n=0,u;u=o[n];n++)e=Math.max(e,u.height);if(e+=1.5*this.MARGIN,e*=this.workspace_.scale,e+=yt.scrollbarThickness,this.height_!==e){for(let n=0,u;u=t[n];n++)this.rectMap_.has(u)&&this.moveRectToBlock_(this.rectMap_.get(u),u);this.targetWorkspace.scrollbar||this.autoClose||this.targetWorkspace.getFlyout()!==this||this.toolboxPosition_!==Ge.TOP||this.targetWorkspace.translate(this.targetWorkspace.scrollX,this.targetWorkspace.scrollY+e),this.height_=e,this.position(),this.targetWorkspace.resizeContents(),this.targetWorkspace.recordDragTargets()}}};r($e.FLYOUTS_HORIZONTAL_TOOLBOX,Ws,dy);var Lr=class extends es{constructor(e,t,o,n,u){super(lt.SKIP_SETUP),this.defaultType="",this.variableTypes=[],this.variable=null,this.SERIALIZABLE=!0,this.menuGenerator_=Lr.dropdownCreate,this.defaultVariableName=typeof e=="string"?e:"",this.size_=new Ze(0,0),e!==lt.SKIP_SETUP&&(u?this.configure_(u):this.setTypes(o,n),t&&this.setValidator(t))}configure_(e){super.configure_(e),this.setTypes(e.variableTypes,e.defaultType)}initModel(){var e=this.getSourceBlock();if(!e)throw new _t;this.variable||(e=i.getOrCreateVariablePackage$$module$build$src$core$variables(e.workspace,null,this.defaultVariableName,this.defaultType),this.doValueUpdate_(e.getId()))}shouldAddBorderRect_(){const e=this.getSourceBlock();if(!e)throw new _t;return super.shouldAddBorderRect_()&&(!this.getConstants().FIELD_DROPDOWN_NO_BORDER_RECT_SHADOW||e.type!=="variables_get")}fromXml(e){var t=this.getSourceBlock();if(!t)throw new _t;const o=e.getAttribute("id"),n=e.textContent,u=e.getAttribute("variabletype")||e.getAttribute("variableType")||"";if(t=i.getOrCreateVariablePackage$$module$build$src$core$variables(t.workspace,o,n,u),u!==null&&u!==t.type)throw Error("Serialized variable type with id '"+t.getId()+"' had type "+t.type+", and does not match variable field that references it: "+zs(e)+".");this.setValue(t.getId())}toXml(e){return this.initModel(),e.id=this.variable.getId(),e.textContent=this.variable.name,this.variable.type&&e.setAttribute("variabletype",this.variable.type),e}saveState(e){var t=this.saveLegacyState(Lr);return t!==null||(this.initModel(),t={id:this.variable.getId()},e&&(t.name=this.variable.name,t.type=this.variable.type)),t}loadState(e){const t=this.getSourceBlock();if(!t)throw new _t;this.loadLegacyState(Lr,e)||(e=i.getOrCreateVariablePackage$$module$build$src$core$variables(t.workspace,e.id||null,e.name,e.type||""),this.setValue(e.getId()))}setSourceBlock(e){if(e.isShadow())throw Error("Variable fields are not allowed to exist on shadow blocks.");super.setSourceBlock(e)}getValue(){return this.variable?this.variable.getId():null}getText(){return this.variable?this.variable.name:""}getVariable(){return this.variable}getValidator(){return this.variable?this.validator_:null}doClassValidation_(e){if(e===null)return null;var t=this.getSourceBlock();if(!t)throw new _t;return t=i.getVariable$$module$build$src$core$variables(t.workspace,e),t?(t=t.type,this.typeIsAllowed(t)?e:(console.warn("Variable type doesn't match this field! Type was "+t),null)):(console.warn("Variable id doesn't point to a real variable! ID was "+e),null)}doValueUpdate_(e){const t=this.getSourceBlock();if(!t)throw new _t;this.variable=i.getVariable$$module$build$src$core$variables(t.workspace,e),super.doValueUpdate_(e)}typeIsAllowed(e){const t=this.getVariableTypes();if(!t)return!0;for(let o=0;othis.max_&&(e.max=`${this.max_}`,xt(e,Et.VALUEMAX,this.max_)),e}static fromJson(e){return new this(e.value,void 0,void 0,void 0,void 0,e)}};Us("field_number",Mp),Mp.prototype.DEFAULT_VALUE=0;var hy=class extends _i{constructor(e,t,o){super(String(e??""),t,o),this.EDITABLE=!1,this.SERIALIZABLE=!0}static fromJson(e){return new this(bt(e.text),void 0,e)}};Us("field_label_serializable",hy);var Ti=class extends lt{constructor(e,t,o){super(lt.SKIP_SETUP),this.SERIALIZABLE=!0,this.CURSOR="default",this.value_=this.value_,this.checkChar=Ti.CHECK_CHAR,e!==lt.SKIP_SETUP&&(o&&this.configure_(o),this.setValue(e),t&&this.setValidator(t))}configure_(e){super.configure_(e),e.checkCharacter&&(this.checkChar=e.checkCharacter)}saveState(){const e=this.saveLegacyState(Ti);return e!==null?e:this.getValueBoolean()}initView(){super.initView();const e=this.getTextElement();Oe(e,"blocklyCheckbox"),e.style.display=this.value_?"block":"none"}render_(){this.textContent_&&(this.textContent_.nodeValue=this.getDisplayText_()),this.updateSize_(this.getConstants().FIELD_CHECKBOX_X_OFFSET)}getDisplayText_(){return this.checkChar}setCheckCharacter(e){this.checkChar=e||Ti.CHECK_CHAR,this.forceRerender()}showEditor_(){this.setValue(!this.value_)}doClassValidation_(e){return e===!0||e==="TRUE"?"TRUE":e===!1||e==="FALSE"?"FALSE":null}doValueUpdate_(e){this.value_=this.convertValueToBool(e),this.textElement_&&(this.textElement_.style.display=this.value_?"block":"none")}getValue(){return this.value_?"TRUE":"FALSE"}getValueBoolean(){return this.value_}getText(){return String(this.convertValueToBool(this.value_))}convertValueToBool(e){return typeof e=="string"?e==="TRUE":!!e}static fromJson(e){return new this(e.checked,void 0,e)}};Ti.CHECK_CHAR="✓",Us("field_checkbox",Ti),Ti.prototype.DEFAULT_VALUE=!1;var py=class{constructor(e,t){this.draggable=e,this.workspace=t,this.dragTarget=null,this.startLoc=e.getRelativeToSurfaceXY()}onDragStart(e){this.draggable.startDrag(e)}onDrag(e,t){this.moveDraggable(e,t),t=this.getRoot(this.draggable),ds(t)&&t.setDeleteStyle(this.wouldDeleteDraggable(e,t)),this.updateDragTarget(e)}updateDragTarget(e){e=this.workspace.getDragTarget(e);const t=this.getRoot(this.draggable);if(this.dragTarget!==e){let o;(o=this.dragTarget)==null||o.onDragExit(t),e==null||e.onDragEnter(t)}e==null||e.onDragOver(t),this.dragTarget=e}moveDraggable(e,t){t=this.pixelsToWorkspaceUnits(t),t=ye.sum(this.startLoc,t),this.draggable.drag(t,e)}wouldDeleteDraggable(e,t){return(e=this.workspace.getDragTarget(e))&&this.workspace.getComponentManager().hasCapability(e.id,gt.Capability.DELETE_AREA)?e.wouldDelete(t):!1}onDragEnd(e){const t=i.getGroup$$module$build$src$core$events$utils();var o=this.workspace.getDragTarget(e);const n=this.getRoot(this.draggable);if(o){let u;(u=this.dragTarget)==null||u.onDrop(n)}this.shouldReturnToStart(e,n)&&this.draggable.revertDrag(),(o=ds(n)&&this.wouldDeleteDraggable(e,n))&&this.draggable instanceof $s&&Ga(this.draggable.getRootBlock()),this.draggable.endDrag(e),o&&ds(n)&&(e=i.getGroup$$module$build$src$core$events$utils(),i.setGroup$$module$build$src$core$events$utils(t),n.dispose(),i.setGroup$$module$build$src$core$events$utils(e))}getRoot(e){return e instanceof $s?e.getRootBlock():e}shouldReturnToStart(e,t){return(e=this.workspace.getDragTarget(e))?e.shouldPreventMove(t):!1}pixelsToWorkspaceUnits(e){return e=new ye(e.x/this.workspace.scale,e.y/this.workspace.scale),this.workspace.isMutator&&e.scale(1/this.workspace.options.parentWorkspace.scale),e}};r($e.BLOCK_DRAGGER,Ws,py);var Pr={};Pr.BlockDragStrategy=Uv,Pr.BubbleDragStrategy=Cv,Pr.CommentDragStrategy=bv,Pr.Dragger=py;var Np=class extends Ss{constructor(e,t,o){super(e?e.workspace.id:void 0),this.type=ee.BLOCK_DRAG,e&&(this.blockId=e.id,this.isStart=t,this.blocks=o)}toJson(){const e=super.toJson();if(this.isStart===void 0)throw Error("Whether this event is the start of a drag is undefined. Either pass the value to the constructor, or call fromJson");if(this.blockId===void 0)throw Error("The block ID is undefined. Either pass a block to the constructor, or call fromJson");return e.isStart=this.isStart,e.blockId=this.blockId,e.blocks=this.blocks,e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new Np),t.isStart=e.isStart,t.blockId=e.blockId,t.blocks=e.blocks,t}};r($e.EVENT,ee.BLOCK_DRAG,Np);var Lp=class extends gi{constructor(e,t,o,n){super(e),this.type=ee.BLOCK_FIELD_INTERMEDIATE_CHANGE,this.recordUndo=!1,e&&(this.name=t,this.oldValue=o,this.newValue=n)}toJson(){const e=super.toJson();if(!this.name)throw Error("The changed field name is undefined. Either pass a name to the constructor, or call fromJson.");return e.name=this.name,e.oldValue=this.oldValue,e.newValue=this.newValue,e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new Lp),t.name=e.name,t.oldValue=e.oldValue,t.newValue=e.newValue,t}isNull(){return this.oldValue===this.newValue}run(e){var t=this.getEventWorkspace_();if(!this.blockId)throw Error("The block ID is undefined. Either pass a block to the constructor, or call fromJson");if(t=t.getBlockById(this.blockId),!t)throw Error("The associated block is undefined. Either pass a block to the constructor, or call fromJson");e=e?this.newValue:this.oldValue,(t=t.getField(this.name))?t.setValue(e):console.warn("Can't set non-existent field: "+this.name)}};r($e.EVENT,ee.BLOCK_FIELD_INTERMEDIATE_CHANGE,Lp);var Pp=class extends gi{constructor(e){super(e),this.type=ee.BLOCK_MOVE,e&&(e.isShadow()&&(this.recordUndo=!1),e=this.currentLocation(),this.oldParentId=e.parentId,this.oldInputName=e.inputName,this.oldCoordinate=e.coordinate)}toJson(){const e=super.toJson();return e.oldParentId=this.oldParentId,e.oldInputName=this.oldInputName,this.oldCoordinate&&(e.oldCoordinate=`${Math.round(this.oldCoordinate.x)}, ${Math.round(this.oldCoordinate.y)}`),e.newParentId=this.newParentId,e.newInputName=this.newInputName,this.newCoordinate&&(e.newCoordinate=`${Math.round(this.newCoordinate.x)}, ${Math.round(this.newCoordinate.y)}`),this.reason&&(e.reason=this.reason),this.recordUndo||(e.recordUndo=this.recordUndo),e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new Pp),t.oldParentId=e.oldParentId,t.oldInputName=e.oldInputName,e.oldCoordinate&&(o=e.oldCoordinate.split(","),t.oldCoordinate=new ye(Number(o[0]),Number(o[1]))),t.newParentId=e.newParentId,t.newInputName=e.newInputName,e.newCoordinate&&(o=e.newCoordinate.split(","),t.newCoordinate=new ye(Number(o[0]),Number(o[1]))),e.reason!==void 0&&(t.reason=e.reason),e.recordUndo!==void 0&&(t.recordUndo=e.recordUndo),t}recordNew(){const e=this.currentLocation();this.newParentId=e.parentId,this.newInputName=e.inputName,this.newCoordinate=e.coordinate}setReason(e){this.reason=e}currentLocation(){var e=this.getEventWorkspace_();if(!this.blockId)throw Error("The block ID is undefined. Either pass a block to the constructor, or call fromJson");var t=e.getBlockById(this.blockId);if(!t)throw Error("The block associated with the block move event could not be found");e={};const o=t.getParent();return o?(e.parentId=o.id,(t=o.getInputWithBlock(t))&&(e.inputName=t.name)):e.coordinate=t.getRelativeToSurfaceXY(),e}isNull(){return this.oldParentId===this.newParentId&&this.oldInputName===this.newInputName&&ye.equals(this.oldCoordinate,this.newCoordinate)}run(e){var t=this.getEventWorkspace_();if(!this.blockId)throw Error("The block ID is undefined. Either pass a block to the constructor, or call fromJson");var o=t.getBlockById(this.blockId);if(o){var n=e?this.newParentId:this.oldParentId,u=e?this.newInputName:this.oldInputName;if(e=e?this.newCoordinate:this.oldCoordinate,n){var g=t.getBlockById(n);if(!g){console.warn("Can't connect to non-existent block: "+n);return}}if(o.getParent()&&o.unplug(),e)u=o.getRelativeToSurfaceXY(),o.moveBy(e.x-u.x,e.y-u.y,this.reason);else{t=o.outputConnection,(!t||o.previousConnection&&o.previousConnection.isConnected())&&(t=o.previousConnection);let I,P;o=(P=t)==null?void 0:P.type,u?(o=g.getInput(u))&&(I=o.connection):o===xe.PREVIOUS_STATEMENT&&(I=g.nextConnection),I&&t?t.connect(I):console.warn("Can't connect to non-existent input: "+u)}}else console.warn("Can't move non-existent block: "+this.blockId)}};r($e.EVENT,ee.BLOCK_MOVE,Pp);var Bp=class extends Ss{constructor(e,t,o){super(e?e.workspace.id:void 0),this.type=ee.BUBBLE_OPEN,e&&(this.blockId=e.id,this.isOpen=t,this.bubbleType=o)}toJson(){const e=super.toJson();if(this.isOpen===void 0)throw Error("Whether this event is for opening the bubble is undefined. Either pass the value to the constructor, or call fromJson");if(!this.bubbleType)throw Error("The type of bubble is undefined. Either pass the value to the constructor, or call fromJson");return e.isOpen=this.isOpen,e.bubbleType=this.bubbleType,e.blockId=this.blockId||"",e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new Bp),t.isOpen=e.isOpen,t.bubbleType=e.bubbleType,t.blockId=e.blockId,t}},jp;(function(e){e.MUTATOR="mutator",e.COMMENT="comment",e.WARNING="warning"})(jp||(jp={})),r($e.EVENT,ee.BUBBLE_OPEN,Bp);var Xs=class extends Xi{constructor(e){super(),this.isBlank=!e,e&&(this.commentId=e.id,this.workspaceId=e.workspace.id,this.group=i.getGroup$$module$build$src$core$events$utils(),this.recordUndo=G())}toJson(){const e=super.toJson();if(!this.commentId)throw Error("The comment ID is undefined. Either pass a comment to the constructor, or call fromJson");return e.commentId=this.commentId,e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new Xs),t.commentId=e.commentId,t}static CommentCreateDeleteHelper(e,t){const o=e.getEventWorkspace_();if(t){if(!e.json)throw Error("Encountered a comment event without proper json");Yn(e.json,o)}else{if(!e.commentId)throw Error("The comment ID is undefined. Either pass a comment to the constructor, or call fromJson");(t=o.getCommentById(e.commentId))?t.dispose():console.warn("Can't delete non-existent comment: "+e.commentId)}}},Fp=class extends Xs{constructor(e,t,o){super(e),this.type=ee.COMMENT_CHANGE,e&&(this.oldContents_=typeof t>"u"?"":t,this.newContents_=typeof o>"u"?"":o)}toJson(){const e=super.toJson();if(!this.oldContents_)throw Error("The old contents is undefined. Either pass a value to the constructor, or call fromJson");if(!this.newContents_)throw Error("The new contents is undefined. Either pass a value to the constructor, or call fromJson");return e.oldContents=this.oldContents_,e.newContents=this.newContents_,e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new Fp),t.oldContents_=e.oldContents,t.newContents_=e.newContents,t}isNull(){return this.oldContents_===this.newContents_}run(e){var t=this.getEventWorkspace_();if(!this.commentId)throw Error("The comment ID is undefined. Either pass a comment to the constructor, or call fromJson");if(t=t.getCommentById(this.commentId)){var o=e?this.newContents_:this.oldContents_;if(o===void 0)throw Error(e?"The new contents is undefined. Either pass a value to the constructor, or call fromJson":"The old contents is undefined. Either pass a value to the constructor, or call fromJson");t.setText(o)}else console.warn("Can't change non-existent comment: "+this.commentId)}};r($e.EVENT,ee.COMMENT_CHANGE,Fp);var zp=class extends Xs{constructor(e,t){super(e),this.newCollapsed=t,this.type=ee.COMMENT_COLLAPSE}toJson(){const e=super.toJson();if(this.newCollapsed===void 0)throw Error("The new collapse value undefined. Either call recordNew, or call fromJson");return e.newCollapsed=this.newCollapsed,e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new zp),t.newCollapsed=e.newCollapsed,t}run(e){var t=this.getEventWorkspace_();if(!this.commentId)throw Error("The comment ID is undefined. Either pass a comment to the constructor, or call fromJson");(t=t.getCommentById(this.commentId))?t.setCollapsed(e?!!this.newCollapsed:!this.newCollapsed):console.warn("Can't collapse or uncollapse non-existent comment: "+this.commentId)}};r($e.EVENT,ee.COMMENT_COLLAPSE,zp);var Up=class extends Xs{constructor(e){super(e),this.type=ee.COMMENT_CREATE,e&&(this.xml=ir(e),this.json=Pi(e,{addCoordinates:!0}))}toJson(){const e=super.toJson();if(!this.xml)throw Error("The comment XML is undefined. Either pass a comment to the constructor, or call fromJson");if(!this.json)throw Error("The comment JSON is undefined. Either pass a block to the constructor, or call fromJson");return e.xml=zs(this.xml),e.json=this.json,e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new Up),t.xml=i.textToDom$$module$build$src$core$utils$xml(e.xml),t.json=e.json,t}run(e){Xs.CommentCreateDeleteHelper(this,e)}};r($e.EVENT,ee.COMMENT_CREATE,Up);var Hp=class extends Xs{constructor(e){super(e),this.type=ee.COMMENT_DELETE,e&&(this.xml=ir(e),this.json=Pi(e,{addCoordinates:!0}))}run(e){Xs.CommentCreateDeleteHelper(this,!e)}toJson(){const e=super.toJson();if(!this.xml)throw Error("The comment XML is undefined. Either pass a comment to the constructor, or call fromJson");if(!this.json)throw Error("The comment JSON is undefined. Either pass a block to the constructor, or call fromJson");return e.xml=zs(this.xml),e.json=this.json,e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new Hp),t.xml=i.textToDom$$module$build$src$core$utils$xml(e.xml),t.json=e.json,t}};r($e.EVENT,ee.COMMENT_DELETE,Hp);var Wp=class extends Ss{constructor(e,t){super(e?e.workspace.id:void 0),this.type=ee.COMMENT_DRAG,e&&(this.commentId=e.id,this.isStart=t)}toJson(){const e=super.toJson();if(this.isStart===void 0)throw Error("Whether this event is the start of a drag is undefined. Either pass the value to the constructor, or call fromJson");if(this.commentId===void 0)throw Error("The comment ID is undefined. Either pass a comment to the constructor, or call fromJson");return e.isStart=this.isStart,e.commentId=this.commentId,e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new Wp),t.isStart=e.isStart,t.commentId=e.commentId,t}};r($e.EVENT,ee.COMMENT_DRAG,Wp);var Gp=class extends Xs{constructor(e){super(e),this.type=ee.COMMENT_MOVE,e&&(this.comment_=e,this.oldCoordinate_=e.getRelativeToSurfaceXY())}recordNew(){if(this.newCoordinate_)throw Error("Tried to record the new position of a comment on the same event twice.");if(!this.comment_)throw Error("The comment is undefined. Pass a comment to the constructor if you want to use the record functionality");this.newCoordinate_=this.comment_.getRelativeToSurfaceXY()}setReason(e){this.reason=e}setOldCoordinate(e){this.oldCoordinate_=e}toJson(){const e=super.toJson();if(!this.oldCoordinate_)throw Error("The old comment position is undefined. Either pass a comment to the constructor, or call fromJson");if(!this.newCoordinate_)throw Error("The new comment position is undefined. Either call recordNew, or call fromJson");return e.oldCoordinate=`${Math.round(this.oldCoordinate_.x)}, ${Math.round(this.oldCoordinate_.y)}`,e.newCoordinate=Math.round(this.newCoordinate_.x)+","+Math.round(this.newCoordinate_.y),e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new Gp),o=e.oldCoordinate.split(","),t.oldCoordinate_=new ye(Number(o[0]),Number(o[1])),o=e.newCoordinate.split(","),t.newCoordinate_=new ye(Number(o[0]),Number(o[1])),t}isNull(){return ye.equals(this.oldCoordinate_,this.newCoordinate_)}run(e){var t=this.getEventWorkspace_();if(!this.commentId)throw Error("The comment ID is undefined. Either pass a comment to the constructor, or call fromJson");if(t=t.getCommentById(this.commentId)){if(e=e?this.newCoordinate_:this.oldCoordinate_,!e)throw Error("Either oldCoordinate_ or newCoordinate_ is undefined. Either pass a comment to the constructor and call recordNew, or call fromJson");t.moveTo(e)}else console.warn("Can't move non-existent comment: "+this.commentId)}};r($e.EVENT,ee.COMMENT_MOVE,Gp);var Vp=class extends Xs{constructor(e){super(e),this.type=ee.COMMENT_RESIZE,e&&(this.oldSize=e.getSize())}recordCurrentSizeAsNewSize(){if(this.newSize)throw Error("Tried to record the new size of a comment on the same event twice.");var e=this.getEventWorkspace_();if(!this.commentId)throw Error("The comment ID is undefined. Either pass a comment to the constructor, or call fromJson");if(e=e.getCommentById(this.commentId),!e)throw Error("The comment associated with the comment resize event could not be found");this.newSize=e.getSize()}toJson(){const e=super.toJson();if(!this.oldSize)throw Error("The old comment size is undefined. Either pass a comment to the constructor, or call fromJson");if(!this.newSize)throw Error("The new comment size is undefined. Either call recordCurrentSizeAsNewSize, or call fromJson");return e.oldWidth=Math.round(this.oldSize.width),e.oldHeight=Math.round(this.oldSize.height),e.newWidth=Math.round(this.newSize.width),e.newHeight=Math.round(this.newSize.height),e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new Vp),t.oldSize=new Ze(e.oldWidth,e.oldHeight),t.newSize=new Ze(e.newWidth,e.newHeight),t}isNull(){return Ze.equals(this.oldSize,this.newSize)}run(e){var t=this.getEventWorkspace_();if(!this.commentId)throw Error("The comment ID is undefined. Either pass a comment to the constructor, or call fromJson");if(t=t.getCommentById(this.commentId)){if(e=e?this.newSize:this.oldSize,!e)throw Error("Either oldSize or newSize is undefined. Either pass a comment to the constructor and call recordCurrentSizeAsNewSize, or call fromJson");t.setSize(e)}else console.warn("Can't resize non-existent comment: "+this.commentId)}};r($e.EVENT,ee.COMMENT_RESIZE,Vp);var Yp=class extends Ss{constructor(e,t,o){super(o),this.type=ee.TOOLBOX_ITEM_SELECT,this.oldItem=e??void 0,this.newItem=t??void 0}toJson(){const e=super.toJson();return e.oldItem=this.oldItem,e.newItem=this.newItem,e}static fromJson(e,t,o){return t=super.fromJson(e,t,o??new Yp),t.oldItem=e.oldItem,t.newItem=e.newItem,t}};r($e.EVENT,ee.TOOLBOX_ITEM_SELECT,Yp);var gy=class extends Xi{constructor(e){super(),this.isBlank=!0,this.recordUndo=!1,this.type=ee.FINISHED_LOADING,this.isBlank=!!e,e&&(this.workspaceId=e.id)}};r($e.EVENT,ee.FINISHED_LOADING,gy);var my,fy,$y,by,vy,yy,_y,wy,ky,Cy,Ty,Sy,Ey,Iy,xy,Dy,Ay,Oy,Ry,My,Ny,Ly,Py,By,jy,Se;i.BLOCK_CHANGE$$module$build$src$core$events$events=ee.BLOCK_CHANGE,i.BLOCK_CREATE$$module$build$src$core$events$events=ee.BLOCK_CREATE,i.BLOCK_DELETE$$module$build$src$core$events$events=ee.BLOCK_DELETE,my=ee.BLOCK_DRAG,i.BLOCK_MOVE$$module$build$src$core$events$events=ee.BLOCK_MOVE,fy=ee.BLOCK_FIELD_INTERMEDIATE_CHANGE,$y=ee.BUBBLE_OPEN,by=ee.BLOCK_CHANGE,vy=ee.CLICK,yy=ee.COMMENT_CHANGE,_y=ee.COMMENT_CREATE,wy=ee.COMMENT_DELETE,ky=ee.COMMENT_MOVE,Cy=ee.COMMENT_RESIZE,Ty=ee.COMMENT_DRAG,Sy=ee.BLOCK_CREATE,Ey=ee.BLOCK_DELETE,Iy=ee.FINISHED_LOADING,xy=ee.MARKER_MOVE,Dy=ee.BLOCK_MOVE,Ay=ee.SELECTED,Oy=ee.THEME_CHANGE,Ry=ee.TOOLBOX_ITEM_SELECT,My=ee.TRASHCAN_OPEN,Ny=ee.UI,Ly=ee.VAR_CREATE,Py=ee.VAR_DELETE,By=ee.VAR_RENAME,jy=ee.VIEWPORT_CHANGE,Se={},Se.Abstract=Xi,Se.BLOCK_CHANGE=i.BLOCK_CHANGE$$module$build$src$core$events$events,Se.BLOCK_CREATE=i.BLOCK_CREATE$$module$build$src$core$events$events,Se.BLOCK_DELETE=i.BLOCK_DELETE$$module$build$src$core$events$events,Se.BLOCK_DRAG=my,Se.BLOCK_FIELD_INTERMEDIATE_CHANGE=fy,Se.BLOCK_MOVE=i.BLOCK_MOVE$$module$build$src$core$events$events,Se.BUBBLE_OPEN=$y,Se.BUMP_EVENTS=mb,Se.BlockBase=gi,Se.BlockChange=mi,Se.BlockCreate=ep,Se.BlockDelete=pp,Se.BlockDrag=Np,Se.BlockFieldIntermediateChange=Lp,Se.BlockMove=Pp,Se.BubbleOpen=Bp,Se.BubbleType=jp,Se.CHANGE=by,Se.CLICK=vy,Se.COMMENT_CHANGE=yy,Se.COMMENT_CREATE=_y,Se.COMMENT_DELETE=wy,Se.COMMENT_DRAG=Ty,Se.COMMENT_MOVE=ky,Se.COMMENT_RESIZE=Cy,Se.CREATE=Sy,Se.Click=vh,Se.ClickTarget=yh,Se.CommentBase=Xs,Se.CommentChange=Fp,Se.CommentCollapse=zp,Se.CommentCreate=Up,Se.CommentDelete=Hp,Se.CommentDrag=Wp,Se.CommentMove=Gp,Se.CommentResize=Vp,Se.DELETE=Ey,Se.FINISHED_LOADING=Iy,Se.FinishedLoading=gy,Se.MARKER_MOVE=xy,Se.MOVE=Dy,Se.MarkerMove=gp,Se.SELECTED=Ay,Se.Selected=wp,Se.THEME_CHANGE=Oy,Se.TOOLBOX_ITEM_SELECT=Ry,Se.TRASHCAN_OPEN=My,Se.ThemeChange=tp,Se.ToolboxItemSelect=Yp,Se.TrashcanOpen=Cp,Se.UI=Ny,Se.UiBase=Ss,Se.VAR_CREATE=Ly,Se.VAR_DELETE=Py,Se.VAR_RENAME=By,Se.VIEWPORT_CHANGE=jy,Se.VarBase=br,Se.VarCreate=Fh,Se.VarDelete=vp,Se.VarRename=yp,Se.ViewportChange=sp,Se.clearPendingUndo=Y,Se.disable=i.disable$$module$build$src$core$events$utils,Se.disableOrphans=me,Se.enable=i.enable$$module$build$src$core$events$utils,Se.filter=M,Se.fire=z,Se.fromJson=ce,Se.get=ne,Se.getDescendantIds=ve,Se.getGroup=i.getGroup$$module$build$src$core$events$utils,Se.getRecordUndo=G,Se.isEnabled=C,Se.setGroup=i.setGroup$$module$build$src$core$events$utils,Se.setRecordUndo=i.setRecordUndo$$module$build$src$core$events$utils;var Os={};Os.BottomRow=ty,Os.ConstantProvider=Qv,Os.Drawer=ey,Os.MarkerSvg=ny,Os.PathObject=ry,Os.RenderInfo=iy,Os.Renderer=Op,Os.RightConnectionShape=sy,Os.StatementInput=Jl,Os.TopRow=oy,mh();var It={};It.registerCleanup=Qd,It.registerCollapse=th,It.registerCollapseExpandBlock=lh,It.registerComment=rh,It.registerCommentCreate=gh,It.registerCommentDelete=hh,It.registerCommentDuplicate=ph,It.registerCommentOptions=cb,It.registerDefaultOptions=mh,It.registerDelete=uh,It.registerDeleteAll=ih,It.registerDisable=ch,It.registerDuplicate=nh,It.registerExpand=sh,It.registerHelp=dh,It.registerInline=ah,It.registerRedo=Zd,It.registerUndo=qd;var ql={};ql.CommentView=yv,ql.RenderedWorkspaceComment=xl,ql.WorkspaceComment=Il;var Br={};Br.Bubble=nt,Br.MiniWorkspaceBubble=vo,Br.TextBubble=Dv,Br.TextInputBubble=Tv;var Fy=class extends Bl{constructor(){super(),this.FIELD_TEXT_BASELINE_CENTER=!1,this.DARK_PATH_OFFSET=1,this.MAX_BOTTOM_WIDTH=30,this.STATEMENT_BOTTOM_SPACER=-this.NOTCH_HEIGHT/2}getCSS_(e){return super.getCSS_(e).concat([`${e} .blocklyInsertionMarker>.blocklyPathLight,`,`${e} .blocklyInsertionMarker>.blocklyPathDark {`,`fill-opacity: ${this.INSERTION_MARKER_OPACITY};`,"stroke: none;","}"])}},zy=class{constructor(e){this.inlineSteps_=this.steps_="",this.info_=e,this.RTL_=this.info_.RTL,e=e.getRenderer(),this.constants_=e.getConstants(),this.highlightConstants_=e.getHighlightConstants(),this.highlightOffset=this.highlightConstants_.OFFSET,this.outsideCornerPaths_=this.highlightConstants_.OUTSIDE_CORNER,this.insideCornerPaths_=this.highlightConstants_.INSIDE_CORNER,this.puzzleTabPaths_=this.highlightConstants_.PUZZLE_TAB,this.notchPaths_=this.highlightConstants_.NOTCH,this.startPaths_=this.highlightConstants_.START_HAT,this.jaggedTeethPaths_=this.highlightConstants_.JAGGED_TEETH}getPath(){return this.steps_+` +`+this.inlineSteps_}drawTopCorner(e){this.steps_+=pt(e.xPos,this.info_.startY);for(let t=0,o;o=e.elements[t];t++)j.isLeftSquareCorner(o)?this.steps_+=this.highlightConstants_.START_POINT:j.isLeftRoundedCorner(o)?this.steps_+=this.outsideCornerPaths_.topLeft(this.RTL_):j.isPreviousConnection(o)?this.steps_+=this.notchPaths_.pathLeft:j.isHat(o)?this.steps_+=this.startPaths_.path(this.RTL_):j.isSpacer(o)&&o.width!==0&&(this.steps_+=De("H",o.xPos+o.width-this.highlightOffset));this.steps_+=De("H",e.xPos+e.width-this.highlightOffset)}drawJaggedEdge_(e){this.info_.RTL&&(this.steps_+=this.jaggedTeethPaths_.pathLeft+De("v",e.height-this.jaggedTeethPaths_.height-this.highlightOffset))}drawValueInput(e){const t=e.getLastInput();if(this.RTL_){const o=e.height-t.connectionHeight;this.steps_+=St(t.xPos+t.width-this.highlightOffset,e.yPos)+this.puzzleTabPaths_.pathDown(this.RTL_)+De("v",o)}else this.steps_+=St(t.xPos+t.width,e.yPos)+this.puzzleTabPaths_.pathDown(this.RTL_)}drawStatementInput(e){const t=e.getLastInput();if(t)if(this.RTL_){const o=e.height-2*this.insideCornerPaths_.height;this.steps_+=St(t.xPos,e.yPos)+this.insideCornerPaths_.pathTop(this.RTL_)+De("v",o)+this.insideCornerPaths_.pathBottom(this.RTL_)+Hs(e.width-t.xPos-this.insideCornerPaths_.width,0)}else this.steps_+=St(t.xPos,e.yPos+e.height)+this.insideCornerPaths_.pathBottom(this.RTL_)+Hs(e.width-t.xPos-this.insideCornerPaths_.width,0)}drawRightSideRow(e){const t=e.xPos+e.width-this.highlightOffset;e instanceof dp&&e.followsStatement&&(this.steps_+=De("H",t)),this.RTL_&&(this.steps_+=De("H",t),e.height>this.highlightOffset&&(this.steps_+=De("V",e.yPos+e.height-this.highlightOffset)))}drawBottomRow(e){if(this.RTL_)this.steps_+=De("V",e.baseline-this.highlightOffset);else{const t=this.info_.bottomRow.elements[0];j.isLeftSquareCorner(t)?this.steps_+=St(e.xPos+this.highlightOffset,e.baseline-this.highlightOffset):j.isLeftRoundedCorner(t)&&(this.steps_+=St(e.xPos,e.baseline),this.steps_+=this.outsideCornerPaths_.bottomLeft())}}drawLeft(){var e=this.info_.outputConnection;e&&(e=e.connectionOffsetY+e.height,this.RTL_?this.steps_+=St(this.info_.startX,e):(this.steps_+=St(this.info_.startX+this.highlightOffset,this.info_.bottomRow.baseline-this.highlightOffset),this.steps_+=De("V",e)),this.steps_+=this.puzzleTabPaths_.pathUp(this.RTL_)),this.RTL_||(e=this.info_.topRow,j.isLeftRoundedCorner(e.elements[0])?this.steps_+=De("V",this.outsideCornerPaths_.height):this.steps_+=De("V",e.capline+this.highlightOffset))}drawInlineInput(e){const t=this.highlightOffset,o=e.xPos+e.connectionWidth;var n=e.centerline-e.height/2;const u=e.width-e.connectionWidth,g=n+t;this.RTL_?(n=e.connectionOffsetY-t,e=e.height-(e.connectionOffsetY+e.connectionHeight)+t,this.inlineSteps_+=St(o-t,g)+De("v",n)+this.puzzleTabPaths_.pathDown(this.RTL_)+De("v",e)+De("h",u)):this.inlineSteps_+=St(e.xPos+e.width+t,g)+De("v",e.height)+De("h",-u)+St(o,n+e.connectionOffsetY)+this.puzzleTabPaths_.pathDown(this.RTL_)}},Uy=class extends jl{constructor(e,t){super(e,t),this.highlighter_=new zy(t)}draw(){this.drawOutline_(),this.drawInternals_(),this.updateConnectionHighlights();const e=this.block_.pathObject;e.setPath(this.outlinePath_+` +`+this.inlinePath_),e.setHighlightPath(this.highlighter_.getPath()),this.info_.RTL&&e.flipRTL(),this.recordSizeOnBlock_()}drawTop_(){this.highlighter_.drawTopCorner(this.info_.topRow),this.highlighter_.drawRightSideRow(this.info_.topRow),super.drawTop_()}drawJaggedEdge_(e){this.highlighter_.drawJaggedEdge_(e),super.drawJaggedEdge_(e)}drawValueInput_(e){this.highlighter_.drawValueInput(e),super.drawValueInput_(e)}drawStatementInput_(e){this.highlighter_.drawStatementInput(e),super.drawStatementInput_(e)}drawRightSideRow_(e){this.highlighter_.drawRightSideRow(e),this.outlinePath_+=De("H",e.xPos+e.width)+De("V",e.yPos+e.height)}drawBottom_(){this.highlighter_.drawBottomRow(this.info_.bottomRow),super.drawBottom_()}drawLeft_(){this.highlighter_.drawLeft(),super.drawLeft_()}drawInlineInput_(e){this.highlighter_.drawInlineInput(e),super.drawInlineInput_(e)}positionInlineInputConnection_(e){const t=e.centerline-e.height/2;if(e.connectionModel){let o=e.xPos+e.connectionWidth+this.constants_.DARK_PATH_OFFSET;this.info_.RTL&&(o*=-1),e.connectionModel.setOffsetInBlock(o,t+e.connectionOffsetY+this.constants_.DARK_PATH_OFFSET)}}positionStatementInputConnection_(e){const t=e.getLastInput();if(t!=null&&t.connectionModel){let o=e.xPos+e.statementEdge+t.notchOffset;o=this.info_.RTL?-1*o:o+this.constants_.DARK_PATH_OFFSET,t.connectionModel.setOffsetInBlock(o,e.yPos+this.constants_.DARK_PATH_OFFSET)}}positionExternalValueConnection_(e){const t=e.getLastInput();if(t&&t.connectionModel){let o=e.xPos+e.width+this.constants_.DARK_PATH_OFFSET;this.info_.RTL&&(o*=-1),t.connectionModel.setOffsetInBlock(o,e.yPos)}}positionNextConnection_(){const e=this.info_.bottomRow;if(e.connection){const t=e.connection,o=t.xPos;t.connectionModel.setOffsetInBlock((this.info_.RTL?-o:o)+this.constants_.DARK_PATH_OFFSET/2,e.baseline+this.constants_.DARK_PATH_OFFSET)}}},Hy=class{constructor(e){this.OFFSET=.5,this.constantProvider=e,this.START_POINT=pt(this.OFFSET,this.OFFSET)}init(){this.INSIDE_CORNER=this.makeInsideCorner(),this.OUTSIDE_CORNER=this.makeOutsideCorner(),this.PUZZLE_TAB=this.makePuzzleTab(),this.NOTCH=this.makeNotch(),this.JAGGED_TEETH=this.makeJaggedTeeth(),this.START_HAT=this.makeStartHat()}makeInsideCorner(){const e=this.constantProvider.CORNER_RADIUS,t=this.OFFSET,o=(1-Math.SQRT1_2)*(e+t)-t,n=pt(o,o)+vt("a","0 0,0",e,Ne(-o-t,e-o)),u=vt("a","0 0,0",e+t,Ne(e+t,e+t)),g=pt(o,-o)+vt("a","0 0,0",e+t,Ne(e-o,o+t));return{width:e+t,height:e,pathTop(I){return I?n:""},pathBottom(I){return I?u:g}}}makeOutsideCorner(){const e=this.constantProvider.CORNER_RADIUS,t=this.OFFSET,o=(1-Math.SQRT1_2)*(e-t)+t,n=pt(o,o)+vt("a","0 0,1",e-t,Ne(e-o,-o+t)),u=pt(t,e)+vt("a","0 0,1",e-t,Ne(e,-e+t)),g=-o,I=pt(o,g)+vt("a","0 0,1",e-t,Ne(-o+t,-g-e));return{height:e,topLeft(P){return P?n:u},bottomLeft(){return I}}}makePuzzleTab(){const e=this.constantProvider.TAB_WIDTH,t=this.constantProvider.TAB_HEIGHT,o=pt(-2,-t+3.4)+Hs(-.45*e,-2.1),n=De("v",2.5)+pt(.97*-e,2.5)+Zt("q",[Ne(.05*-e,10),Ne(.3*e,9.5)])+pt(.67*e,-1.9)+De("v",2.5),u=De("v",-1.5)+pt(-.92*e,-.5)+Zt("q",[Ne(-.19*e,-5.5),Ne(0,-11)])+pt(.92*e,1),g=pt(-5,t-.7)+Hs(.46*e,-2.1);return{width:e,height:t,pathUp(I){return I?o:u},pathDown(I){return I?n:g}}}makeNotch(){return{pathLeft:De("h",this.OFFSET)+this.constantProvider.NOTCH.pathLeft}}makeJaggedTeeth(){return{pathLeft:Hs(5.1,2.6)+pt(-10.2,6.8)+Hs(5.1,2.6),height:12,width:10.2}}makeStartHat(){const e=this.constantProvider.START_HAT.height,t=pt(25,-8.7)+Zt("c",[Ne(29.7,-6.2),Ne(57.2,-.5),Ne(75,8.7)]),o=Zt("c",[Ne(17.8,-9.2),Ne(45.3,-14.9),Ne(75,-8.7)])+St(100.5,e+.5);return{path(n){return n?t:o}}}},Wy=class extends cp{constructor(e,t){super(e,t),this.constants_=e,this.connectedBlock&&(this.width+=this.constants_.DARK_PATH_OFFSET,this.height+=this.constants_.DARK_PATH_OFFSET)}},Gy=class extends xr{constructor(e,t){super(e,t),this.constants_=e,this.connectedBlock&&(this.height+=this.constants_.DARK_PATH_OFFSET)}},Vy=class extends Or{constructor(e,t){super(e,t),this.renderer_=e}getRenderer(){return this.renderer_}populateBottomRow_(){super.populateBottomRow_(),this.block_.inputList.length&&this.block_.inputList[this.block_.inputList.length-1]instanceof ls||(this.bottomRow.minHeight=this.constants_.MEDIUM_PADDING-this.constants_.DARK_PATH_OFFSET)}addInput_(e,t){this.isInline&&e instanceof i.ValueInput$$module$build$src$core$inputs$value_input?(t.elements.push(new Wy(this.constants_,e)),t.hasInlineInput=!0):e instanceof ls?(t.elements.push(new Gy(this.constants_,e)),t.hasStatement=!0):e instanceof i.ValueInput$$module$build$src$core$inputs$value_input?(t.elements.push(new Pl(this.constants_,e)),t.hasExternalInput=!0):(e instanceof Ys||e instanceof Co)&&(t.minHeight=Math.max(t.minHeight,this.constants_.DUMMY_INPUT_MIN_HEIGHT),t.hasDummyInput=!0),this.isInline||t.align!==null||(t.align=e.align)}addElemSpacing_(){let e=!1;for(let o=0,n;n=this.rows[o];o++)n.hasExternalInput&&(e=!0);for(let o=0,n;n=this.rows[o];o++){var t=n.elements;if(n.elements=[],n.startsWithElemSpacer()&&n.elements.push(new as(this.constants_,this.getInRowSpacing_(null,t[0]))),t.length){for(let u=0;u>>/handdelete.cur"), auto; } @@ -1009,13 +1009,13 @@ Blockly.YourGeneratorName.nameDB_.setVariableMap(workspace.getVariableMap());`), .blocklyToolboxContents:focus { outline: none; } -`),r($e.TOOLBOX,Ws,Jy);var vT="11.2.2",yT=xe.INPUT_VALUE,_T=xe.OUTPUT_VALUE,wT=xe.NEXT_STATEMENT,kT=xe.PREVIOUS_STATEMENT,CT=Ge.TOP,TT=Ge.BOTTOM,ST=Ge.LEFT,ET=Ge.RIGHT;gn.prototype.newBlock=function(e,t){return new Uo(this,e,t)},cs.prototype.newBlock=function(e,t){return new $s(this,e,t)},gn.prototype.newComment=function(e){return new El(this,e)},cs.prototype.newComment=function(e){return new Il(this,e)},cs.newTrashcan=function(e){return new Gv(e)},vo.prototype.newWorkspaceSvg=function(e){return new cs(e)},i.Names$$module$build$src$core$names.prototype.populateProcedures=function(e){e=qa(e),e=e[0].concat(e[1]);for(let t=0;t{this.setState({popper:x.I18n.t("Copied"),anchorEl:i}),setTimeout(()=>this.setState({popper:"",anchorEl:null}),1e3)},50)}render(){const s=new Blob([this.props.text],{type:"application/xml"}),i=`${this.props.scriptId.substring(10)}.xml`;return m.jsxs(Pt,{onClose:()=>!1,maxWidth:"lg",sx:{"& .MuiDialog-paper":Wr.dialog},fullWidth:!0,open:!0,"aria-labelledby":"export-dialog-title",children:[m.jsx(Xt,{id:"export-dialog-title",children:x.I18n.t("Export selected blocks")}),m.jsx(Wt,{style:Wr.overflowY,children:m.jsx("pre",{id:"export-text",style:{...Wr.textArea,...this.props.themeType==="dark"?void 0:Wr.textAreaLight},children:this.props.text})}),m.jsxs(Bt,{children:[m.jsx(Ue,{variant:"contained",color:"secondary",startIcon:m.jsx(kc,{}),children:m.jsx("a",{download:i,target:"_blank",rel:"noreferrer",href:URL.createObjectURL(s),style:{textDecoration:"inherit",color:"inherit"},children:x.I18n.t("Download as file")})}),m.jsx(Ue,{variant:"contained",onClick:r=>this.onCopy(r),color:"secondary",startIcon:m.jsx(cx,{}),children:x.I18n.t("Copy to clipboard")}),m.jsx(Ue,{variant:"contained",onClick:()=>this.handleCancel(),color:"primary",startIcon:m.jsx(so,{}),children:x.I18n.t("Close")}),m.jsx(YT,{id:"popper",style:{zIndex:1e4},open:!!this.state.popper,placement:"top",anchorEl:this.state.anchorEl,transition:!0,children:({TransitionProps:r})=>m.jsx(JT,{...r,timeout:350,children:m.jsx(Rw,{children:m.jsx("p",{style:Wr.typography,children:this.state.popper})})})}),m.jsx("textarea",{id:"copy_input",readOnly:!0,style:{position:"absolute",left:-9999},tabIndex:-1,"aria-hidden":!0,value:this.props.text})]})]},"export-dialog")}}const Mt={textArea:{width:"calc(100% - 10px)",height:"calc(80% - 20px)",resize:"none",fontFamily:"monospace",fontSize:"1em",backgroundColor:"transparent",borderRadius:4,outline:"none"},dropzone:{marginTop:20,width:"100%",borderWidth:5,borderStyle:"dashed",borderColor:"#d0cccc",textAlign:"center",boxSizing:"border-box",paddingTop:45,borderRadius:10,height:"calc(100% - 10px)"},dropzoneDiv:{width:"100%",height:"20%",position:"relative"},dropzoneRejected:{borderColor:"#970000"},dropzoneAccepted:{borderColor:"#17cd02"},icon:{height:"80%",width:"80%",opacity:.3,color:"#eeeeee",position:"absolute",top:"50%",left:"50%",transform:"translate(-50%,-50%)",zIndex:0},iconError:{color:"#ffc3c6"},iconOk:{color:"#aaeebc"},text:{top:"50%",left:"50%",transform:"translate(-50%,-50%)",color:"#868686",position:"absolute",zIndex:1},dialog:{height:"95%"},fullHeight:{height:"100%",overflow:"hidden"}};class Gm extends _e.Component{constructor(s){super(s),this.state={text:"",imageStatus:"",error:""}}componentDidMount(){setTimeout(()=>{var s;try{(s=window.document.getElementById("import-text-area"))==null||s.focus()}catch{}},100)}static readFileDataUrl(s,i){const r=new FileReader;r.onload=()=>{i(null,{data:r.result,name:s.name})},r.onabort=()=>{console.error("file reading was aborted"),i(x.I18n.t("file reading was aborted"))},r.onerror=l=>{console.error("file reading has failed"),i(x.I18n.t("file reading has failed: %s",l))},r.readAsText(s)}handleDropFile(s){if(!(s!=null&&s.length))return;const i=s[s.length-1];i&&Gm.readFileDataUrl(i,(r,l)=>{var c;r||!l?this.setState({error:r||"No data"}):this.setState({text:((c=l.data)==null?void 0:c.toString())||""})})}handleCancel(){this.props.onClose()}handleOk(){this.props.onClose(this.state.text)}onChange(s){this.setState({text:s.target.value})}render(){const s={...Mt.dropzone,...this.state.imageStatus==="accepted"?Mt.dropzoneAccepted:this.state.imageStatus==="rejected"?Mt.dropzoneRejected:void 0};return m.jsxs(Pt,{onClose:()=>!1,maxWidth:"lg",sx:{"& .MuiDialog-paper":Mt.dialog},fullWidth:!0,open:!0,"aria-labelledby":"import-dialog-title",children:[m.jsx(Xt,{id:"import-dialog-title",children:x.I18n.t("Import blocks")}),m.jsxs(Wt,{style:Mt.fullHeight,children:[m.jsx("textarea",{autoFocus:!0,id:"import-text-area",placeholder:x.I18n.t("Paste your blocks here"),style:{...Mt.textArea,color:this.props.themeType==="dark"?"#ffffff":"#000000"},onChange:i=>this.onChange(i),value:this.state.text}),m.jsx(Lw,{maxSize:5e7,onDrop:(i,r)=>{var l,c,d;i.length?this.handleDropFile(i):window.alert(((d=(c=(l=r==null?void 0:r[0])==null?void 0:l.errors)==null?void 0:c[0])==null?void 0:d.message)||x.I18n.t("ra_Cannot upload"))},multiple:!1,accept:{"text/plain":[],"text/xml":[],"application/xml":[]},children:({getRootProps:i,getInputProps:r,isDragActive:l,isDragReject:c})=>c?(this.state.imageStatus!=="rejected"&&this.setState({imageStatus:"rejected"}),m.jsxs("div",{style:{...s,...Mt.dropzoneDiv},...i(),children:[m.jsx("input",{...r()}),m.jsx("span",{style:Mt.text,children:x.I18n.t("Some files will be rejected")},"text"),m.jsx(Yc,{style:{...Mt.icon,...Mt.iconError}},"icon")]})):l?(this.state.imageStatus!=="accepted"&&this.setState({imageStatus:"accepted"}),m.jsxs("div",{style:{...s,...Mt.dropzoneDiv},...i(),children:[m.jsx("input",{...r()}),m.jsx("span",{style:Mt.text,children:x.I18n.t("All files will be accepted")},"text"),m.jsx(Pw,{style:{...Mt.icon,...Mt.iconOk}},"icon")]})):(this.state.imageStatus!=="wait"&&this.setState({imageStatus:"wait"}),m.jsxs("div",{style:{...s,...Mt.dropzoneDiv},...i(),children:[m.jsx("input",{...r()}),m.jsx("span",{style:Mt.text,children:x.I18n.t("Drop some files here or click...")},"text"),m.jsx(Bw,{style:Mt.icon},"icon")]}))})]}),m.jsxs(Bt,{children:[m.jsx(Ue,{variant:"contained",disabled:!this.state.text,onClick:()=>this.handleOk(),color:"primary",startIcon:m.jsx(qo,{}),children:x.I18n.t("Import")}),m.jsx(Ue,{color:"grey",variant:"contained",onClick:()=>this.handleCancel(),startIcon:m.jsx(so,{}),children:x.I18n.t("Close")})]})]})}}const je=window.Blockly;class vg extends Error{constructor(){super("The field has not yet been attached to its input. Call appendField to attach it.")}}class Rc extends je.Field{textGroup=null;borderRect_=null;maxLines_=1/0;isOverflowedY_=!1;constructor(s,i,r){super(s),s!==Symbol("SKIP_SETUP")&&(r&&this.configure_(r),this.SERIALIZABLE=!0,this.setValue((s==null?void 0:s.toString())||""),i&&this.setValidator(i))}configure_(s){super.configure_(s),s.maxLines&&this.setMaxLines(s.maxLines)}toXml(s){return s.textContent=this.getValue().replace(/\n/g," "),s}fromXml(s){this.setValue(s.textContent.replace(/ /g,` +`),r($e.TOOLBOX,Ws,qy);var yT="11.2.2",_T=xe.INPUT_VALUE,wT=xe.OUTPUT_VALUE,kT=xe.NEXT_STATEMENT,CT=xe.PREVIOUS_STATEMENT,TT=Ge.TOP,ST=Ge.BOTTOM,ET=Ge.LEFT,IT=Ge.RIGHT;gn.prototype.newBlock=function(e,t){return new Uo(this,e,t)},cs.prototype.newBlock=function(e,t){return new $s(this,e,t)},gn.prototype.newComment=function(e){return new Il(this,e)},cs.prototype.newComment=function(e){return new xl(this,e)},cs.newTrashcan=function(e){return new Yv(e)},vo.prototype.newWorkspaceSvg=function(e){return new cs(e)},i.Names$$module$build$src$core$names.prototype.populateProcedures=function(e){e=qa(e),e=e[0].concat(e[1]);for(let t=0;t{this.setState({popper:x.I18n.t("Copied"),anchorEl:i}),setTimeout(()=>this.setState({popper:"",anchorEl:null}),1e3)},50)}render(){const s=new Blob([this.props.text],{type:"application/xml"}),i=`${this.props.scriptId.substring(10)}.xml`;return m.jsxs(Pt,{onClose:()=>!1,maxWidth:"lg",sx:{"& .MuiDialog-paper":Wr.dialog},fullWidth:!0,open:!0,"aria-labelledby":"export-dialog-title",children:[m.jsx(qt,{id:"export-dialog-title",children:x.I18n.t("Export selected blocks")}),m.jsx(Wt,{style:Wr.overflowY,children:m.jsx("pre",{id:"export-text",style:{...Wr.textArea,...this.props.themeType==="dark"?void 0:Wr.textAreaLight},children:this.props.text})}),m.jsxs(Bt,{children:[m.jsx(Ue,{variant:"contained",color:"secondary",startIcon:m.jsx(Cc,{}),children:m.jsx("a",{download:i,target:"_blank",rel:"noreferrer",href:URL.createObjectURL(s),style:{textDecoration:"inherit",color:"inherit"},children:x.I18n.t("Download as file")})}),m.jsx(Ue,{variant:"contained",onClick:r=>this.onCopy(r),color:"secondary",startIcon:m.jsx(ux,{}),children:x.I18n.t("Copy to clipboard")}),m.jsx(Ue,{variant:"contained",onClick:()=>this.handleCancel(),color:"primary",startIcon:m.jsx(so,{}),children:x.I18n.t("Close")}),m.jsx(JT,{id:"popper",style:{zIndex:1e4},open:!!this.state.popper,placement:"top",anchorEl:this.state.anchorEl,transition:!0,children:({TransitionProps:r})=>m.jsx(XT,{...r,timeout:350,children:m.jsx(Rw,{children:m.jsx("p",{style:Wr.typography,children:this.state.popper})})})}),m.jsx("textarea",{id:"copy_input",readOnly:!0,style:{position:"absolute",left:-9999},tabIndex:-1,"aria-hidden":!0,value:this.props.text})]})]},"export-dialog")}}const Nt={textArea:{width:"calc(100% - 10px)",height:"calc(80% - 20px)",resize:"none",fontFamily:"monospace",fontSize:"1em",backgroundColor:"transparent",borderRadius:4,outline:"none"},dropzone:{marginTop:20,width:"100%",borderWidth:5,borderStyle:"dashed",borderColor:"#d0cccc",textAlign:"center",boxSizing:"border-box",paddingTop:45,borderRadius:10,height:"calc(100% - 10px)"},dropzoneDiv:{width:"100%",height:"20%",position:"relative"},dropzoneRejected:{borderColor:"#970000"},dropzoneAccepted:{borderColor:"#17cd02"},icon:{height:"80%",width:"80%",opacity:.3,color:"#eeeeee",position:"absolute",top:"50%",left:"50%",transform:"translate(-50%,-50%)",zIndex:0},iconError:{color:"#ffc3c6"},iconOk:{color:"#aaeebc"},text:{top:"50%",left:"50%",transform:"translate(-50%,-50%)",color:"#868686",position:"absolute",zIndex:1},dialog:{height:"95%"},fullHeight:{height:"100%",overflow:"hidden"}};class Ym extends _e.Component{constructor(s){super(s),this.state={text:"",imageStatus:"",error:""}}componentDidMount(){setTimeout(()=>{var s;try{(s=window.document.getElementById("import-text-area"))==null||s.focus()}catch{}},100)}static readFileDataUrl(s,i){const r=new FileReader;r.onload=()=>{i(null,{data:r.result,name:s.name})},r.onabort=()=>{console.error("file reading was aborted"),i(x.I18n.t("file reading was aborted"))},r.onerror=l=>{console.error("file reading has failed"),i(x.I18n.t("file reading has failed: %s",l))},r.readAsText(s)}handleDropFile(s){if(!(s!=null&&s.length))return;const i=s[s.length-1];i&&Ym.readFileDataUrl(i,(r,l)=>{var c;r||!l?this.setState({error:r||"No data"}):this.setState({text:((c=l.data)==null?void 0:c.toString())||""})})}handleCancel(){this.props.onClose()}handleOk(){this.props.onClose(this.state.text)}onChange(s){this.setState({text:s.target.value})}render(){const s={...Nt.dropzone,...this.state.imageStatus==="accepted"?Nt.dropzoneAccepted:this.state.imageStatus==="rejected"?Nt.dropzoneRejected:void 0};return m.jsxs(Pt,{onClose:()=>!1,maxWidth:"lg",sx:{"& .MuiDialog-paper":Nt.dialog},fullWidth:!0,open:!0,"aria-labelledby":"import-dialog-title",children:[m.jsx(qt,{id:"import-dialog-title",children:x.I18n.t("Import blocks")}),m.jsxs(Wt,{style:Nt.fullHeight,children:[m.jsx("textarea",{autoFocus:!0,id:"import-text-area",placeholder:x.I18n.t("Paste your blocks here"),style:{...Nt.textArea,color:this.props.themeType==="dark"?"#ffffff":"#000000"},onChange:i=>this.onChange(i),value:this.state.text}),m.jsx(Pw,{maxSize:5e7,onDrop:(i,r)=>{var l,c,d;i.length?this.handleDropFile(i):window.alert(((d=(c=(l=r==null?void 0:r[0])==null?void 0:l.errors)==null?void 0:c[0])==null?void 0:d.message)||x.I18n.t("ra_Cannot upload"))},multiple:!1,accept:{"text/plain":[],"text/xml":[],"application/xml":[]},children:({getRootProps:i,getInputProps:r,isDragActive:l,isDragReject:c})=>c?(this.state.imageStatus!=="rejected"&&this.setState({imageStatus:"rejected"}),m.jsxs("div",{style:{...s,...Nt.dropzoneDiv},...i(),children:[m.jsx("input",{...r()}),m.jsx("span",{style:Nt.text,children:x.I18n.t("Some files will be rejected")},"text"),m.jsx(Jc,{style:{...Nt.icon,...Nt.iconError}},"icon")]})):l?(this.state.imageStatus!=="accepted"&&this.setState({imageStatus:"accepted"}),m.jsxs("div",{style:{...s,...Nt.dropzoneDiv},...i(),children:[m.jsx("input",{...r()}),m.jsx("span",{style:Nt.text,children:x.I18n.t("All files will be accepted")},"text"),m.jsx(Bw,{style:{...Nt.icon,...Nt.iconOk}},"icon")]})):(this.state.imageStatus!=="wait"&&this.setState({imageStatus:"wait"}),m.jsxs("div",{style:{...s,...Nt.dropzoneDiv},...i(),children:[m.jsx("input",{...r()}),m.jsx("span",{style:Nt.text,children:x.I18n.t("Drop some files here or click...")},"text"),m.jsx(jw,{style:Nt.icon},"icon")]}))})]}),m.jsxs(Bt,{children:[m.jsx(Ue,{variant:"contained",disabled:!this.state.text,onClick:()=>this.handleOk(),color:"primary",startIcon:m.jsx(Xo,{}),children:x.I18n.t("Import")}),m.jsx(Ue,{color:"grey",variant:"contained",onClick:()=>this.handleCancel(),startIcon:m.jsx(so,{}),children:x.I18n.t("Close")})]})]})}}const je=window.Blockly;class _g extends Error{constructor(){super("The field has not yet been attached to its input. Call appendField to attach it.")}}class Rc extends je.Field{textGroup=null;borderRect_=null;maxLines_=1/0;isOverflowedY_=!1;constructor(s,i,r){super(s),s!==Symbol("SKIP_SETUP")&&(r&&this.configure_(r),this.SERIALIZABLE=!0,this.setValue((s==null?void 0:s.toString())||""),i&&this.setValidator(i))}configure_(s){super.configure_(s),s.maxLines&&this.setMaxLines(s.maxLines)}toXml(s){return s.textContent=this.getValue().replace(/\n/g," "),s}fromXml(s){this.setValue(s.textContent.replace(/ /g,` `))}saveState(){const s=this.saveLegacyState(Rc);return s!==null?s:this.getValue()}loadState(s){this.loadLegacyState(je.Field,s)||this.setValue(s)}initView(){this.createBorderRect_(),this.textGroup=je.utils.dom.createSvgElement(je.utils.Svg.G,{class:"blocklyEditableText"},this.fieldGroup_)}onHtmlInputKeyDownSuper_(s){s.key==="Enter"?(je.WidgetDiv.hideIfOwner(this),je.dropDownDiv.hideWithoutAnimation()):s.key==="Escape"?(this.setValue(this.htmlInput_.getAttribute("data-untyped-default-value"),!1),je.WidgetDiv.hideIfOwner(this),je.dropDownDiv.hideWithoutAnimation()):s.key==="Tab"&&(je.WidgetDiv.hideIfOwner(this),je.dropDownDiv.hideWithoutAnimation(),this.sourceBlock_.tab(this,!s.shiftKey),s.preventDefault())}onHtmlInputChange_(s){const i=this.value_;this.setValue(this.getValueFromEditorText_(this.htmlInput_.value),!1),this.sourceBlock_&&je.Events.isEnabled()&&this.value_!==i&&je.Events.fire(new(je.Events.get("block_field_intermediate_change"))(this.sourceBlock_,this.name||null,i,this.value_))}onFinishEditing_(s){}getValueFromEditorText_(s){return s}bindInputEvents_(s){this.onKeyDownWrapper_=je.browserEvents.conditionalBind(s,"keydown",this,this.onHtmlInputKeyDown_),this.onKeyInputWrapper_=je.browserEvents.conditionalBind(s,"input",this,this.onHtmlInputChange_)}getDisplayText_(){const s=this.getSourceBlock();if(!s)throw new Error("The field has not yet been attached to its input. Call appendField to attach it.");let i=this.getText();if(!i)return je.Field.NBSP;const r=i.split(` `);i="";const l=this.isOverflowedY_?this.maxLines_:r.length;for(let c=0;cthis.maxDisplayLength?d=`${d.substring(0,this.maxDisplayLength-4)}...`:this.isOverflowedY_&&c===l-1&&(d=`${d.substring(0,d.length-3)}...`),d=d.replace(/\s/g,je.Field.NBSP),i+=d,c!==l-1&&(i+=` `)}return s.RTL&&(i+="‏"),i}doValueUpdate_(s){super.doValueUpdate_(s),this.value_!==null&&(this.isOverflowedY_=this.value_.split(` `).length>this.maxLines_)}render_(){const s=this.getSourceBlock();if(!s)throw new Error("The field has not yet been attached to its input. Call appendField to attach it.");let i;const r=this.textGroup;for(;i=r.firstChild;)r.removeChild(i);const l=this.getConstants();if(!l)throw Error("Constants not found");const c=this.getDisplayText_().split(` `);let d=0;for(let h=0;hd&&(d=b),h+=s.FIELD_TEXT_HEIGHT+(p>0?s.FIELD_BORDER_RECT_Y_PADDING:0)}if(this.isBeingEdited_){const p=String(this.value_).split(` -`),f=je.utils.dom.createSvgElement(je.utils.Svg.TEXT,{class:"blocklyText blocklyMultilineText"});for(let w=0;wthis.maxDisplayLength&&(p[w]=p[w].substring(0,this.maxDisplayLength)),f.textContent=p[w];const v=je.utils.dom.getFastTextWidth(f,r,l,c);v>d&&(d=v)}const b=this.htmlInput_,y=b.offsetWidth-b.clientWidth;d+=y}this.borderRect_&&(h+=s.FIELD_BORDER_RECT_Y_PADDING*2,d+=s.FIELD_BORDER_RECT_X_PADDING*2+1,this.borderRect_.setAttribute("width",`${d}`),this.borderRect_.setAttribute("height",`${h}`)),this.size_.width=d,this.size_.height=h,this.positionBorderRect_()}showInlineEditor_(s){const i=this.getSourceBlock();if(!i)throw new vg;je.WidgetDiv.show(this,i.RTL,this.widgetDispose_.bind(this),this.workspace_),this.htmlInput_=this.widgetCreate_(),this.isBeingEdited_=!0,this.valueWhenEditorWasOpened_=this.value_,s||(this.htmlInput_.focus({preventScroll:!0}),this.htmlInput_.select())}getEditorText_(s){return`${s}`}getScaledBBox(){let s,i,r;const l=this.getSourceBlock();if(!l)throw new vg;if(this.isFullBlockField()){const c=this.sourceBlock_.getHeightWidth(),d=l.workspace.scale;r=this.getAbsoluteXY_(),s=(c.width+1)*d,i=(c.height+1)*d,je.utils.userAgent.GECKO?(r.x+=1.5*d,r.y+=1.5*d):(r.x-=.5*d,r.y-=.5*d)}else{const c=this.borderRect_.getBoundingClientRect();r=je.utils.style.getPageOffset(this.borderRect_),s=c.width,i=c.height}return new je.utils.Rect(r.y,r.y+i,r.x,r.x+s)}resizeEditor_(){je.renderManagement.finishQueuedRenders().then(()=>{const s=this.getSourceBlock();if(!s)throw new vg;const i=je.WidgetDiv.getDiv(),r=this.getScaledBBox();i.style.width=`${r.right-r.left}px`,i.style.height=`${r.bottom-r.top}px`;const l=s.RTL?r.right-i.offsetWidth:r.left,c=r.top;i.style.left=`${l}px`,i.style.top=`${c}px`})}unbindInputEvents_(){this.onKeyDownWrapper_&&(je.browserEvents.unbind(this.onKeyDownWrapper_),this.onKeyDownWrapper_=null),this.onKeyInputWrapper_&&(je.browserEvents.unbind(this.onKeyInputWrapper_),this.onKeyInputWrapper_=null)}getClickTarget_(){return this.clickTarget_||this.getSvgRoot()}widgetDispose_(){this.isBeingEdited_=!1,this.isTextValid_=!0,this.forceRerender(),this.onFinishEditing_(this.value_),this.sourceBlock_&&je.Events.isEnabled()&&this.valueWhenEditorWasOpened_!==null&&this.valueWhenEditorWasOpened_!==this.value_&&(je.Events.fire(new(je.Events.get("change"))(this.sourceBlock_,"field",this.name||null,this.valueWhenEditorWasOpened_,this.value_)),this.valueWhenEditorWasOpened_=null),je.Events.setGroup(!1),this.unbindInputEvents_();const s=je.WidgetDiv.getDiv().style;s.width="auto",s.height="auto",s.fontSize="",s.transition="",s.boxShadow="",this.htmlInput_=null;const i=this.getClickTarget_();if(!i)throw new Error("A click target has not been set.");je.utils.dom.removeClass(i,"editing")}showEditor_(s,i){this.workspace_=this.sourceBlock_.workspace,!i&&this.workspace_.options.modalInputs&&(je.utils.userAgent.MOBILE||je.utils.userAgent.ANDROID||je.utils.userAgent.IPAD)?this.showPromptEditor_():this.showInlineEditor_(!!i),this.forceRerender()}widgetCreate_(){const s=je.WidgetDiv.getDiv(),i=this.workspace_.getScale(),r=this.getConstants();if(!r)throw Error("Constants not found");const l=document.createElement("textarea");l.className="blocklyHtmlInput blocklyHtmlTextAreaInput",l.setAttribute("spellcheck",String(this.spellcheck_));const c=`${r.FIELD_TEXT_FONTSIZE*i}pt`;s.style.fontSize=c,l.style.fontSize=c;const d=`${je.FieldTextInput.BORDERRADIUS*i}px`;l.style.borderRadius=d;const h=r.FIELD_BORDER_RECT_X_PADDING*i,p=r.FIELD_BORDER_RECT_Y_PADDING*i/2;l.style.padding=`${p}px ${h}px ${p}px ${h}px`;const f=r.FIELD_TEXT_HEIGHT+r.FIELD_BORDER_RECT_Y_PADDING;return l.style.lineHeight=`${f*i}px`,s.appendChild(l),l.value=l.defaultValue=this.getEditorText_(this.value_),l.setAttribute("data-untyped-default-value",String(this.value_)),l.setAttribute("data-old-value",""),je.utils.userAgent.GECKO?setTimeout(this.resizeEditor_.bind(this),0):this.resizeEditor_(),this.bindInputEvents_(l),l}setMaxLines(s){typeof s=="number"&&s>0&&s!==this.maxLines_&&(this.maxLines_=s,this.forceRerender())}getMaxLines(){return this.maxLines_}onHtmlInputKeyDown_(s){s.key!=="Enter"&&this.onHtmlInputKeyDownSuper_(s)}static fromJson(s){const i=je.utils.parsing.replaceMessageReferences(s.text);return new this(i,void 0,s)}}je.Css.register(` +`),f=je.utils.dom.createSvgElement(je.utils.Svg.TEXT,{class:"blocklyText blocklyMultilineText"});for(let w=0;wthis.maxDisplayLength&&(p[w]=p[w].substring(0,this.maxDisplayLength)),f.textContent=p[w];const v=je.utils.dom.getFastTextWidth(f,r,l,c);v>d&&(d=v)}const b=this.htmlInput_,y=b.offsetWidth-b.clientWidth;d+=y}this.borderRect_&&(h+=s.FIELD_BORDER_RECT_Y_PADDING*2,d+=s.FIELD_BORDER_RECT_X_PADDING*2+1,this.borderRect_.setAttribute("width",`${d}`),this.borderRect_.setAttribute("height",`${h}`)),this.size_.width=d,this.size_.height=h,this.positionBorderRect_()}showInlineEditor_(s){const i=this.getSourceBlock();if(!i)throw new _g;je.WidgetDiv.show(this,i.RTL,this.widgetDispose_.bind(this),this.workspace_),this.htmlInput_=this.widgetCreate_(),this.isBeingEdited_=!0,this.valueWhenEditorWasOpened_=this.value_,s||(this.htmlInput_.focus({preventScroll:!0}),this.htmlInput_.select())}getEditorText_(s){return`${s}`}getScaledBBox(){let s,i,r;const l=this.getSourceBlock();if(!l)throw new _g;if(this.isFullBlockField()){const c=this.sourceBlock_.getHeightWidth(),d=l.workspace.scale;r=this.getAbsoluteXY_(),s=(c.width+1)*d,i=(c.height+1)*d,je.utils.userAgent.GECKO?(r.x+=1.5*d,r.y+=1.5*d):(r.x-=.5*d,r.y-=.5*d)}else{const c=this.borderRect_.getBoundingClientRect();r=je.utils.style.getPageOffset(this.borderRect_),s=c.width,i=c.height}return new je.utils.Rect(r.y,r.y+i,r.x,r.x+s)}resizeEditor_(){je.renderManagement.finishQueuedRenders().then(()=>{const s=this.getSourceBlock();if(!s)throw new _g;const i=je.WidgetDiv.getDiv(),r=this.getScaledBBox();i.style.width=`${r.right-r.left}px`,i.style.height=`${r.bottom-r.top}px`;const l=s.RTL?r.right-i.offsetWidth:r.left,c=r.top;i.style.left=`${l}px`,i.style.top=`${c}px`})}unbindInputEvents_(){this.onKeyDownWrapper_&&(je.browserEvents.unbind(this.onKeyDownWrapper_),this.onKeyDownWrapper_=null),this.onKeyInputWrapper_&&(je.browserEvents.unbind(this.onKeyInputWrapper_),this.onKeyInputWrapper_=null)}getClickTarget_(){return this.clickTarget_||this.getSvgRoot()}widgetDispose_(){this.isBeingEdited_=!1,this.isTextValid_=!0,this.forceRerender(),this.onFinishEditing_(this.value_),this.sourceBlock_&&je.Events.isEnabled()&&this.valueWhenEditorWasOpened_!==null&&this.valueWhenEditorWasOpened_!==this.value_&&(je.Events.fire(new(je.Events.get("change"))(this.sourceBlock_,"field",this.name||null,this.valueWhenEditorWasOpened_,this.value_)),this.valueWhenEditorWasOpened_=null),je.Events.setGroup(!1),this.unbindInputEvents_();const s=je.WidgetDiv.getDiv().style;s.width="auto",s.height="auto",s.fontSize="",s.transition="",s.boxShadow="",this.htmlInput_=null;const i=this.getClickTarget_();if(!i)throw new Error("A click target has not been set.");je.utils.dom.removeClass(i,"editing")}showEditor_(s,i){this.workspace_=this.sourceBlock_.workspace,!i&&this.workspace_.options.modalInputs&&(je.utils.userAgent.MOBILE||je.utils.userAgent.ANDROID||je.utils.userAgent.IPAD)?this.showPromptEditor_():this.showInlineEditor_(!!i),this.forceRerender()}widgetCreate_(){const s=je.WidgetDiv.getDiv(),i=this.workspace_.getScale(),r=this.getConstants();if(!r)throw Error("Constants not found");const l=document.createElement("textarea");l.className="blocklyHtmlInput blocklyHtmlTextAreaInput",l.setAttribute("spellcheck",String(this.spellcheck_));const c=`${r.FIELD_TEXT_FONTSIZE*i}pt`;s.style.fontSize=c,l.style.fontSize=c;const d=`${je.FieldTextInput.BORDERRADIUS*i}px`;l.style.borderRadius=d;const h=r.FIELD_BORDER_RECT_X_PADDING*i,p=r.FIELD_BORDER_RECT_Y_PADDING*i/2;l.style.padding=`${p}px ${h}px ${p}px ${h}px`;const f=r.FIELD_TEXT_HEIGHT+r.FIELD_BORDER_RECT_Y_PADDING;return l.style.lineHeight=`${f*i}px`,s.appendChild(l),l.value=l.defaultValue=this.getEditorText_(this.value_),l.setAttribute("data-untyped-default-value",String(this.value_)),l.setAttribute("data-old-value",""),je.utils.userAgent.GECKO?setTimeout(this.resizeEditor_.bind(this),0):this.resizeEditor_(),this.bindInputEvents_(l),l}setMaxLines(s){typeof s=="number"&&s>0&&s!==this.maxLines_&&(this.maxLines_=s,this.forceRerender())}getMaxLines(){return this.maxLines_}onHtmlInputKeyDown_(s){s.key!=="Enter"&&this.onHtmlInputKeyDownSuper_(s)}static fromJson(s){const i=je.utils.parsing.replaceMessageReferences(s.text);return new this(i,void 0,s)}}je.Css.register(` .blocklyHtmlTextAreaInput { font-family: monospace; resize: none; @@ -1027,7 +1027,7 @@ Blockly.YourGeneratorName.nameDB_.setVariableMap(workspace.getVariableMap());`), .blocklyHtmlTextAreaInputOverflowedY { overflow-y: scroll; } -`);const yC="text_multiline",oR={type:yC,message0:"%1 %2",args0:[{type:"field_image",src:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAARCAYAAADpPU2iAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAdhgAAHYYBXaITgQAAABh0RVh0U29mdHdhcmUAcGFpbnQubmV0IDQuMS42/U4J6AAAAP1JREFUOE+Vks0KQUEYhjmRIja4ABtZ2dm5A3t3Ia6AUm7CylYuQRaUhZSlLZJiQbFAyRnPN33y01HOW08z8873zpwzM4F3GWOCruvGIE4/rLaV+Nq1hVGMBqzhqlxgCys4wJA65xnogMHsQ5lujnYHTejBBCK2mE4abjCgMGhNxHgDFWjDSG07kdfVa2pZMf4ZyMAdWmpZMfYOsLiDMYMjlMB+K613QISRhTnITnsYg5yUd0DETmEoMlkFOeIT/A58iyK5E18BuTBfgYXfwNJv4P9/oEBerLylOnRhygmGdPpTTBZAPkde61lbQe4moWUvYUZYLfUNftIY4zwA5X2Z9AYnQrEAAAAASUVORK5CYII=",width:12,height:17,alt:"¶"},{type:"field_multilinetext",name:"TEXT",text:""}],output:"String",style:"text_blocks",helpUrl:"%{BKY_TEXT_TEXT_HELPURL}",tooltip:"%{BKY_TEXT_TEXT_TOOLTIP}",extensions:["parent_tooltip_when_inline"]};function iR(a,s){const i=s.multiline_quote_(a.getFieldValue("TEXT")),r=i.indexOf("+")!==-1?6.2:0;return[i,r]}const nR=window.Blockly.common.createBlockDefinitionsFromJsonArray([oR]);nR[yC];const Je=window.Blockly;class lm extends Je.Field{picker=null;highlightedIndex=null;boundEvents=[];SERIALIZABLE=!0;CURSOR="default";isDirty_=!1;colours=["#ffffff","#cccccc","#c0c0c0","#999999","#666666","#333333","#000000","#ffcccc","#ff6666","#ff0000","#cc0000","#990000","#660000","#330000","#ffcc99","#ff9966","#ff9900","#ff6600","#cc6600","#993300","#663300","#ffff99","#ffff66","#ffcc66","#ffcc33","#cc9933","#996633","#663333","#ffffcc","#ffff33","#ffff00","#ffcc00","#999900","#666600","#333300","#99ff99","#66ff99","#33ff33","#33cc00","#009900","#006600","#003300","#99ffff","#33ffff","#66cccc","#00cccc","#339999","#336666","#003333","#ccffff","#66ffff","#33ccff","#3366ff","#3333ff","#000099","#000066","#ccccff","#9999ff","#6666cc","#6633ff","#6600cc","#333399","#330099","#ffccff","#ff99ff","#cc66cc","#cc33cc","#993399","#663366","#330033"];titles=[];columns=7;constructor(s,i,r){super(s),s!==Symbol("SKIP_SETUP")&&(r&&this.configure_(r),this.setValue(s),i&&this.setValidator(i))}configure_(s){super.configure_(s),s.colourOptions&&(this.colours=s.colourOptions),s.colourTitles&&(this.titles=s.colourTitles),s.columns&&(this.columns=s.columns)}initView(){const s=this.getConstants();if(!s)throw Error("Constants not found");this.size_=new Je.utils.Size(s.FIELD_COLOUR_DEFAULT_WIDTH,s.FIELD_COLOUR_DEFAULT_HEIGHT),this.createBorderRect_(),this.getBorderRect().style.fillOpacity="1",this.getBorderRect().setAttribute("stroke","#fff"),this.isFullBlockField()&&(this.clickTarget_=this.sourceBlock_.getSvgRoot())}isFullBlockField(){if(!this.getSourceBlock())throw new Je.UnattachedFieldError;const i=this.getConstants();return this.blockIsSimpleReporter()&&!!(i!=null&&i.FIELD_COLOUR_FULL_BLOCK)}blockIsSimpleReporter(){const s=this.getSourceBlock();if(!s)throw new Je.UnattachedFieldError;if(!s.outputConnection)return!1;for(const i of s.inputList)if(i.connection||i.fieldRow.length>1)return!1;return!0}applyColour(){const s=this.getSourceBlock();if(!s)throw new Je.UnattachedFieldError;if(!this.fieldGroup_)return;const i=this.borderRect_;if(!i)throw new Error("The border rect has not been initialized");this.isFullBlockField()?(i.style.display="none",s.pathObject.svgPath.setAttribute("fill",this.getValue()),s.pathObject.svgPath.setAttribute("stroke","#fff")):(i.style.display="block",i.style.fill=this.getValue())}getSize(){var s;return(s=this.getConstants())!=null&&s.FIELD_COLOUR_FULL_BLOCK&&(this.render_(),this.isDirty_=!1),super.getSize()}render_(){super.render_();const s=this.getSourceBlock();if(!s)throw new Je.UnattachedFieldError;s.applyColour()}updateSize_(s){const i=this.getConstants();if(!i)return;let r,l;this.isFullBlockField()?(r=(s??0)*2,l=i.FIELD_TEXT_HEIGHT):(r=i.FIELD_COLOUR_DEFAULT_WIDTH,l=i.FIELD_COLOUR_DEFAULT_HEIGHT),this.size_.height=l,this.size_.width=r,this.positionBorderRect_()}doClassValidation_(s){return typeof s!="string"?null:Je.utils.colour.parse(s)}getText(){let s=this.value_;return/^#(.)\1(.)\2(.)\3$/.test(s)&&(s=`#${s[1]}${s[3]}${s[5]}`),s}setColours(s,i){return this.colours=s,i&&(this.titles=i),this}setColumns(s){return this.columns=s,this}showEditor_(){if(this.dropdownCreate(),!this.picker)throw Error("Picker not found");Je.DropDownDiv.getContentDiv().appendChild(this.picker),Je.DropDownDiv.showPositionedByField(this,this.dropdownDispose.bind(this)),this.picker.focus({preventScroll:!0})}onClick(s){const i=s.target,r=i==null?void 0:i.getAttribute("data-colour");r!==null&&(this.setValue(r),Je.DropDownDiv.hideIfOwner(this))}onKeyDown(s){let i=!0,r;switch(s.key){case"ArrowUp":this.moveHighlightBy(0,-1);break;case"ArrowDown":this.moveHighlightBy(0,1);break;case"ArrowLeft":this.moveHighlightBy(-1,0);break;case"ArrowRight":this.moveHighlightBy(1,0);break;case"Enter":if(r=this.getHighlighted(),r){const l=r.getAttribute("data-colour");l!==null&&this.setValue(l)}Je.DropDownDiv.hideWithoutAnimation();break;default:i=!1}i&&s.stopPropagation()}moveHighlightBy(s,i){if(!this.highlightedIndex)return;const r=this.colours,l=this.columns;let c=this.highlightedIndex%l,d=Math.floor(this.highlightedIndex/l);c+=s,d+=i,s<0?c<0&&d>0?(c=l-1,d--):c<0&&(c=0):s>0?c>l-1&&dl-1&&c--:i<0?d<0&&(d=0):i>0&&d>Math.floor(r.length/l)-1&&(d=Math.floor(r.length/l)-1);const h=this.picker.childNodes[d].childNodes[c],p=d*l+c;this.setHighlightedCell(h,p)}onMouseMove(s){const i=s.target,r=i&&Number(i.getAttribute("data-index"));r!==null&&r!==this.highlightedIndex&&this.setHighlightedCell(i,r)}onMouseEnter(){var s;(s=this.picker)==null||s.focus({preventScroll:!0})}onMouseLeave(){var i;(i=this.picker)==null||i.blur();const s=this.getHighlighted();s&&Je.utils.dom.removeClass(s,"blocklyColourHighlighted")}getHighlighted(){var l;if(!this.highlightedIndex)return null;const s=this.highlightedIndex%this.columns,i=Math.floor(this.highlightedIndex/this.columns),r=(l=this.picker)==null?void 0:l.childNodes[i];return r?r.childNodes[s]:null}setHighlightedCell(s,i){const r=this.getHighlighted();r&&Je.utils.dom.removeClass(r,"blocklyColourHighlighted"),Je.utils.dom.addClass(s,"blocklyColourHighlighted"),this.highlightedIndex=i;const l=s.getAttribute("id");l&&this.picker&&Je.utils.aria.setState(this.picker,Je.utils.aria.State.ACTIVEDESCENDANT,l)}dropdownCreate(){const s=this.columns,i=this.colours,r=this.getValue(),l=document.createElement("table");l.className="blocklyColourTable",l.tabIndex=0,l.dir="ltr",Je.utils.aria.setRole(l,Je.utils.aria.Role.GRID),Je.utils.aria.setState(l,Je.utils.aria.State.EXPANDED,!0),Je.utils.aria.setState(l,Je.utils.aria.State.ROWCOUNT,Math.floor(i.length/s)),Je.utils.aria.setState(l,Je.utils.aria.State.COLCOUNT,s);let c=null;for(let d=0;d1)return!1;return!0}applyColour(){const s=this.getSourceBlock();if(!s)throw new Je.UnattachedFieldError;if(!this.fieldGroup_)return;const i=this.borderRect_;if(!i)throw new Error("The border rect has not been initialized");this.isFullBlockField()?(i.style.display="none",s.pathObject.svgPath.setAttribute("fill",this.getValue()),s.pathObject.svgPath.setAttribute("stroke","#fff")):(i.style.display="block",i.style.fill=this.getValue())}getSize(){var s;return(s=this.getConstants())!=null&&s.FIELD_COLOUR_FULL_BLOCK&&(this.render_(),this.isDirty_=!1),super.getSize()}render_(){super.render_();const s=this.getSourceBlock();if(!s)throw new Je.UnattachedFieldError;s.applyColour()}updateSize_(s){const i=this.getConstants();if(!i)return;let r,l;this.isFullBlockField()?(r=(s??0)*2,l=i.FIELD_TEXT_HEIGHT):(r=i.FIELD_COLOUR_DEFAULT_WIDTH,l=i.FIELD_COLOUR_DEFAULT_HEIGHT),this.size_.height=l,this.size_.width=r,this.positionBorderRect_()}doClassValidation_(s){return typeof s!="string"?null:Je.utils.colour.parse(s)}getText(){let s=this.value_;return/^#(.)\1(.)\2(.)\3$/.test(s)&&(s=`#${s[1]}${s[3]}${s[5]}`),s}setColours(s,i){return this.colours=s,i&&(this.titles=i),this}setColumns(s){return this.columns=s,this}showEditor_(){if(this.dropdownCreate(),!this.picker)throw Error("Picker not found");Je.DropDownDiv.getContentDiv().appendChild(this.picker),Je.DropDownDiv.showPositionedByField(this,this.dropdownDispose.bind(this)),this.picker.focus({preventScroll:!0})}onClick(s){const i=s.target,r=i==null?void 0:i.getAttribute("data-colour");r!==null&&(this.setValue(r),Je.DropDownDiv.hideIfOwner(this))}onKeyDown(s){let i=!0,r;switch(s.key){case"ArrowUp":this.moveHighlightBy(0,-1);break;case"ArrowDown":this.moveHighlightBy(0,1);break;case"ArrowLeft":this.moveHighlightBy(-1,0);break;case"ArrowRight":this.moveHighlightBy(1,0);break;case"Enter":if(r=this.getHighlighted(),r){const l=r.getAttribute("data-colour");l!==null&&this.setValue(l)}Je.DropDownDiv.hideWithoutAnimation();break;default:i=!1}i&&s.stopPropagation()}moveHighlightBy(s,i){if(!this.highlightedIndex)return;const r=this.colours,l=this.columns;let c=this.highlightedIndex%l,d=Math.floor(this.highlightedIndex/l);c+=s,d+=i,s<0?c<0&&d>0?(c=l-1,d--):c<0&&(c=0):s>0?c>l-1&&dl-1&&c--:i<0?d<0&&(d=0):i>0&&d>Math.floor(r.length/l)-1&&(d=Math.floor(r.length/l)-1);const h=this.picker.childNodes[d].childNodes[c],p=d*l+c;this.setHighlightedCell(h,p)}onMouseMove(s){const i=s.target,r=i&&Number(i.getAttribute("data-index"));r!==null&&r!==this.highlightedIndex&&this.setHighlightedCell(i,r)}onMouseEnter(){var s;(s=this.picker)==null||s.focus({preventScroll:!0})}onMouseLeave(){var i;(i=this.picker)==null||i.blur();const s=this.getHighlighted();s&&Je.utils.dom.removeClass(s,"blocklyColourHighlighted")}getHighlighted(){var l;if(!this.highlightedIndex)return null;const s=this.highlightedIndex%this.columns,i=Math.floor(this.highlightedIndex/this.columns),r=(l=this.picker)==null?void 0:l.childNodes[i];return r?r.childNodes[s]:null}setHighlightedCell(s,i){const r=this.getHighlighted();r&&Je.utils.dom.removeClass(r,"blocklyColourHighlighted"),Je.utils.dom.addClass(s,"blocklyColourHighlighted"),this.highlightedIndex=i;const l=s.getAttribute("id");l&&this.picker&&Je.utils.aria.setState(this.picker,Je.utils.aria.State.ACTIVEDESCENDANT,l)}dropdownCreate(){const s=this.columns,i=this.colours,r=this.getValue(),l=document.createElement("table");l.className="blocklyColourTable",l.tabIndex=0,l.dir="ltr",Je.utils.aria.setRole(l,Je.utils.aria.Role.GRID),Je.utils.aria.setState(l,Je.utils.aria.State.EXPANDED,!0),Je.utils.aria.setState(l,Je.utils.aria.State.ROWCOUNT,Math.floor(i.length/s)),Je.utils.aria.setState(l,Je.utils.aria.State.COLCOUNT,s);let c=null;for(let d=0;d{typeof a[s]=="function"&&(a.forBlock[s]||(console.log(`Migrating Blockly.JavaScript.${s} to Blockly.JavaScript.forBlock.${s}`),a.forBlock[s]=a[s],delete a[s]))})}let cc=!1,uc=!1,yg=null,_g=null;const hw=[];function TC(a,s,i,r){var l;if(r=r||[],(a.tagName==="BLOCK"||a.tagName==="block")&&(i=a.id),a.tagName==="FIELD"||a.tagName==="field")for(let c=0;cTC(c,s,i,r)),r}class et extends _e.Component{blockly=null;blocklyWorkspace=null;originalCode;someSelected=null;changeTimer=null;someSelectedTime=0;ignoreChanges=!1;blinkBlock;onResizeBind;didUpdate=null;lastCommand="";lastSearch;static Blockly=window.Blockly;constructor(s){super(s),this.state={languageOwnLoaded:uc,languageBlocklyLoaded:cc,changed:!1,message:"",error:"",themeType:this.props.themeType,exportText:"",importText:!1,searchText:this.props.searchText||"",showInputPrompt:null},this.originalCode=s.code||"",this.someSelected=null,this.onResizeBind=this.onResize.bind(this),this.lastSearch=this.props.searchText||"",this.blinkBlock=null,bR(),et.Blockly.dialog.setPrompt(this.onShowNameDialog),this.loadLanguages()}onShowNameDialog=(s,i,r)=>{this.setState({showInputPrompt:{promptText:s,defaultText:i,callback:r,value:i}})};static loadJS(s,i,r){const l=document.createElement("script");try{l.src=s,l.onload=i,l.onerror=i,(r||window.document.body).appendChild(l)}catch(c){console.error(`Cannot load ${s}: ${c}`),i&&i()}}static loadScripts(s,i){if(!(s!=null&&s.length)){i&&i();return}const r=s.pop();r&&!hw.includes(r)?(hw.push(r),et.loadJS(`../../adapter/${r}/blockly.js`,()=>setTimeout(()=>et.loadScripts(s,i),0))):setTimeout(()=>et.loadScripts(s,i),0)}static loadCustomBlockly(s,i){var l;const r=[];for(const c in s)!Object.prototype.hasOwnProperty.call(s,c)||!s[c]||!c.match(/^system\.adapter\./)||s[c].type!=="adapter"||(l=s[c].common)!=null&&l.blockly&&(console.log(`Detected custom blockly: ${s[c].common.name}`),r.push(s[c].common.name));et.loadScripts(r,i)}static loadXMLDoc(s){let i;return window.DOMParser?i=r=>new window.DOMParser().parseFromString(r,"text/xml"):typeof window.ActiveXObject<"u"&&new window.ActiveXObject("Microsoft.XMLDOM")?i=r=>{const l=new window.ActiveXObject("Microsoft.XMLDOM");return l.async="false",l.loadXML(r),l}:i=()=>null,i(s)}searchBlocks(s){if(this.blocklyWorkspace){const i=et.Blockly.Xml.workspaceToDom(this.blocklyWorkspace),r=TC(i,s.toLowerCase());return console.log(`Search "${s}" found blocks: ${r.length?JSON.stringify(r):"none"}`),r}return[]}searchId(){const s=this.lastSearch?this.searchBlocks(this.lastSearch):null;s!=null&&s.length?(this.someSelected=s,this.someSelected.forEach(i=>{var r;return(r=this.blocklyWorkspace)==null?void 0:r.highlightBlock(i,!0)}),this.someSelectedTime=Date.now()):this.someSelected&&(this.someSelected.forEach(i=>{var r;return(r=this.blocklyWorkspace)==null?void 0:r.highlightBlock(i,!1)}),this.someSelected=null)}UNSAFE_componentWillReceiveProps(s){s.command&&this.lastCommand!==s.command&&(this.lastCommand=s.command,setTimeout(()=>this.lastCommand="",300),this.lastCommand==="check"?this.blocklyCheckBlocks((i,r)=>{i?(r&&et.blocklyBlinkBlock(r),this.setState({error:{text:x.I18n.t(i),title:x.I18n.t("Error was found")}}),this.blinkBlock=r):this.setState({message:x.I18n.t("Ok")})}):this.lastCommand==="export"?this.exportBlocks():this.lastCommand==="import"&&this.importBlocks()),s.searchText!==this.lastSearch&&(this.lastSearch=s.searchText,this.searchId()),this.state.themeType!==s.themeType&&this.setState({themeType:s.themeType},()=>this.updateBackground()),this.originalCode!==s.code&&(this.originalCode=s.code||"",this.loadCode(),this.searchId())}loadLanguages(){if(!cc){const s=window.document.createElement("script");s.setAttribute("type","text/javascript"),s.setAttribute("src",`google-blockly/msg/js/${x.I18n.getLanguage()}.js`),s.onload=()=>{cc=!0,this.setState({languageBlocklyLoaded:cc})},window.document.getElementsByTagName("head")[0].appendChild(s)}if(!uc){const s=window.document.createElement("script");s.setAttribute("type","text/javascript"),s.setAttribute("src",`google-blockly/own/msg/${x.I18n.getLanguage()}.js`),s.onload=()=>{uc=!0,this.setState({languageOwnLoaded:uc})},window.document.getElementsByTagName("head")[0].appendChild(s)}}onResize(){this.blocklyWorkspace&&et.Blockly.svgResize(this.blocklyWorkspace)}static jsCode2Blockly(s){s=s||"";const i=s.split(/[\r\n]+|\r|\n/g);let r="";for(let c=i.length-1;c>=0;c--)if(i[c].substring(0,2)==="//"){r=i[c].substring(2);break}if(r.substring(0,4)==="s.select(),i),setTimeout(()=>s.unselect(),i+150)}blocklyRemoveOrphanedShadows(){if(this.blocklyWorkspace){const s=this.blocklyWorkspace.getAllBlocks();let i;for(let r=0;i=s[r];r++)if(i.isShadow()){const l=i.getConnections_(!0);let c;for(let d=0;c=l[d];d++)if(!c.targetConnection){i.dispose();break}}}}blocklyCheckBlocks(s){let i;if(!this.blocklyWorkspace||this.blocklyWorkspace.getAllBlocks().length===0)return s&&s("no blocks found"),!1;let r=this.blocklyGetUnconnectedBlock();return r?i="not properly connected":(r=this.blocklyGetBlockWithWarning(),r&&(i="warning on this block")),r?(s?s(i,r):et.blocklyBlinkBlock(r),!1):(s(),!0)}blocklyGetUnconnectedBlock(){var r;const s=(r=this.blocklyWorkspace)==null?void 0:r.getAllBlocks();let i;if(s)for(let l=0;i=s[l];l++){const c=i.getConnections_(!0);let d;for(let h=0;d=c[h];h++)if(!d.sourceBlock_||(d.type===et.Blockly.INPUT_VALUE||d.type===et.Blockly.OUTPUT_VALUE)&&!d.targetConnection&&!d._optional)return i}return null}blocklyGetBlockWithWarning(){var r;const s=(r=this.blocklyWorkspace)==null?void 0:r.getAllBlocks();let i;if(s){for(let l=0;i=s[l];l++)if(i.warning)return i}return null}blocklyCode2JSCode(s){if(!this.blocklyWorkspace)return"";let i=et.Blockly.JavaScript.workspaceToCode(this.blocklyWorkspace);if(!s){i+=` -`;const r=et.Blockly.Xml.workspaceToDom(this.blocklyWorkspace),l=et.Blockly.Xml.domToText(r);i+=`//${btoa(encodeURIComponent(l))}`}return i}exportBlocks(){if(!this.blocklyWorkspace)return;let s;const i=et.Blockly.getSelected();if(i){const r=et.Blockly.Xml.blockToDom(i),l=i.getRelativeToSurfaceXY();r.setAttribute("x",(i.RTL?-l.x:l.x).toString()),r.setAttribute("y",l.y.toString()),s=et.Blockly.Xml.domToPrettyText(r)}else{const r=et.Blockly.Xml.workspaceToDom(this.blocklyWorkspace);s=et.Blockly.Xml.domToPrettyText(r)}this.setState({exportText:s})}importBlocks(){this.setState({importText:!0})}onImportBlocks(s){if(this.blocklyWorkspace&&(s=(s||"").trim(),s))try{s.startsWith("${s}`),s=s.replace(/[\n\r]/g,"").replace(/.*<\/variables>/g,""),window.scripts.loading=!0;const i=et.Blockly.utils.xml.textToDom(s);et.Blockly.Xml.appendDomToWorkspace(i,this.blocklyWorkspace),window.scripts.loading=!1,this.onBlocklyChanged()}catch(i){this.setState({error:{text:i.toString(),title:x.I18n.t("Import error")}})}}loadCode(){if(this.blocklyWorkspace){this.ignoreChanges=!0,this.blocklyWorkspace.clear();try{const s=et.jsCode2Blockly(this.originalCode)||'';window.scripts.loading=!0;const i=et.Blockly.utils.xml.textToDom(s);et.Blockly.Xml.domToWorkspace(i,this.blocklyWorkspace),window.scripts.loading=!1}catch(s){console.error(s),setTimeout(()=>this.setState({error:x.I18n.t("Cannot extract Blockly code!")}))}setTimeout(()=>this.ignoreChanges=!1,100)}}onBlocklyChanged(){this.blocklyRemoveOrphanedShadows(),this.setState({changed:!0}),this.onChange()}async componentDidUpdate(){if(!this.blockly||(this.didUpdate&&(clearTimeout(this.didUpdate),this.didUpdate=null),this.blocklyWorkspace))return;window.addEventListener("resize",this.onResizeBind,!1),yg=yg||await this.getToolbox(),_g=_g||et.Blockly.utils.xml.textToDom(yg),this.blocklyWorkspace=et.Blockly.inject(this.blockly,{renderer:"thrasos",theme:this.state.themeType==="dark"?dw:"classic",media:"google-blockly/media/",toolbox:_g,zoom:{controls:!0,wheel:!1,startScale:1,maxScale:3,minScale:.3,scaleSpeed:1.2,pinch:!0},move:{scrollbars:{horizontal:!0,vertical:!0},drag:!0,wheel:!0},trashcan:!0,grid:{spacing:25,length:1,snap:!0},sounds:!1}),window.scripts={blocklyWorkspace:this.blocklyWorkspace},this.blocklyWorkspace.registerToolboxCategoryCallback("PROCEDURE",window.Blockly.Procedures.flyoutCategoryNew),this.blocklyWorkspace.addChangeListener(i=>{var r;if(this.someSelected&&Date.now()-this.someSelectedTime>500){const l=(r=this.blocklyWorkspace)==null?void 0:r.getAllBlocks();this.someSelected=null,l==null||l.forEach(c=>c.removeSelect())}[et.Blockly.Events.UI,et.Blockly.Events.CREATE,et.Blockly.Events.VIEWPORT_CHANGE].includes(i.type)||this.ignoreChanges||(this.changeTimer&&clearTimeout(this.changeTimer),this.changeTimer=setTimeout(()=>{this.changeTimer=null,this.onBlocklyChanged()},200))}),this.loadCode(),this.onResize();const s=document.getElementsByClassName("blocklyToolboxDiv")[0];this.blockly.appendChild(s),this.updateBackground(),setTimeout(()=>this.searchId(),200)}updateBackground(){var s;this.state.themeType==="dark"?(s=this.blocklyWorkspace)==null||s.setTheme(dw):this.blocklyWorkspace&&(this.blocklyWorkspace.getThemeManager(),this.blocklyWorkspace.setTheme(et.Blockly.Themes.Classic))}componentWillUnmount(){this.blocklyWorkspace&&(this.blocklyWorkspace.dispose(),this.blocklyWorkspace=null,this.changeTimer&&clearTimeout(this.changeTimer),this.changeTimer=null,window.removeEventListener("resize",this.onResizeBind))}onChange(){this.originalCode=this.blocklyCode2JSCode(),this.props.onChange&&this.props.onChange(this.originalCode)}async getToolbox(s){const i=window.document.getElementById("toolbox");let r=i==null?void 0:i.outerHTML;if(!r)return s?(console.error("Cannot load blocks!"),""):new Promise(l=>{setTimeout(()=>l(this.getToolbox(!0)),500)});if(r=r.replace(/{(\w+)}/g,(l,c)=>window.MSG[c]),window.Blockly.CustomBlocks){let l="";const c=x.I18n.getLanguage();for(let d=0;d`;for(const f in p.blocks)Object.prototype.hasOwnProperty.call(p.blocks,f)&&(l+=p.blocks[f]);l+=""}r=r.replace("%%CUSTOM_BLOCKS%%",l)}return r}renderMessageDialog(){return this.state.message?m.jsx(x.Message,{text:typeof this.state.message=="object"?this.state.message.text:this.state.message,title:typeof this.state.message=="object"?this.state.message.title:"",onClose:()=>this.setState({message:""})},"dialogMessage"):null}renderErrorDialog(){return this.state.error?m.jsx(su,{text:typeof this.state.error=="object"?this.state.error.text.toString():this.state.error,title:typeof this.state.error=="object"?this.state.error.title:"",onClose:()=>{this.blinkBlock&&(et.blocklyBlinkBlock(this.blinkBlock),this.blinkBlock=null),this.setState({error:""})}},"dialogError"):null}renderExportDialog(){return this.state.exportText?m.jsx(sR,{themeType:this.state.themeType,onClose:()=>this.setState({exportText:""}),text:this.state.exportText,scriptId:this.props.scriptId},"dialogExport"):null}renderImportDialog(){return this.state.importText?m.jsx(Gm,{themeType:this.props.themeType,onClose:s=>{this.setState({importText:!1}),this.onImportBlocks(s)}},"dialogImport"):null}renderDialogPrompt(){return this.state.showInputPrompt?m.jsxs(Pt,{onClose:()=>{var i;const s=(i=this.state.showInputPrompt)==null?void 0:i.callback;s&&s(null),this.setState({showInputPrompt:null})},maxWidth:"sm",fullWidth:!0,open:!0,children:[m.jsx(Xt,{children:this.state.showInputPrompt.promptText}),m.jsx(Wt,{children:m.jsx(Eo,{variant:"standard",fullWidth:!0,autoFocus:!0,value:this.state.showInputPrompt.value,onKeyUp:s=>{var i,r;if(s.key==="Enter"){const l=(i=this.state.showInputPrompt)==null?void 0:i.callback,c=(r=this.state.showInputPrompt)==null?void 0:r.value;l&&l(c===void 0?null:c),this.setState({showInputPrompt:null})}},onChange:s=>{var r,l;const i={...this.state.showInputPrompt};(r=this.state.showInputPrompt)!=null&&r.callback&&(i.callback=(l=this.state.showInputPrompt)==null?void 0:l.callback),i.value=s.target.value,this.setState({showInputPrompt:i})}})}),m.jsxs(Bt,{children:[m.jsx(Ue,{variant:"contained",disabled:!this.state.showInputPrompt.value,onClick:()=>{var r,l;const s=(r=this.state.showInputPrompt)==null?void 0:r.callback,i=(l=this.state.showInputPrompt)==null?void 0:l.value;s&&s(i===void 0?null:i),this.setState({showInputPrompt:null})},color:"primary",startIcon:m.jsx(qo,{}),children:x.I18n.t("Apply")}),m.jsx(Ue,{color:"grey",variant:"contained",onClick:()=>{var i;const s=(i=this.state.showInputPrompt)==null?void 0:i.callback;s&&s(null),this.setState({showInputPrompt:null})},startIcon:m.jsx(so,{}),children:x.I18n.t("Close")})]})]},"inputDialog"):null}render(){return this.state.languageBlocklyLoaded&&this.state.languageOwnLoaded?(this.didUpdate=setTimeout(()=>{this.didUpdate=null,this.componentDidUpdate()},100),[m.jsx("div",{ref:s=>this.blockly=s,style:{width:"100%",height:"100%",position:"relative"}},"blocklyDOM"),this.renderDialogPrompt(),this.renderMessageDialog(),this.renderErrorDialog(),this.renderExportDialog(),this.renderImportDialog()]):null}}const vR=Object.freeze(Object.defineProperty({__proto__:null,default:et},Symbol.toStringTag,{value:"Module"})),yR="_nameCard_15el3_28",_R="_iconThemCard_15el3_40",wR="_iconThemCardSelectable_15el3_49",kR="_iconHelp_15el3_53",CR="_blockName_15el3_64",TR="_controlMenuTop_15el3_123",SR="_debugInfo_15el3_132",ER="_tagCard_15el3_142",IR="_displayFlex_15el3_161",xR="_blockMarginTop_15el3_166",DR="_nameBlock_15el3_167",AR="_frontText_15el3_171",RR="_backText_15el3_177",OR="_iconTag_15el3_181",NR="_displayItalic_15el3_191",Oe={nameCard:yR,iconThemCard:_R,iconThemCardSelectable:wR,iconHelp:kR,blockName:CR,controlMenuTop:TR,debugInfo:SR,tagCard:ER,displayFlex:IR,blockMarginTop:xR,nameBlock:DR,frontText:AR,backText:RR,iconTag:OR,displayItalic:NR},MR="_root_1dr6a_1",LR="_square_1dr6a_11",PR="_icon_1dr6a_16",wg={root:MR,square:LR,icon:PR},Jr=({fullWidth:a,size:s,onClick:i,style:r,className:l,value:c,square:d,icon:h})=>m.jsx(Ue,{variant:"outlined",color:"primary",onClick:i,fullWidth:a,style:r,className:x.Utils.clsx(wg.root,l,d?wg.square:""),size:s||"medium",children:h?m.jsx(x.Icon,{className:wg.icon,src:h}):c}),BR="_root_1ucda_1",jR={root:BR},FR=({size:a,value:s,title:i,onChange:r,className:l,customValue:c,disabled:d})=>{const[h,p]=kt(!1);return m.jsxs(m.Fragment,{children:[m.jsx(wc,{disabled:d,checked:!!(c?s:h),className:x.Utils.clsx(jR.root,l),onChange:f=>{c&&p(f.target.checked),r&&r(f.target.checked)},size:a||"medium"}),i||null]})},SC=dm(FR),zR="_root_19roy_1",pw={root:zR},Ei=a=>{const[s,i]=kt(""),{value:r,type:l,error:c,className:d,icon:h,label:p,style:f,onChange:b,fullWidth:y,autoComplete:w,customValue:v,autoFocus:_,rows:$,size:S,variant:T,multiline:E,disabled:D}=Object.assign({value:"",type:"text",error:"",className:null,table:!1,native:{},variant:"standard",size:"medium",component:null,styleComponentBlock:null,fullWidth:!1,autoComplete:"",customValue:!1,autoFocus:!1,rows:1},a);return m.jsx(Eo,{error:!!c,autoFocus:_,fullWidth:y,label:p,disabled:D,variant:T,multiline:E,rows:$,value:v?r:s,type:l,helperText:c,style:f,className:x.Utils.clsx(pw.root,d),autoComplete:w,onChange:M=>{!v&&i(M.target.value),b&&b(M.target.value)},slotProps:{input:{endAdornment:h?m.jsx(Aw,{position:"end",children:m.jsx(x.Icon,{className:pw.icon,src:h})}):null}},margin:"normal",size:S})},UR={formControl:{m:"10px 0","& .MuiFormControl-marginNormal":{mt:0,mb:0},"& > *":{color:"#2d0440 !important"},"& .MuiSelect-icon":{color:"#81688c"},"& label.Mui-focused":{color:"#81688c"},"& .MuiInput-underline:after":{borderBottomColor:"#510573"},"& .MuiInput-underline:before":{borderBottomColor:"#81688c"},"& .MuiInput-underline:hover:before":{borderBottomColor:"#81688c"}}},HR=({multiple:a,value:s,customValue:i,socket:r,title:l,attr:c,adapter:d,style:h,onChange:p,onInstanceHide:f})=>{const[b,y]=kt(s||"test1"),[w,v]=kt([]);return Lt(()=>{r==null||r.getAdapterInstances(d).then(_=>{const $=_.map(S=>({value:S._id.replace("system.adapter.",""),title:S._id.replace("system.adapter.","")}));$.length===1?f($[0].value):$.unshift({value:d,title:x.I18n.t("All")}),v($)})},[r,d,f]),m.jsxs(Di,{sx:UR.formControl,fullWidth:!0,style:h,children:[m.jsx(Ai,{variant:"standard",value:(i?s:b)||"_",fullWidth:!0,multiple:a,renderValue:_=>a&&Array.isArray(_)?_.join(", "):_,onChange:_=>{!i&&y(_.target.value),p(_.target.value)},input:c?m.jsx(Pn,{name:c,id:`${c}-helper`}):m.jsx(Pn,{name:c}),children:w.map(_=>m.jsx(it,{style:{placeContent:"space-between"},value:_.value||"_",children:x.I18n.t(_.title)},`key-${_.value}`))}),l?m.jsx(Ow,{children:x.I18n.t(l)}):null]})},WR="_modalWrapper_587ci_33",GR="_modalDialog_587ci_40",gw={modalWrapper:WR,modalDialog:GR},cm=({onClose:a,children:s,titleButtonApply:i,titleButtonClose:r,onApply:l,className:c,textInput:d,defaultValue:h,disabled:p})=>{const[f,b]=kt(h||""),[y]=kt(h||"");return m.jsxs(Pt,{open:!0,maxWidth:"md",disableEscapeKeyDown:!1,onClose:a,classes:{paper:gw.modalDialog},className:gw.modalWrapper,children:[m.jsxs(Wt,{children:[d&&m.jsx(Ei,{className:c,autoComplete:"off",fullWidth:!0,variant:"outlined",size:"medium",rows:10,multiline:!0,value:f,onChange:b,customValue:!0}),!d&&s]}),m.jsxs(Bt,{children:[m.jsx(Ue,{disabled:p===void 0?y===f:p,onClick:()=>l(d?f:null),variant:"contained",color:"primary",children:x.I18n.t(i||"Ok")}),m.jsx(Ue,{color:"grey",onClick:a,variant:"contained",children:x.I18n.t(r||"Cancel")})]})]})},VR="_root_15mo1_1",KR={root:VR},YR=({multiple:a,value:s,customValue:i,title:r,attr:l,options:c,style:d,onChange:h,className:p,doNotTranslate:f,doNotTranslate2:b})=>{const[y,w]=kt(s===void 0?c[0].value:s),v=i?s:y,_=v===""||v===null||v===void 0?"_":v;return m.jsxs(Di,{variant:"standard",className:x.Utils.clsx(KR.root,p),fullWidth:!0,style:d,children:[m.jsxs(Ai,{variant:"standard",value:_,fullWidth:!0,multiple:a,renderValue:$=>{if(a&&Array.isArray($)){$.sort();let T=$.indexOf("0");T!==-1&&($.splice(T,1),$.push("0")),T=$.indexOf("_"),T!==-1&&($.splice(T,1),$.unshift("_"));const E=c.find(M=>M.only);return E&&$.includes(E.value)?E.titleShort?f?E.titleShort:x.I18n.t(E.titleShort):f?E.title:x.I18n.t(E.title):$.map(M=>c.find(P=>P.value===M||M==="_"&&P.value==="")||M).map(M=>typeof M=="object"?M.titleShort?f?M.titleShort:x.I18n.t(M.titleShort):f?M.title:x.I18n.t(M.title):f?M:x.I18n.t(M)).join(", ")}const S=c?c.find(T=>T.value===$||$==="_"&&T.value===""):null;return S!=null&&S.title?f?S==null?void 0:S.title:x.I18n.t(S==null?void 0:S.title):$},onChange:$=>{if(i||w($.target.value),a){const S=$.target.value,T=c.find(E=>E.only);if(T){const E=T.value;if(S.length===c.length-1&&S.includes(E))return h(S.filter(D=>D!==E),l);if(S.includes(E))return h(c.map(D=>D.value),l)}}h($.target.value,l)},input:l?m.jsx(Pn,{name:l,id:`${l}-helper`}):m.jsx(Pn,{name:l}),children:[!a&&(c==null?void 0:c.map($=>m.jsxs(it,{style:{placeContent:"space-between"},value:$.value===""||$.value===null||$.value===void 0?"_":$.value,children:[f?$.title:x.I18n.t($.title),$.title2&&m.jsx("div",{children:b?$.title2:x.I18n.t($.title2)})]},`key-${$.value}`))),a&&(c==null?void 0:c.map($=>m.jsxs(it,{style:{placeContent:"space-between"},value:$.value||"_",children:[f?$.title:x.I18n.t($.title)," ",m.jsx(SC,{customValue:!0,value:s==null?void 0:s.includes($.value)})]},`key-${$.value}`)))]}),r?m.jsx(Ow,{children:x.I18n.t(r)}):null]})},JR="_root_1gt4d_1",qR="_mark_1gt4d_27",mw={root:JR,mark:qR},XR=({size:a,value:s,style:i,onChange:r,className:l,customValue:c,min:d,max:h,step:p,unit:f})=>{const[b,y]=kt(0);d=d!==void 0?d:0,h=h!==void 0?h:0,p=p!==void 0?p:(h-d)/100;const w=[{value:d,label:d+(f||"")},{value:h,label:h+(f||"")}];return m.jsx(qT,{defaultValue:c?s:b,"aria-labelledby":"discrete-slider",valueLabelDisplay:"auto",classes:{mark:mw.mark},marks:w,step:p,min:d,max:h,value:c?s:b,style:i,className:x.Utils.clsx(mw.root,l),onChange:(v,_)=>{Array.isArray(_)?(!c&&y(_[0]),r(_[0])):(!c&&y(_),r(_))},size:a||"medium"})},ZR="_root_rzul6_1",QR={root:ZR},eO=({label:a,size:s,value:i,style:r,onChange:l,className:c,customValue:d})=>{const[h,p]=kt(!1);return m.jsx(Mg,{className:QR.root,control:m.jsx(Nw,{checked:d?i:h,style:r,className:c,onChange:f=>{d||p(f.target.checked),l(f.target.checked)},size:s||"medium"}),label:a??"all"})},tO=dm(eO),sO="_root_135pm_1",oO={root:sO},iO=({value:a,style:s,onChange:i,className:r})=>m.jsx(Eo,{variant:"standard",id:"time",type:"time",onChange:l=>i(l.currentTarget.value),value:a,className:x.Utils.clsx(oO.root,r),fullWidth:!0,style:s,slotProps:{htmlInput:{step:300},inputLabel:{shrink:!0}}}),nO="_root_135pm_1",dc={root:nO},kg=[31,29,31,30,31,30,31,31,30,31,30,31],rO=({value:a,onChange:s,className:i,style:r})=>{const[l,c]=(a||"01.01").toString().split(".");let d=parseInt(c,10)||0,h=parseInt(l,10)||0;h>12?h=12:h<0&&(h=0),d>kg[h]?d=kg[h]:d<0&&(d=0);const p=[];for(let f=0;fs(`${f.target.value.toString().padStart(2,"0")}.${d.toString().padStart(2,"0")}`),value:h,children:[m.jsx(it,{style:{placeContent:"space-between"},value:0,children:x.I18n.t("Any month")},0),m.jsx(it,{style:{placeContent:"space-between"},value:1,children:x.I18n.t("January")},1),m.jsx(it,{style:{placeContent:"space-between"},value:2,children:x.I18n.t("February")},2),m.jsx(it,{style:{placeContent:"space-between"},value:3,children:x.I18n.t("March")},3),m.jsx(it,{style:{placeContent:"space-between"},value:4,children:x.I18n.t("April")},4),m.jsx(it,{style:{placeContent:"space-between"},value:5,children:x.I18n.t("May")},5),m.jsx(it,{style:{placeContent:"space-between"},value:6,children:x.I18n.t("June")},6),m.jsx(it,{style:{placeContent:"space-between"},value:7,children:x.I18n.t("July")},7),m.jsx(it,{style:{placeContent:"space-between"},value:8,children:x.I18n.t("August")},8),m.jsx(it,{style:{placeContent:"space-between"},value:9,children:x.I18n.t("September")},9),m.jsx(it,{style:{placeContent:"space-between"},value:10,children:x.I18n.t("October")},10),m.jsx(it,{style:{placeContent:"space-between"},value:11,children:x.I18n.t("November")},11),m.jsx(it,{style:{placeContent:"space-between"},value:12,children:x.I18n.t("December")},12)]})}),m.jsx(Di,{variant:"standard",className:x.Utils.clsx(dc.root,i),style:r,children:m.jsxs(Ai,{variant:"standard",className:x.Utils.clsx(dc.root,i),margin:"dense",label:x.I18n.t("Date"),onChange:f=>s(`${h.toString().padStart(2,"0")}.${f.target.value.toString().padStart(2,"0")}`),value:d,children:[m.jsx(it,{style:{placeContent:"space-between"},value:0,children:x.I18n.t("Any")},"A"),p.map(f=>m.jsx(it,{style:{placeContent:"space-between"},value:f,children:f},f))]})})]})},Cg={},aO={Shuffle:bx,Apps:rx,Functions:hx,Language:kS,AddBox:nx,Pause:bc,Subject:yx,PlayForWork:fx,Brightness3:ax,HelpOutline:pk,Storage:vx,AccessTime:ix,PlayArrow:Wg,FlashOn:ux};function fw({iconName:a,className:s,adapter:i,socket:r,onClick:l,style:c}){const[d,h]=kt("");if(Lt(()=>{i&&r&&(Cg[i]instanceof Promise||(Cg[i]=r.getObject(`system.adapter.${i}`)),Cg[i].then(f=>{var b;return((b=f==null?void 0:f.common)==null?void 0:b.icon)&&h(`../../adapter/${i}/${f.common.icon}`)}))},[i,r]),i)return m.jsx("img",{onClick:f=>l&&l(f),src:d||"",className:s,style:c,alt:""});const p=a&&aO[a]||CS;return m.jsx(p,{className:s,style:c,onClick:f=>l&&l(f)})}let Tg;function lO(a){return Tg=Tg||x.I18n.getLanguage(),a&&typeof a=="object"?a[Tg]||a.en:a||""}function Ln(a){return a===null?"null":a===void 0?"undefined":Array.isArray(a)?a.join(", "):typeof a=="object"?JSON.stringify(a):a.toString()}class at extends xw{debugHideTimeout=null;lastObjectIdChange=0;enableSimulationProcessing=!1;lastDebugMessage=0;debugMessageTimeout=null;static getStaticData(){return{acceptedBy:"actions",name:"Not found",id:"ActionEmpty",icon:"Shuffle"}}static compile(s,i){return""}constructor(s,i){super(s),i||={};const r=s.settings||{tagCard:i.tagCardArray?typeof i.tagCardArray[0]!="string"?i.tagCardArray[0].title:i.tagCardArray[0]:""};!r.tagCard&&i.tagCardArray&&(r.tagCard=typeof i.tagCardArray[0]!="string"?i.tagCardArray[0].title:i.tagCardArray[0]),this.state={inputs:i.inputs||s.inputs||[],name:i.name||s.name||"",icon:i.icon||s.icon||"",adapter:i.adapter||s.adapter||"",helpDialog:i.helpDialog||s.helpDialog||"",tagCardArray:i.tagCardArray||[],openTagMenu:!1,openModal:!1,iconTag:!1,error:"",helpText:"",instanceSelectionOptions:[],instanceSelectionDef:"",hideAttributes:[],settings:r,debugMessage:null,enableSimulation:this.props.enableSimulation}}componentWillUnmount(){this.debugMessageTimeout&&(clearTimeout(this.debugMessageTimeout),this.debugMessageTimeout=null),this.debugHideTimeout&&(clearTimeout(this.debugHideTimeout),this.debugHideTimeout=null)}onTagChange(s,i,r,l,c){let d=!1;const h=JSON.parse(JSON.stringify(this.state.settings));this.state.inputs.forEach(p=>{const f=p.attr,b=p.defaultValue;f&&b!==void 0&&h[f]===void 0&&(d=!0,h[f]=b)}),d?(this.setState({settings:h},()=>i==null?void 0:i()),this.props.onChange(h)):i&&i()}onUpdate(){}onValueChanged(s,i){}renderText(s,i,r){const{className:l}=this.props,{attr:c,frontText:d,backText:h,nameBlock:p,name:f,doNotTranslate:b,doNotTranslateBack:y}=s;return m.jsxs(Dg,{children:[m.jsxs("div",{className:x.Utils.clsx(Oe.displayFlex,Oe.blockMarginTop),children:[d&&m.jsx("div",{className:Oe.frontText,children:b?d:x.I18n.t(d)}),m.jsx(Ei,{className:l,autoComplete:"off",label:lO(f),variant:"outlined",size:"small",fullWidth:!0,value:i,onChange:r,customValue:!0}),h&&m.jsx("div",{className:Oe.backText,children:y?h:x.I18n.t(h)})]}),p&&m.jsx("div",{className:Oe.nameBlock,children:x.I18n.t(p)})]},c)}renderSwitch(s,i,r){const{className:l}=this.props,{attr:c,frontText:d,backText:h,nameBlock:p,doNotTranslate:f,doNotTranslateBack:b}=s;return m.jsxs("div",{children:[m.jsxs("div",{className:x.Utils.clsx(Oe.displayFlex,Oe.blockMarginTop),children:[d&&m.jsx("div",{className:Oe.frontText,children:f?d:x.I18n.t(d)}),m.jsx(tO,{className:l,label:"",customValue:!0,value:i,onChange:r}),h&&m.jsx("div",{className:Oe.backText,children:b?h:x.I18n.t(h)})]}),p&&m.jsx("div",{className:Oe.nameBlock,children:x.I18n.t(p)})]},c)}renderNameText({attr:s,signature:i,doNotTranslate:r,defaultValue:l},c){return m.jsx("div",{className:x.Utils.clsx(i?Oe.displayItalic:Oe.displayFlex,Oe.blockMarginTop),children:c?r?c:x.I18n.t(c):r?l:x.I18n.t(l)},s)}renderNumber(s,i,r){const{className:l}=this.props,{settings:c}=this.state,{attr:d,backText:h,frontText:p,openCheckbox:f,doNotTranslate:b,doNotTranslateBack:y}=s;let w=!0;return f&&(w=typeof c.offset=="boolean"?c.offset:!0),w?m.jsxs("div",{className:x.Utils.clsx(Oe.displayFlex,Oe.blockMarginTop),children:[p&&m.jsx("div",{className:Oe.frontText,children:b?p:x.I18n.t(p)}),m.jsx(Ei,{className:x.Utils.clsx(l,s.className),fullWidth:!0,autoComplete:"off",label:s.noHelperText?"":"number",variant:"outlined",size:"small",type:"number",value:i,onChange:r,customValue:!0}),h&&m.jsx("div",{className:Oe.backText,children:y?h:x.I18n.t(h)})]},d):null}renderColor(s,i,r){const{className:l}=this.props,{attr:c,backText:d,frontText:h,doNotTranslate:p,doNotTranslateBack:f}=s;return m.jsxs("div",{className:x.Utils.clsx(Oe.displayFlex,Oe.blockMarginTop),children:[h&&m.jsx("div",{className:Oe.frontText,children:p?h:x.I18n.t(h)}),m.jsx(Ei,{className:l,autoComplete:"off",fullWidth:!0,variant:"outlined",size:"small",type:"color",value:i,onChange:r}),d&&m.jsx("div",{className:Oe.backText,children:f?d:x.I18n.t(d)})]},c)}renderCheckbox(s,i,r){const{className:l}=this.props,{settings:c}=this.state,{attr:d,backText:h,frontText:p,defaultValue:f,doNotTranslate:b,doNotTranslateBack:y}=s;return m.jsxs("div",{className:Oe.displayFlex,children:[p&&m.jsx("div",{className:Oe.frontText,children:b?p:x.I18n.t(p)}),m.jsx(SC,{className:l,size:"small",value:typeof c[d]=="boolean"?!!c[d]:!!f,customValue:!0,onChange:r}),h&&m.jsx("div",{onClick:()=>r(typeof c[d]=="boolean"?!c[d]:!f),className:Oe.backText,children:y?h:x.I18n.t(h)})]},d)}renderSlider(s,i,r){const{className:l}=this.props,{attr:c,frontText:d,backText:h,nameBlock:p,min:f,max:b,step:y,unit:w,doNotTranslate:v,doNotTranslateBack:_}=s;return m.jsxs("div",{children:[m.jsxs("div",{className:Oe.displayFlex,style:{marginRight:20},children:[d&&m.jsx("div",{className:Oe.frontText,children:v?d:x.I18n.t(d)}),m.jsx(XR,{customValue:!0,min:f,max:b,step:y,unit:w,className:l,autoComplete:"off",label:"number",variant:"outlined",size:"small",value:i,onChange:$=>{console.log($),r($)}}),h&&m.jsx("div",{style:{marginLeft:20},className:Oe.backText,children:_?h:x.I18n.t(h)})]}),p&&m.jsx("div",{className:Oe.nameBlock,children:x.I18n.t(p)})]},c)}renderButton(s,i,r){const{className:l}=this.props,{attr:c,frontText:d,backText:h,doNotTranslate:p,doNotTranslateBack:f}=s;return m.jsxs("div",{className:x.Utils.clsx(Oe.displayFlex,Oe.blockMarginTop),children:[d&&m.jsx("div",{className:Oe.frontText,children:p?d:x.I18n.t(d)}),m.jsx(Jr,{fullWidth:!0,value:i.toString(),className:l,onClick:()=>r(i)}),h&&m.jsx("div",{className:Oe.backText,children:f?h:x.I18n.t(h)})]},c)}async findIcon(s){var i;if(!s)return null;if((i=s.common)!=null&&i.icon)return x.getSelectIdIcon(s,"../..");if(s.type==="state"||s.type==="channel"){const r=s._id.split(".");r.pop();const l=r.join(".");try{const c=await this.props.socket.getObject(l);return await this.findIcon(c)}catch{return null}}return null}renderObjectID(s,i,r){const{attr:l,openCheckbox:c,checkReadOnly:d}=s,{settings:h}=this.state,p=this.state[`showSelectId${l}`],{className:f,socket:b,style:y}=this.props;let w=!0;c&&(w=typeof h.offset=="boolean"?h.offset:!0);const v=h[l],_=v?this.state[v]:void 0;return v&&!_&&_!==!1&&setTimeout(async $=>{var D;const S=await b.getObject(i),T=await this.findIcon(S),E={[$]:S||!1,[`${$}___icon`]:T,error:d&&this.lastObjectIdChange&&Date.now()-this.lastObjectIdChange<1e3&&((D=S==null?void 0:S.common)==null?void 0:D.write)===!1?x.I18n.t("Read only ID selected: %s",h[$]):""};this.setState(E)},0,v),w?m.jsxs("div",{className:Oe.blockMarginTop,children:[m.jsxs("div",{className:Oe.displayFlex,children:[s.title?m.jsx("div",{children:x.I18n.t(s.title)}):null,m.jsx(Ei,{className:f,style:y,autoComplete:"off",fullWidth:!0,disabled:!0,variant:"outlined",size:"small",value:i,customValue:!0}),m.jsx(Jr,{icon:this.state[`${v}___icon`],square:!0,style:{...y||void 0,marginLeft:7},value:"...",className:f,onClick:()=>{const $={};$[`showSelectId${l}`]=!0,this.setState($)}})]}),_?m.jsx("div",{className:x.Utils.clsx(Oe.nameBlock,Oe.displayItalic),children:x.Utils.getObjectNameFromObj(_,x.I18n.getLanguage())}):null,p?m.jsx(x.DialogSelectID,{theme:this.props.theme,imagePrefix:"../..",dialogName:"javascript",themeType:x.Utils.getThemeName(),socket:b,selected:i,onClose:()=>{const $={};$[`showSelectId${l}`]=!1,this.setState($)},onOk:($,S)=>{const T={};T[`showSelectId${l}`]=!1;const E=Array.isArray($)?$[0]:$;this.setState(T,async()=>{var M,P,W,G,z,Z,he,Ce,O,K;const D=E?await b.getObject(E):void 0;this.lastObjectIdChange=Date.now(),r({[l]:$,[`${l}Role`]:(M=D==null?void 0:D.common)==null?void 0:M.role,[`${l}Type`]:(P=D==null?void 0:D.common)==null?void 0:P.type,[`${l}Unit`]:(W=D==null?void 0:D.common)==null?void 0:W.unit,[`${l}States`]:(G=D==null?void 0:D.common)==null?void 0:G.states,[`${l}Min`]:(z=D==null?void 0:D.common)==null?void 0:z.min,[`${l}Max`]:(Z=D==null?void 0:D.common)==null?void 0:Z.max,[`${l}Step`]:(he=D==null?void 0:D.common)==null?void 0:he.step,[`${l}Def`]:(Ce=D==null?void 0:D.common)==null?void 0:Ce.def,[`${l}Write`]:(O=D==null?void 0:D.common)==null?void 0:O.write,[`${l}Read`]:(K=D==null?void 0:D.common)==null?void 0:K.read},()=>this.props.setOnUpdate&&this.props.setOnUpdate(!0))})}}):null]},l):null}renderIconTag(){return m.jsx("div",{className:Oe.iconTag,onClick:s=>{this.state.settings.tagCard&&(this.state.tagCardArray.length<3?this.onChangeTag():this.setState({openTagMenu:s.currentTarget}))},children:this.state.settings.tagCard})}renderTime(s,i,r){const{attr:l,backText:c,frontText:d,doNotTranslate:h,doNotTranslateBack:p}=s;return m.jsxs("div",{className:Oe.displayFlex,style:{whiteSpace:"nowrap"},children:[d&&m.jsx("div",{className:Oe.frontText,children:h?d:x.I18n.t(d)}),m.jsx(iO,{value:i,onChange:r}),c&&m.jsx("div",{className:Oe.backText,children:p?c:x.I18n.t(c)})]},l)}renderSelect(s,i,r){const{className:l,style:c}=this.props,{name:d,options:h,frontText:p,backText:f,attr:b,multiple:y,doNotTranslate:w,doNotTranslate2:v,doNotTranslateBack:_}=s;return m.jsxs("div",{className:x.Utils.clsx(Oe.displayFlex,Oe.blockMarginTop),style:{whiteSpace:"nowrap"},children:[p&&m.jsx("div",{className:Oe.frontText,children:x.I18n.t(p)}),m.jsx(YR,{attr:b,doNotTranslate:w,doNotTranslate2:v,title:d,className:l,style:c,options:h,value:i,onChange:r,multiple:y,customValue:!0}),f&&m.jsx("div",{className:Oe.backText,children:_?f:x.I18n.t(f)})]},b)}renderInstance(s,i,r){const{socket:l}=this.props,{name:c,frontText:d,backText:h,attr:p,adapter:f,doNotTranslate:b,doNotTranslateBack:y}=s;return this.state.hideAttributes.includes(p)?null:m.jsxs("div",{className:x.Utils.clsx(Oe.displayFlex,Oe.blockMarginTop),style:{whiteSpace:"nowrap"},children:[d&&m.jsx("div",{className:Oe.frontText,children:b?d:x.I18n.t(d)}),m.jsx(HR,{attr:p,socket:l,adapter:f,title:c,value:i,onChange:w=>{r(Array.isArray(w)?w[0]:w)},customValue:!0,onInstanceHide:w=>this.setState({hideAttributes:[...this.state.hideAttributes,p]},()=>r(w))}),h&&m.jsx("div",{className:Oe.backText,children:y?h:x.I18n.t(h)})]},p)}renderDialog(s){const{onShowDialog:i,frontText:r,backText:l,attr:c,icon:d,doNotTranslate:h,doNotTranslateBack:p}=s;return m.jsxs("div",{className:x.Utils.clsx(Oe.displayFlex,Oe.blockMarginTop),style:{whiteSpace:"nowrap"},children:[r&&m.jsx("div",{className:Oe.frontText,children:h?r:x.I18n.t(r)}),m.jsx(fw,{iconName:d,className:x.Utils.clsx(Oe.iconDialog),onClick:()=>i&&i()}),l&&m.jsx("div",{className:Oe.backText,children:p?l:x.I18n.t(l)})]},c)}renderModalInput(s,i,r){const{openModal:l}=this.state,{className:c}=this.props,{attr:d,nameBlock:h,frontText:p,backText:f,noTextEdit:b,doNotTranslate:y,doNotTranslateBack:w}=s;return m.jsxs("div",{children:[m.jsxs("div",{className:x.Utils.clsx(Oe.displayFlex,Oe.blockMarginTop),children:[p&&m.jsx("div",{className:Oe.frontText,children:y?p:x.I18n.t(p)}),m.jsx(Ei,{disabled:!!b,className:c,autoComplete:"off",fullWidth:!0,variant:"outlined",size:"small",value:i,onChange:r,customValue:!0}),m.jsx(Jr,{square:!0,style:{marginLeft:5},value:"...",className:c,onClick:()=>this.setState({openModal:!0})}),f&&m.jsx("div",{className:Oe.backText,children:w?f:x.I18n.t(f)})]}),l?m.jsx(cm,{onApply:v=>this.setState({openModal:!1},()=>v!=null&&r(v)),onClose:()=>this.setState({openModal:!1}),defaultValue:i,textInput:!0}):null,h&&m.jsx("div",{className:Oe.nameBlock,children:x.I18n.t(h)})]},d)}renderDate(s,i,r){const{attr:l,backText:c,frontText:d,doNotTranslate:h,doNotTranslateBack:p}=s;return m.jsxs("div",{className:Oe.displayFlex,style:{whiteSpace:"nowrap"},children:[d&&m.jsx("div",{className:Oe.frontText,children:h?d:x.I18n.t(d)}),m.jsx(rO,{value:i,onChange:r}),c&&m.jsx("div",{className:Oe.backText,children:p?c:x.I18n.t(c)})]},l)}static getReplacesInText(s){var r;let i="";return(r=s.trigger)!=null&&r.oidType?i=".replace(/%s/g, obj.state.val).replace(/%id/g, obj.id).replace(/%name/g, obj.common && obj.common.name).replace(/%old/g, obj.oldState.val)":s.conditionsStates.length&&(i=`.replace(/%s/g, ${s.conditionsStates[0].name}).replace(/%id/g, "${s.conditionsStates[0].id}")`),i}renderTags(){const{tagCardArray:s,openTagMenu:i}=this.state,{tagCard:r}=this.state.settings;let l=r!=="="&&r!=="<>"&&r!==">="&&r!=="()"&&r!=="."&&r!=="<="&&r!=="<"&&r!==">"&&r?x.I18n.t(r):r;return s.length>=3&&(l=m.jsxs("div",{children:[m.jsx("div",{"aria-controls":"simple-menu","aria-haspopup":"true",onClick:c=>{this.setState({openTagMenu:c.currentTarget},()=>{this.props.isTourOpen&&this.props.tourStep===Ns.openTagsMenu&&setTimeout(()=>this.props.setTourStep&&this.props.setTourStep(Ns.selectIntervalTag),300)})},children:l}),m.jsx(pm,{id:"simple-menu",anchorEl:i,keepMounted:!0,open:!!i,onClose:()=>this.setState({openTagMenu:null}),children:s.map((c,d)=>{let h;return typeof c!="string"?h=c.title:h=c,m.jsxs(it,{selected:h===r,className:`tag-card-${h}`,style:{placeContent:"space-between"},onClick:p=>{p.stopPropagation(),this.props.isTourOpen&&(this.props.tourStep===Ns.openTagsMenu||this.props.tourStep===Ns.selectIntervalTag)&&h==="interval"&&setTimeout(()=>{var b,y;return(y=(b=this.props).setTourStep)==null?void 0:y.call(b,Ns.selectActions)},500);const f=JSON.parse(JSON.stringify(this.state.settings));f.tagCard=h,this.setState({openTagMenu:null,settings:f},()=>{this.props.onChange(this.state.settings),this.onTagChange(this.state.settings.tagCard)})},children:[h.search(/>|<|<>|<=|>=|=/)!==-1?h:x.I18n.t(h),typeof c!="string"&&c.title2&&m.jsx("div",{style:{marginLeft:4},children:x.I18n.t(c.title2)})]},`${h}_${d}`)})})]})),l}getData(){return{acceptedBy:"triggers",name:"",id:""}}onChangeTag(){const{tagCardArray:s,settings:i,settings:{tagCard:r}}=this.state;let l;if(typeof s[0]!="string"?l=s.map(c=>c.title):l=[...s],r&&l.length<3){const c={...i},d=l[(l.indexOf(r)+1)%l.length];c.tagCard=d,this.setState({settings:c},()=>{this.props.onChange(c),this.onTagChange(d)})}}componentDidMount(){this.onTagChange()}componentDidUpdate(){this.props.acceptedBy!=="triggers"&&this.props.onUpdate&&setTimeout(()=>this.onUpdate(),0)}onChangeInput(s){return(i,r,l)=>{const c=JSON.parse(JSON.stringify(this.state.settings));typeof i=="object"&&(!r||typeof r=="function")?(Object.keys(i).forEach(d=>c[d]=i[d]),typeof r=="function"&&(l=r,r=void 0)):c[r||s]=i,c.id=this.getData().id,c._id=this.props._id,this.setState({settings:c},()=>{this.onValueChanged(i,r||s),this.props.onChange(c),l==null||l()})}}renderSpecific(){return null}renderDebug(s){return""}renderDebugInfo(){return this.state.debugMessage?m.jsx("div",{className:Oe.debugInfo,style:{opacity:1,height:22,bottom:-22},children:this.renderDebug?this.renderDebug(this.state.debugMessage):x.I18n.t("executed")},this.state.debugMessage.ts):null}renderCron(s,i,r){return null}renderWizard(s,i,r){return null}renderWriteState(){return null}renderInputElement(s,i){const{nameRender:r,defaultValue:l,attr:c}=s,{settings:d}=this.state;let h=c?d[c]:void 0;switch(h===void 0&&(h=l),r){case"renderTime":return c?this.renderTime(s,h,this.onChangeInput(c)):m.jsx("div",{children:x.I18n.t("Invalid renderTime")},`invalid_${i}`);case"renderNameText":return this.renderNameText(s,l);case"renderSelect":return c?this.renderSelect(s,h,this.onChangeInput(c)):m.jsx("div",{children:x.I18n.t("Invalid renderSelect")},`invalid_${i}`);case"renderModalInput":return c?this.renderModalInput(s,h,this.onChangeInput(c)):m.jsx("div",{children:x.I18n.t("Invalid renderModalInput")},`invalid_${i}`);case"renderObjectID":return c?this.renderObjectID(s,h,this.onChangeInput(c)):m.jsx("div",{children:x.I18n.t("Invalid renderObjectID")},`invalid_${i}`);case"renderDialog":return c?this.renderDialog(s):m.jsx("div",{children:x.I18n.t("Invalid renderDialog")},`invalid_${i}`);case"renderInstance":return c?this.renderInstance(s,h,this.onChangeInput(c)):m.jsx("div",{children:x.I18n.t("Invalid renderInstance")},`invalid_${i}`);case"renderText":return c?this.renderText(s,h,this.onChangeInput(c)):m.jsx("div",{children:x.I18n.t("Invalid renderText")},`invalid_${i}`);case"renderSlider":return c?this.renderSlider(s,h,this.onChangeInput(c)):m.jsx("div",{children:x.I18n.t("Invalid renderSlider")},`invalid_${i}`);case"renderCheckbox":return c?this.renderCheckbox(s,h,this.onChangeInput(c)):m.jsx("div",{children:x.I18n.t("Invalid renderCheckbox")},`invalid_${i}`);case"renderButton":return c?this.renderButton(s,h,this.onChangeInput(c)):m.jsx("div",{children:x.I18n.t("Invalid renderButton")},`invalid_${i}`);case"renderColor":return c?this.renderColor(s,h,this.onChangeInput(c)):m.jsx("div",{children:x.I18n.t("Invalid renderColor")},`invalid_${i}`);case"renderSwitch":return c?this.renderSwitch(s,h,this.onChangeInput(c)):m.jsx("div",{children:x.I18n.t("Invalid renderSwitch")},`invalid_${i}`);case"renderDate":return c?this.renderDate(s,h,this.onChangeInput(c)):m.jsx("div",{children:x.I18n.t("Invalid renderDate")},`invalid_${i}`);case"renderCron":return c?this.renderCron(s,h,this.onChangeInput(c)):m.jsx("div",{children:x.I18n.t("Invalid renderCron")},`invalid_${i}`);case"renderWizard":return c?this.renderWizard(s,h,this.onChangeInput(c)):m.jsx("div",{children:x.I18n.t("Invalid renderWizard")},`invalid_${i}`);case"renderWriteState":return this.renderWriteState();case"renderNumber":return c?this.renderNumber(s,h,this.onChangeInput(c)):m.jsx("div",{children:x.I18n.t("Invalid renderNumber")},`invalid_${i}`);default:return this[r]?this[r](s,h,c?this.onChangeInput(c):null):m.jsx("div",{children:x.I18n.t("Invalid input type: %s",r)},`invalid_${i}`)}}render(){var w;const{inputs:s,name:i,icon:r,iconTag:l,settings:c,adapter:d,settings:{tagCard:h},helpDialog:p}=this.state,{socket:f,notFound:b}=this.props;this.state.settings&&!this.state.settings.tagCard&&((w=this.state.tagCardArray)!=null&&w.length)&&setTimeout(()=>{const v=JSON.parse(JSON.stringify(this.state.settings));v.tagCard=typeof this.state.tagCardArray[0]!="string"?this.state.tagCardArray[0].title:this.state.tagCardArray[0],this.setState({settings:v})},50),this.state.enableSimulation!==this.props.enableSimulation&&!this.enableSimulationProcessing&&(this.enableSimulationProcessing=!0,setTimeout(()=>{this.setState({enableSimulation:this.props.enableSimulation},()=>{this.enableSimulationProcessing=!1})},50));let y;if(this.props.onDebugMessage)for(let v=this.props.onDebugMessage.length-1;v>=0;v--){const _=this.props.onDebugMessage[v];if(_.blockId===this.props._id&&_.ts>this.lastDebugMessage&&_.ts>Date.now()-1e3){y=_;break}}return y&&(this.lastDebugMessage=y.ts,this.debugMessageTimeout&&clearTimeout(this.debugMessageTimeout),this.debugHideTimeout&&(clearTimeout(this.debugHideTimeout),this.debugHideTimeout=null),this.debugMessageTimeout=setTimeout(v=>{const _=JSON.parse(v),$=_.hideTimeout||5e3;this.debugMessageTimeout=null,this.setState({debugMessage:_},()=>{this.debugHideTimeout&&clearTimeout(this.debugHideTimeout),this.debugHideTimeout=setTimeout(()=>{this.debugHideTimeout=null,this.setState({debugMessage:null})},$)})},50,JSON.stringify(y))),m.jsxs(Dg,{children:[l?this.renderIconTag():m.jsx(fw,{iconName:r,className:x.Utils.clsx(Oe.iconThemCard,h&&this.state.tagCardArray.length&&Oe.iconThemCardSelectable),adapter:d,socket:f,onClick:v=>{h&&(this.state.tagCardArray.length<3?this.onChangeTag():this.setState({openTagMenu:v.currentTarget}))}}),m.jsxs("div",{className:Oe.blockName,children:[m.jsxs("span",{className:Oe.nameCard,children:[x.I18n.t(i),b?x.I18n.t("%s not found",c.id):"",p?m.jsx(qe,{className:Oe.iconHelp,size:"small",onClick:()=>this.setState({helpText:x.I18n.t(p)}),children:m.jsx(pk,{})}):null]}),s.map((v,_)=>this.renderInputElement(v,_))]}),h&&m.jsx("div",{className:Oe.controlMenuTop,style:{opacity:1,height:22,top:-22},children:m.jsx("div",{onClick:()=>this.onChangeTag(),className:x.Utils.clsx(Oe.tagCard,"tag-card"),children:this.renderTags()})}),this.renderDebugInfo(),this.state.error?m.jsx(x.DialogError,{title:x.I18n.t("Warning"),text:this.state.error,onClose:()=>this.setState({error:""})}):null,this.state.helpText?m.jsx(x.DialogMessage,{title:x.I18n.t("Instructions"),text:this.state.helpText,onClose:()=>this.setState({helpText:""})}):null,this.renderSpecific()]})}}const $w={en:{name:"Google - English",engine:"google",params:[]},de:{name:"Google - Deutsch",engine:"google",params:[]},ru:{name:"Google - Русский",engine:"google",params:[]},it:{name:"Google - Italiano",engine:"google",params:[]},es:{name:"Google - Espaniol",engine:"google",params:[]},fr:{name:"Google - Français",engine:"google",params:[]},ru_YA:{name:"Yandex - Русский",engine:"yandex",params:["key","voice","emotion","ill","drunk","robot"],voice:["jane","zahar"],emotion:["none","good","neutral","evil","mixed"]},ru_YA_CLOUD:{name:"Yandex Cloud - Русский",engine:"yandexCloud",params:["key","folderID","voice","emotion"],voice:["alyss","oksana","jane","zahar"],emotion:["good","neutral","evil"]},"en-US":{name:"PicoTTS - Englisch US",engine:"PicoTTS",params:[]},"en-GB":{name:"PicoTTS - Englisch GB",engine:"PicoTTS",params:[]},"de-DE":{name:"PicoTTS - Deutsch",engine:"PicoTTS",params:[]},"it-IT":{name:"PicoTTS - Italiano",engine:"PicoTTS",params:[]},"es-ES":{name:"PicoTTS - Espaniol",engine:"PicoTTS",params:[]},"fr-FR":{name:"PicoTTS - Français",engine:"PicoTTS",params:[]},"ru-RU_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"ru-RU",ename:"Tatyana",ssml:!0,name:"Cloud - Русский - Татьяна"},"ru-RU_CLOUD_Male":{gender:"Male",engine:"cloud",params:["cloud"],language:"ru-RU",ename:"Maxim",ssml:!0,name:"Cloud - Русский - Максим"},"de-DE_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"de-DE",ename:"Marlene",ssml:!0,name:"Cloud - Deutsch - Marlene"},"de-DE_CLOUD_Male":{gender:"Male",engine:"cloud",params:["cloud"],language:"de-DE",ename:"Hans",ssml:!0,name:"Cloud - Deutsch - Hans"},"en-US_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"en-US",ename:"Salli",ssml:!0,name:"Cloud - en-US - Female - Salli"},"en-US_CLOUD_Male":{gender:"Male",engine:"cloud",params:["cloud"],language:"en-US",ename:"Joey",ssml:!0,name:"Cloud - en-US - Male - Joey"},"da-DK_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"da-DK",ename:"Naja",ssml:!0,name:"Cloud - da-DK - Female - Naja"},"da-DK_CLOUD_Male":{gender:"Male",engine:"cloud",params:["cloud"],language:"da-DK",ename:"Mads",ssml:!0,name:"Cloud - da-DK - Male - Mads"},"en-AU_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"en-AU",ename:"Nicole",ssml:!0,name:"Cloud - en-AU - Female - Nicole"},"en-AU_CLOUD_Male":{gender:"Male",engine:"cloud",params:["cloud"],language:"en-AU",ename:"Russell",ssml:!0,name:"Cloud - en-AU - Male - Russell"},"en-GB_CLOUD_Female_Amy":{gender:"Female",engine:"cloud",params:["cloud"],language:"en-GB",ename:"Amy",ssml:!0,name:"Cloud - en-GB - Female - Amy"},"en-GB_CLOUD_Male":{gender:"Male",engine:"cloud",params:["cloud"],language:"en-GB",ename:"Brian",ssml:!0,name:"Cloud - en-GB - Male - Brian"},"en-GB_CLOUD_Female_Emma":{gender:"Female",engine:"cloud",params:["cloud"],language:"en-GB",ename:"Emma",ssml:!0,name:"Cloud - en-GB - Female - Emma"},"en-GB-WLS_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"en-GB-WLS",ename:"Gwyneth",ssml:!0,name:"Cloud - en-GB-WLS - Female - Gwyneth"},"en-GB-WLS_CLOUD_Male":{gender:"Male",engine:"cloud",params:["cloud"],language:"en-GB-WLS",ename:"Geraint",ssml:!0,name:"Cloud - en-GB-WLS - Male - Geraint"},"cy-GB_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"cy-GB",ename:"Gwyneth",ssml:!0,name:"Cloud - cy-GB - Female - Gwyneth"},"cy-GB_CLOUD_Male":{gender:"Male",engine:"cloud",params:["cloud"],language:"cy-GB",ename:"Geraint",ssml:!0,name:"Cloud - cy-GB - Male - Geraint"},"en-IN_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"en-IN",ename:"Raveena",ssml:!0,name:"Cloud - en-IN - Female - Raveena"},"en-US_CLOUD_Male_Chipmunk":{gender:"Male",engine:"cloud",params:["cloud"],language:"en-US",ename:"Chipmunk",ssml:!0,name:"Cloud - en-US - Male - Chipmunk"},"en-US_CLOUD_Male_Eric":{gender:"Male",engine:"cloud",params:["cloud"],language:"en-US",ename:"Eric",ssml:!0,name:"Cloud - en-US - Male - Eric"},"en-US_CLOUD_Female_Ivy":{gender:"Female",engine:"cloud",params:["cloud"],language:"en-US",ename:"Ivy",ssml:!0,name:"Cloud - en-US - Female - Ivy"},"en-US_CLOUD_Female_Jennifer":{gender:"Female",engine:"cloud",params:["cloud"],language:"en-US",ename:"Jennifer",ssml:!0,name:"Cloud - en-US - Female - Jennifer"},"en-US_CLOUD_Male_Justin":{gender:"Male",engine:"cloud",params:["cloud"],language:"en-US",ename:"Justin",ssml:!0,name:"Cloud - en-US - Male - Justin"},"en-US_CLOUD_Female_Kendra":{gender:"Female",engine:"cloud",params:["cloud"],language:"en-US",ename:"Kendra",ssml:!0,name:"Cloud - en-US - Female - Kendra"},"en-US_CLOUD_Female_Kimberly":{gender:"Female",engine:"cloud",params:["cloud"],language:"en-US",ename:"Kimberly",ssml:!0,name:"Cloud - en-US - Female - Kimberly"},"es-ES_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"es-ES",ename:"Conchita",ssml:!0,name:"Cloud - es-ES - Female - Conchita"},"es-ES_CLOUD_Male":{gender:"Male",engine:"cloud",params:["cloud"],language:"es-ES",ename:"Enrique",ssml:!0,name:"Cloud - es-ES - Male - Enrique"},"es-US_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"es-US",ename:"Penelope",ssml:!0,name:"Cloud - es-US - Female - Penelope"},"es-US_CLOUD_Male":{gender:"Male",engine:"cloud",params:["cloud"],language:"es-US",ename:"Miguel",ssml:!0,name:"Cloud - es-US - Male - Miguel"},"fr-CA_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"fr-CA",ename:"Chantal",ssml:!0,name:"Cloud - fr-CA - Female - Chantal"},"fr-FR_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"fr-FR",ename:"Celine",ssml:!0,name:"Cloud - fr-FR - Female - Celine"},"fr-FR_CLOUD_Male":{gender:"Male",engine:"cloud",params:["cloud"],language:"fr-FR",ename:"Mathieu",ssml:!0,name:"Cloud - fr-FR - Male - Mathieu"},"is-IS_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"is-IS",ename:"Dora",ssml:!0,name:"Cloud - is-IS - Female - Dora"},"is-IS_CLOUD_Male":{gender:"Male",engine:"cloud",params:["cloud"],language:"is-IS",ename:"Karl",ssml:!0,name:"Cloud - is-IS - Male - Karl"},"it-IT_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"it-IT",ename:"Carla",ssml:!0,name:"Cloud - it-IT - Female - Carla"},"it-IT_CLOUD_Male":{gender:"Male",engine:"cloud",params:["cloud"],language:"it-IT",ename:"Giorgio",ssml:!0,name:"Cloud - it-IT - Male - Giorgio"},"nb-NO_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"nb-NO",ename:"Liv",ssml:!0,name:"Cloud - nb-NO - Female - Liv"},"nl-NL_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"nl-NL",ename:"Lotte",ssml:!0,name:"Cloud - nl-NL - Female - Lotte"},"nl-NL_CLOUD_Male":{gender:"Male",engine:"cloud",params:["cloud"],language:"nl-NL",ename:"Ruben",ssml:!0,name:"Cloud - nl-NL - Male - Ruben"},"pl-PL_CLOUD_Female_Agnieszka":{gender:"Female",engine:"cloud",params:["cloud"],language:"pl-PL",ename:"Agnieszka",ssml:!0,name:"Cloud - pl-PL - Female - Agnieszka"},"pl-PL_CLOUD_Male_Jacek":{gender:"Male",engine:"cloud",params:["cloud"],language:"pl-PL",ename:"Jacek",ssml:!0,name:"Cloud - pl-PL - Male - Jacek"},"pl-PL_CLOUD_Female_Ewa":{gender:"Female",engine:"cloud",params:["cloud"],language:"pl-PL",ename:"Ewa",ssml:!0,name:"Cloud - pl-PL - Female - Ewa"},"pl-PL_CLOUD_Male_Jan":{gender:"Male",engine:"cloud",params:["cloud"],language:"pl-PL",ename:"Jan",ssml:!0,name:"Cloud - pl-PL - Male - Jan"},"pl-PL_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"pl-PL",ename:"Maja",ssml:!0,name:"Cloud - pl-PL - Female - Maja"},"pt-BR_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"pt-BR",ename:"Vitoria",ssml:!0,name:"Cloud - pt-BR - Female - Vitoria"},"pt-BR_CLOUD_Male":{gender:"Male",engine:"cloud",params:["cloud"],language:"pt-BR",ename:"Ricardo",ssml:!0,name:"Cloud - pt-BR - Male - Ricardo"},"pt-PT_CLOUD_Male":{gender:"Male",engine:"cloud",params:["cloud"],language:"pt-PT",ename:"Cristiano",ssml:!0,name:"Cloud - pt-PT - Male - Cristiano"},"pt-PT_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"pt-PT",ename:"Ines",ssml:!0,name:"Cloud - pt-PT - Female - Ines"},"ro-RO_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"ro-RO",ename:"Carmen",ssml:!0,name:"Cloud - ro-RO - Female - Carmen"},"sv-SE_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"sv-SE",ename:"Astrid",ssml:!0,name:"Cloud - sv-SE - Female - Astrid"},"tr-TR_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"tr-TR",ename:"Filiz",ssml:!0,name:"Cloud - tr-TR - Female - Filiz"},"ru-RU_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"ru-RU",ename:"Tatyana",ssml:!0,name:"AWS Polly - Русский - Татьяна"},"ru-RU_AP_Male":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"ru-RU",ename:"Maxim",ssml:!0,name:"AWS Polly - Русский - Максим"},"de-DE_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"de-DE",ename:"Marlene",ssml:!0,name:"AWS Polly - Deutsch - Marlene"},"de-DE_AP_Female_Vicky":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"de-DE",ename:"Vicky",ssml:!0,name:"AWS Polly - Deutsch - Vicky"},"de-DE_AP_Male":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"de-DE",ename:"Hans",ssml:!0,name:"AWS Polly - Deutsch - Hans"},"en-US_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"en-US",ename:"Salli",ssml:!0,name:"AWS Polly - en-US - Female - Salli"},"en-US_AP_Male":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"en-US",ename:"Joey",ssml:!0,name:"AWS Polly - en-US - Male - Joey"},"da-DK_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"da-DK",ename:"Naja",ssml:!0,name:"AWS Polly - da-DK - Female - Naja"},"da-DK_AP_Male":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"da-DK",ename:"Mads",ssml:!0,name:"AWS Polly - da-DK - Male - Mads"},"en-AU_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"en-AU",ename:"Nicole",ssml:!0,name:"AWS Polly - en-AU - Female - Nicole"},"en-AU_AP_Male":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"en-AU",ename:"Russell",ssml:!0,name:"AWS Polly - en-AU - Male - Russell"},"en-GB_AP_Female_Amy":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"en-GB",ename:"Amy",ssml:!0,name:"AWS Polly - en-GB - Female - Amy"},"en-GB_AP_Male":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"en-GB",ename:"Brian",ssml:!0,name:"AWS Polly - en-GB - Male - Brian"},"en-GB_AP_Female_Emma":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"en-GB",ename:"Emma",ssml:!0,name:"AWS Polly - en-GB - Female - Emma"},"en-GB-WLS_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"en-GB-WLS",ename:"Gwyneth",ssml:!0,name:"AWS Polly - en-GB-WLS - Female - Gwyneth"},"en-GB-WLS_AP_Male":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"en-GB-WLS",ename:"Geraint",ssml:!0,name:"AWS Polly - en-GB-WLS - Male - Geraint"},"cy-GB_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"cy-GB",ename:"Gwyneth",ssml:!0,name:"AWS Polly - cy-GB - Female - Gwyneth"},"cy-GB_AP_Male":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"cy-GB",ename:"Geraint",ssml:!0,name:"AWS Polly - cy-GB - Male - Geraint"},"en-IN_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"en-IN",ename:"Raveena",ssml:!0,name:"AWS Polly - en-IN - Female - Raveena"},"en-US_AP_Male_Chipmunk":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"en-US",ename:"Chipmunk",ssml:!0,name:"AWS Polly - en-US - Male - Chipmunk"},"en-US_AP_Male_Eric":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"en-US",ename:"Eric",ssml:!0,name:"AWS Polly - en-US - Male - Eric"},"en-US_AP_Female_Ivy":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"en-US",ename:"Ivy",ssml:!0,name:"AWS Polly - en-US - Female - Ivy"},"en-US_AP_Female_Jennifer":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"en-US",ename:"Jennifer",ssml:!0,name:"AWS Polly - en-US - Female - Jennifer"},"en-US_AP_Male_Justin":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"en-US",ename:"Justin",ssml:!0,name:"AWS Polly - en-US - Male - Justin"},"en-US_AP_Female_Kendra":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"en-US",ename:"Kendra",ssml:!0,name:"AWS Polly - en-US - Female - Kendra"},"en-US_AP_Female_Kimberly":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"en-US",ename:"Kimberly",ssml:!0,name:"AWS Polly - en-US - Female - Kimberly"},"es-ES_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"es-ES",ename:"Conchita",ssml:!0,name:"AWS Polly - es-ES - Female - Conchita"},"es-ES_AP_Male":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"es-ES",ename:"Enrique",ssml:!0,name:"AWS Polly - es-ES - Male - Enrique"},"es-US_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"es-US",ename:"Penelope",ssml:!0,name:"AWS Polly - es-US - Female - Penelope"},"es-US_AP_Male":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"es-US",ename:"Miguel",ssml:!0,name:"AWS Polly - es-US - Male - Miguel"},"fr-CA_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"fr-CA",ename:"Chantal",ssml:!0,name:"AWS Polly - fr-CA - Female - Chantal"},"fr-FR_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"fr-FR",ename:"Celine",ssml:!0,name:"AWS Polly - fr-FR - Female - Celine"},"fr-FR_AP_Male":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"fr-FR",ename:"Mathieu",ssml:!0,name:"AWS Polly - fr-FR - Male - Mathieu"},"is-IS_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"is-IS",ename:"Dora",ssml:!0,name:"AWS Polly - is-IS - Female - Dora"},"is-IS_AP_Male":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"is-IS",ename:"Karl",ssml:!0,name:"AWS Polly - is-IS - Male - Karl"},"it-IT_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"it-IT",ename:"Carla",ssml:!0,name:"AWS Polly - it-IT - Female - Carla"},"it-IT_AP_Male":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"it-IT",ename:"Giorgio",ssml:!0,name:"AWS Polly - it-IT - Male - Giorgio"},"nb-NO_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"nb-NO",ename:"Liv",ssml:!0,name:"AWS Polly - nb-NO - Female - Liv"},"nl-NL_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"nl-NL",ename:"Lotte",ssml:!0,name:"AWS Polly - nl-NL - Female - Lotte"},"nl-NL_AP_Male":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"nl-NL",ename:"Ruben",ssml:!0,name:"AWS Polly - nl-NL - Male - Ruben"},"pl-PL_AP_Female_Agnieszka":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"pl-PL",ename:"Agnieszka",ssml:!0,name:"AWS Polly - pl-PL - Female - Agnieszka"},"pl-PL_AP_Male_Jacek":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"pl-PL",ename:"Jacek",ssml:!0,name:"AWS Polly - pl-PL - Male - Jacek"},"pl-PL_AP_Female_Ewa":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"pl-PL",ename:"Ewa",ssml:!0,name:"AWS Polly - pl-PL - Female - Ewa"},"pl-PL_AP_Male_Jan":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"pl-PL",ename:"Jan",ssml:!0,name:"AWS Polly - pl-PL - Male - Jan"},"pl-PL_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"pl-PL",ename:"Maja",ssml:!0,name:"AWS Polly - pl-PL - Female - Maja"},"pt-BR_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"pt-BR",ename:"Vitoria",ssml:!0,name:"AWS Polly - pt-BR - Female - Vitoria"},"pt-BR_AP_Male":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"pt-BR",ename:"Ricardo",ssml:!0,name:"AWS Polly - pt-BR - Male - Ricardo"},"pt-PT_AP_Male":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"pt-PT",ename:"Cristiano",ssml:!0,name:"AWS Polly - pt-PT - Male - Cristiano"},"pt-PT_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"pt-PT",ename:"Ines",ssml:!0,name:"AWS Polly - pt-PT - Female - Ines"},"ro-RO_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"ro-RO",ename:"Carmen",ssml:!0,name:"AWS Polly - ro-RO - Female - Carmen"},"sv-SE_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"sv-SE",ename:"Astrid",ssml:!0,name:"AWS Polly - sv-SE - Female - Astrid"},"tr-TR_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"tr-TR",ename:"Filiz",ssml:!0,name:"AWS Polly - tr-TR - Female - Filiz"}};class Oc extends at{constructor(s){super(s,Oc.getStaticData())}static compile(s,i){return s.text?`// Sayit ${s.text||""} +`)}(${i}, ${r}, ${l})`,2]}const wO=window.Blockly.common.createBlockDefinitionsFromJsonArray([yO]);wO[TC];function kO(){window.Blockly.FieldMultilineInput||(window.Blockly.fieldRegistry.register("field_multilinetext",Rc),window.Blockly.JavaScript.forBlock.text_multiline=cO,window.Blockly.FieldMultilineInput=Rc,Object.assign(window.Blockly.Blocks,window.Blockly.common.createBlockDefinitionsFromJsonArray([{type:"text_multiline",message0:"%1 %2",args0:[{type:"field_image",src:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAARCAYAAADpPU2iAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAdhgAAHYYBXaITgQAAABh0RVh0U29mdHdhcmUAcGFpbnQubmV0IDQuMS42/U4J6AAAAP1JREFUOE+Vks0KQUEYhjmRIja4ABtZ2dm5A3t3Ia6AUm7CylYuQRaUhZSlLZJiQbFAyRnPN33y01HOW08z8873zpwzM4F3GWOCruvGIE4/rLaV+Nq1hVGMBqzhqlxgCys4wJA65xnogMHsQ5lujnYHTejBBCK2mE4abjCgMGhNxHgDFWjDSG07kdfVa2pZMf4ZyMAdWmpZMfYOsLiDMYMjlMB+K613QISRhTnITnsYg5yUd0DETmEoMlkFOeIT/A58iyK5E18BuTBfgYXfwNJv4P9/oEBerLylOnRhygmGdPpTTBZAPkde61lbQe4moWUvYUZYLfUNftIY4zwA5X2Z9AYnQrEAAAAASUVORK5CYII=",width:12,height:17,alt:"¶"},{type:"field_multilinetext",name:"TEXT",text:""}],output:"String",style:"text_blocks",helpUrl:"%{BKY_TEXT_TEXT_HELPURL}",tooltip:"%{BKY_TEXT_TEXT_TOOLTIP}",extensions:["parent_tooltip_when_inline"]}]))),window.Blockly.FieldColour||(window.Blockly.fieldRegistry.register("field_colour",dm),window.Blockly.JavaScript.forBlock.colour_picker=hO,window.Blockly.JavaScript.forBlock.colour_blend=_O,window.Blockly.JavaScript.forBlock.colour_random=mO,window.Blockly.JavaScript.forBlock.colour_rgb=bO,window.Blockly.FieldColour=dm,Object.assign(window.Blockly.Blocks,window.Blockly.common.createBlockDefinitionsFromJsonArray([{type:"colour_picker",message0:"%1",args0:[{type:"field_colour",name:"COLOUR",colour:"#ff0000"}],output:"Colour",helpUrl:"%{BKY_COLOUR_PICKER_HELPURL}",style:"colour_blocks",tooltip:"%{BKY_COLOUR_PICKER_TOOLTIP}",extensions:["parent_tooltip_when_inline"]}])),Object.assign(window.Blockly.Blocks,window.Blockly.common.createBlockDefinitionsFromJsonArray([{type:"colour_random",message0:"%{BKY_COLOUR_RANDOM_TITLE}",output:"Colour",helpUrl:"%{BKY_COLOUR_RANDOM_HELPURL}",style:"colour_blocks",tooltip:"%{BKY_COLOUR_RANDOM_TOOLTIP}"}])),Object.assign(window.Blockly.Blocks,window.Blockly.common.createBlockDefinitionsFromJsonArray([{type:"colour_rgb",message0:"%{BKY_COLOUR_RGB_TITLE} %{BKY_COLOUR_RGB_RED} %1 %{BKY_COLOUR_RGB_GREEN} %2 %{BKY_COLOUR_RGB_BLUE} %3",args0:[{type:"input_value",name:"RED",check:"Number",align:"RIGHT"},{type:"input_value",name:"GREEN",check:"Number",align:"RIGHT"},{type:"input_value",name:"BLUE",check:"Number",align:"RIGHT"}],output:"Colour",helpUrl:"%{BKY_COLOUR_RGB_HELPURL}",style:"colour_blocks",tooltip:"%{BKY_COLOUR_RGB_TOOLTIP}"}])),Object.assign(window.Blockly.Blocks,window.Blockly.common.createBlockDefinitionsFromJsonArray([{type:"colour_blend",message0:"%{BKY_COLOUR_BLEND_TITLE} %{BKY_COLOUR_BLEND_COLOUR1} %1 %{BKY_COLOUR_BLEND_COLOUR2} %2 %{BKY_COLOUR_BLEND_RATIO} %3",args0:[{type:"input_value",name:"COLOUR1",check:"Colour",align:"RIGHT"},{type:"input_value",name:"COLOUR2",check:"Colour",align:"RIGHT"},{type:"input_value",name:"RATIO",check:"Number",align:"RIGHT"}],output:"Colour",helpUrl:"%{BKY_COLOUR_BLEND_HELPURL}",style:"colour_blocks",tooltip:"%{BKY_COLOUR_BLEND_TOOLTIP}"}])));const a=window.Blockly.JavaScript;a.forBlock&&Object.keys(a).forEach(s=>{typeof a[s]=="function"&&(a.forBlock[s]||(console.log(`Migrating Blockly.JavaScript.${s} to Blockly.JavaScript.forBlock.${s}`),a.forBlock[s]=a[s],delete a[s]))})}let uc=!1,dc=!1,wg=null,kg=null;const pw=[];function SC(a,s,i,r){var l;if(r=r||[],(a.tagName==="BLOCK"||a.tagName==="block")&&(i=a.id),a.tagName==="FIELD"||a.tagName==="field")for(let c=0;cSC(c,s,i,r)),r}class Xe extends _e.Component{blockly=null;blocklyWorkspace=null;originalCode;someSelected=null;changeTimer=null;someSelectedTime=0;ignoreChanges=!1;blinkBlock;onResizeBind;resizeObserver=null;didUpdate=null;lastCommand="";lastSearch;static Blockly=window.Blockly;constructor(s){super(s),this.state={languageOwnLoaded:dc,languageBlocklyLoaded:uc,changed:!1,message:"",error:"",themeType:this.props.themeType,exportText:"",importText:!1,searchText:this.props.searchText||"",showInputPrompt:null},this.originalCode=s.code||"",this.someSelected=null,this.onResizeBind=this.onResize.bind(this),this.lastSearch=this.props.searchText||"",this.blinkBlock=null,kO(),Xe.Blockly.dialog.setPrompt(this.onShowNameDialog),this.loadLanguages()}onShowNameDialog=(s,i,r)=>{this.setState({showInputPrompt:{promptText:s,defaultText:i,callback:r,value:i}})};static loadJS(s,i,r){const l=document.createElement("script");try{l.src=s,l.onload=i,l.onerror=i,(r||window.document.body).appendChild(l)}catch(c){console.error(`Cannot load ${s}: ${c}`),i&&i()}}static loadScripts(s,i){if(!(s!=null&&s.length)){i&&i();return}const r=s.pop();r&&!pw.includes(r)?(pw.push(r),Xe.loadJS(`../../adapter/${r}/blockly.js`,()=>setTimeout(()=>Xe.loadScripts(s,i),0))):setTimeout(()=>Xe.loadScripts(s,i),0)}static loadCustomBlockly(s,i){var l;const r=[];for(const c in s)!Object.prototype.hasOwnProperty.call(s,c)||!s[c]||!c.match(/^system\.adapter\./)||s[c].type!=="adapter"||(l=s[c].common)!=null&&l.blockly&&(console.log(`Detected custom blockly: ${s[c].common.name}`),r.push(s[c].common.name));Xe.loadScripts(r,i)}static loadXMLDoc(s){let i;return window.DOMParser?i=r=>new window.DOMParser().parseFromString(r,"text/xml"):typeof window.ActiveXObject<"u"&&new window.ActiveXObject("Microsoft.XMLDOM")?i=r=>{const l=new window.ActiveXObject("Microsoft.XMLDOM");return l.async="false",l.loadXML(r),l}:i=()=>null,i(s)}searchBlocks(s){if(this.blocklyWorkspace){const i=Xe.Blockly.Xml.workspaceToDom(this.blocklyWorkspace),r=SC(i,s.toLowerCase());return console.log(`Search "${s}" found blocks: ${r.length?JSON.stringify(r):"none"}`),r}return[]}searchId(){const s=this.lastSearch?this.searchBlocks(this.lastSearch):null;s!=null&&s.length?(this.someSelected=s,this.someSelected.forEach(i=>{var r;return(r=this.blocklyWorkspace)==null?void 0:r.highlightBlock(i,!0)}),this.someSelectedTime=Date.now()):this.someSelected&&(this.someSelected.forEach(i=>{var r;return(r=this.blocklyWorkspace)==null?void 0:r.highlightBlock(i,!1)}),this.someSelected=null)}UNSAFE_componentWillReceiveProps(s){s.command&&this.lastCommand!==s.command&&(this.lastCommand=s.command,setTimeout(()=>this.lastCommand="",300),this.lastCommand==="check"?this.blocklyCheckBlocks((i,r)=>{i?(r&&Xe.blocklyBlinkBlock(r),this.setState({error:{text:x.I18n.t(i),title:x.I18n.t("Error was found")}}),this.blinkBlock=r):this.setState({message:x.I18n.t("Ok")})}):this.lastCommand==="export"?this.exportBlocks():this.lastCommand==="import"&&this.importBlocks()),s.searchText!==this.lastSearch&&(this.lastSearch=s.searchText,this.searchId()),this.state.themeType!==s.themeType&&this.setState({themeType:s.themeType},()=>this.updateBackground()),this.originalCode!==s.code&&(this.originalCode=s.code||"",this.loadCode(),this.searchId())}loadLanguages(){if(!uc){const s=window.document.createElement("script");s.setAttribute("type","text/javascript"),s.setAttribute("src",`google-blockly/msg/js/${x.I18n.getLanguage()}.js`),s.onload=()=>{uc=!0,this.setState({languageBlocklyLoaded:uc})},window.document.getElementsByTagName("head")[0].appendChild(s)}if(!dc){const s=window.document.createElement("script");s.setAttribute("type","text/javascript"),s.setAttribute("src",`google-blockly/own/msg/${x.I18n.getLanguage()}.js`),s.onload=()=>{dc=!0,this.setState({languageOwnLoaded:dc})},window.document.getElementsByTagName("head")[0].appendChild(s)}}onResize(){this.blocklyWorkspace&&Xe.Blockly.svgResize(this.blocklyWorkspace)}static jsCode2Blockly(s){s=s||"";const i=s.split(/[\r\n]+|\r|\n/g);let r="";for(let c=i.length-1;c>=0;c--)if(i[c].substring(0,2)==="//"){r=i[c].substring(2);break}if(r.substring(0,4)==="s.select(),i),setTimeout(()=>s.unselect(),i+150)}blocklyRemoveOrphanedShadows(){if(this.blocklyWorkspace){const s=this.blocklyWorkspace.getAllBlocks();let i;for(let r=0;i=s[r];r++)if(i.isShadow()){const l=i.getConnections_(!0);let c;for(let d=0;c=l[d];d++)if(!c.targetConnection){i.dispose();break}}}}blocklyCheckBlocks(s){let i;if(!this.blocklyWorkspace||this.blocklyWorkspace.getAllBlocks().length===0)return s&&s("no blocks found"),!1;let r=this.blocklyGetUnconnectedBlock();return r?i="not properly connected":(r=this.blocklyGetBlockWithWarning(),r&&(i="warning on this block")),r?(s?s(i,r):Xe.blocklyBlinkBlock(r),!1):(s(),!0)}blocklyGetUnconnectedBlock(){var r;const s=(r=this.blocklyWorkspace)==null?void 0:r.getAllBlocks();let i;if(s)for(let l=0;i=s[l];l++){const c=i.getConnections_(!0);let d;for(let h=0;d=c[h];h++)if(!d.sourceBlock_||(d.type===Xe.Blockly.INPUT_VALUE||d.type===Xe.Blockly.OUTPUT_VALUE)&&!d.targetConnection&&!d._optional)return i}return null}blocklyGetBlockWithWarning(){var r;const s=(r=this.blocklyWorkspace)==null?void 0:r.getAllBlocks();let i;if(s){for(let l=0;i=s[l];l++)if(i.warning)return i}return null}appendBlocksFromXml(s){this.onImportBlocks(s)}applyAiBlocks(s){var i,r;if(this.blocklyWorkspace&&(s=(s||"").trim(),!!s))try{s.startsWith("${s}`),s=s.replace(/[\n\r]/g,"").replace(/.*<\/variables>/g,"");const l=Xe.Blockly.utils.xml.textToDom(s),c=Array.from(l.querySelectorAll(":scope > block"));if(c.length===0)return;const d=E=>{const D=E.getAttribute("type")||"",R=[];for(const L of Array.from(E.children))L.tagName==="field"&&R.push(`${L.getAttribute("name")}=${L.textContent}`),L.tagName==="mutation"&&R.push(`mut:${L.outerHTML}`);return`${D}|${R.join(",")}`},h=E=>{const D=E.type||"",R=[];for(const L of E.inputList||[])for(const H of L.fieldRow||[])H.name&&H.getValue&&R.push(`${H.name}=${H.getValue()}`);if(E.mutationToDom)try{const L=E.mutationToDom();L&&R.push(`mut:${L.outerHTML}`)}catch{}return`${D}|${R.join(",")}`},p=c.map(E=>d(E)),f=this.blocklyWorkspace.getTopBlocks(!1),b=f.map(E=>h(E)),y=new Array(f.length).fill(!1),w=[];for(let E=0;E1){const E=new Set;for(const D of c)E.add(`${D.getAttribute("x")||"0"},${D.getAttribute("y")||"0"}`);if(E.size===1){let D=10;for(const R of c)R.setAttribute("x","10"),R.setAttribute("y",String(D)),D+=200}}Xe.Blockly.Xml.appendDomToWorkspace(l,this.blocklyWorkspace);const $=this.blocklyWorkspace.getTopBlocks(!1),T=$.slice(-c.length);let S=10;for(const E of $.slice(0,-c.length)){const D=E.getRelativeToSurfaceXY(),R=E.getHeightWidth();S=Math.max(S,D.y+R.height+30)}for(let E=0;E${s}`),s=s.replace(/[\n\r]/g,"").replace(/.*<\/variables>/g,""),window.scripts.loading=!0;const i=Xe.Blockly.utils.xml.textToDom(s),r=Array.from(i.querySelectorAll(":scope > block"));if(r.length>1){const l=new Set;for(const c of r)l.add(`${c.getAttribute("x")||"0"},${c.getAttribute("y")||"0"}`);if(l.size===1){let c=parseInt(r[0].getAttribute("y")||"0",10);for(const d of r)d.setAttribute("y",String(c)),c+=200}}if(Xe.Blockly.Xml.appendDomToWorkspace(i,this.blocklyWorkspace),r.length>1){const c=this.blocklyWorkspace.getTopBlocks(!1).slice(-r.length);if(c.length>1){let d=c[0].getRelativeToSurfaceXY().y;for(const h of c){const p=h.getRelativeToSurfaceXY();h.moveBy(0,d-p.y),d+=h.getHeightWidth().height+20}}}window.scripts.loading=!1,this.onBlocklyChanged()}catch(i){this.setState({error:{text:i.toString(),title:x.I18n.t("Import error")}})}}loadCode(){if(this.blocklyWorkspace){this.ignoreChanges=!0,this.blocklyWorkspace.clear();try{const s=Xe.jsCode2Blockly(this.originalCode)||'';window.scripts.loading=!0;const i=Xe.Blockly.utils.xml.textToDom(s);Xe.Blockly.Xml.domToWorkspace(i,this.blocklyWorkspace),window.scripts.loading=!1}catch(s){console.error(s),setTimeout(()=>this.setState({error:x.I18n.t("Cannot extract Blockly code!")}))}setTimeout(()=>this.ignoreChanges=!1,100)}}onBlocklyChanged(){this.blocklyRemoveOrphanedShadows(),this.setState({changed:!0}),this.onChange()}async componentDidUpdate(){var i,r;if(!this.blockly||(this.didUpdate&&(clearTimeout(this.didUpdate),this.didUpdate=null),this.blocklyWorkspace))return;window.addEventListener("resize",this.onResizeBind,!1),!this.resizeObserver&&this.blockly&&(this.resizeObserver=new ResizeObserver(()=>this.onResize()),this.resizeObserver.observe(this.blockly)),wg=wg||await this.getToolbox(),kg=kg||Xe.Blockly.utils.xml.textToDom(wg),this.blocklyWorkspace=Xe.Blockly.inject(this.blockly,{renderer:"thrasos",theme:this.state.themeType==="dark"?hw:"classic",media:"google-blockly/media/",toolbox:kg,zoom:{controls:!0,wheel:!1,startScale:1,maxScale:3,minScale:.3,scaleSpeed:1.2,pinch:!0},move:{scrollbars:{horizontal:!0,vertical:!0},drag:!0,wheel:!0},trashcan:!0,grid:{spacing:25,length:1,snap:!0},sounds:!1}),window.scripts={blocklyWorkspace:this.blocklyWorkspace},this.blocklyWorkspace.registerToolboxCategoryCallback("PROCEDURE",window.Blockly.Procedures.flyoutCategoryNew),this.blocklyWorkspace.addChangeListener(l=>{var c;if(this.someSelected&&Date.now()-this.someSelectedTime>500){const d=(c=this.blocklyWorkspace)==null?void 0:c.getAllBlocks();this.someSelected=null,d==null||d.forEach(h=>h.removeSelect())}[Xe.Blockly.Events.UI,Xe.Blockly.Events.CREATE,Xe.Blockly.Events.VIEWPORT_CHANGE].includes(l.type)||this.ignoreChanges||(this.changeTimer&&clearTimeout(this.changeTimer),this.changeTimer=setTimeout(()=>{this.changeTimer=null,this.onBlocklyChanged()},200))}),this.loadCode(),this.onResize();const s=document.getElementsByClassName("blocklyToolboxDiv")[0];if(this.blockly.appendChild(s),(r=(i=window.Blockly)==null?void 0:i.FieldOID)!=null&&r.DISPLAY_MODE_KEYS){const l=this.blocklyWorkspace,c=l.configureContextMenu;l.configureContextMenu=(d,h)=>{var b,y,w,v;c&&c.call(l,d,h);const p=window.Blockly.FieldOID,f=p.DISPLAY_MODE_KEYS;for(let _=0;_p.setDisplayMode(_,l),scope:{workspace:l},weight:200+_})}}}this.updateBackground(),setTimeout(()=>this.searchId(),200)}updateBackground(){var s;this.state.themeType==="dark"?(s=this.blocklyWorkspace)==null||s.setTheme(hw):this.blocklyWorkspace&&(this.blocklyWorkspace.getThemeManager(),this.blocklyWorkspace.setTheme(Xe.Blockly.Themes.Classic))}componentWillUnmount(){this.blocklyWorkspace&&(this.blocklyWorkspace.dispose(),this.blocklyWorkspace=null,this.changeTimer&&clearTimeout(this.changeTimer),this.changeTimer=null,window.removeEventListener("resize",this.onResizeBind),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null))}onChange(){this.originalCode=this.blocklyCode2JSCode(),this.props.onChange&&this.props.onChange(this.originalCode)}async getToolbox(s){const i=window.document.getElementById("toolbox");let r=i==null?void 0:i.outerHTML;if(!r)return s?(console.error("Cannot load blocks!"),""):new Promise(l=>{setTimeout(()=>l(this.getToolbox(!0)),500)});if(r=r.replace(/{(\w+)}/g,(l,c)=>window.MSG[c]),window.Blockly.CustomBlocks){let l="";const c=x.I18n.getLanguage();for(let d=0;d`;for(const f in p.blocks)Object.prototype.hasOwnProperty.call(p.blocks,f)&&(l+=p.blocks[f]);l+=""}r=r.replace("%%CUSTOM_BLOCKS%%",l)}return r}renderMessageDialog(){return this.state.message?m.jsx(x.Message,{text:typeof this.state.message=="object"?this.state.message.text:this.state.message,title:typeof this.state.message=="object"?this.state.message.title:"",onClose:()=>this.setState({message:""})},"dialogMessage"):null}renderErrorDialog(){return this.state.error?m.jsx(ou,{text:typeof this.state.error=="object"?this.state.error.text.toString():this.state.error,title:typeof this.state.error=="object"?this.state.error.title:"",onClose:()=>{this.blinkBlock&&(Xe.blocklyBlinkBlock(this.blinkBlock),this.blinkBlock=null),this.setState({error:""})}},"dialogError"):null}renderExportDialog(){return this.state.exportText?m.jsx(aO,{themeType:this.state.themeType,onClose:()=>this.setState({exportText:""}),text:this.state.exportText,scriptId:this.props.scriptId},"dialogExport"):null}renderImportDialog(){return this.state.importText?m.jsx(Ym,{themeType:this.props.themeType,onClose:s=>{this.setState({importText:!1}),this.onImportBlocks(s)}},"dialogImport"):null}renderDialogPrompt(){return this.state.showInputPrompt?m.jsxs(Pt,{onClose:()=>{var i;const s=(i=this.state.showInputPrompt)==null?void 0:i.callback;s&&s(null),this.setState({showInputPrompt:null})},maxWidth:"sm",fullWidth:!0,open:!0,children:[m.jsx(qt,{children:this.state.showInputPrompt.promptText}),m.jsx(Wt,{children:m.jsx(Eo,{variant:"standard",fullWidth:!0,autoFocus:!0,value:this.state.showInputPrompt.value,onKeyUp:s=>{var i,r;if(s.key==="Enter"){const l=(i=this.state.showInputPrompt)==null?void 0:i.callback,c=(r=this.state.showInputPrompt)==null?void 0:r.value;l&&l(c===void 0?null:c),this.setState({showInputPrompt:null})}},onChange:s=>{var r,l;const i={...this.state.showInputPrompt};(r=this.state.showInputPrompt)!=null&&r.callback&&(i.callback=(l=this.state.showInputPrompt)==null?void 0:l.callback),i.value=s.target.value,this.setState({showInputPrompt:i})}})}),m.jsxs(Bt,{children:[m.jsx(Ue,{variant:"contained",disabled:!this.state.showInputPrompt.value,onClick:()=>{var r,l;const s=(r=this.state.showInputPrompt)==null?void 0:r.callback,i=(l=this.state.showInputPrompt)==null?void 0:l.value;s&&s(i===void 0?null:i),this.setState({showInputPrompt:null})},color:"primary",startIcon:m.jsx(Xo,{}),children:x.I18n.t("Apply")}),m.jsx(Ue,{color:"grey",variant:"contained",onClick:()=>{var i;const s=(i=this.state.showInputPrompt)==null?void 0:i.callback;s&&s(null),this.setState({showInputPrompt:null})},startIcon:m.jsx(so,{}),children:x.I18n.t("Close")})]})]},"inputDialog"):null}render(){return this.state.languageBlocklyLoaded&&this.state.languageOwnLoaded?(this.didUpdate=setTimeout(()=>{this.didUpdate=null,this.componentDidUpdate()},100),[m.jsx("div",{ref:s=>this.blockly=s,style:{width:"100%",height:"100%",position:"relative"}},"blocklyDOM"),this.renderDialogPrompt(),this.renderMessageDialog(),this.renderErrorDialog(),this.renderExportDialog(),this.renderImportDialog()]):null}}const CO=Object.freeze(Object.defineProperty({__proto__:null,default:Xe},Symbol.toStringTag,{value:"Module"})),TO="_nameCard_15el3_28",SO="_iconThemCard_15el3_40",EO="_iconThemCardSelectable_15el3_49",IO="_iconHelp_15el3_53",xO="_blockName_15el3_64",DO="_controlMenuTop_15el3_123",AO="_debugInfo_15el3_132",OO="_tagCard_15el3_142",RO="_displayFlex_15el3_161",MO="_blockMarginTop_15el3_166",NO="_nameBlock_15el3_167",LO="_frontText_15el3_171",PO="_backText_15el3_177",BO="_iconTag_15el3_181",jO="_displayItalic_15el3_191",Re={nameCard:TO,iconThemCard:SO,iconThemCardSelectable:EO,iconHelp:IO,blockName:xO,controlMenuTop:DO,debugInfo:AO,tagCard:OO,displayFlex:RO,blockMarginTop:MO,nameBlock:NO,frontText:LO,backText:PO,iconTag:BO,displayItalic:jO},FO="_root_1dr6a_1",zO="_square_1dr6a_11",UO="_icon_1dr6a_16",Cg={root:FO,square:zO,icon:UO},Xr=({fullWidth:a,size:s,onClick:i,style:r,className:l,value:c,square:d,icon:h})=>m.jsx(Ue,{variant:"outlined",color:"primary",onClick:i,fullWidth:a,style:r,className:x.Utils.clsx(Cg.root,l,d?Cg.square:""),size:s||"medium",children:h?m.jsx(x.Icon,{className:Cg.icon,src:h}):c}),HO="_root_1ucda_1",WO={root:HO},GO=({size:a,value:s,title:i,onChange:r,className:l,customValue:c,disabled:d})=>{const[h,p]=kt(!1);return m.jsxs(m.Fragment,{children:[m.jsx(Yr,{disabled:d,checked:!!(c?s:h),className:x.Utils.clsx(WO.root,l),onChange:f=>{c&&p(f.target.checked),r&&r(f.target.checked)},size:a||"medium"}),i||null]})},EC=gm(GO),VO="_root_19roy_1",gw={root:VO},Ei=a=>{const[s,i]=kt(""),{value:r,type:l,error:c,className:d,icon:h,label:p,style:f,onChange:b,fullWidth:y,autoComplete:w,customValue:v,autoFocus:_,rows:$,size:T,variant:S,multiline:E,disabled:D}=Object.assign({value:"",type:"text",error:"",className:null,table:!1,native:{},variant:"standard",size:"medium",component:null,styleComponentBlock:null,fullWidth:!1,autoComplete:"",customValue:!1,autoFocus:!1,rows:1},a);return m.jsx(Eo,{error:!!c,autoFocus:_,fullWidth:y,label:p,disabled:D,variant:S,multiline:E,rows:$,value:v?r:s,type:l,helperText:c,style:f,className:x.Utils.clsx(gw.root,d),autoComplete:w,onChange:R=>{!v&&i(R.target.value),b&&b(R.target.value)},slotProps:{input:{endAdornment:h?m.jsx(Ow,{position:"end",children:m.jsx(x.Icon,{className:gw.icon,src:h})}):null}},margin:"normal",size:T})},YO={formControl:{m:"10px 0","& .MuiFormControl-marginNormal":{mt:0,mb:0},"& > *":{color:"#2d0440 !important"},"& .MuiSelect-icon":{color:"#81688c"},"& label.Mui-focused":{color:"#81688c"},"& .MuiInput-underline:after":{borderBottomColor:"#510573"},"& .MuiInput-underline:before":{borderBottomColor:"#81688c"},"& .MuiInput-underline:hover:before":{borderBottomColor:"#81688c"}}},KO=({multiple:a,value:s,customValue:i,socket:r,title:l,attr:c,adapter:d,style:h,onChange:p,onInstanceHide:f})=>{const[b,y]=kt(s||"test1"),[w,v]=kt([]);return Lt(()=>{r==null||r.getAdapterInstances(d).then(_=>{const $=_.map(T=>({value:T._id.replace("system.adapter.",""),title:T._id.replace("system.adapter.","")}));$.length===1?f($[0].value):$.unshift({value:d,title:x.I18n.t("All")}),v($)})},[r,d,f]),m.jsxs(Di,{sx:YO.formControl,fullWidth:!0,style:h,children:[m.jsx(Ai,{variant:"standard",value:(i?s:b)||"_",fullWidth:!0,multiple:a,renderValue:_=>a&&Array.isArray(_)?_.join(", "):_,onChange:_=>{!i&&y(_.target.value),p(_.target.value)},input:c?m.jsx(Pn,{name:c,id:`${c}-helper`}):m.jsx(Pn,{name:c}),children:w.map(_=>m.jsx(tt,{style:{placeContent:"space-between"},value:_.value||"_",children:x.I18n.t(_.title)},`key-${_.value}`))}),l?m.jsx(Mw,{children:x.I18n.t(l)}):null]})},JO="_modalWrapper_587ci_33",XO="_modalDialog_587ci_40",mw={modalWrapper:JO,modalDialog:XO},hm=({onClose:a,children:s,titleButtonApply:i,titleButtonClose:r,onApply:l,className:c,textInput:d,defaultValue:h,disabled:p})=>{const[f,b]=kt(h||""),[y]=kt(h||"");return m.jsxs(Pt,{open:!0,maxWidth:"md",disableEscapeKeyDown:!1,onClose:a,classes:{paper:mw.modalDialog},className:mw.modalWrapper,children:[m.jsxs(Wt,{children:[d&&m.jsx(Ei,{className:c,autoComplete:"off",fullWidth:!0,variant:"outlined",size:"medium",rows:10,multiline:!0,value:f,onChange:b,customValue:!0}),!d&&s]}),m.jsxs(Bt,{children:[m.jsx(Ue,{disabled:p===void 0?y===f:p,onClick:()=>l(d?f:null),variant:"contained",color:"primary",children:x.I18n.t(i||"Ok")}),m.jsx(Ue,{color:"grey",onClick:a,variant:"contained",children:x.I18n.t(r||"Cancel")})]})]})},qO="_root_15mo1_1",ZO={root:qO},QO=({multiple:a,value:s,customValue:i,title:r,attr:l,options:c,style:d,onChange:h,className:p,doNotTranslate:f,doNotTranslate2:b})=>{const[y,w]=kt(s===void 0?c[0].value:s),v=i?s:y,_=v===""||v===null||v===void 0?"_":v;return m.jsxs(Di,{variant:"standard",className:x.Utils.clsx(ZO.root,p),fullWidth:!0,style:d,children:[m.jsxs(Ai,{variant:"standard",value:_,fullWidth:!0,multiple:a,renderValue:$=>{if(a&&Array.isArray($)){$.sort();let S=$.indexOf("0");S!==-1&&($.splice(S,1),$.push("0")),S=$.indexOf("_"),S!==-1&&($.splice(S,1),$.unshift("_"));const E=c.find(R=>R.only);return E&&$.includes(E.value)?E.titleShort?f?E.titleShort:x.I18n.t(E.titleShort):f?E.title:x.I18n.t(E.title):$.map(R=>c.find(L=>L.value===R||R==="_"&&L.value==="")||R).map(R=>typeof R=="object"?R.titleShort?f?R.titleShort:x.I18n.t(R.titleShort):f?R.title:x.I18n.t(R.title):f?R:x.I18n.t(R)).join(", ")}const T=c?c.find(S=>S.value===$||$==="_"&&S.value===""):null;return T!=null&&T.title?f?T==null?void 0:T.title:x.I18n.t(T==null?void 0:T.title):$},onChange:$=>{if(i||w($.target.value),a){const T=$.target.value,S=c.find(E=>E.only);if(S){const E=S.value;if(T.length===c.length-1&&T.includes(E))return h(T.filter(D=>D!==E),l);if(T.includes(E))return h(c.map(D=>D.value),l)}}h($.target.value,l)},input:l?m.jsx(Pn,{name:l,id:`${l}-helper`}):m.jsx(Pn,{name:l}),children:[!a&&(c==null?void 0:c.map($=>m.jsxs(tt,{style:{placeContent:"space-between"},value:$.value===""||$.value===null||$.value===void 0?"_":$.value,children:[f?$.title:x.I18n.t($.title),$.title2&&m.jsx("div",{children:b?$.title2:x.I18n.t($.title2)})]},`key-${$.value}`))),a&&(c==null?void 0:c.map($=>m.jsxs(tt,{style:{placeContent:"space-between"},value:$.value||"_",children:[f?$.title:x.I18n.t($.title)," ",m.jsx(EC,{customValue:!0,value:s==null?void 0:s.includes($.value)})]},`key-${$.value}`)))]}),r?m.jsx(Mw,{children:x.I18n.t(r)}):null]})},eR="_root_1gt4d_1",tR="_mark_1gt4d_27",fw={root:eR,mark:tR},sR=({size:a,value:s,style:i,onChange:r,className:l,customValue:c,min:d,max:h,step:p,unit:f})=>{const[b,y]=kt(0);d=d!==void 0?d:0,h=h!==void 0?h:0,p=p!==void 0?p:(h-d)/100;const w=[{value:d,label:d+(f||"")},{value:h,label:h+(f||"")}];return m.jsx(qT,{defaultValue:c?s:b,"aria-labelledby":"discrete-slider",valueLabelDisplay:"auto",classes:{mark:fw.mark},marks:w,step:p,min:d,max:h,value:c?s:b,style:i,className:x.Utils.clsx(fw.root,l),onChange:(v,_)=>{Array.isArray(_)?(!c&&y(_[0]),r(_[0])):(!c&&y(_),r(_))},size:a||"medium"})},oR="_root_rzul6_1",iR={root:oR},nR=({label:a,size:s,value:i,style:r,onChange:l,className:c,customValue:d})=>{const[h,p]=kt(!1);return m.jsx(Bg,{className:iR.root,control:m.jsx(Nw,{checked:d?i:h,style:r,className:c,onChange:f=>{d||p(f.target.checked),l(f.target.checked)},size:s||"medium"}),label:a??"all"})},rR=gm(nR),aR="_root_135pm_1",lR={root:aR},cR=({value:a,style:s,onChange:i,className:r})=>m.jsx(Eo,{variant:"standard",id:"time",type:"time",onChange:l=>i(l.currentTarget.value),value:a,className:x.Utils.clsx(lR.root,r),fullWidth:!0,style:s,slotProps:{htmlInput:{step:300},inputLabel:{shrink:!0}}}),uR="_root_135pm_1",hc={root:uR},Tg=[31,29,31,30,31,30,31,31,30,31,30,31],dR=({value:a,onChange:s,className:i,style:r})=>{const[l,c]=(a||"01.01").toString().split(".");let d=parseInt(c,10)||0,h=parseInt(l,10)||0;h>12?h=12:h<0&&(h=0),d>Tg[h]?d=Tg[h]:d<0&&(d=0);const p=[];for(let f=0;fs(`${f.target.value.toString().padStart(2,"0")}.${d.toString().padStart(2,"0")}`),value:h,children:[m.jsx(tt,{style:{placeContent:"space-between"},value:0,children:x.I18n.t("Any month")},0),m.jsx(tt,{style:{placeContent:"space-between"},value:1,children:x.I18n.t("January")},1),m.jsx(tt,{style:{placeContent:"space-between"},value:2,children:x.I18n.t("February")},2),m.jsx(tt,{style:{placeContent:"space-between"},value:3,children:x.I18n.t("March")},3),m.jsx(tt,{style:{placeContent:"space-between"},value:4,children:x.I18n.t("April")},4),m.jsx(tt,{style:{placeContent:"space-between"},value:5,children:x.I18n.t("May")},5),m.jsx(tt,{style:{placeContent:"space-between"},value:6,children:x.I18n.t("June")},6),m.jsx(tt,{style:{placeContent:"space-between"},value:7,children:x.I18n.t("July")},7),m.jsx(tt,{style:{placeContent:"space-between"},value:8,children:x.I18n.t("August")},8),m.jsx(tt,{style:{placeContent:"space-between"},value:9,children:x.I18n.t("September")},9),m.jsx(tt,{style:{placeContent:"space-between"},value:10,children:x.I18n.t("October")},10),m.jsx(tt,{style:{placeContent:"space-between"},value:11,children:x.I18n.t("November")},11),m.jsx(tt,{style:{placeContent:"space-between"},value:12,children:x.I18n.t("December")},12)]})}),m.jsx(Di,{variant:"standard",className:x.Utils.clsx(hc.root,i),style:r,children:m.jsxs(Ai,{variant:"standard",className:x.Utils.clsx(hc.root,i),margin:"dense",label:x.I18n.t("Date"),onChange:f=>s(`${h.toString().padStart(2,"0")}.${f.target.value.toString().padStart(2,"0")}`),value:d,children:[m.jsx(tt,{style:{placeContent:"space-between"},value:0,children:x.I18n.t("Any")},"A"),p.map(f=>m.jsx(tt,{style:{placeContent:"space-between"},value:f,children:f},f))]})})]})},Sg={},hR={Shuffle:vx,Apps:ax,Functions:px,Language:CS,AddBox:rx,Pause:vc,Subject:_x,PlayForWork:$x,Brightness3:lx,HelpOutline:gk,Storage:yx,AccessTime:nx,PlayArrow:Yg,FlashOn:dx};function $w({iconName:a,className:s,adapter:i,socket:r,onClick:l,style:c}){const[d,h]=kt("");if(Lt(()=>{i&&r&&(Sg[i]instanceof Promise||(Sg[i]=r.getObject(`system.adapter.${i}`)),Sg[i].then(f=>{var b;return((b=f==null?void 0:f.common)==null?void 0:b.icon)&&h(`../../adapter/${i}/${f.common.icon}`)}))},[i,r]),i)return m.jsx("img",{onClick:f=>l&&l(f),src:d||"",className:s,style:c,alt:""});const p=a&&hR[a]||TS;return m.jsx(p,{className:s,style:c,onClick:f=>l&&l(f)})}let Eg;function pR(a){return Eg=Eg||x.I18n.getLanguage(),a&&typeof a=="object"?a[Eg]||a.en:a||""}function Ln(a){return a===null?"null":a===void 0?"undefined":Array.isArray(a)?a.join(", "):typeof a=="object"?JSON.stringify(a):a.toString()}class at extends Dw{debugHideTimeout=null;lastObjectIdChange=0;enableSimulationProcessing=!1;lastDebugMessage=0;debugMessageTimeout=null;static getStaticData(){return{acceptedBy:"actions",name:"Not found",id:"ActionEmpty",icon:"Shuffle"}}static compile(s,i){return""}constructor(s,i){super(s),i||={};const r=s.settings||{tagCard:i.tagCardArray?typeof i.tagCardArray[0]!="string"?i.tagCardArray[0].title:i.tagCardArray[0]:""};!r.tagCard&&i.tagCardArray&&(r.tagCard=typeof i.tagCardArray[0]!="string"?i.tagCardArray[0].title:i.tagCardArray[0]),this.state={inputs:i.inputs||s.inputs||[],name:i.name||s.name||"",icon:i.icon||s.icon||"",adapter:i.adapter||s.adapter||"",helpDialog:i.helpDialog||s.helpDialog||"",tagCardArray:i.tagCardArray||[],openTagMenu:!1,openModal:!1,iconTag:!1,error:"",helpText:"",instanceSelectionOptions:[],instanceSelectionDef:"",hideAttributes:[],settings:r,debugMessage:null,enableSimulation:this.props.enableSimulation}}componentWillUnmount(){this.debugMessageTimeout&&(clearTimeout(this.debugMessageTimeout),this.debugMessageTimeout=null),this.debugHideTimeout&&(clearTimeout(this.debugHideTimeout),this.debugHideTimeout=null)}onTagChange(s,i,r,l,c){let d=!1;const h=JSON.parse(JSON.stringify(this.state.settings));this.state.inputs.forEach(p=>{const f=p.attr,b=p.defaultValue;f&&b!==void 0&&h[f]===void 0&&(d=!0,h[f]=b)}),d?(this.setState({settings:h},()=>i==null?void 0:i()),this.props.onChange(h)):i&&i()}onUpdate(){}onValueChanged(s,i){}renderText(s,i,r){const{className:l}=this.props,{attr:c,frontText:d,backText:h,nameBlock:p,name:f,doNotTranslate:b,doNotTranslateBack:y}=s;return m.jsxs(Og,{children:[m.jsxs("div",{className:x.Utils.clsx(Re.displayFlex,Re.blockMarginTop),children:[d&&m.jsx("div",{className:Re.frontText,children:b?d:x.I18n.t(d)}),m.jsx(Ei,{className:l,autoComplete:"off",label:pR(f),variant:"outlined",size:"small",fullWidth:!0,value:i,onChange:r,customValue:!0}),h&&m.jsx("div",{className:Re.backText,children:y?h:x.I18n.t(h)})]}),p&&m.jsx("div",{className:Re.nameBlock,children:x.I18n.t(p)})]},c)}renderSwitch(s,i,r){const{className:l}=this.props,{attr:c,frontText:d,backText:h,nameBlock:p,doNotTranslate:f,doNotTranslateBack:b}=s;return m.jsxs("div",{children:[m.jsxs("div",{className:x.Utils.clsx(Re.displayFlex,Re.blockMarginTop),children:[d&&m.jsx("div",{className:Re.frontText,children:f?d:x.I18n.t(d)}),m.jsx(rR,{className:l,label:"",customValue:!0,value:i,onChange:r}),h&&m.jsx("div",{className:Re.backText,children:b?h:x.I18n.t(h)})]}),p&&m.jsx("div",{className:Re.nameBlock,children:x.I18n.t(p)})]},c)}renderNameText({attr:s,signature:i,doNotTranslate:r,defaultValue:l},c){return m.jsx("div",{className:x.Utils.clsx(i?Re.displayItalic:Re.displayFlex,Re.blockMarginTop),children:c?r?c:x.I18n.t(c):r?l:x.I18n.t(l)},s)}renderNumber(s,i,r){const{className:l}=this.props,{settings:c}=this.state,{attr:d,backText:h,frontText:p,openCheckbox:f,doNotTranslate:b,doNotTranslateBack:y}=s;let w=!0;return f&&(w=typeof c.offset=="boolean"?c.offset:!0),w?m.jsxs("div",{className:x.Utils.clsx(Re.displayFlex,Re.blockMarginTop),children:[p&&m.jsx("div",{className:Re.frontText,children:b?p:x.I18n.t(p)}),m.jsx(Ei,{className:x.Utils.clsx(l,s.className),fullWidth:!0,autoComplete:"off",label:s.noHelperText?"":"number",variant:"outlined",size:"small",type:"number",value:i,onChange:r,customValue:!0}),h&&m.jsx("div",{className:Re.backText,children:y?h:x.I18n.t(h)})]},d):null}renderColor(s,i,r){const{className:l}=this.props,{attr:c,backText:d,frontText:h,doNotTranslate:p,doNotTranslateBack:f}=s;return m.jsxs("div",{className:x.Utils.clsx(Re.displayFlex,Re.blockMarginTop),children:[h&&m.jsx("div",{className:Re.frontText,children:p?h:x.I18n.t(h)}),m.jsx(Ei,{className:l,autoComplete:"off",fullWidth:!0,variant:"outlined",size:"small",type:"color",value:i,onChange:r}),d&&m.jsx("div",{className:Re.backText,children:f?d:x.I18n.t(d)})]},c)}renderCheckbox(s,i,r){const{className:l}=this.props,{settings:c}=this.state,{attr:d,backText:h,frontText:p,defaultValue:f,doNotTranslate:b,doNotTranslateBack:y}=s;return m.jsxs("div",{className:Re.displayFlex,children:[p&&m.jsx("div",{className:Re.frontText,children:b?p:x.I18n.t(p)}),m.jsx(EC,{className:l,size:"small",value:typeof c[d]=="boolean"?!!c[d]:!!f,customValue:!0,onChange:r}),h&&m.jsx("div",{onClick:()=>r(typeof c[d]=="boolean"?!c[d]:!f),className:Re.backText,children:y?h:x.I18n.t(h)})]},d)}renderSlider(s,i,r){const{className:l}=this.props,{attr:c,frontText:d,backText:h,nameBlock:p,min:f,max:b,step:y,unit:w,doNotTranslate:v,doNotTranslateBack:_}=s;return m.jsxs("div",{children:[m.jsxs("div",{className:Re.displayFlex,style:{marginRight:20},children:[d&&m.jsx("div",{className:Re.frontText,children:v?d:x.I18n.t(d)}),m.jsx(sR,{customValue:!0,min:f,max:b,step:y,unit:w,className:l,autoComplete:"off",label:"number",variant:"outlined",size:"small",value:i,onChange:$=>{console.log($),r($)}}),h&&m.jsx("div",{style:{marginLeft:20},className:Re.backText,children:_?h:x.I18n.t(h)})]}),p&&m.jsx("div",{className:Re.nameBlock,children:x.I18n.t(p)})]},c)}renderButton(s,i,r){const{className:l}=this.props,{attr:c,frontText:d,backText:h,doNotTranslate:p,doNotTranslateBack:f}=s;return m.jsxs("div",{className:x.Utils.clsx(Re.displayFlex,Re.blockMarginTop),children:[d&&m.jsx("div",{className:Re.frontText,children:p?d:x.I18n.t(d)}),m.jsx(Xr,{fullWidth:!0,value:i.toString(),className:l,onClick:()=>r(i)}),h&&m.jsx("div",{className:Re.backText,children:f?h:x.I18n.t(h)})]},c)}async findIcon(s){var i;if(!s)return null;if((i=s.common)!=null&&i.icon)return x.getSelectIdIcon(s,"../..");if(s.type==="state"||s.type==="channel"){const r=s._id.split(".");r.pop();const l=r.join(".");try{const c=await this.props.socket.getObject(l);return await this.findIcon(c)}catch{return null}}return null}renderObjectID(s,i,r){const{attr:l,openCheckbox:c,checkReadOnly:d}=s,{settings:h}=this.state,p=this.state[`showSelectId${l}`],{className:f,socket:b,style:y}=this.props;let w=!0;c&&(w=typeof h.offset=="boolean"?h.offset:!0);const v=h[l],_=v?this.state[v]:void 0;return v&&!_&&_!==!1&&setTimeout(async $=>{var D;const T=await b.getObject(i),S=await this.findIcon(T),E={[$]:T||!1,[`${$}___icon`]:S,error:d&&this.lastObjectIdChange&&Date.now()-this.lastObjectIdChange<1e3&&((D=T==null?void 0:T.common)==null?void 0:D.write)===!1?x.I18n.t("Read only ID selected: %s",h[$]):""};this.setState(E)},0,v),w?m.jsxs("div",{className:Re.blockMarginTop,children:[m.jsxs("div",{className:Re.displayFlex,children:[s.title?m.jsx("div",{children:x.I18n.t(s.title)}):null,m.jsx(Ei,{className:f,style:y,autoComplete:"off",fullWidth:!0,disabled:!0,variant:"outlined",size:"small",value:i,customValue:!0}),m.jsx(Xr,{icon:this.state[`${v}___icon`],square:!0,style:{...y||void 0,marginLeft:7},value:"...",className:f,onClick:()=>{const $={};$[`showSelectId${l}`]=!0,this.setState($)}})]}),_?m.jsx("div",{className:x.Utils.clsx(Re.nameBlock,Re.displayItalic),children:x.Utils.getObjectNameFromObj(_,x.I18n.getLanguage())}):null,p?m.jsx(x.DialogSelectID,{theme:this.props.theme,imagePrefix:"../..",dialogName:"javascript",themeType:x.Utils.getThemeName(),socket:b,selected:i,onClose:()=>{const $={};$[`showSelectId${l}`]=!1,this.setState($)},onOk:($,T)=>{const S={};S[`showSelectId${l}`]=!1;const E=Array.isArray($)?$[0]:$;this.setState(S,async()=>{var R,L,H,G,z,Z,he,Ce,M,Y;const D=E?await b.getObject(E):void 0;this.lastObjectIdChange=Date.now(),r({[l]:$,[`${l}Role`]:(R=D==null?void 0:D.common)==null?void 0:R.role,[`${l}Type`]:(L=D==null?void 0:D.common)==null?void 0:L.type,[`${l}Unit`]:(H=D==null?void 0:D.common)==null?void 0:H.unit,[`${l}States`]:(G=D==null?void 0:D.common)==null?void 0:G.states,[`${l}Min`]:(z=D==null?void 0:D.common)==null?void 0:z.min,[`${l}Max`]:(Z=D==null?void 0:D.common)==null?void 0:Z.max,[`${l}Step`]:(he=D==null?void 0:D.common)==null?void 0:he.step,[`${l}Def`]:(Ce=D==null?void 0:D.common)==null?void 0:Ce.def,[`${l}Write`]:(M=D==null?void 0:D.common)==null?void 0:M.write,[`${l}Read`]:(Y=D==null?void 0:D.common)==null?void 0:Y.read},()=>this.props.setOnUpdate&&this.props.setOnUpdate(!0))})}}):null]},l):null}renderIconTag(){return m.jsx("div",{className:Re.iconTag,onClick:s=>{this.state.settings.tagCard&&(this.state.tagCardArray.length<3?this.onChangeTag():this.setState({openTagMenu:s.currentTarget}))},children:this.state.settings.tagCard})}renderTime(s,i,r){const{attr:l,backText:c,frontText:d,doNotTranslate:h,doNotTranslateBack:p}=s;return m.jsxs("div",{className:Re.displayFlex,style:{whiteSpace:"nowrap"},children:[d&&m.jsx("div",{className:Re.frontText,children:h?d:x.I18n.t(d)}),m.jsx(cR,{value:i,onChange:r}),c&&m.jsx("div",{className:Re.backText,children:p?c:x.I18n.t(c)})]},l)}renderSelect(s,i,r){const{className:l,style:c}=this.props,{name:d,options:h,frontText:p,backText:f,attr:b,multiple:y,doNotTranslate:w,doNotTranslate2:v,doNotTranslateBack:_}=s;return m.jsxs("div",{className:x.Utils.clsx(Re.displayFlex,Re.blockMarginTop),style:{whiteSpace:"nowrap"},children:[p&&m.jsx("div",{className:Re.frontText,children:x.I18n.t(p)}),m.jsx(QO,{attr:b,doNotTranslate:w,doNotTranslate2:v,title:d,className:l,style:c,options:h,value:i,onChange:r,multiple:y,customValue:!0}),f&&m.jsx("div",{className:Re.backText,children:_?f:x.I18n.t(f)})]},b)}renderInstance(s,i,r){const{socket:l}=this.props,{name:c,frontText:d,backText:h,attr:p,adapter:f,doNotTranslate:b,doNotTranslateBack:y}=s;return this.state.hideAttributes.includes(p)?null:m.jsxs("div",{className:x.Utils.clsx(Re.displayFlex,Re.blockMarginTop),style:{whiteSpace:"nowrap"},children:[d&&m.jsx("div",{className:Re.frontText,children:b?d:x.I18n.t(d)}),m.jsx(KO,{attr:p,socket:l,adapter:f,title:c,value:i,onChange:w=>{r(Array.isArray(w)?w[0]:w)},customValue:!0,onInstanceHide:w=>this.setState({hideAttributes:[...this.state.hideAttributes,p]},()=>r(w))}),h&&m.jsx("div",{className:Re.backText,children:y?h:x.I18n.t(h)})]},p)}renderDialog(s){const{onShowDialog:i,frontText:r,backText:l,attr:c,icon:d,doNotTranslate:h,doNotTranslateBack:p}=s;return m.jsxs("div",{className:x.Utils.clsx(Re.displayFlex,Re.blockMarginTop),style:{whiteSpace:"nowrap"},children:[r&&m.jsx("div",{className:Re.frontText,children:h?r:x.I18n.t(r)}),m.jsx($w,{iconName:d,className:x.Utils.clsx(Re.iconDialog),onClick:()=>i&&i()}),l&&m.jsx("div",{className:Re.backText,children:p?l:x.I18n.t(l)})]},c)}renderModalInput(s,i,r){const{openModal:l}=this.state,{className:c}=this.props,{attr:d,nameBlock:h,frontText:p,backText:f,noTextEdit:b,doNotTranslate:y,doNotTranslateBack:w}=s;return m.jsxs("div",{children:[m.jsxs("div",{className:x.Utils.clsx(Re.displayFlex,Re.blockMarginTop),children:[p&&m.jsx("div",{className:Re.frontText,children:y?p:x.I18n.t(p)}),m.jsx(Ei,{disabled:!!b,className:c,autoComplete:"off",fullWidth:!0,variant:"outlined",size:"small",value:i,onChange:r,customValue:!0}),m.jsx(Xr,{square:!0,style:{marginLeft:5},value:"...",className:c,onClick:()=>this.setState({openModal:!0})}),f&&m.jsx("div",{className:Re.backText,children:w?f:x.I18n.t(f)})]}),l?m.jsx(hm,{onApply:v=>this.setState({openModal:!1},()=>v!=null&&r(v)),onClose:()=>this.setState({openModal:!1}),defaultValue:i,textInput:!0}):null,h&&m.jsx("div",{className:Re.nameBlock,children:x.I18n.t(h)})]},d)}renderDate(s,i,r){const{attr:l,backText:c,frontText:d,doNotTranslate:h,doNotTranslateBack:p}=s;return m.jsxs("div",{className:Re.displayFlex,style:{whiteSpace:"nowrap"},children:[d&&m.jsx("div",{className:Re.frontText,children:h?d:x.I18n.t(d)}),m.jsx(dR,{value:i,onChange:r}),c&&m.jsx("div",{className:Re.backText,children:p?c:x.I18n.t(c)})]},l)}static getReplacesInText(s){var r;let i="";return(r=s.trigger)!=null&&r.oidType?i=".replace(/%s/g, obj.state.val).replace(/%id/g, obj.id).replace(/%name/g, obj.common && obj.common.name).replace(/%old/g, obj.oldState.val)":s.conditionsStates.length&&(i=`.replace(/%s/g, ${s.conditionsStates[0].name}).replace(/%id/g, "${s.conditionsStates[0].id}")`),i}renderTags(){const{tagCardArray:s,openTagMenu:i}=this.state,{tagCard:r}=this.state.settings;let l=r!=="="&&r!=="<>"&&r!==">="&&r!=="()"&&r!=="."&&r!=="<="&&r!=="<"&&r!==">"&&r?x.I18n.t(r):r;return s.length>=3&&(l=m.jsxs("div",{children:[m.jsx("div",{"aria-controls":"simple-menu","aria-haspopup":"true",onClick:c=>{this.setState({openTagMenu:c.currentTarget},()=>{this.props.isTourOpen&&this.props.tourStep===Ms.openTagsMenu&&setTimeout(()=>this.props.setTourStep&&this.props.setTourStep(Ms.selectIntervalTag),300)})},children:l}),m.jsx(kc,{id:"simple-menu",anchorEl:i,keepMounted:!0,open:!!i,onClose:()=>this.setState({openTagMenu:null}),children:s.map((c,d)=>{let h;return typeof c!="string"?h=c.title:h=c,m.jsxs(tt,{selected:h===r,className:`tag-card-${h}`,style:{placeContent:"space-between"},onClick:p=>{p.stopPropagation(),this.props.isTourOpen&&(this.props.tourStep===Ms.openTagsMenu||this.props.tourStep===Ms.selectIntervalTag)&&h==="interval"&&setTimeout(()=>{var b,y;return(y=(b=this.props).setTourStep)==null?void 0:y.call(b,Ms.selectActions)},500);const f=JSON.parse(JSON.stringify(this.state.settings));f.tagCard=h,this.setState({openTagMenu:null,settings:f},()=>{this.props.onChange(this.state.settings),this.onTagChange(this.state.settings.tagCard)})},children:[h.search(/>|<|<>|<=|>=|=/)!==-1?h:x.I18n.t(h),typeof c!="string"&&c.title2&&m.jsx("div",{style:{marginLeft:4},children:x.I18n.t(c.title2)})]},`${h}_${d}`)})})]})),l}getData(){return{acceptedBy:"triggers",name:"",id:""}}onChangeTag(){const{tagCardArray:s,settings:i,settings:{tagCard:r}}=this.state;let l;if(typeof s[0]!="string"?l=s.map(c=>c.title):l=[...s],r&&l.length<3){const c={...i},d=l[(l.indexOf(r)+1)%l.length];c.tagCard=d,this.setState({settings:c},()=>{this.props.onChange(c),this.onTagChange(d)})}}componentDidMount(){this.onTagChange()}componentDidUpdate(){this.props.acceptedBy!=="triggers"&&this.props.onUpdate&&setTimeout(()=>this.onUpdate(),0)}onChangeInput(s){return(i,r,l)=>{const c=JSON.parse(JSON.stringify(this.state.settings));typeof i=="object"&&(!r||typeof r=="function")?(Object.keys(i).forEach(d=>c[d]=i[d]),typeof r=="function"&&(l=r,r=void 0)):c[r||s]=i,c.id=this.getData().id,c._id=this.props._id,this.setState({settings:c},()=>{this.onValueChanged(i,r||s),this.props.onChange(c),l==null||l()})}}renderSpecific(){return null}renderDebug(s){return""}renderDebugInfo(){return this.state.debugMessage?m.jsx("div",{className:Re.debugInfo,style:{opacity:1,height:22,bottom:-22},children:this.renderDebug?this.renderDebug(this.state.debugMessage):x.I18n.t("executed")},this.state.debugMessage.ts):null}renderCron(s,i,r){return null}renderWizard(s,i,r){return null}renderWriteState(){return null}renderInputElement(s,i){const{nameRender:r,defaultValue:l,attr:c}=s,{settings:d}=this.state;let h=c?d[c]:void 0;switch(h===void 0&&(h=l),r){case"renderTime":return c?this.renderTime(s,h,this.onChangeInput(c)):m.jsx("div",{children:x.I18n.t("Invalid renderTime")},`invalid_${i}`);case"renderNameText":return this.renderNameText(s,l);case"renderSelect":return c?this.renderSelect(s,h,this.onChangeInput(c)):m.jsx("div",{children:x.I18n.t("Invalid renderSelect")},`invalid_${i}`);case"renderModalInput":return c?this.renderModalInput(s,h,this.onChangeInput(c)):m.jsx("div",{children:x.I18n.t("Invalid renderModalInput")},`invalid_${i}`);case"renderObjectID":return c?this.renderObjectID(s,h,this.onChangeInput(c)):m.jsx("div",{children:x.I18n.t("Invalid renderObjectID")},`invalid_${i}`);case"renderDialog":return c?this.renderDialog(s):m.jsx("div",{children:x.I18n.t("Invalid renderDialog")},`invalid_${i}`);case"renderInstance":return c?this.renderInstance(s,h,this.onChangeInput(c)):m.jsx("div",{children:x.I18n.t("Invalid renderInstance")},`invalid_${i}`);case"renderText":return c?this.renderText(s,h,this.onChangeInput(c)):m.jsx("div",{children:x.I18n.t("Invalid renderText")},`invalid_${i}`);case"renderSlider":return c?this.renderSlider(s,h,this.onChangeInput(c)):m.jsx("div",{children:x.I18n.t("Invalid renderSlider")},`invalid_${i}`);case"renderCheckbox":return c?this.renderCheckbox(s,h,this.onChangeInput(c)):m.jsx("div",{children:x.I18n.t("Invalid renderCheckbox")},`invalid_${i}`);case"renderButton":return c?this.renderButton(s,h,this.onChangeInput(c)):m.jsx("div",{children:x.I18n.t("Invalid renderButton")},`invalid_${i}`);case"renderColor":return c?this.renderColor(s,h,this.onChangeInput(c)):m.jsx("div",{children:x.I18n.t("Invalid renderColor")},`invalid_${i}`);case"renderSwitch":return c?this.renderSwitch(s,h,this.onChangeInput(c)):m.jsx("div",{children:x.I18n.t("Invalid renderSwitch")},`invalid_${i}`);case"renderDate":return c?this.renderDate(s,h,this.onChangeInput(c)):m.jsx("div",{children:x.I18n.t("Invalid renderDate")},`invalid_${i}`);case"renderCron":return c?this.renderCron(s,h,this.onChangeInput(c)):m.jsx("div",{children:x.I18n.t("Invalid renderCron")},`invalid_${i}`);case"renderWizard":return c?this.renderWizard(s,h,this.onChangeInput(c)):m.jsx("div",{children:x.I18n.t("Invalid renderWizard")},`invalid_${i}`);case"renderWriteState":return this.renderWriteState();case"renderNumber":return c?this.renderNumber(s,h,this.onChangeInput(c)):m.jsx("div",{children:x.I18n.t("Invalid renderNumber")},`invalid_${i}`);default:return this[r]?this[r](s,h,c?this.onChangeInput(c):null):m.jsx("div",{children:x.I18n.t("Invalid input type: %s",r)},`invalid_${i}`)}}render(){var w;const{inputs:s,name:i,icon:r,iconTag:l,settings:c,adapter:d,settings:{tagCard:h},helpDialog:p}=this.state,{socket:f,notFound:b}=this.props;this.state.settings&&!this.state.settings.tagCard&&((w=this.state.tagCardArray)!=null&&w.length)&&setTimeout(()=>{const v=JSON.parse(JSON.stringify(this.state.settings));v.tagCard=typeof this.state.tagCardArray[0]!="string"?this.state.tagCardArray[0].title:this.state.tagCardArray[0],this.setState({settings:v})},50),this.state.enableSimulation!==this.props.enableSimulation&&!this.enableSimulationProcessing&&(this.enableSimulationProcessing=!0,setTimeout(()=>{this.setState({enableSimulation:this.props.enableSimulation},()=>{this.enableSimulationProcessing=!1})},50));let y;if(this.props.onDebugMessage)for(let v=this.props.onDebugMessage.length-1;v>=0;v--){const _=this.props.onDebugMessage[v];if(_.blockId===this.props._id&&_.ts>this.lastDebugMessage&&_.ts>Date.now()-1e3){y=_;break}}return y&&(this.lastDebugMessage=y.ts,this.debugMessageTimeout&&clearTimeout(this.debugMessageTimeout),this.debugHideTimeout&&(clearTimeout(this.debugHideTimeout),this.debugHideTimeout=null),this.debugMessageTimeout=setTimeout(v=>{const _=JSON.parse(v),$=_.hideTimeout||5e3;this.debugMessageTimeout=null,this.setState({debugMessage:_},()=>{this.debugHideTimeout&&clearTimeout(this.debugHideTimeout),this.debugHideTimeout=setTimeout(()=>{this.debugHideTimeout=null,this.setState({debugMessage:null})},$)})},50,JSON.stringify(y))),m.jsxs(Og,{children:[l?this.renderIconTag():m.jsx($w,{iconName:r,className:x.Utils.clsx(Re.iconThemCard,h&&this.state.tagCardArray.length&&Re.iconThemCardSelectable),adapter:d,socket:f,onClick:v=>{h&&(this.state.tagCardArray.length<3?this.onChangeTag():this.setState({openTagMenu:v.currentTarget}))}}),m.jsxs("div",{className:Re.blockName,children:[m.jsxs("span",{className:Re.nameCard,children:[x.I18n.t(i),b?x.I18n.t("%s not found",c.id):"",p?m.jsx(qe,{className:Re.iconHelp,size:"small",onClick:()=>this.setState({helpText:x.I18n.t(p)}),children:m.jsx(gk,{})}):null]}),s.map((v,_)=>this.renderInputElement(v,_))]}),h&&m.jsx("div",{className:Re.controlMenuTop,style:{opacity:1,height:22,top:-22},children:m.jsx("div",{onClick:()=>this.onChangeTag(),className:x.Utils.clsx(Re.tagCard,"tag-card"),children:this.renderTags()})}),this.renderDebugInfo(),this.state.error?m.jsx(x.DialogError,{title:x.I18n.t("Warning"),text:this.state.error,onClose:()=>this.setState({error:""})}):null,this.state.helpText?m.jsx(x.DialogMessage,{title:x.I18n.t("Instructions"),text:this.state.helpText,onClose:()=>this.setState({helpText:""})}):null,this.renderSpecific()]})}}const bw={en:{name:"Google - English",engine:"google",params:[]},de:{name:"Google - Deutsch",engine:"google",params:[]},ru:{name:"Google - Русский",engine:"google",params:[]},it:{name:"Google - Italiano",engine:"google",params:[]},es:{name:"Google - Espaniol",engine:"google",params:[]},fr:{name:"Google - Français",engine:"google",params:[]},ru_YA:{name:"Yandex - Русский",engine:"yandex",params:["key","voice","emotion","ill","drunk","robot"],voice:["jane","zahar"],emotion:["none","good","neutral","evil","mixed"]},ru_YA_CLOUD:{name:"Yandex Cloud - Русский",engine:"yandexCloud",params:["key","folderID","voice","emotion"],voice:["alyss","oksana","jane","zahar"],emotion:["good","neutral","evil"]},"en-US":{name:"PicoTTS - Englisch US",engine:"PicoTTS",params:[]},"en-GB":{name:"PicoTTS - Englisch GB",engine:"PicoTTS",params:[]},"de-DE":{name:"PicoTTS - Deutsch",engine:"PicoTTS",params:[]},"it-IT":{name:"PicoTTS - Italiano",engine:"PicoTTS",params:[]},"es-ES":{name:"PicoTTS - Espaniol",engine:"PicoTTS",params:[]},"fr-FR":{name:"PicoTTS - Français",engine:"PicoTTS",params:[]},"ru-RU_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"ru-RU",ename:"Tatyana",ssml:!0,name:"Cloud - Русский - Татьяна"},"ru-RU_CLOUD_Male":{gender:"Male",engine:"cloud",params:["cloud"],language:"ru-RU",ename:"Maxim",ssml:!0,name:"Cloud - Русский - Максим"},"de-DE_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"de-DE",ename:"Marlene",ssml:!0,name:"Cloud - Deutsch - Marlene"},"de-DE_CLOUD_Male":{gender:"Male",engine:"cloud",params:["cloud"],language:"de-DE",ename:"Hans",ssml:!0,name:"Cloud - Deutsch - Hans"},"en-US_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"en-US",ename:"Salli",ssml:!0,name:"Cloud - en-US - Female - Salli"},"en-US_CLOUD_Male":{gender:"Male",engine:"cloud",params:["cloud"],language:"en-US",ename:"Joey",ssml:!0,name:"Cloud - en-US - Male - Joey"},"da-DK_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"da-DK",ename:"Naja",ssml:!0,name:"Cloud - da-DK - Female - Naja"},"da-DK_CLOUD_Male":{gender:"Male",engine:"cloud",params:["cloud"],language:"da-DK",ename:"Mads",ssml:!0,name:"Cloud - da-DK - Male - Mads"},"en-AU_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"en-AU",ename:"Nicole",ssml:!0,name:"Cloud - en-AU - Female - Nicole"},"en-AU_CLOUD_Male":{gender:"Male",engine:"cloud",params:["cloud"],language:"en-AU",ename:"Russell",ssml:!0,name:"Cloud - en-AU - Male - Russell"},"en-GB_CLOUD_Female_Amy":{gender:"Female",engine:"cloud",params:["cloud"],language:"en-GB",ename:"Amy",ssml:!0,name:"Cloud - en-GB - Female - Amy"},"en-GB_CLOUD_Male":{gender:"Male",engine:"cloud",params:["cloud"],language:"en-GB",ename:"Brian",ssml:!0,name:"Cloud - en-GB - Male - Brian"},"en-GB_CLOUD_Female_Emma":{gender:"Female",engine:"cloud",params:["cloud"],language:"en-GB",ename:"Emma",ssml:!0,name:"Cloud - en-GB - Female - Emma"},"en-GB-WLS_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"en-GB-WLS",ename:"Gwyneth",ssml:!0,name:"Cloud - en-GB-WLS - Female - Gwyneth"},"en-GB-WLS_CLOUD_Male":{gender:"Male",engine:"cloud",params:["cloud"],language:"en-GB-WLS",ename:"Geraint",ssml:!0,name:"Cloud - en-GB-WLS - Male - Geraint"},"cy-GB_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"cy-GB",ename:"Gwyneth",ssml:!0,name:"Cloud - cy-GB - Female - Gwyneth"},"cy-GB_CLOUD_Male":{gender:"Male",engine:"cloud",params:["cloud"],language:"cy-GB",ename:"Geraint",ssml:!0,name:"Cloud - cy-GB - Male - Geraint"},"en-IN_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"en-IN",ename:"Raveena",ssml:!0,name:"Cloud - en-IN - Female - Raveena"},"en-US_CLOUD_Male_Chipmunk":{gender:"Male",engine:"cloud",params:["cloud"],language:"en-US",ename:"Chipmunk",ssml:!0,name:"Cloud - en-US - Male - Chipmunk"},"en-US_CLOUD_Male_Eric":{gender:"Male",engine:"cloud",params:["cloud"],language:"en-US",ename:"Eric",ssml:!0,name:"Cloud - en-US - Male - Eric"},"en-US_CLOUD_Female_Ivy":{gender:"Female",engine:"cloud",params:["cloud"],language:"en-US",ename:"Ivy",ssml:!0,name:"Cloud - en-US - Female - Ivy"},"en-US_CLOUD_Female_Jennifer":{gender:"Female",engine:"cloud",params:["cloud"],language:"en-US",ename:"Jennifer",ssml:!0,name:"Cloud - en-US - Female - Jennifer"},"en-US_CLOUD_Male_Justin":{gender:"Male",engine:"cloud",params:["cloud"],language:"en-US",ename:"Justin",ssml:!0,name:"Cloud - en-US - Male - Justin"},"en-US_CLOUD_Female_Kendra":{gender:"Female",engine:"cloud",params:["cloud"],language:"en-US",ename:"Kendra",ssml:!0,name:"Cloud - en-US - Female - Kendra"},"en-US_CLOUD_Female_Kimberly":{gender:"Female",engine:"cloud",params:["cloud"],language:"en-US",ename:"Kimberly",ssml:!0,name:"Cloud - en-US - Female - Kimberly"},"es-ES_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"es-ES",ename:"Conchita",ssml:!0,name:"Cloud - es-ES - Female - Conchita"},"es-ES_CLOUD_Male":{gender:"Male",engine:"cloud",params:["cloud"],language:"es-ES",ename:"Enrique",ssml:!0,name:"Cloud - es-ES - Male - Enrique"},"es-US_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"es-US",ename:"Penelope",ssml:!0,name:"Cloud - es-US - Female - Penelope"},"es-US_CLOUD_Male":{gender:"Male",engine:"cloud",params:["cloud"],language:"es-US",ename:"Miguel",ssml:!0,name:"Cloud - es-US - Male - Miguel"},"fr-CA_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"fr-CA",ename:"Chantal",ssml:!0,name:"Cloud - fr-CA - Female - Chantal"},"fr-FR_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"fr-FR",ename:"Celine",ssml:!0,name:"Cloud - fr-FR - Female - Celine"},"fr-FR_CLOUD_Male":{gender:"Male",engine:"cloud",params:["cloud"],language:"fr-FR",ename:"Mathieu",ssml:!0,name:"Cloud - fr-FR - Male - Mathieu"},"is-IS_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"is-IS",ename:"Dora",ssml:!0,name:"Cloud - is-IS - Female - Dora"},"is-IS_CLOUD_Male":{gender:"Male",engine:"cloud",params:["cloud"],language:"is-IS",ename:"Karl",ssml:!0,name:"Cloud - is-IS - Male - Karl"},"it-IT_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"it-IT",ename:"Carla",ssml:!0,name:"Cloud - it-IT - Female - Carla"},"it-IT_CLOUD_Male":{gender:"Male",engine:"cloud",params:["cloud"],language:"it-IT",ename:"Giorgio",ssml:!0,name:"Cloud - it-IT - Male - Giorgio"},"nb-NO_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"nb-NO",ename:"Liv",ssml:!0,name:"Cloud - nb-NO - Female - Liv"},"nl-NL_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"nl-NL",ename:"Lotte",ssml:!0,name:"Cloud - nl-NL - Female - Lotte"},"nl-NL_CLOUD_Male":{gender:"Male",engine:"cloud",params:["cloud"],language:"nl-NL",ename:"Ruben",ssml:!0,name:"Cloud - nl-NL - Male - Ruben"},"pl-PL_CLOUD_Female_Agnieszka":{gender:"Female",engine:"cloud",params:["cloud"],language:"pl-PL",ename:"Agnieszka",ssml:!0,name:"Cloud - pl-PL - Female - Agnieszka"},"pl-PL_CLOUD_Male_Jacek":{gender:"Male",engine:"cloud",params:["cloud"],language:"pl-PL",ename:"Jacek",ssml:!0,name:"Cloud - pl-PL - Male - Jacek"},"pl-PL_CLOUD_Female_Ewa":{gender:"Female",engine:"cloud",params:["cloud"],language:"pl-PL",ename:"Ewa",ssml:!0,name:"Cloud - pl-PL - Female - Ewa"},"pl-PL_CLOUD_Male_Jan":{gender:"Male",engine:"cloud",params:["cloud"],language:"pl-PL",ename:"Jan",ssml:!0,name:"Cloud - pl-PL - Male - Jan"},"pl-PL_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"pl-PL",ename:"Maja",ssml:!0,name:"Cloud - pl-PL - Female - Maja"},"pt-BR_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"pt-BR",ename:"Vitoria",ssml:!0,name:"Cloud - pt-BR - Female - Vitoria"},"pt-BR_CLOUD_Male":{gender:"Male",engine:"cloud",params:["cloud"],language:"pt-BR",ename:"Ricardo",ssml:!0,name:"Cloud - pt-BR - Male - Ricardo"},"pt-PT_CLOUD_Male":{gender:"Male",engine:"cloud",params:["cloud"],language:"pt-PT",ename:"Cristiano",ssml:!0,name:"Cloud - pt-PT - Male - Cristiano"},"pt-PT_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"pt-PT",ename:"Ines",ssml:!0,name:"Cloud - pt-PT - Female - Ines"},"ro-RO_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"ro-RO",ename:"Carmen",ssml:!0,name:"Cloud - ro-RO - Female - Carmen"},"sv-SE_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"sv-SE",ename:"Astrid",ssml:!0,name:"Cloud - sv-SE - Female - Astrid"},"tr-TR_CLOUD_Female":{gender:"Female",engine:"cloud",params:["cloud"],language:"tr-TR",ename:"Filiz",ssml:!0,name:"Cloud - tr-TR - Female - Filiz"},"ru-RU_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"ru-RU",ename:"Tatyana",ssml:!0,name:"AWS Polly - Русский - Татьяна"},"ru-RU_AP_Male":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"ru-RU",ename:"Maxim",ssml:!0,name:"AWS Polly - Русский - Максим"},"de-DE_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"de-DE",ename:"Marlene",ssml:!0,name:"AWS Polly - Deutsch - Marlene"},"de-DE_AP_Female_Vicky":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"de-DE",ename:"Vicky",ssml:!0,name:"AWS Polly - Deutsch - Vicky"},"de-DE_AP_Male":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"de-DE",ename:"Hans",ssml:!0,name:"AWS Polly - Deutsch - Hans"},"en-US_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"en-US",ename:"Salli",ssml:!0,name:"AWS Polly - en-US - Female - Salli"},"en-US_AP_Male":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"en-US",ename:"Joey",ssml:!0,name:"AWS Polly - en-US - Male - Joey"},"da-DK_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"da-DK",ename:"Naja",ssml:!0,name:"AWS Polly - da-DK - Female - Naja"},"da-DK_AP_Male":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"da-DK",ename:"Mads",ssml:!0,name:"AWS Polly - da-DK - Male - Mads"},"en-AU_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"en-AU",ename:"Nicole",ssml:!0,name:"AWS Polly - en-AU - Female - Nicole"},"en-AU_AP_Male":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"en-AU",ename:"Russell",ssml:!0,name:"AWS Polly - en-AU - Male - Russell"},"en-GB_AP_Female_Amy":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"en-GB",ename:"Amy",ssml:!0,name:"AWS Polly - en-GB - Female - Amy"},"en-GB_AP_Male":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"en-GB",ename:"Brian",ssml:!0,name:"AWS Polly - en-GB - Male - Brian"},"en-GB_AP_Female_Emma":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"en-GB",ename:"Emma",ssml:!0,name:"AWS Polly - en-GB - Female - Emma"},"en-GB-WLS_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"en-GB-WLS",ename:"Gwyneth",ssml:!0,name:"AWS Polly - en-GB-WLS - Female - Gwyneth"},"en-GB-WLS_AP_Male":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"en-GB-WLS",ename:"Geraint",ssml:!0,name:"AWS Polly - en-GB-WLS - Male - Geraint"},"cy-GB_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"cy-GB",ename:"Gwyneth",ssml:!0,name:"AWS Polly - cy-GB - Female - Gwyneth"},"cy-GB_AP_Male":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"cy-GB",ename:"Geraint",ssml:!0,name:"AWS Polly - cy-GB - Male - Geraint"},"en-IN_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"en-IN",ename:"Raveena",ssml:!0,name:"AWS Polly - en-IN - Female - Raveena"},"en-US_AP_Male_Chipmunk":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"en-US",ename:"Chipmunk",ssml:!0,name:"AWS Polly - en-US - Male - Chipmunk"},"en-US_AP_Male_Eric":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"en-US",ename:"Eric",ssml:!0,name:"AWS Polly - en-US - Male - Eric"},"en-US_AP_Female_Ivy":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"en-US",ename:"Ivy",ssml:!0,name:"AWS Polly - en-US - Female - Ivy"},"en-US_AP_Female_Jennifer":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"en-US",ename:"Jennifer",ssml:!0,name:"AWS Polly - en-US - Female - Jennifer"},"en-US_AP_Male_Justin":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"en-US",ename:"Justin",ssml:!0,name:"AWS Polly - en-US - Male - Justin"},"en-US_AP_Female_Kendra":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"en-US",ename:"Kendra",ssml:!0,name:"AWS Polly - en-US - Female - Kendra"},"en-US_AP_Female_Kimberly":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"en-US",ename:"Kimberly",ssml:!0,name:"AWS Polly - en-US - Female - Kimberly"},"es-ES_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"es-ES",ename:"Conchita",ssml:!0,name:"AWS Polly - es-ES - Female - Conchita"},"es-ES_AP_Male":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"es-ES",ename:"Enrique",ssml:!0,name:"AWS Polly - es-ES - Male - Enrique"},"es-US_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"es-US",ename:"Penelope",ssml:!0,name:"AWS Polly - es-US - Female - Penelope"},"es-US_AP_Male":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"es-US",ename:"Miguel",ssml:!0,name:"AWS Polly - es-US - Male - Miguel"},"fr-CA_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"fr-CA",ename:"Chantal",ssml:!0,name:"AWS Polly - fr-CA - Female - Chantal"},"fr-FR_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"fr-FR",ename:"Celine",ssml:!0,name:"AWS Polly - fr-FR - Female - Celine"},"fr-FR_AP_Male":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"fr-FR",ename:"Mathieu",ssml:!0,name:"AWS Polly - fr-FR - Male - Mathieu"},"is-IS_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"is-IS",ename:"Dora",ssml:!0,name:"AWS Polly - is-IS - Female - Dora"},"is-IS_AP_Male":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"is-IS",ename:"Karl",ssml:!0,name:"AWS Polly - is-IS - Male - Karl"},"it-IT_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"it-IT",ename:"Carla",ssml:!0,name:"AWS Polly - it-IT - Female - Carla"},"it-IT_AP_Male":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"it-IT",ename:"Giorgio",ssml:!0,name:"AWS Polly - it-IT - Male - Giorgio"},"nb-NO_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"nb-NO",ename:"Liv",ssml:!0,name:"AWS Polly - nb-NO - Female - Liv"},"nl-NL_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"nl-NL",ename:"Lotte",ssml:!0,name:"AWS Polly - nl-NL - Female - Lotte"},"nl-NL_AP_Male":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"nl-NL",ename:"Ruben",ssml:!0,name:"AWS Polly - nl-NL - Male - Ruben"},"pl-PL_AP_Female_Agnieszka":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"pl-PL",ename:"Agnieszka",ssml:!0,name:"AWS Polly - pl-PL - Female - Agnieszka"},"pl-PL_AP_Male_Jacek":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"pl-PL",ename:"Jacek",ssml:!0,name:"AWS Polly - pl-PL - Male - Jacek"},"pl-PL_AP_Female_Ewa":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"pl-PL",ename:"Ewa",ssml:!0,name:"AWS Polly - pl-PL - Female - Ewa"},"pl-PL_AP_Male_Jan":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"pl-PL",ename:"Jan",ssml:!0,name:"AWS Polly - pl-PL - Male - Jan"},"pl-PL_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"pl-PL",ename:"Maja",ssml:!0,name:"AWS Polly - pl-PL - Female - Maja"},"pt-BR_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"pt-BR",ename:"Vitoria",ssml:!0,name:"AWS Polly - pt-BR - Female - Vitoria"},"pt-BR_AP_Male":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"pt-BR",ename:"Ricardo",ssml:!0,name:"AWS Polly - pt-BR - Male - Ricardo"},"pt-PT_AP_Male":{gender:"Male",engine:"polly",params:["accessKey","secretKey","region"],language:"pt-PT",ename:"Cristiano",ssml:!0,name:"AWS Polly - pt-PT - Male - Cristiano"},"pt-PT_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"pt-PT",ename:"Ines",ssml:!0,name:"AWS Polly - pt-PT - Female - Ines"},"ro-RO_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"ro-RO",ename:"Carmen",ssml:!0,name:"AWS Polly - ro-RO - Female - Carmen"},"sv-SE_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"sv-SE",ename:"Astrid",ssml:!0,name:"AWS Polly - sv-SE - Female - Astrid"},"tr-TR_AP_Female":{gender:"Female",engine:"polly",params:["accessKey","secretKey","region"],language:"tr-TR",ename:"Filiz",ssml:!0,name:"AWS Polly - tr-TR - Female - Filiz"}};class Mc extends at{constructor(s){super(s,Mc.getStaticData())}static compile(s,i){return s.text?`// Sayit ${s.text||""} const subActionVar${s._id} = "${s.language&&s.language!=="_"?`${s.language};`:""}${s.volume?`${s.volume};`:""}${(s.text||"").replace(/"/g,'\\"')}"${at.getReplacesInText(i)}; _sendToFrontEnd(${s._id}, {text: subActionVar${s._id}}); await setStateAsync("${s.instance}.tts.text", subActionVar${s._id});`:`// no text defined -_sendToFrontEnd(${s._id}, {text: 'No text defined'});`}renderDebug(s){return`${x.I18n.t("Say:")} ${s.data.text}`}onTagChange(){const s=x.I18n.getLanguage(),r=Object.keys($w).filter(l=>l.startsWith(s)).map(l=>({title:$w[l].name,value:l}));r.unshift({title:"Default",value:"_"}),this.setState({inputs:[{attr:"instance",nameRender:"renderInstance",adapter:"sayit",defaultValue:"sayit.0",frontText:"Instance:"},{nameRender:"renderSelect",frontText:"Language:",options:r,defaultValue:"_",attr:"language"},{nameRender:"renderNameText",defaultValue:"Volume",attr:"textVol"},{nameRender:"renderSlider",attr:"volume",defaultValue:100,min:0,max:100},{attr:"text",nameRender:"renderModalInput",defaultValue:"Hallo",nameBlock:"",frontText:"Text:"}]},()=>super.onTagChange())}static getStaticData(){return{acceptedBy:"actions",name:"Say It",id:"ActionSayText",adapter:"sayit",title:"Say some text via sayit adapter",helpDialog:"You can use %s in the text to display current trigger value or %id to display the triggered object ID"}}getData(){return Oc.getStaticData()}}class Nc extends at{constructor(s){super(s,Nc.getStaticData())}static compile(s,i){const r=(s.text||"").replace(/"/g,'\\"');return r?`// Pushover ${s.text||""} +_sendToFrontEnd(${s._id}, {text: 'No text defined'});`}renderDebug(s){return`${x.I18n.t("Say:")} ${s.data.text}`}onTagChange(){const s=x.I18n.getLanguage(),r=Object.keys(bw).filter(l=>l.startsWith(s)).map(l=>({title:bw[l].name,value:l}));r.unshift({title:"Default",value:"_"}),this.setState({inputs:[{attr:"instance",nameRender:"renderInstance",adapter:"sayit",defaultValue:"sayit.0",frontText:"Instance:"},{nameRender:"renderSelect",frontText:"Language:",options:r,defaultValue:"_",attr:"language"},{nameRender:"renderNameText",defaultValue:"Volume",attr:"textVol"},{nameRender:"renderSlider",attr:"volume",defaultValue:100,min:0,max:100},{attr:"text",nameRender:"renderModalInput",defaultValue:"Hallo",nameBlock:"",frontText:"Text:"}]},()=>super.onTagChange())}static getStaticData(){return{acceptedBy:"actions",name:"Say It",id:"ActionSayText",adapter:"sayit",title:"Say some text via sayit adapter",helpDialog:"You can use %s in the text to display current trigger value or %id to display the triggered object ID"}}getData(){return Mc.getStaticData()}}class Nc extends at{constructor(s){super(s,Nc.getStaticData())}static compile(s,i){const r=(s.text||"").replace(/"/g,'\\"');return r?`// Pushover ${s.text||""} const subActionVar${s._id} = "${r}"${at.getReplacesInText(i)}; _sendToFrontEnd(${s._id}, {text: subActionVar${s._id}}); sendTo("${s.instance}", "send", { @@ -1102,11 +1102,11 @@ _sendToFrontEnd(${s._id}, {text: 'No text defined'});`}renderDebug(s){return`${x sound: "${s.sound}", priority: ${s.priority} });`:`// no text defined -_sendToFrontEnd(${s._id}, {text: 'No text defined'});`}renderDebug(s){return`Sent: ${s.data.text}`}onTagChange(){this.setState({inputs:[{nameRender:"renderInstance",adapter:"pushover",frontText:"Instance:",defaultValue:"pushover.0",attr:"instance"},{nameRender:"renderModalInput",attr:"text",defaultValue:"Hello",nameBlock:"",frontText:"Text:"},{nameRender:"renderText",attr:"title",defaultValue:"ioBroker",frontText:"Title:"},{nameRender:"renderSelect",attr:"sound",defaultValue:"magic",frontText:"Sound:",doNotTranslate:!0,options:[{value:"pushover",title:"pushover"},{value:"bike",title:"bike"},{value:"bugle",title:"bugle"},{value:"cashregister",title:"cashregister"},{value:"classical",title:"classical"},{value:"cosmic",title:"cosmic"},{value:"falling",title:"falling"},{value:"gamelan",title:"gamelan"},{value:"incoming",title:"incoming"},{value:"intermission",title:"intermission"},{value:"magic",title:"magic"},{value:"mechanical",title:"mechanical"},{value:"pianobar",title:"pianobar"},{value:"siren",title:"siren"},{value:"spacealarm",title:"spacealarm"},{value:"tugboat",title:"tugboat"},{value:"alien",title:"alien"},{value:"climb",title:"climb"},{value:"persistent",title:"persistent"},{value:"echo",title:"echo"},{value:"updown",title:"updown"},{value:"none",title:"none"}]},{nameRender:"renderSelect",attr:"priority",defaultValue:-1,frontText:"Priority:",options:[{value:-1,title:"quiet"},{value:0,title:"normal"},{value:1,title:"high-priority"},{value:2,title:"acknowledgment"}]}]},()=>super.onTagChange())}static getStaticData(){return{acceptedBy:"actions",name:"Pushover",id:"ActionPushover",adapter:"pushover",title:"Sends message via pushover",helpDialog:"You can use %s in the text to display current trigger value or %id to display the triggered object ID"}}getData(){return Nc.getStaticData()}}class Mc extends at{constructor(s){super(s,Mc.getStaticData())}static compile(s,i){const r=(s.text||"").replace(/"/g,'\\"');return r?`// whatsapp ${r||""} +_sendToFrontEnd(${s._id}, {text: 'No text defined'});`}renderDebug(s){return`Sent: ${s.data.text}`}onTagChange(){this.setState({inputs:[{nameRender:"renderInstance",adapter:"pushover",frontText:"Instance:",defaultValue:"pushover.0",attr:"instance"},{nameRender:"renderModalInput",attr:"text",defaultValue:"Hello",nameBlock:"",frontText:"Text:"},{nameRender:"renderText",attr:"title",defaultValue:"ioBroker",frontText:"Title:"},{nameRender:"renderSelect",attr:"sound",defaultValue:"magic",frontText:"Sound:",doNotTranslate:!0,options:[{value:"pushover",title:"pushover"},{value:"bike",title:"bike"},{value:"bugle",title:"bugle"},{value:"cashregister",title:"cashregister"},{value:"classical",title:"classical"},{value:"cosmic",title:"cosmic"},{value:"falling",title:"falling"},{value:"gamelan",title:"gamelan"},{value:"incoming",title:"incoming"},{value:"intermission",title:"intermission"},{value:"magic",title:"magic"},{value:"mechanical",title:"mechanical"},{value:"pianobar",title:"pianobar"},{value:"siren",title:"siren"},{value:"spacealarm",title:"spacealarm"},{value:"tugboat",title:"tugboat"},{value:"alien",title:"alien"},{value:"climb",title:"climb"},{value:"persistent",title:"persistent"},{value:"echo",title:"echo"},{value:"updown",title:"updown"},{value:"none",title:"none"}]},{nameRender:"renderSelect",attr:"priority",defaultValue:-1,frontText:"Priority:",options:[{value:-1,title:"quiet"},{value:0,title:"normal"},{value:1,title:"high-priority"},{value:2,title:"acknowledgment"}]}]},()=>super.onTagChange())}static getStaticData(){return{acceptedBy:"actions",name:"Pushover",id:"ActionPushover",adapter:"pushover",title:"Sends message via pushover",helpDialog:"You can use %s in the text to display current trigger value or %id to display the triggered object ID"}}getData(){return Nc.getStaticData()}}class Lc extends at{constructor(s){super(s,Lc.getStaticData())}static compile(s,i){const r=(s.text||"").replace(/"/g,'\\"');return r?`// whatsapp ${r||""} const subActionVar${s._id} = "${(r||"").replace(/"/g,'\\"')}"${at.getReplacesInText(i)}; _sendToFrontEnd(${s._id}, {text: subActionVar${s._id}}); sendTo("${s.instance}", "send", {text: subActionVar${s._id}${s.phone?`, phone: "${s.phone.replace(/"/g,'\\"')}"`:""}});`:`// no text defined -_sendToFrontEnd(${s._id}, {text: 'No text defined'});`}renderDebug(s){return`${x.I18n.t("Sent:")} ${s.data.text}`}onTagChange(){this.setState({inputs:[{nameRender:"renderInstance",adapter:"whatsapp-cmb",frontText:"Instance:",defaultValue:"whatsapp-cmb.0",attr:"instance"},{nameRender:"renderModalInput",attr:"text",defaultValue:"Hello",nameBlock:"",frontText:"Text:"},{nameRender:"renderText",attr:"phone",defaultValue:"",frontText:"Phone:",backText:"(optional)"}]},()=>super.onTagChange())}static getStaticData(){return{acceptedBy:"actions",name:"Whatsapp-cmb",id:"ActionWhatsappcmb",adapter:"whatsapp-cmb",title:"Sends message via whatsapp-cmb",helpDialog:"You can use %s in the text to display current trigger value or %id to display the triggered object ID"}}getData(){return Mc.getStaticData()}}class Lc extends at{constructor(s){super(s,Lc.getStaticData())}static compile(s,i){const r=(s.text||"").replace(/"/g,'\\"');return r?`// Pushsafer ${s.text||""} +_sendToFrontEnd(${s._id}, {text: 'No text defined'});`}renderDebug(s){return`${x.I18n.t("Sent:")} ${s.data.text}`}onTagChange(){this.setState({inputs:[{nameRender:"renderInstance",adapter:"whatsapp-cmb",frontText:"Instance:",defaultValue:"whatsapp-cmb.0",attr:"instance"},{nameRender:"renderModalInput",attr:"text",defaultValue:"Hello",nameBlock:"",frontText:"Text:"},{nameRender:"renderText",attr:"phone",defaultValue:"",frontText:"Phone:",backText:"(optional)"}]},()=>super.onTagChange())}static getStaticData(){return{acceptedBy:"actions",name:"Whatsapp-cmb",id:"ActionWhatsappcmb",adapter:"whatsapp-cmb",title:"Sends message via whatsapp-cmb",helpDialog:"You can use %s in the text to display current trigger value or %id to display the triggered object ID"}}getData(){return Lc.getStaticData()}}class Pc extends at{constructor(s){super(s,Pc.getStaticData())}static compile(s,i){const r=(s.text||"").replace(/"/g,'\\"');return r?`// Pushsafer ${s.text||""} const subActionVar${s._id} = "${r}"${at.getReplacesInText(i)}; _sendToFrontEnd(${s._id}, {text: subActionVar${s._id}}); sendTo("${s.instance}", "send", { @@ -1116,7 +1116,7 @@ _sendToFrontEnd(${s._id}, {text: 'No text defined'});`}renderDebug(s){return`${x priority: ${s.priority}, ${s.vibration&&s.vibration!=="_"?`vibration: ${s.vibration},`:""} });`:`// no text defined -_sendToFrontEnd(${s._id}, {text: 'No text defined'});`}renderDebug(s){return`Sent: ${s.data.text}`}onTagChange(){this.setState({inputs:[{nameRender:"renderInstance",adapter:"pushsafer",frontText:"Instance:",defaultValue:"pushsafer.0",attr:"instance"},{nameRender:"renderModalInput",attr:"text",defaultValue:"Hello",nameBlock:"",frontText:"Text:"},{nameRender:"renderText",attr:"title",defaultValue:"ioBroker",frontText:"Title:"},{nameRender:"renderSelect",attr:"sound",defaultValue:"magic",frontText:"Sound:",doNotTranslate:!0,options:[{value:"_",title:"Device Default"},{value:"0",title:"Silent"},{value:"1",title:"Ahem (IM)"},{value:"2",title:"Applause (Mail)"},{value:"3",title:"Arrow (Reminder)"},{value:"4",title:"Baby (SMS)"},{value:"5",title:"Bell (Alarm)"},{value:"6",title:"Bicycle (Alarm2)"},{value:"7",title:"Boing (Alarm3)"},{value:"8",title:"Buzzer (Alarm4)"},{value:"9",title:"Camera (Alarm5)"},{value:"10",title:"Car Horn (Alarm6)"},{value:"11",title:"Cash Register (Alarm7)"},{value:"12",title:"Chime (Alarm8)"},{value:"13",title:"Creaky Door (Alarm9)"},{value:"14",title:"Cuckoo Clock (Alarm10)"},{value:"15",title:"Disconnect (Call)"},{value:"16",title:"Dog (Call2)"},{value:"17",title:"Doorbell (Call3)"},{value:"18",title:"Fanfare (Call4)"},{value:"19",title:"Gun Shot (Call5)"},{value:"20",title:"Honk (Call6)"},{value:"21",title:"Jaw Harp (Call7)"},{value:"22",title:"Morse (Call8)"},{value:"23",title:"Electricity (Call9)"},{value:"24",title:"Radio Tuner (Call10)"},{value:"25",title:"Sirens"},{value:"26",title:"Military Trumpets"},{value:"27",title:"Ufo"},{value:"28",title:"Whah Whah Whah"},{value:"29",title:"Man Saying Goodbye"},{value:"30",title:"Man Saying Hello"},{value:"31",title:"Man Saying No"},{value:"32",title:"Man Saying Ok"},{value:"33",title:"Man Saying Ooohhhweee"},{value:"34",title:"Man Saying Warning"},{value:"35",title:"Man Saying Welcome"},{value:"36",title:"Man Saying Yeah"},{value:"37",title:"Man Saying Yes"},{value:"38",title:"Beep short"},{value:"39",title:"Weeeee short"},{value:"40",title:"Cut in and out short"},{value:"41",title:"Finger flicking glas short"},{value:"42",title:"Wa Wa Waaaa short"},{value:"43",title:"Laser short"},{value:"44",title:"Wind Chime short"},{value:"45",title:"Echo short"},{value:"46",title:"Zipper short"},{value:"47",title:"HiHat short"},{value:"48",title:"Beep 2 short"},{value:"49",title:"Beep 3 short"},{value:"50",title:"Beep 4 short"},{value:"51",title:"The Alarm is armed"},{value:"52",title:"The Alarm is disarmed"},{value:"53",title:"The Backup is ready"},{value:"54",title:"The Door is closed"},{value:"55",title:"The Door is opend"},{value:"56",title:"The Window is closed"},{value:"57",title:"The Window is open"},{value:"58",title:"The Light is off"},{value:"59",title:"The Light is on"},{value:"60",title:"The Doorbell rings"},{value:"61",title:"Pager short"},{value:"62",title:"Pager long"}]},{nameRender:"renderSelect",attr:"priority",defaultValue:0,frontText:"Priority:",options:[{value:-2,title:"lowest priority"},{value:-1,title:"lower priority"},{value:0,title:"normal priority"},{value:1,title:"high priority"},{value:2,title:"highest priority"}]},{nameRender:"renderSelect",attr:"vibration",defaultValue:0,frontText:"Vibration:",options:[{value:"_",title:"default"},{value:1,title:"1"},{value:2,title:"2"},{value:3,title:"3"}]}]},()=>super.onTagChange())}static getStaticData(){return{acceptedBy:"actions",name:"Pushsafer",id:"ActionPushsafer",adapter:"pushsafer",title:"Sends message via Pushsafer",helpDialog:"You can use %s in the text to display current trigger value or %id to display the triggered object ID"}}getData(){return Lc.getStaticData()}}const EC=`async function (obj) { +_sendToFrontEnd(${s._id}, {text: 'No text defined'});`}renderDebug(s){return`Sent: ${s.data.text}`}onTagChange(){this.setState({inputs:[{nameRender:"renderInstance",adapter:"pushsafer",frontText:"Instance:",defaultValue:"pushsafer.0",attr:"instance"},{nameRender:"renderModalInput",attr:"text",defaultValue:"Hello",nameBlock:"",frontText:"Text:"},{nameRender:"renderText",attr:"title",defaultValue:"ioBroker",frontText:"Title:"},{nameRender:"renderSelect",attr:"sound",defaultValue:"magic",frontText:"Sound:",doNotTranslate:!0,options:[{value:"_",title:"Device Default"},{value:"0",title:"Silent"},{value:"1",title:"Ahem (IM)"},{value:"2",title:"Applause (Mail)"},{value:"3",title:"Arrow (Reminder)"},{value:"4",title:"Baby (SMS)"},{value:"5",title:"Bell (Alarm)"},{value:"6",title:"Bicycle (Alarm2)"},{value:"7",title:"Boing (Alarm3)"},{value:"8",title:"Buzzer (Alarm4)"},{value:"9",title:"Camera (Alarm5)"},{value:"10",title:"Car Horn (Alarm6)"},{value:"11",title:"Cash Register (Alarm7)"},{value:"12",title:"Chime (Alarm8)"},{value:"13",title:"Creaky Door (Alarm9)"},{value:"14",title:"Cuckoo Clock (Alarm10)"},{value:"15",title:"Disconnect (Call)"},{value:"16",title:"Dog (Call2)"},{value:"17",title:"Doorbell (Call3)"},{value:"18",title:"Fanfare (Call4)"},{value:"19",title:"Gun Shot (Call5)"},{value:"20",title:"Honk (Call6)"},{value:"21",title:"Jaw Harp (Call7)"},{value:"22",title:"Morse (Call8)"},{value:"23",title:"Electricity (Call9)"},{value:"24",title:"Radio Tuner (Call10)"},{value:"25",title:"Sirens"},{value:"26",title:"Military Trumpets"},{value:"27",title:"Ufo"},{value:"28",title:"Whah Whah Whah"},{value:"29",title:"Man Saying Goodbye"},{value:"30",title:"Man Saying Hello"},{value:"31",title:"Man Saying No"},{value:"32",title:"Man Saying Ok"},{value:"33",title:"Man Saying Ooohhhweee"},{value:"34",title:"Man Saying Warning"},{value:"35",title:"Man Saying Welcome"},{value:"36",title:"Man Saying Yeah"},{value:"37",title:"Man Saying Yes"},{value:"38",title:"Beep short"},{value:"39",title:"Weeeee short"},{value:"40",title:"Cut in and out short"},{value:"41",title:"Finger flicking glas short"},{value:"42",title:"Wa Wa Waaaa short"},{value:"43",title:"Laser short"},{value:"44",title:"Wind Chime short"},{value:"45",title:"Echo short"},{value:"46",title:"Zipper short"},{value:"47",title:"HiHat short"},{value:"48",title:"Beep 2 short"},{value:"49",title:"Beep 3 short"},{value:"50",title:"Beep 4 short"},{value:"51",title:"The Alarm is armed"},{value:"52",title:"The Alarm is disarmed"},{value:"53",title:"The Backup is ready"},{value:"54",title:"The Door is closed"},{value:"55",title:"The Door is opend"},{value:"56",title:"The Window is closed"},{value:"57",title:"The Window is open"},{value:"58",title:"The Light is off"},{value:"59",title:"The Light is on"},{value:"60",title:"The Doorbell rings"},{value:"61",title:"Pager short"},{value:"62",title:"Pager long"}]},{nameRender:"renderSelect",attr:"priority",defaultValue:0,frontText:"Priority:",options:[{value:-2,title:"lowest priority"},{value:-1,title:"lower priority"},{value:0,title:"normal priority"},{value:1,title:"high priority"},{value:2,title:"highest priority"}]},{nameRender:"renderSelect",attr:"vibration",defaultValue:0,frontText:"Vibration:",options:[{value:"_",title:"default"},{value:1,title:"1"},{value:2,title:"2"},{value:3,title:"3"}]}]},()=>super.onTagChange())}static getStaticData(){return{acceptedBy:"actions",name:"Pushsafer",id:"ActionPushsafer",adapter:"pushsafer",title:"Sends message via Pushsafer",helpDialog:"You can use %s in the text to display current trigger value or %id to display the triggered object ID"}}getData(){return Pc.getStaticData()}}const IC=`async function (obj) { "__%%DEBUG_TRIGGER%%__"; __%%CONDITIONS_VARS%%__ const _cond = __%%CONDITION%%__; @@ -1128,7 +1128,7 @@ __%%THEN%%__ } else { __%%ELSE%%__ } -}`,IC=`async function (obj) { +}`,xC=`async function (obj) { "__%%DEBUG_TRIGGER%%__"; __%%CONDITIONS_VARS%%__ const _cond = __%%CONDITION%%__; @@ -1142,7 +1142,7 @@ __%%THEN%%__ __%%STATE%%__ = false; __%%ELSE%%__ } -}`,cO=`"__%%DEBUG_TRIGGER%%__"; +}`,gR=`"__%%DEBUG_TRIGGER%%__"; __%%CONDITIONS_VARS%%__ const _cond = __%%CONDITION%%__; @@ -1152,9 +1152,9 @@ if (_cond) { __%%THEN%%__ } else { __%%ELSE%%__ -}`,Sg={triggers:[],conditions:[[]],justCheck:!1,actions:{then:[],else:[]}};function uO(a,s,i){const r=[];let l=a.triggers;l.length||(l=[{id:"TriggerScriptSave"}]);const c=[],d=[],h=a.conditions.find(f=>f.find(b=>b.tagCard==="()"));l.forEach((f,b)=>{var w;const y=Vm(f.id,i);if(y){const v={trigger:f,condition:{index:0},justCheck:h?!1:a.justCheck||!a.conditions.length||!a.conditions[0].length,conditionsDebug:[],conditionsVars:[],conditionsStates:[]},_=y.compile(f,v),$=dO(a.conditions,v,i),S=bw(a.actions.then,v,i),T=bw(a.actions.else,v,i);c.push(`cond${b}`),(w=v.prelines)!=null&&w.length&&v.prelines.forEach(E=>d.push(E)),_.includes(" __%%CONDITIONS_VARS%%__")&&(v.conditionsVars=v.conditionsVars.map((E,D)=>D?` ${E}`:E),v.conditionsDebug=v.conditionsDebug.map((E,D)=>D?` ${E}`:E)),r.push(_.replace("__%%CONDITIONS_VARS%%__",v.conditionsVars.join(` +}`,Ig={triggers:[],conditions:[[]],justCheck:!1,actions:{then:[],else:[]}};function mR(a,s,i){const r=[];let l=a.triggers;l.length||(l=[{id:"TriggerScriptSave"}]);const c=[],d=[],h=a.conditions.find(f=>f.find(b=>b.tagCard==="()"));l.forEach((f,b)=>{var w;const y=Km(f.id,i);if(y){const v={trigger:f,condition:{index:0},justCheck:h?!1:a.justCheck||!a.conditions.length||!a.conditions[0].length,conditionsDebug:[],conditionsVars:[],conditionsStates:[]},_=y.compile(f,v),$=fR(a.conditions,v,i),T=vw(a.actions.then,v,i),S=vw(a.actions.else,v,i);c.push(`cond${b}`),(w=v.prelines)!=null&&w.length&&v.prelines.forEach(E=>d.push(E)),_.includes(" __%%CONDITIONS_VARS%%__")&&(v.conditionsVars=v.conditionsVars.map((E,D)=>D?` ${E}`:E),v.conditionsDebug=v.conditionsDebug.map((E,D)=>D?` ${E}`:E)),r.push(_.replace("__%%CONDITIONS_VARS%%__",v.conditionsVars.join(` `)).replace('"__%%DEBUG_CONDITIONS%%__";',v.conditionsDebug.join(` -`)).replace("__%%CONDITION%%__",$).replace("__%%THEN%%__",S||"// ignore").replace("__%%ELSE%%__",T||"// ignore").replace(/__%%STATE%%__/g,`cond${b}`))}});let p=r.join(` +`)).replace("__%%CONDITION%%__",$).replace("__%%THEN%%__",T||"// ignore").replace("__%%ELSE%%__",S||"// ignore").replace(/__%%STATE%%__/g,`cond${b}`))}});let p=r.join(` `);return(!a.justCheck||h)&&(p=`${c.map(f=>`let ${f} = false;`).join(` `)} @@ -1162,16 +1162,16 @@ __%%ELSE%%__ ${p}`),d&&(p=`${d.join(` `)} -${p}`),p}function Vm(a,s){return s.find(i=>i.getStaticData&&i.getStaticData().id===a)}function bw(a,s,i){const r=[];return a==null||a.forEach(l=>{const c=Vm(l.id,i);c&&r.push(c.compile(l,s))}),` ${r.join(` +${p}`),p}function Km(a,s){return s.find(i=>i.getStaticData&&i.getStaticData().id===a)}function vw(a,s,i){const r=[];return a==null||a.forEach(l=>{const c=Km(l.id,i);c&&r.push(c.compile(l,s))}),` ${r.join(` - `)}`}function dO(a,s,i){const r=[];let l=0;return a==null||a.forEach(c=>{const d=[];c!=null&&c.length&&(c.forEach(h=>{const p=Vm(h.id,i);p&&(s.condition.index=l++,d.push(p.compile(h,s)))}),r.push(`(${d.join(`) && - (`)})`))}),r.length?r.length===1?r[0]||"true":`(${r.join(") || (")})`:"true"}function hO(a,s){return uO(a,null,s)}function Cne(a){if(!a)return Sg;const s=a.split(` -`);try{const i=(s.pop()||"").replace(/^\/\//,"");let r=JSON.parse(i);return r.triggers||(r=Sg),r}catch{return Sg}}function Tne(a,s){let i="";const r=hO(a,s);return i+=r,i+=` + `)}`}function fR(a,s,i){const r=[];let l=0;return a==null||a.forEach(c=>{const d=[];c!=null&&c.length&&(c.forEach(h=>{const p=Km(h.id,i);p&&(s.condition.index=l++,d.push(p.compile(h,s)))}),r.push(`(${d.join(`) && + (`)})`))}),r.length?r.length===1?r[0]||"true":`(${r.join(") || (")})`:"true"}function $R(a,s){return mR(a,null,s)}function xne(a){if(!a)return Ig;const s=a.split(` +`);try{const i=(s.pop()||"").replace(/^\/\//,"");let r=JSON.parse(i);return r.triggers||(r=Ig),r}catch{return Ig}}function Dne(a,s){let i="";const r=$R(a,s);return i+=r,i+=` /* const demo = ${JSON.stringify(a,null,2).replace(/\*\//g,"* /")}; */ `,`${i} -//${JSON.stringify(a)}`}class Pc extends at{constructor(s){super(s,Pc.getStaticData())}static compile(s,i){return cO.replace('"__%%DEBUG_TRIGGER%%__"',`_sendToFrontEnd(${s._id}, {trigger: true})`)}renderDebug(){return x.I18n.t("Triggered")}onTagChange(s){this.setState({inputs:[{nameRender:"renderNameText",defaultValue:"On script save or adapter start",attr:"script"}]},()=>super.onTagChange())}static getStaticData(){return{acceptedBy:"triggers",name:"Start script",id:"TriggerScriptSave",icon:"PlayArrow",title:"Triggers the on script saving or the javascript instance restart"}}getData(){return Pc.getStaticData()}}var xC={exports:{}};(function(a,s){(function(){var i=Math.PI,r=Math.sin,l=Math.cos,c=Math.tan,d=Math.asin,h=Math.atan2,p=Math.acos,f=i/180,b=1e3*60*60*24,y=2440588,w=2451545;function v(re){return re.valueOf()/b-.5+y}function _(re){return new Date((re+.5-y)*b)}function $(re){return v(re)-w}var S=f*23.4397;function T(re,B){return h(r(re)*l(S)-c(B)*r(S),l(re))}function E(re,B){return d(r(B)*l(S)+l(B)*r(S)*r(re))}function D(re,B,N){return h(r(re),l(re)*r(B)-c(N)*l(B))}function M(re,B,N){return d(r(B)*r(N)+l(B)*l(N)*l(re))}function P(re,B){return f*(280.16+360.9856235*re)-B}function W(re){return re<0&&(re=0),2967e-7/Math.tan(re+.00312536/(re+.08901179))}function G(re){return f*(357.5291+.98560028*re)}function z(re){var B=f*(1.9148*r(re)+.02*r(2*re)+3e-4*r(3*re)),N=f*102.9372;return re+B+N+i}function Z(re){var B=G(re),N=z(B);return{dec:E(N,0),ra:T(N,0)}}var he={};he.getPosition=function(re,B,N){var te=f*-N,q=f*B,se=$(re),F=Z(se),Te=P(se,te)-F.ra;return{azimuth:D(Te,q,F.dec),altitude:M(Te,q,F.dec)}};var Ce=he.times=[[-.833,"sunrise","sunset"],[-.3,"sunriseEnd","sunsetStart"],[-6,"dawn","dusk"],[-12,"nauticalDawn","nauticalDusk"],[-18,"nightEnd","night"],[6,"goldenHourEnd","goldenHour"]];he.addTime=function(re,B,N){Ce.push([re,B,N])};var O=9e-4;function K(re,B){return Math.round(re-O-B/(2*i))}function C(re,B,N){return O+(re+B)/(2*i)+N}function Q(re,B,N){return w+re+.0053*r(B)-.0069*r(2*N)}function ve(re,B,N){return p((r(re)-r(B)*r(N))/(l(B)*l(N)))}function ce(re,B,N,te,q,se,F){var Te=ve(re,N,te),ae=C(Te,B,q);return Q(ae,se,F)}he.getTimes=function(re,B,N){var te=f*-N,q=f*B,se=$(re),F=K(se,te),Te=C(0,te,F),ae=G(Te),we=z(ae),Ie=E(we,0),Ne=Q(Te,ae,we),Ae,We,k,X,Y,R={solarNoon:_(Ne),nadir:_(Ne+.5)};for(Ae=0,We=Ce.length;Ae=0&&(U=Math.sqrt(X)/(Math.abs(Ne)*2),R=We-U,A=We+U,Math.abs(R)<=1&&Y++,Math.abs(A)<=1&&Y++,R<-1&&(R=A)),Y===1?F<0?we=H+R:Ie=H+R:Y===2&&(we=H+(k<0?A:R),Ie=H+(k<0?R:A)),!(we&&Ie));H+=2)F=ae;var ue={};return we&&(ue.rise=me(q,we)),Ie&&(ue.set=me(q,Ie)),!we&&!Ie&&(ue[k>0?"alwaysUp":"alwaysDown"]=!0),ue},a.exports=he})()})(xC);var pO=xC.exports;const DC=Xo(pO),gO='{"time":{"start":"00:00","end":"24:00","mode":"hours","interval":1},"period":{"days":1}}';class Ii extends at{coordinates=null;constructor(s){super(s,Ii.getStaticData())}static compile(s,i){var c;let r="",l=i.justCheck?EC:IC;if(l=l.replace('"__%%DEBUG_TRIGGER%%__"',`_sendToFrontEnd(${s._id}, {trigger: true})`),s.tagCard==="interval")r=`setInterval(${l}, ${s.interval||1} * ${s.unit==="s"?1e3:s.unit==="m"?6e4:36e5});`;else if(s.tagCard==="cron")r=`schedule("${s.cron}", ${l});`;else if(s.tagCard==="at"){const[d,h]=(s.at||"").split(":");let p="*";if((c=s==null?void 0:s.dow)!=null&&c.length&&!s.dow.includes("_")){const f=[...s.dow].map(v=>parseInt(v,10));f.sort();const b=[];let y=f[0],w=1;for(;w1?(y===f[w-1]?b.push(y.toString()):f[w-1]-y===1?b.push(`${y},${f[w-1]}`):b.push(`${y}-${f[w-1]}`),y=f[w]):w===f.length-1&&(y===f[w-1]||f[w]-y===1?b.push(`${y},${f[w]}`):b.push(`${y}-${f[w]}`));p=b.join(",")}r=`schedule("${h||"0"} ${d||"0"} * * ${p}", ${l});`}else s.tagCard==="astro"?r=`schedule({astro: "${s.astro}", shift: ${s.offset?s.offsetValue:0}}, ${l});`:s.tagCard==="wizard"&&(r=`schedule('${s.wizard}', ${l});`);return r}static _time2String(s){return s?`${s.getHours().toString().padStart(2,"0")}:${s.getMinutes().toString().padStart(2,"0")}`:"--:--"}async _setAstro(s,i,r){var p,f;if(s||=this.state.settings.astro||"solarNoon",i??=this.state.settings.offset,r??=this.state.settings.offsetValue,r=parseInt(r,10)||0,!this.coordinates){const b=await this.props.socket.getObject("system.adapter.javascript.0"),y=(p=b==null?void 0:b.native)==null?void 0:p.latitude,w=(f=b==null?void 0:b.native)==null?void 0:f.longitude;if(!y&&!w){const v=await this.props.socket.getObject("system.config");v!=null&&v.common&&(v.common.latitude||v.common.longitude)?this.coordinates={latitude:parseFloat(v.common.latitude),longitude:parseFloat(v.common.longitude)}:this.coordinates=null}else this.coordinates={latitude:parseFloat(y),longitude:parseFloat(w)}}const l=this.coordinates&&DC.getTimes(new Date,this.coordinates.latitude,this.coordinates.longitude),c=l?Object.keys(l).map(b=>({value:b,title:b,title2:`[${Ii._time2String(l[b])}]`,order:l?Ii._time2String(l[b]):"??:??"})):[];c.sort((b,y)=>b.order>y.order?1:b.ordersuper.onTagChange())}_setInterval(s){s=parseInt(s||this.state.settings.interval,10)||30;let i;s===1?i=[{value:"s",title:"second"},{value:"m",title:"minute"},{value:"h",title:"hour"}]:i=[{value:"s",title:"seconds"},{value:"m",title:"minutes"},{value:"h",title:"hours"}],this.setState({inputs:[{nameRender:"renderNumber",attr:"interval",frontText:"every",defaultValue:30,className:"block-input-interval"},{nameRender:"renderSelect",attr:"unit",defaultValue:"s",options:i}]},()=>super.onTagChange())}renderDebug(s){return x.I18n.t("Triggered")}onValueChanged(s,i){this.state.settings.tagCard==="astro"?i==="astro"?this._setAstro(s):i==="offset"?this._setAstro(void 0,s):i==="offsetValue"&&this._setAstro(void 0,void 0,s):this.state.settings.tagCard==="interval"&&i==="interval"&&this._setInterval(s)}renderCron(s,i,r){const{className:l}=this.props;return m.jsxs("div",{children:[m.jsxs("div",{style:{display:"flex",alignItems:"baseline"},children:[m.jsx("div",{style:{width:"100%"},children:this.renderText({nameRender:"renderText",attr:"cron",defaultValue:i},this.state.settings.cron||i,r)}),m.jsx(Jr,{square:!0,style:{marginLeft:7},value:"...",className:l,onClick:()=>this.setState({openDialog:!0,textCron:this.state.settings.cron})})]}),this.state.openDialog?m.jsx(cm,{disabled:this.state.settings.cron===this.state.textCron,onApply:()=>{const c=this.state.textCron;r(c,"cron",()=>{r(x.convertCronToText(c,x.I18n.getLanguage()),"addText"),this.setState({openDialog:!1})})},onClose:()=>this.setState({openDialog:!1,textCron:""}),children:m.jsx(x.ComplexCron,{cronExpression:this.state.settings.cron,onChange:c=>this.setState({textCron:c}),language:x.I18n.getLanguage()})}):null,this.renderNameText({nameRender:"renderNameText",defaultValue:x.I18n.t("every hour at 0 minutes"),attr:"addText",signature:!0,doNotTranslate:!0},this.state.settings.addText||x.I18n.t("every hour at 0 minutes"))]},"cron")}renderWizard(s,i,r){const{className:l}=this.props;return m.jsxs("div",{children:[m.jsxs("div",{style:{display:"flex",alignItems:"center",marginTop:7},children:[m.jsx(Ei,{className:l,autoComplete:"off",fullWidth:!0,variant:"outlined",size:"small",multiline:!0,rows:2,value:this.state.settings.wizardText,onChange:c=>r(c),customValue:!0}),m.jsx(Jr,{square:!0,style:{marginLeft:7},value:"...",className:l,onClick:()=>this.setState({openDialog:!0,wizard:this.state.settings.wizard,wizardText:x.Schedule.state2text(this.state.settings.wizard)})})]}),this.state.openDialog?m.jsx(cm,{disabled:this.state.settings.wizard===this.state.wizard,onApply:()=>this.setState({openDialog:!1},()=>{const c=JSON.parse(this.state.wizard);c.valid||={from:x.Schedule.now2string()},c.valid.from||=x.Schedule.now2string(),r({wizardText:this.state.wizardText,wizard:JSON.stringify(c)})}),onClose:()=>this.setState({openDialog:!1}),children:m.jsx(x.Schedule,{theme:this.props.theme,schedule:i,onChange:(c,d)=>this.setState({wizardText:d||"",wizard:c})})}):null]},"wizard")}onTagChange(s){switch(s||=this.state.settings.tagCard,s){case"interval":this._setInterval();break;case"cron":this.setState({inputs:[{nameRender:"renderCron",attr:"cron",defaultValue:"0 * * * *"}]},()=>super.onTagChange());break;case"wizard":{const i=JSON.parse(gO);i.valid||={from:x.Schedule.now2string()},i.valid.from||=x.Schedule.now2string(),this.setState({inputs:[{nameRender:"renderWizard",attr:"wizard",defaultValue:JSON.stringify(i)}]},()=>super.onTagChange(null,()=>{const r=x.Schedule.state2text(this.state.settings.wizard||i);if(this.state.settings.wizard!==r){const l=JSON.parse(JSON.stringify(this.state.settings));l.wizardText=r,this.setState({settings:l}),this.props.onChange(l)}}));break}case"at":this.setState({inputs:[{nameRender:"renderTime",prefix:"at",attr:"at",defaultValue:"07:30"},{nameRender:"renderSelect",attr:"dow",default:"",multiple:!0,defaultValue:["_","1","2","3","4","5","6","0"],options:[{value:"_",title:"Every day",only:!0},{value:"1",title:"Monday",titleShort:"Mo"},{value:"2",title:"Tuesday",titleShort:"Tu"},{value:"3",title:"Wednesday",titleShort:"We"},{value:"4",title:"Thursday",titleShort:"Th"},{value:"5",title:"Friday",titleShort:"Fr"},{value:"6",title:"Saturday",titleShort:"Sa"},{value:"0",title:"Sunday",titleShort:"Su"}]}]},()=>super.onTagChange());break;case"astro":this._setAstro();break}}static getStaticData(){return{acceptedBy:"triggers",name:"Schedule",id:"TriggerScheduleBlock",icon:"AccessTime",tagCardArray:["cron","wizard","interval","at","astro"],title:"Triggers the rule periodically or on some specific time"}}getData(){return Ii.getStaticData()}}const In={valueAck:{color:"#b02323"},valueNotAck:{color:"#12ac15"}},AC=_e.forwardRef((a,s)=>m.jsx(XT,{direction:"up",ref:s,...a}));AC.displayName="Transition";class Bc extends at{inputRef;constructor(s){super(s,Bc.getStaticData()),this.inputRef=_e.createRef()}static compile(s,i){let r=i.justCheck?EC:IC;return r=r.replace('"__%%DEBUG_TRIGGER%%__"',`_sendToFrontEnd(${s._id}, {val: obj.state.val, ack: obj.state.ack, valOld: obj.oldState && obj.oldState.val, ackOld: obj.oldState && obj.oldState.ack})`),`on({id: "${s.oid||""}", change: "${s.tagCard==="on update"?"any":"ne"}"}, ${r});`}renderDebug(s){return s.data.valOld!==void 0?m.jsxs("span",{children:[x.I18n.t("Triggered")," ",m.jsx("span",{style:s.data.ackOld?In.valueAck:In.valueNotAck,children:Ln(s.data.valOld)})," ","→"," ",m.jsx("span",{style:s.data.ack?In.valueAck:In.valueNotAck,children:Ln(s.data.val)})]}):m.jsxs("span",{children:[x.I18n.t("Triggered")," ",m.jsx("span",{style:s.data.ack?In.valueAck:In.valueNotAck,children:Ln(s.data.val)})]})}onWriteValue(){this.setState({openSimulate:!1});let s=this.state.simulateValue;window.localStorage.setItem(`javascript.app.${this.state.settings.oid}_ack`,this.state.simulateAck?"true":"false"),this.state.settings.oidType==="boolean"?(s=s===!0||s==="true"||s==="1",window.localStorage.setItem(`javascript.app.${this.state.settings.oid}`,s?"true":"false")):this.state.settings.oidType==="number"?(s=parseFloat(s)||0,window.localStorage.setItem(`javascript.app.${this.state.settings.oid}`,s.toString())):window.localStorage.setItem(`javascript.app.${this.state.settings.oid}`,(s==null?void 0:s.toString())||""),this.props.socket.setState(this.state.settings.oid,{val:s,ack:!!this.state.simulateAck})}renderWriteState(){return[m.jsx(Ue,{disabled:!this.state.settings.oid||!this.state.enableSimulation,variant:"contained",color:"primary",onClick:()=>{this.setState({openSimulate:!0,simulateValue:this.state.settings.oidType==="boolean"?window.localStorage.getItem(`javascript.app.${this.state.settings.oid}`)==="true":window.localStorage.getItem(`javascript.app.${this.state.settings.oid}`)||"",simulateAck:window.localStorage.getItem(`javascript.app.${this.state.settings.oid}_ack`)==="true"}),setTimeout(()=>{var s;return(s=this.inputRef.current)==null?void 0:s.focus()},200)},children:x.I18n.t("Simulate")},"buttonWrite"),m.jsxs(Pt,{open:!!this.state.openSimulate,TransitionComponent:AC,keepMounted:!0,onClose:()=>this.setState({openSimulate:!1}),"aria-labelledby":"simulate-dialog-slide-title","aria-describedby":"simulate-dialog-slide-description",children:[m.jsx(Xt,{id:"simulate-dialog-slide-title",children:x.I18n.t("Trigger with value")}),m.jsxs(Wt,{children:[this.state.settings.oidType==="boolean"?m.jsx(Mg,{control:m.jsx(Nw,{inputRef:this.inputRef,onKeyUp:s=>s.key==="Enter"&&this.onWriteValue(),value:!!this.state.simulateValue,onChange:s=>this.setState({simulateValue:s.target.checked})}),label:x.I18n.t("Value")}):m.jsx(Eo,{variant:"standard",inputRef:this.inputRef,label:x.I18n.t("Value"),fullWidth:!0,onKeyUp:s=>s.key==="Enter"&&this.onWriteValue(),value:!this.state.simulateValue&&this.state.simulateValue!==0?"":this.state.simulateValue,onChange:s=>this.setState({simulateValue:s.target.value})}),m.jsx("br",{}),m.jsx(Mg,{control:m.jsx(wc,{checked:!!this.state.simulateAck,onChange:s=>this.setState({simulateAck:s.target.checked}),color:"primary"}),label:x.I18n.t("Ack")})]}),m.jsxs(Bt,{children:[m.jsxs(Ue,{variant:"contained",onClick:()=>this.onWriteValue(),color:"primary",children:[m.jsx(TS,{}),x.I18n.t("Write")]}),m.jsxs(Ue,{color:"grey",variant:"contained",onClick:()=>this.setState({openSimulate:!1}),children:[m.jsx(Yc,{}),x.I18n.t("Close")]})]})]},"dialogWrite")]}onTagChange(s){this.setState({inputs:[{nameRender:"renderObjectID",attr:"oid",defaultValue:""},{nameRender:"renderWriteState"}]},()=>{super.onTagChange()})}static getStaticData(){return{acceptedBy:"triggers",name:"State",id:"TriggerState",icon:"FlashOn",tagCardArray:["on change","on update"],title:"Triggers the rule on update or change of some state"}}getData(){return Bc.getStaticData()}}const mO=""+new URL("hysteresis-CLhhemcG.png",import.meta.url).href,vw=`function __hysteresis(val, limit, state, hist, comp) { +//${JSON.stringify(a)}`}class Bc extends at{constructor(s){super(s,Bc.getStaticData())}static compile(s,i){return gR.replace('"__%%DEBUG_TRIGGER%%__"',`_sendToFrontEnd(${s._id}, {trigger: true})`)}renderDebug(){return x.I18n.t("Triggered")}onTagChange(s){this.setState({inputs:[{nameRender:"renderNameText",defaultValue:"On script save or adapter start",attr:"script"}]},()=>super.onTagChange())}static getStaticData(){return{acceptedBy:"triggers",name:"Start script",id:"TriggerScriptSave",icon:"PlayArrow",title:"Triggers the on script saving or the javascript instance restart"}}getData(){return Bc.getStaticData()}}var DC={exports:{}};(function(a,s){(function(){var i=Math.PI,r=Math.sin,l=Math.cos,c=Math.tan,d=Math.asin,h=Math.atan2,p=Math.acos,f=i/180,b=1e3*60*60*24,y=2440588,w=2451545;function v(re){return re.valueOf()/b-.5+y}function _(re){return new Date((re+.5-y)*b)}function $(re){return v(re)-w}var T=f*23.4397;function S(re,B){return h(r(re)*l(T)-c(B)*r(T),l(re))}function E(re,B){return d(r(B)*l(T)+l(B)*r(T)*r(re))}function D(re,B,N){return h(r(re),l(re)*r(B)-c(N)*l(B))}function R(re,B,N){return d(r(B)*r(N)+l(B)*l(N)*l(re))}function L(re,B){return f*(280.16+360.9856235*re)-B}function H(re){return re<0&&(re=0),2967e-7/Math.tan(re+.00312536/(re+.08901179))}function G(re){return f*(357.5291+.98560028*re)}function z(re){var B=f*(1.9148*r(re)+.02*r(2*re)+3e-4*r(3*re)),N=f*102.9372;return re+B+N+i}function Z(re){var B=G(re),N=z(B);return{dec:E(N,0),ra:S(N,0)}}var he={};he.getPosition=function(re,B,N){var te=f*-N,X=f*B,se=$(re),F=Z(se),Te=L(se,te)-F.ra;return{azimuth:D(Te,X,F.dec),altitude:R(Te,X,F.dec)}};var Ce=he.times=[[-.833,"sunrise","sunset"],[-.3,"sunriseEnd","sunsetStart"],[-6,"dawn","dusk"],[-12,"nauticalDawn","nauticalDusk"],[-18,"nightEnd","night"],[6,"goldenHourEnd","goldenHour"]];he.addTime=function(re,B,N){Ce.push([re,B,N])};var M=9e-4;function Y(re,B){return Math.round(re-M-B/(2*i))}function C(re,B,N){return M+(re+B)/(2*i)+N}function Q(re,B,N){return w+re+.0053*r(B)-.0069*r(2*N)}function ve(re,B,N){return p((r(re)-r(B)*r(N))/(l(B)*l(N)))}function ce(re,B,N,te,X,se,F){var Te=ve(re,N,te),ae=C(Te,B,X);return Q(ae,se,F)}he.getTimes=function(re,B,N){var te=f*-N,X=f*B,se=$(re),F=Y(se,te),Te=C(0,te,F),ae=G(Te),we=z(ae),Ie=E(we,0),Me=Q(Te,ae,we),Ae,We,k,q,K,O={solarNoon:_(Me),nadir:_(Me+.5)};for(Ae=0,We=Ce.length;Ae=0&&(U=Math.sqrt(q)/(Math.abs(Me)*2),O=We-U,A=We+U,Math.abs(O)<=1&&K++,Math.abs(A)<=1&&K++,O<-1&&(O=A)),K===1?F<0?we=W+O:Ie=W+O:K===2&&(we=W+(k<0?A:O),Ie=W+(k<0?O:A)),!(we&&Ie));W+=2)F=ae;var ue={};return we&&(ue.rise=me(X,we)),Ie&&(ue.set=me(X,Ie)),!we&&!Ie&&(ue[k>0?"alwaysUp":"alwaysDown"]=!0),ue},a.exports=he})()})(DC);var bR=DC.exports;const AC=qo(bR),vR='{"time":{"start":"00:00","end":"24:00","mode":"hours","interval":1},"period":{"days":1}}';class Ii extends at{coordinates=null;constructor(s){super(s,Ii.getStaticData())}static compile(s,i){var c;let r="",l=i.justCheck?IC:xC;if(l=l.replace('"__%%DEBUG_TRIGGER%%__"',`_sendToFrontEnd(${s._id}, {trigger: true})`),s.tagCard==="interval")r=`setInterval(${l}, ${s.interval||1} * ${s.unit==="s"?1e3:s.unit==="m"?6e4:36e5});`;else if(s.tagCard==="cron")r=`schedule("${s.cron}", ${l});`;else if(s.tagCard==="at"){const[d,h]=(s.at||"").split(":");let p="*";if((c=s==null?void 0:s.dow)!=null&&c.length&&!s.dow.includes("_")){const f=[...s.dow].map(v=>parseInt(v,10));f.sort();const b=[];let y=f[0],w=1;for(;w1?(y===f[w-1]?b.push(y.toString()):f[w-1]-y===1?b.push(`${y},${f[w-1]}`):b.push(`${y}-${f[w-1]}`),y=f[w]):w===f.length-1&&(y===f[w-1]||f[w]-y===1?b.push(`${y},${f[w]}`):b.push(`${y}-${f[w]}`));p=b.join(",")}r=`schedule("${h||"0"} ${d||"0"} * * ${p}", ${l});`}else s.tagCard==="astro"?r=`schedule({astro: "${s.astro}", shift: ${s.offset?s.offsetValue:0}}, ${l});`:s.tagCard==="wizard"&&(r=`schedule('${s.wizard}', ${l});`);return r}static _time2String(s){return s?`${s.getHours().toString().padStart(2,"0")}:${s.getMinutes().toString().padStart(2,"0")}`:"--:--"}async _setAstro(s,i,r){var p,f;if(s||=this.state.settings.astro||"solarNoon",i??=this.state.settings.offset,r??=this.state.settings.offsetValue,r=parseInt(r,10)||0,!this.coordinates){const b=await this.props.socket.getObject("system.adapter.javascript.0"),y=(p=b==null?void 0:b.native)==null?void 0:p.latitude,w=(f=b==null?void 0:b.native)==null?void 0:f.longitude;if(!y&&!w){const v=await this.props.socket.getObject("system.config");v!=null&&v.common&&(v.common.latitude||v.common.longitude)?this.coordinates={latitude:parseFloat(v.common.latitude),longitude:parseFloat(v.common.longitude)}:this.coordinates=null}else this.coordinates={latitude:parseFloat(y),longitude:parseFloat(w)}}const l=this.coordinates&&AC.getTimes(new Date,this.coordinates.latitude,this.coordinates.longitude),c=l?Object.keys(l).map(b=>({value:b,title:b,title2:`[${Ii._time2String(l[b])}]`,order:l?Ii._time2String(l[b]):"??:??"})):[];c.sort((b,y)=>b.order>y.order?1:b.ordersuper.onTagChange())}_setInterval(s){s=parseInt(s||this.state.settings.interval,10)||30;let i;s===1?i=[{value:"s",title:"second"},{value:"m",title:"minute"},{value:"h",title:"hour"}]:i=[{value:"s",title:"seconds"},{value:"m",title:"minutes"},{value:"h",title:"hours"}],this.setState({inputs:[{nameRender:"renderNumber",attr:"interval",frontText:"every",defaultValue:30,className:"block-input-interval"},{nameRender:"renderSelect",attr:"unit",defaultValue:"s",options:i}]},()=>super.onTagChange())}renderDebug(s){return x.I18n.t("Triggered")}onValueChanged(s,i){this.state.settings.tagCard==="astro"?i==="astro"?this._setAstro(s):i==="offset"?this._setAstro(void 0,s):i==="offsetValue"&&this._setAstro(void 0,void 0,s):this.state.settings.tagCard==="interval"&&i==="interval"&&this._setInterval(s)}renderCron(s,i,r){const{className:l}=this.props;return m.jsxs("div",{children:[m.jsxs("div",{style:{display:"flex",alignItems:"baseline"},children:[m.jsx("div",{style:{width:"100%"},children:this.renderText({nameRender:"renderText",attr:"cron",defaultValue:i},this.state.settings.cron||i,r)}),m.jsx(Xr,{square:!0,style:{marginLeft:7},value:"...",className:l,onClick:()=>this.setState({openDialog:!0,textCron:this.state.settings.cron})})]}),this.state.openDialog?m.jsx(hm,{disabled:this.state.settings.cron===this.state.textCron,onApply:()=>{const c=this.state.textCron;r(c,"cron",()=>{r(x.convertCronToText(c,x.I18n.getLanguage()),"addText"),this.setState({openDialog:!1})})},onClose:()=>this.setState({openDialog:!1,textCron:""}),children:m.jsx(x.ComplexCron,{cronExpression:this.state.settings.cron,onChange:c=>this.setState({textCron:c}),language:x.I18n.getLanguage()})}):null,this.renderNameText({nameRender:"renderNameText",defaultValue:x.I18n.t("every hour at 0 minutes"),attr:"addText",signature:!0,doNotTranslate:!0},this.state.settings.addText||x.I18n.t("every hour at 0 minutes"))]},"cron")}renderWizard(s,i,r){const{className:l}=this.props;return m.jsxs("div",{children:[m.jsxs("div",{style:{display:"flex",alignItems:"center",marginTop:7},children:[m.jsx(Ei,{className:l,autoComplete:"off",fullWidth:!0,variant:"outlined",size:"small",multiline:!0,rows:2,value:this.state.settings.wizardText,onChange:c=>r(c),customValue:!0}),m.jsx(Xr,{square:!0,style:{marginLeft:7},value:"...",className:l,onClick:()=>this.setState({openDialog:!0,wizard:this.state.settings.wizard,wizardText:x.Schedule.state2text(this.state.settings.wizard)})})]}),this.state.openDialog?m.jsx(hm,{disabled:this.state.settings.wizard===this.state.wizard,onApply:()=>this.setState({openDialog:!1},()=>{const c=JSON.parse(this.state.wizard);c.valid||={from:x.Schedule.now2string()},c.valid.from||=x.Schedule.now2string(),r({wizardText:this.state.wizardText,wizard:JSON.stringify(c)})}),onClose:()=>this.setState({openDialog:!1}),children:m.jsx(x.Schedule,{theme:this.props.theme,schedule:i,onChange:(c,d)=>this.setState({wizardText:d||"",wizard:c})})}):null]},"wizard")}onTagChange(s){switch(s||=this.state.settings.tagCard,s){case"interval":this._setInterval();break;case"cron":this.setState({inputs:[{nameRender:"renderCron",attr:"cron",defaultValue:"0 * * * *"}]},()=>super.onTagChange());break;case"wizard":{const i=JSON.parse(vR);i.valid||={from:x.Schedule.now2string()},i.valid.from||=x.Schedule.now2string(),this.setState({inputs:[{nameRender:"renderWizard",attr:"wizard",defaultValue:JSON.stringify(i)}]},()=>super.onTagChange(null,()=>{const r=x.Schedule.state2text(this.state.settings.wizard||i);if(this.state.settings.wizard!==r){const l=JSON.parse(JSON.stringify(this.state.settings));l.wizardText=r,this.setState({settings:l}),this.props.onChange(l)}}));break}case"at":this.setState({inputs:[{nameRender:"renderTime",prefix:"at",attr:"at",defaultValue:"07:30"},{nameRender:"renderSelect",attr:"dow",default:"",multiple:!0,defaultValue:["_","1","2","3","4","5","6","0"],options:[{value:"_",title:"Every day",only:!0},{value:"1",title:"Monday",titleShort:"Mo"},{value:"2",title:"Tuesday",titleShort:"Tu"},{value:"3",title:"Wednesday",titleShort:"We"},{value:"4",title:"Thursday",titleShort:"Th"},{value:"5",title:"Friday",titleShort:"Fr"},{value:"6",title:"Saturday",titleShort:"Sa"},{value:"0",title:"Sunday",titleShort:"Su"}]}]},()=>super.onTagChange());break;case"astro":this._setAstro();break}}static getStaticData(){return{acceptedBy:"triggers",name:"Schedule",id:"TriggerScheduleBlock",icon:"AccessTime",tagCardArray:["cron","wizard","interval","at","astro"],title:"Triggers the rule periodically or on some specific time"}}getData(){return Ii.getStaticData()}}const In={valueAck:{color:"#b02323"},valueNotAck:{color:"#12ac15"}},OC=_e.forwardRef((a,s)=>m.jsx(ZT,{direction:"up",ref:s,...a}));OC.displayName="Transition";class jc extends at{inputRef;constructor(s){super(s,jc.getStaticData()),this.inputRef=_e.createRef()}static compile(s,i){let r=i.justCheck?IC:xC;return r=r.replace('"__%%DEBUG_TRIGGER%%__"',`_sendToFrontEnd(${s._id}, {val: obj.state.val, ack: obj.state.ack, valOld: obj.oldState && obj.oldState.val, ackOld: obj.oldState && obj.oldState.ack})`),`on({id: "${s.oid||""}", change: "${s.tagCard==="on update"?"any":"ne"}"}, ${r});`}renderDebug(s){return s.data.valOld!==void 0?m.jsxs("span",{children:[x.I18n.t("Triggered")," ",m.jsx("span",{style:s.data.ackOld?In.valueAck:In.valueNotAck,children:Ln(s.data.valOld)})," ","→"," ",m.jsx("span",{style:s.data.ack?In.valueAck:In.valueNotAck,children:Ln(s.data.val)})]}):m.jsxs("span",{children:[x.I18n.t("Triggered")," ",m.jsx("span",{style:s.data.ack?In.valueAck:In.valueNotAck,children:Ln(s.data.val)})]})}onWriteValue(){this.setState({openSimulate:!1});let s=this.state.simulateValue;window.localStorage.setItem(`javascript.app.${this.state.settings.oid}_ack`,this.state.simulateAck?"true":"false"),this.state.settings.oidType==="boolean"?(s=s===!0||s==="true"||s==="1",window.localStorage.setItem(`javascript.app.${this.state.settings.oid}`,s?"true":"false")):this.state.settings.oidType==="number"?(s=parseFloat(s)||0,window.localStorage.setItem(`javascript.app.${this.state.settings.oid}`,s.toString())):window.localStorage.setItem(`javascript.app.${this.state.settings.oid}`,(s==null?void 0:s.toString())||""),this.props.socket.setState(this.state.settings.oid,{val:s,ack:!!this.state.simulateAck})}renderWriteState(){return[m.jsx(Ue,{disabled:!this.state.settings.oid||!this.state.enableSimulation,variant:"contained",color:"primary",onClick:()=>{this.setState({openSimulate:!0,simulateValue:this.state.settings.oidType==="boolean"?window.localStorage.getItem(`javascript.app.${this.state.settings.oid}`)==="true":window.localStorage.getItem(`javascript.app.${this.state.settings.oid}`)||"",simulateAck:window.localStorage.getItem(`javascript.app.${this.state.settings.oid}_ack`)==="true"}),setTimeout(()=>{var s;return(s=this.inputRef.current)==null?void 0:s.focus()},200)},children:x.I18n.t("Simulate")},"buttonWrite"),m.jsxs(Pt,{open:!!this.state.openSimulate,TransitionComponent:OC,keepMounted:!0,onClose:()=>this.setState({openSimulate:!1}),"aria-labelledby":"simulate-dialog-slide-title","aria-describedby":"simulate-dialog-slide-description",children:[m.jsx(qt,{id:"simulate-dialog-slide-title",children:x.I18n.t("Trigger with value")}),m.jsxs(Wt,{children:[this.state.settings.oidType==="boolean"?m.jsx(Bg,{control:m.jsx(Nw,{inputRef:this.inputRef,onKeyUp:s=>s.key==="Enter"&&this.onWriteValue(),value:!!this.state.simulateValue,onChange:s=>this.setState({simulateValue:s.target.checked})}),label:x.I18n.t("Value")}):m.jsx(Eo,{variant:"standard",inputRef:this.inputRef,label:x.I18n.t("Value"),fullWidth:!0,onKeyUp:s=>s.key==="Enter"&&this.onWriteValue(),value:!this.state.simulateValue&&this.state.simulateValue!==0?"":this.state.simulateValue,onChange:s=>this.setState({simulateValue:s.target.value})}),m.jsx("br",{}),m.jsx(Bg,{control:m.jsx(Yr,{checked:!!this.state.simulateAck,onChange:s=>this.setState({simulateAck:s.target.checked}),color:"primary"}),label:x.I18n.t("Ack")})]}),m.jsxs(Bt,{children:[m.jsxs(Ue,{variant:"contained",onClick:()=>this.onWriteValue(),color:"primary",children:[m.jsx(SS,{}),x.I18n.t("Write")]}),m.jsxs(Ue,{color:"grey",variant:"contained",onClick:()=>this.setState({openSimulate:!1}),children:[m.jsx(Jc,{}),x.I18n.t("Close")]})]})]},"dialogWrite")]}onTagChange(s){this.setState({inputs:[{nameRender:"renderObjectID",attr:"oid",defaultValue:""},{nameRender:"renderWriteState"}]},()=>{super.onTagChange()})}static getStaticData(){return{acceptedBy:"triggers",name:"State",id:"TriggerState",icon:"FlashOn",tagCardArray:["on change","on update"],title:"Triggers the rule on update or change of some state"}}getData(){return jc.getStaticData()}}const yR=""+new URL("hysteresis-CLhhemcG.png",import.meta.url).href,yw=`function __hysteresis(val, limit, state, hist, comp) { let cond1, cond2; if (comp === '>') { cond1 = val > limit + hist; @@ -1200,35 +1200,35 @@ const demo = ${JSON.stringify(a,null,2).replace(/\*\//g,"* /")}; } else { return state; } -}`;class qr extends at{constructor(s){super(s,qr.getStaticData())}isAllTriggersOnState(){var s,i,r,l;return!!((i=(s=this.props.userRules)==null?void 0:s.triggers)!=null&&i.find(c=>c.id==="TriggerState"))&&!((l=(r=this.props.userRules)==null?void 0:r.triggers)!=null&&l.find(c=>c.id!=="TriggerState"))}static compile(s,i){var d,h;let r=s.value;r==null&&(r=!1);let l,c;if(s.tagCard==="()")i.prelines||=[],i.prelines.find(p=>p!==vw)||i.prelines.push(vw),s.useTrigger?(l="obj.state.val",r===""&&(r=0),c=`__hysteresis(subCondVar${s._id}, ${r}, __%%STATE%%__, ${s.hist}, "${s.histComp}")`):(l=`(await getStateAsync("${s.oid}")).val`,r===""&&(r=0),typeof r=="string"&&parseFloat(r.trim()).toString()!==r.trim()&&(r=`"${r}"`),c=`__hysteresis(subCondVar${s._id}, ${r}, __%%STATE%%__, ${s.hist}, "${s.histComp}")`);else if(s.tagCard!=="includes"){const p=s.tagCard==="="?"==":s.tagCard==="<>"?"!=":s.tagCard;s.useTrigger?(l="obj.state.val",((d=i==null?void 0:i.trigger)==null?void 0:d.oidType)==="string"?(r=r.replace(/"/g,'\\"'),c=`subCondVar${s._id} ${p} "${r}"`):(r===""&&(r=0),typeof r=="string"&&parseFloat(r.trim()).toString()!==r.trim()&&(r=`"${r}"`),c=`subCondVar${s._id} ${p} ${r}`)):(l=`(await getStateAsync("${s.oid}")).val`,s.oidType==="string"?(r=r.replace(/"/g,'\\"'),c=`subCondVar${s._id} ${p} "${r}"`):(r===""&&(r=0),typeof r=="string"&&parseFloat(r.trim()).toString()!==r.trim()&&(r=`"${r}"`),c=`subCondVar${s._id} ${p} ${r}`))}else s.useTrigger?(l="obj.state.val",((h=i==null?void 0:i.trigger)==null?void 0:h.oidType)==="string"?(r=r.replace(/"/g,'\\"'),c=`obj.state.val.includes("${r}")`):c="false"):(l=`(await getStateAsync("${s.oid}")).val`,s.oidType==="string"?(r=r.replace(/"/g,'\\"'),c=`subCondVar${s._id}.includes("${r}")`):c="false");return i.conditionsStates.push({name:`subCondVar${s._id}`,id:s.oid}),i.conditionsVars.push(`const subCondVar${s._id} = ${l};`),i.conditionsVars.push(`const subCond${s._id} = ${c};`),i.conditionsDebug.push(`_sendToFrontEnd(${s._id}, {result: subCond${s._id}, value: subCondVar${s._id}, compareWith: "${r}"});`),`subCond${s._id}`}renderDebug(s){const i=this.state.settings.tagCard;return i!=="()"?`${s.data.result.toString().toUpperCase()} [${s.data.value} ${i} ${s.data.compareWith}]`:x.I18n.t("Triggered")}onShowHelp=()=>this.setState({showHysteresisHelp:!0});_setInputs(s,i,r,l,c){var $,S;const d=this.isAllTriggersOnState();i=i||this.state.settings.tagCard,r=r||this.state.settings.oidType,l=l||this.state.settings.oidUnit,c=c||this.state.settings.oidStates,s===void 0&&(s=this.state.settings.useTrigger),d&&s&&((S=($=this.props.userRules)==null?void 0:$.triggers)==null?void 0:S.length)===1&&(r=this.props.userRules.triggers[0].oidType,l=this.props.userRules.triggers[0].oidUnit,c=this.props.userRules.triggers[0].oidStates);const h=qr.getStaticData().tagCardArray,p=h.find(T=>T.title===i)||h[0];let f,b=null;r==="number"?(f=[{title:"=",title2:"[equal]",text:"equal to"},{title:">=",title2:"[greater or equal]",text:"greater or equal"},{title:">",title2:"[greater]",text:"greater than"},{title:"<=",title2:"[less or equal]",text:"less or equal"},{title:"<",title2:"[less]",text:"less than"},{title:"<>",title2:"[not equal]",text:"not equal to"},{title:"()",title2:"[hysteresis]",text:"hysteresis"}],c&&(b=Object.keys(c).map(T=>c?{value:T,title:c[T]}:null).filter(T=>T))):r==="boolean"?(f=[{title:"=",title2:"[equal]",text:"equal to"},{title:"<>",title2:"[not equal]",text:"not equal to"}],b=[{title:"false",value:!1},{title:"true",value:!0}]):(f=[{title:"=",title2:"[equal]",text:"equal to"},{title:">=",title2:"[greater or equal]",text:"greater or equal"},{title:">",title2:"[greater]",text:"greater than"},{title:"<=",title2:"[less or equal]",text:"less or equal"},{title:"<",title2:"[less]",text:"less than"},{title:"<>",title2:"[not equal]",text:"not equal to"},{title:".",title2:"[includes]",text:"includes"}],c&&(b=Object.keys(c).map(T=>({value:T,title:c?c[T]:T.toString()}))));let y=null;f.find(T=>T.title===i)||(i=f[0].title,y=y||{...this.state.settings},y.tagCard=i);let w,v={nameRender:"renderText",defaultValue:"",attr:"value",frontText:i==="()"?"Limit":(p==null?void 0:p.text)||"compare with",doNotTranslateBack:!0,backText:l};b&&(v={nameRender:"renderSelect",defaultValue:b[0].value,options:b,attr:"value",frontText:(p==null?void 0:p.text)||"compare with",doNotTranslateBack:!0,backText:l},b.find(T=>T.value===this.state.settings.value)||(y=y||{...this.state.settings},y.value=b[0].value),b.length<=2&&(f=[{title:"=",title2:"[equal]",text:"equal to"},{title:"<>",title2:"[not equal]",text:"not equal to"}])),d&&s?w=[{backText:"use trigger value",nameRender:"renderCheckbox",attr:"useTrigger",defaultValue:!1},v]:d?w=[{backText:"use trigger value",nameRender:"renderCheckbox",attr:"useTrigger"},{nameRender:"renderObjectID",attr:"oid",defaultValue:""},v]:w=[{nameRender:"renderObjectID",attr:"oid",defaultValue:""},v],i==="()"&&(w.splice(1,0,{nameRender:"renderDialog",icon:"HelpOutline",frontText:"Explanation",onShowDialog:this.onShowHelp}),w.splice(2,0,{nameRender:"renderSelect",attr:"histComp",defaultValue:">",frontText:"Condition",doNotTranslate:!0,options:[{title:">",value:">"},{title:">=",value:">="},{title:"<",value:"<"},{title:"<=",value:"<="},{title:"=",value:"="},{title:"<>",value:"<>"}]}),w.push({frontText:"Δ",doNotTranslate:!0,nameRender:"renderNumber",noHelperText:!0,attr:"hist",defaultValue:1,doNotTranslateBack:!0,backText:l}));const _={iconTag:!0,tagCardArray:f,inputs:w};this.setState(_,()=>super.onTagChange(null,()=>{y&&(this.setState({settings:y}),this.props.onChange(y))}))}onValueChanged(s,i){typeof s=="object"?this._setInputs(s.useTrigger,s.tagCard,s.oidType,s.states):i==="useTrigger"?this._setInputs(s):i==="oidType"?this._setInputs(void 0,void 0,s):i==="oidUnit"?this._setInputs(void 0,void 0,void 0,s):i==="oidStates"&&this._setInputs(void 0,void 0,void 0,void 0,s)}onUpdate(){this._setInputs(this.state.settings.useTrigger)}onTagChange(s){this._setInputs(this.state.settings.useTrigger,s)}static getStaticData(){return{acceptedBy:"conditions",name:"State condition",id:"ConditionState",icon:"Shuffle",tagCardArray:[{title:"=",title2:"[equal]",text:"equal to"},{title:">=",title2:"[greater or equal]",text:"greater or equal"},{title:">",title2:"[greater]",text:"greater than"},{title:"<=",title2:"[less or equal]",text:"less or equal"},{title:"<",title2:"[less]",text:"less than"},{title:"<>",title2:"[not equal]",text:"not equal to"},{title:".",title2:"[includes]",text:"includes"},{title:"()",title2:"[hysteresis]",text:"hysteresis"}],title:"Compares the state value with user defined value"}}getData(){return qr.getStaticData()}renderSpecific(){return this.state.showHysteresisHelp?m.jsxs(Pt,{open:!0,maxWidth:"md",onClose:()=>this.setState({showHysteresisHelp:!1}),"aria-labelledby":"alert-dialog-title","aria-describedby":"alert-dialog-description",children:[m.jsx(Wt,{children:m.jsx(Dw,{id:"alert-dialog-description",children:m.jsx("img",{src:mO,alt:"Hysteresis"})})}),m.jsx(Bt,{children:m.jsx(Ue,{onClick:()=>this.setState({showHysteresisHelp:!1}),color:"primary",autoFocus:!0,children:x.I18n.t("OK")})})]}):null}}const yw=[31,29,31,30,31,30,31,31,30,31,30,31];class Xr extends at{constructor(s){super(s,Xr.getStaticData())}static compile(s,i){const r=s.tagCard==="="?"===":s.tagCard==="<>"?"!==":s.tagCard;let l;if(s.withDate){const[c,d]=(s.date||"01.01").toString().split(".");let h=parseInt(d,10)||0,p=parseInt(c,10)||0;p>12?p=12:p<0&&(p=0),h>yw[p]?h=yw[p]:h<0&&(h=0),h&&p?l=`formatDate(Date.now(), 'MM.DD-hh:mm') ${r} "${s.date}-${s.time}"`:h===0&&p?l=`formatDate(Date.now(), 'MM-hh:mm') ${r} "${p.toString().padStart(2,"0")}-${s.time}"`:p===0&&h?l=`formatDate(Date.now(), 'DD-hh:mm') ${r} "${h.toString().padStart(2,"0")}-${s.time}"`:l=`formatDate(Date.now(), 'hh:mm') ${r} "${s.time}"`}else l=`formatDate(Date.now(), 'hh:mm') ${r} "${s.time}"`;return i.conditionsVars.push(`const subCond${s._id} = ${l};`),i.conditionsDebug.push(`_sendToFrontEnd(${s._id}, {result: subCond${s._id}});`),`subCond${s._id}`}_setInputs(s,i){i=i===void 0?this.state.settings.withDate:i,s=s||this.state.settings.tagCard;const r=Xr.getStaticData().tagCardArray,l=r==null?void 0:r.find(d=>d.title===s),c=[{nameRender:"renderNameText",attr:"interval",defaultValue:"Actual time of day"},{frontText:(l==null?void 0:l.text)||s,nameRender:"renderTime",attr:"time",defaultValue:"12:00"},{frontText:"with date",nameRender:"renderCheckbox",attr:"withDate",defaultValue:!1}];i&&c.push({nameRender:"renderDate",attr:"date",defaultValue:"01.01"}),this.setState({inputs:c,iconTag:!0},()=>super.onTagChange())}onValueChanged(s,i){i==="withDate"&&this._setInputs(void 0,s)}onTagChange(s){this._setInputs(s)}static getStaticData(){return{acceptedBy:"conditions",name:"Time condition",id:"ConditionTime",icon:"Shuffle",tagCardArray:[{title:"=",title2:"[equal]",text:"equal to"},{title:">=",title2:"[greater or equal]",text:"greater or equal"},{title:">",title2:"[greater]",text:"greater than"},{title:"<=",title2:"[less or equal]",text:"less or equal"},{title:"<",title2:"[less]",text:"less than"},{title:"<>",title2:"[not equal]",text:"not equal to"}],title:"Compares current time with the user specific time"}}getData(){return Xr.getStaticData()}}class Vo extends at{coordinates=null;constructor(s){super(s,Vo.getStaticData())}static compile(s,i){const r=s.tagCard==="="?"===":s.tagCard==="<>"?"!==":s.tagCard;let l;s.offset&&(l=parseInt(s.offsetValue,10)||0);const c=`formatDate(Date.now(), 'hh:mm') ${r} formatDate(getAstroDate("${s.astro}"${l?`, undefined, ${l}`:""}), 'hh:mm')`;return i.conditionsVars.push(`const subCond${s._id} = ${c};`),i.conditionsDebug.push(`_sendToFrontEnd(${s._id}, {result: ${c}});`),c}static _time2String(s){return s?`${s.getHours().toString().padStart(2,"0")}:${s.getMinutes().toString().padStart(2,"0")}`:"--:--"}onValueChanged(s,i){i==="astro"?this._setAstro(s):i==="offset"?this._setAstro(void 0,s):i==="offsetValue"&&this._setAstro(void 0,void 0,s)}async _setAstro(s,i,r){if(s=s||this.state.settings.astro||"solarNoon",i=i===void 0?this.state.settings.offset:i,r=r===void 0?this.state.settings.offsetValue:r,r=parseInt(r,10)||0,!this.coordinates){const b=await this.props.socket.getObject("system.adapter.javascript.0");if(!(b!=null&&b.native.latitude)&&!(b!=null&&b.native.longitude)){const y=await this.props.socket.getObject("system.config");y&&(y.common.latitude||y.common.longitude)?this.coordinates={latitude:y.common.latitude,longitude:y.common.longitude}:this.coordinates=null}else this.coordinates={latitude:b==null?void 0:b.native.latitude,longitude:b==null?void 0:b.native.longitude}}const l=this.coordinates?DC.getTimes(new Date,this.coordinates.latitude,this.coordinates.longitude):null,c=l?Object.keys(l).map(b=>({value:b,title:b,title2:`[${Vo._time2String(l[b])}]`,order:Vo._time2String(l[b])})):[];c.sort((b,y)=>b.order>y.order?1:b.orderb.title===this.state.settings.tagCard)||d[0];let p="--:--";if(s&&l&&l[s]){const b=new Date(l[s]);i&&b.setMinutes(b.getMinutes()+parseInt(r,10)),p=`(${x.I18n.t(h.text)} ${Vo._time2String(b)})`}let f;i?f=[{nameRender:"renderNameText",defaultValue:"Actual time of day",attr:"text"},{frontText:h.text,attr:"astro",nameRender:"renderSelect",options:c,doNotTranslate2:!0,defaultValue:"solarNoon"},{backText:"with offset",nameRender:"renderCheckbox",attr:"offset"},{backText:r===1?"minute":"minutes",frontText:"offset",nameRender:"renderNumber",defaultValue:0,attr:"offsetValue",noHelperText:!0},{nameRender:"renderNameText",attr:"textTime",doNotTranslate:!0,defaultValue:p}]:f=[{nameRender:"renderNameText",defaultValue:"Actual time of day",attr:"text"},{frontText:h.text,attr:"astro",nameRender:"renderSelect",options:c,doNotTranslate2:!0,defaultValue:"solarNoon"},{backText:"with offset",nameRender:"renderCheckbox",attr:"offset"},{nameRender:"renderNameText",attr:"textTime",doNotTranslate:!0,defaultValue:p}],this.setState({inputs:f},()=>super.onTagChange())}onTagChange(){this._setAstro()}static getStaticData(){return{acceptedBy:"conditions",name:"Astronomical",id:"ConditionAstronomical",icon:"Brightness3",tagCardArray:[{title:"=",title2:"[equal]",text:"equal to"},{title:">=",title2:"[greater or equal]",text:"greater or equal to"},{title:">",title2:"[greater]",text:"greater than"},{title:"<=",title2:"[less or equal]",text:"less or equal to"},{title:"<",title2:"[less]",text:"less than"},{title:"<>",title2:"[not equal]",text:"not equal to"}],title:"Compares current time with astronomical event"}}getData(){return Vo.getStaticData()}}const _w={valueAck:{color:"#b02323"},valueNotAck:{color:"#12ac15"}};class jc extends at{constructor(s){super(s,jc.getStaticData())}isAllTriggersOnState(){var s,i,r,l;return!!((i=(s=this.props.userRules)==null?void 0:s.triggers)!=null&&i.find(c=>c.id==="TriggerState"))&&!((l=(r=this.props.userRules)==null?void 0:r.triggers)!=null&&l.find(c=>c.id!=="TriggerState"))}static compile(s,i){let r=s.value;s.useTrigger?r=s.toggle?"!obj.state.val":"obj.state.val":(r==null&&(r=""),typeof s.value=="string"&&parseFloat(s.value).toString()!==s.value&&s.value!=="true"&&s.value!=="false"&&(r=`"${r.replace(/"/g,'\\"')}"${at.getReplacesInText(i)}`));let l;return s.toggle&&!s.useTrigger?l=`const subActionVar${s._id} = !(await getStateAsync("${s.oid}")).val`:l=`const subActionVar${s._id} = ${r}`,`// set state ${s.oid} to ${s.toggle&&!s.useTrigger?"toggle":r} +}`;class qr extends at{constructor(s){super(s,qr.getStaticData())}isAllTriggersOnState(){var s,i,r,l;return!!((i=(s=this.props.userRules)==null?void 0:s.triggers)!=null&&i.find(c=>c.id==="TriggerState"))&&!((l=(r=this.props.userRules)==null?void 0:r.triggers)!=null&&l.find(c=>c.id!=="TriggerState"))}static compile(s,i){var d,h;let r=s.value;r==null&&(r=!1);let l,c;if(s.tagCard==="()")i.prelines||=[],i.prelines.find(p=>p!==yw)||i.prelines.push(yw),s.useTrigger?(l="obj.state.val",r===""&&(r=0),c=`__hysteresis(subCondVar${s._id}, ${r}, __%%STATE%%__, ${s.hist}, "${s.histComp}")`):(l=`(await getStateAsync("${s.oid}")).val`,r===""&&(r=0),typeof r=="string"&&parseFloat(r.trim()).toString()!==r.trim()&&(r=`"${r}"`),c=`__hysteresis(subCondVar${s._id}, ${r}, __%%STATE%%__, ${s.hist}, "${s.histComp}")`);else if(s.tagCard!=="includes"){const p=s.tagCard==="="?"==":s.tagCard==="<>"?"!=":s.tagCard;s.useTrigger?(l="obj.state.val",((d=i==null?void 0:i.trigger)==null?void 0:d.oidType)==="string"?(r=r.replace(/"/g,'\\"'),c=`subCondVar${s._id} ${p} "${r}"`):(r===""&&(r=0),typeof r=="string"&&parseFloat(r.trim()).toString()!==r.trim()&&(r=`"${r}"`),c=`subCondVar${s._id} ${p} ${r}`)):(l=`(await getStateAsync("${s.oid}")).val`,s.oidType==="string"?(r=r.replace(/"/g,'\\"'),c=`subCondVar${s._id} ${p} "${r}"`):(r===""&&(r=0),typeof r=="string"&&parseFloat(r.trim()).toString()!==r.trim()&&(r=`"${r}"`),c=`subCondVar${s._id} ${p} ${r}`))}else s.useTrigger?(l="obj.state.val",((h=i==null?void 0:i.trigger)==null?void 0:h.oidType)==="string"?(r=r.replace(/"/g,'\\"'),c=`obj.state.val.includes("${r}")`):c="false"):(l=`(await getStateAsync("${s.oid}")).val`,s.oidType==="string"?(r=r.replace(/"/g,'\\"'),c=`subCondVar${s._id}.includes("${r}")`):c="false");return i.conditionsStates.push({name:`subCondVar${s._id}`,id:s.oid}),i.conditionsVars.push(`const subCondVar${s._id} = ${l};`),i.conditionsVars.push(`const subCond${s._id} = ${c};`),i.conditionsDebug.push(`_sendToFrontEnd(${s._id}, {result: subCond${s._id}, value: subCondVar${s._id}, compareWith: "${r}"});`),`subCond${s._id}`}renderDebug(s){const i=this.state.settings.tagCard;return i!=="()"?`${s.data.result.toString().toUpperCase()} [${s.data.value} ${i} ${s.data.compareWith}]`:x.I18n.t("Triggered")}onShowHelp=()=>this.setState({showHysteresisHelp:!0});_setInputs(s,i,r,l,c){var $,T;const d=this.isAllTriggersOnState();i=i||this.state.settings.tagCard,r=r||this.state.settings.oidType,l=l||this.state.settings.oidUnit,c=c||this.state.settings.oidStates,s===void 0&&(s=this.state.settings.useTrigger),d&&s&&((T=($=this.props.userRules)==null?void 0:$.triggers)==null?void 0:T.length)===1&&(r=this.props.userRules.triggers[0].oidType,l=this.props.userRules.triggers[0].oidUnit,c=this.props.userRules.triggers[0].oidStates);const h=qr.getStaticData().tagCardArray,p=h.find(S=>S.title===i)||h[0];let f,b=null;r==="number"?(f=[{title:"=",title2:"[equal]",text:"equal to"},{title:">=",title2:"[greater or equal]",text:"greater or equal"},{title:">",title2:"[greater]",text:"greater than"},{title:"<=",title2:"[less or equal]",text:"less or equal"},{title:"<",title2:"[less]",text:"less than"},{title:"<>",title2:"[not equal]",text:"not equal to"},{title:"()",title2:"[hysteresis]",text:"hysteresis"}],c&&(b=Object.keys(c).map(S=>c?{value:S,title:c[S]}:null).filter(S=>S))):r==="boolean"?(f=[{title:"=",title2:"[equal]",text:"equal to"},{title:"<>",title2:"[not equal]",text:"not equal to"}],b=[{title:"false",value:!1},{title:"true",value:!0}]):(f=[{title:"=",title2:"[equal]",text:"equal to"},{title:">=",title2:"[greater or equal]",text:"greater or equal"},{title:">",title2:"[greater]",text:"greater than"},{title:"<=",title2:"[less or equal]",text:"less or equal"},{title:"<",title2:"[less]",text:"less than"},{title:"<>",title2:"[not equal]",text:"not equal to"},{title:".",title2:"[includes]",text:"includes"}],c&&(b=Object.keys(c).map(S=>({value:S,title:c?c[S]:S.toString()}))));let y=null;f.find(S=>S.title===i)||(i=f[0].title,y=y||{...this.state.settings},y.tagCard=i);let w,v={nameRender:"renderText",defaultValue:"",attr:"value",frontText:i==="()"?"Limit":(p==null?void 0:p.text)||"compare with",doNotTranslateBack:!0,backText:l};b&&(v={nameRender:"renderSelect",defaultValue:b[0].value,options:b,attr:"value",frontText:(p==null?void 0:p.text)||"compare with",doNotTranslateBack:!0,backText:l},b.find(S=>S.value===this.state.settings.value)||(y=y||{...this.state.settings},y.value=b[0].value),b.length<=2&&(f=[{title:"=",title2:"[equal]",text:"equal to"},{title:"<>",title2:"[not equal]",text:"not equal to"}])),d&&s?w=[{backText:"use trigger value",nameRender:"renderCheckbox",attr:"useTrigger",defaultValue:!1},v]:d?w=[{backText:"use trigger value",nameRender:"renderCheckbox",attr:"useTrigger"},{nameRender:"renderObjectID",attr:"oid",defaultValue:""},v]:w=[{nameRender:"renderObjectID",attr:"oid",defaultValue:""},v],i==="()"&&(w.splice(1,0,{nameRender:"renderDialog",icon:"HelpOutline",frontText:"Explanation",onShowDialog:this.onShowHelp}),w.splice(2,0,{nameRender:"renderSelect",attr:"histComp",defaultValue:">",frontText:"Condition",doNotTranslate:!0,options:[{title:">",value:">"},{title:">=",value:">="},{title:"<",value:"<"},{title:"<=",value:"<="},{title:"=",value:"="},{title:"<>",value:"<>"}]}),w.push({frontText:"Δ",doNotTranslate:!0,nameRender:"renderNumber",noHelperText:!0,attr:"hist",defaultValue:1,doNotTranslateBack:!0,backText:l}));const _={iconTag:!0,tagCardArray:f,inputs:w};this.setState(_,()=>super.onTagChange(null,()=>{y&&(this.setState({settings:y}),this.props.onChange(y))}))}onValueChanged(s,i){typeof s=="object"?this._setInputs(s.useTrigger,s.tagCard,s.oidType,s.states):i==="useTrigger"?this._setInputs(s):i==="oidType"?this._setInputs(void 0,void 0,s):i==="oidUnit"?this._setInputs(void 0,void 0,void 0,s):i==="oidStates"&&this._setInputs(void 0,void 0,void 0,void 0,s)}onUpdate(){this._setInputs(this.state.settings.useTrigger)}onTagChange(s){this._setInputs(this.state.settings.useTrigger,s)}static getStaticData(){return{acceptedBy:"conditions",name:"State condition",id:"ConditionState",icon:"Shuffle",tagCardArray:[{title:"=",title2:"[equal]",text:"equal to"},{title:">=",title2:"[greater or equal]",text:"greater or equal"},{title:">",title2:"[greater]",text:"greater than"},{title:"<=",title2:"[less or equal]",text:"less or equal"},{title:"<",title2:"[less]",text:"less than"},{title:"<>",title2:"[not equal]",text:"not equal to"},{title:".",title2:"[includes]",text:"includes"},{title:"()",title2:"[hysteresis]",text:"hysteresis"}],title:"Compares the state value with user defined value"}}getData(){return qr.getStaticData()}renderSpecific(){return this.state.showHysteresisHelp?m.jsxs(Pt,{open:!0,maxWidth:"md",onClose:()=>this.setState({showHysteresisHelp:!1}),"aria-labelledby":"alert-dialog-title","aria-describedby":"alert-dialog-description",children:[m.jsx(Wt,{children:m.jsx(Aw,{id:"alert-dialog-description",children:m.jsx("img",{src:yR,alt:"Hysteresis"})})}),m.jsx(Bt,{children:m.jsx(Ue,{onClick:()=>this.setState({showHysteresisHelp:!1}),color:"primary",autoFocus:!0,children:x.I18n.t("OK")})})]}):null}}const _w=[31,29,31,30,31,30,31,31,30,31,30,31];class Zr extends at{constructor(s){super(s,Zr.getStaticData())}static compile(s,i){const r=s.tagCard==="="?"===":s.tagCard==="<>"?"!==":s.tagCard;let l;if(s.withDate){const[c,d]=(s.date||"01.01").toString().split(".");let h=parseInt(d,10)||0,p=parseInt(c,10)||0;p>12?p=12:p<0&&(p=0),h>_w[p]?h=_w[p]:h<0&&(h=0),h&&p?l=`formatDate(Date.now(), 'MM.DD-hh:mm') ${r} "${s.date}-${s.time}"`:h===0&&p?l=`formatDate(Date.now(), 'MM-hh:mm') ${r} "${p.toString().padStart(2,"0")}-${s.time}"`:p===0&&h?l=`formatDate(Date.now(), 'DD-hh:mm') ${r} "${h.toString().padStart(2,"0")}-${s.time}"`:l=`formatDate(Date.now(), 'hh:mm') ${r} "${s.time}"`}else l=`formatDate(Date.now(), 'hh:mm') ${r} "${s.time}"`;return i.conditionsVars.push(`const subCond${s._id} = ${l};`),i.conditionsDebug.push(`_sendToFrontEnd(${s._id}, {result: subCond${s._id}});`),`subCond${s._id}`}_setInputs(s,i){i=i===void 0?this.state.settings.withDate:i,s=s||this.state.settings.tagCard;const r=Zr.getStaticData().tagCardArray,l=r==null?void 0:r.find(d=>d.title===s),c=[{nameRender:"renderNameText",attr:"interval",defaultValue:"Actual time of day"},{frontText:(l==null?void 0:l.text)||s,nameRender:"renderTime",attr:"time",defaultValue:"12:00"},{frontText:"with date",nameRender:"renderCheckbox",attr:"withDate",defaultValue:!1}];i&&c.push({nameRender:"renderDate",attr:"date",defaultValue:"01.01"}),this.setState({inputs:c,iconTag:!0},()=>super.onTagChange())}onValueChanged(s,i){i==="withDate"&&this._setInputs(void 0,s)}onTagChange(s){this._setInputs(s)}static getStaticData(){return{acceptedBy:"conditions",name:"Time condition",id:"ConditionTime",icon:"Shuffle",tagCardArray:[{title:"=",title2:"[equal]",text:"equal to"},{title:">=",title2:"[greater or equal]",text:"greater or equal"},{title:">",title2:"[greater]",text:"greater than"},{title:"<=",title2:"[less or equal]",text:"less or equal"},{title:"<",title2:"[less]",text:"less than"},{title:"<>",title2:"[not equal]",text:"not equal to"}],title:"Compares current time with the user specific time"}}getData(){return Zr.getStaticData()}}class Vo extends at{coordinates=null;constructor(s){super(s,Vo.getStaticData())}static compile(s,i){const r=s.tagCard==="="?"===":s.tagCard==="<>"?"!==":s.tagCard;let l;s.offset&&(l=parseInt(s.offsetValue,10)||0);const c=`formatDate(Date.now(), 'hh:mm') ${r} formatDate(getAstroDate("${s.astro}"${l?`, undefined, ${l}`:""}), 'hh:mm')`;return i.conditionsVars.push(`const subCond${s._id} = ${c};`),i.conditionsDebug.push(`_sendToFrontEnd(${s._id}, {result: ${c}});`),c}static _time2String(s){return s?`${s.getHours().toString().padStart(2,"0")}:${s.getMinutes().toString().padStart(2,"0")}`:"--:--"}onValueChanged(s,i){i==="astro"?this._setAstro(s):i==="offset"?this._setAstro(void 0,s):i==="offsetValue"&&this._setAstro(void 0,void 0,s)}async _setAstro(s,i,r){if(s=s||this.state.settings.astro||"solarNoon",i=i===void 0?this.state.settings.offset:i,r=r===void 0?this.state.settings.offsetValue:r,r=parseInt(r,10)||0,!this.coordinates){const b=await this.props.socket.getObject("system.adapter.javascript.0");if(!(b!=null&&b.native.latitude)&&!(b!=null&&b.native.longitude)){const y=await this.props.socket.getObject("system.config");y&&(y.common.latitude||y.common.longitude)?this.coordinates={latitude:y.common.latitude,longitude:y.common.longitude}:this.coordinates=null}else this.coordinates={latitude:b==null?void 0:b.native.latitude,longitude:b==null?void 0:b.native.longitude}}const l=this.coordinates?AC.getTimes(new Date,this.coordinates.latitude,this.coordinates.longitude):null,c=l?Object.keys(l).map(b=>({value:b,title:b,title2:`[${Vo._time2String(l[b])}]`,order:Vo._time2String(l[b])})):[];c.sort((b,y)=>b.order>y.order?1:b.orderb.title===this.state.settings.tagCard)||d[0];let p="--:--";if(s&&l&&l[s]){const b=new Date(l[s]);i&&b.setMinutes(b.getMinutes()+parseInt(r,10)),p=`(${x.I18n.t(h.text)} ${Vo._time2String(b)})`}let f;i?f=[{nameRender:"renderNameText",defaultValue:"Actual time of day",attr:"text"},{frontText:h.text,attr:"astro",nameRender:"renderSelect",options:c,doNotTranslate2:!0,defaultValue:"solarNoon"},{backText:"with offset",nameRender:"renderCheckbox",attr:"offset"},{backText:r===1?"minute":"minutes",frontText:"offset",nameRender:"renderNumber",defaultValue:0,attr:"offsetValue",noHelperText:!0},{nameRender:"renderNameText",attr:"textTime",doNotTranslate:!0,defaultValue:p}]:f=[{nameRender:"renderNameText",defaultValue:"Actual time of day",attr:"text"},{frontText:h.text,attr:"astro",nameRender:"renderSelect",options:c,doNotTranslate2:!0,defaultValue:"solarNoon"},{backText:"with offset",nameRender:"renderCheckbox",attr:"offset"},{nameRender:"renderNameText",attr:"textTime",doNotTranslate:!0,defaultValue:p}],this.setState({inputs:f},()=>super.onTagChange())}onTagChange(){this._setAstro()}static getStaticData(){return{acceptedBy:"conditions",name:"Astronomical",id:"ConditionAstronomical",icon:"Brightness3",tagCardArray:[{title:"=",title2:"[equal]",text:"equal to"},{title:">=",title2:"[greater or equal]",text:"greater or equal to"},{title:">",title2:"[greater]",text:"greater than"},{title:"<=",title2:"[less or equal]",text:"less or equal to"},{title:"<",title2:"[less]",text:"less than"},{title:"<>",title2:"[not equal]",text:"not equal to"}],title:"Compares current time with astronomical event"}}getData(){return Vo.getStaticData()}}const ww={valueAck:{color:"#b02323"},valueNotAck:{color:"#12ac15"}};class Fc extends at{constructor(s){super(s,Fc.getStaticData())}isAllTriggersOnState(){var s,i,r,l;return!!((i=(s=this.props.userRules)==null?void 0:s.triggers)!=null&&i.find(c=>c.id==="TriggerState"))&&!((l=(r=this.props.userRules)==null?void 0:r.triggers)!=null&&l.find(c=>c.id!=="TriggerState"))}static compile(s,i){let r=s.value;s.useTrigger?r=s.toggle?"!obj.state.val":"obj.state.val":(r==null&&(r=""),typeof s.value=="string"&&parseFloat(s.value).toString()!==s.value&&s.value!=="true"&&s.value!=="false"&&(r=`"${r.replace(/"/g,'\\"')}"${at.getReplacesInText(i)}`));let l;return s.toggle&&!s.useTrigger?l=`const subActionVar${s._id} = !(await getStateAsync("${s.oid}")).val`:l=`const subActionVar${s._id} = ${r}`,`// set state ${s.oid} to ${s.toggle&&!s.useTrigger?"toggle":r} ${l}; _sendToFrontEnd(${s._id}, {val: subActionVar${s._id}, ack: ${s.tagCard==="update"}}); - await setStateAsync("${s.oid}", subActionVar${s._id}, ${s.tagCard==="update"});`}renderDebug(s){return m.jsxs("span",{children:[x.I18n.t("Set:")," ",m.jsx("span",{style:s.data.ack?_w.valueAck:_w.valueNotAck,children:Ln(s.data.val)})]})}_setInputs(s,i){const r=this.isAllTriggersOnState();i=i===void 0?this.state.settings.toggle:i,s=s===void 0?this.state.settings.useTrigger:s;let l="",c;const{oidType:d,oidUnit:h,oidStates:p,oidMax:f,oidMin:b,oidRole:y,oidWrite:w,oidStep:v}=this.state.settings;let _;d&&(d==="number"?(l="number",f!==void 0&&b!==void 0&&(l="slider")):d==="boolean"?(l="boolean",y&&y.includes("button")&&w&&(l="button")):(l="",y&&y.includes("color")&&(l="color")),p&&(c=Object.keys(p).map(S=>({value:S,title:p[S]})),l="select"));let $;if(r&&s)$=[{backText:"use trigger value",nameRender:"renderCheckbox",attr:"useTrigger",defaultValue:!1}],l==="boolean"&&$.push({backText:"toggle value",attr:"toggle",nameRender:"renderCheckbox",defaultValue:!1});else{switch(l){case"number":$=[{backText:h||"",frontText:"with",nameRender:"renderNumber",defaultValue:f===void 0?0:f,attr:"value"}],this.state.settings.value!==void 0&&isNaN(parseFloat(this.state.settings.value))&&(_={value:f===void 0?0:f});break;case"slider":{$=[{nameRender:"renderSlider",defaultValue:f,min:b,max:f,unit:h,step:v,attr:"value"}];const S=parseFloat(this.state.settings.value);this.state.settings.value!==void 0&&(isNaN(S)||Sf)&&(_={value:f});break}case"select":$=[{nameRender:"renderSelect",frontText:"with",options:c,defaultValue:(c==null?void 0:c[0].value)||"",attr:"value"}],this.state.settings.value!==void 0&&!(c!=null&&c.find(S=>S.value===this.state.settings.value))&&(_={value:(c==null?void 0:c[0].value)||""});break;case"boolean":$=[{backText:"toggle value",attr:"toggle",nameRender:"renderCheckbox",defaultValue:!1}],i||$.push({backText:"true",frontText:"false",nameRender:"renderSwitch",defaultValue:!1,attr:"value"}),this.state.settings.value!==void 0&&this.state.settings.value!==!1&&this.state.settings.value!==!0&&(_={value:!1});break;case"button":$=[{nameRender:"renderButton",defaultValue:!0,attr:"value"}],this.state.settings.value!==void 0&&this.state.settings.value!==!0&&(_={value:!0});break;case"color":$=[{nameRender:"renderColor",frontText:"with",defaultValue:"#FFFFFF",attr:"value"}],this.state.settings.value!==void 0&&(typeof this.state.settings.value!="string"||!this.state.settings.value.startsWith("#")&&!this.state.settings.value.startsWith("rgb"))&&(_={value:"#FFFFFF"});break;default:$=[{backText:h||"",frontText:"with",nameRender:"renderText",defaultValue:"",attr:"value"}];break}r&&$.unshift({backText:"use trigger value",nameRender:"renderCheckbox",attr:"useTrigger"})}return{inputs:$,newSettings:_}}onTagChange(s,i,r,l,c){c=c===void 0?this.state.settings.useTrigger:c;const{inputs:d,newSettings:h}=this._setInputs(c,l);d.unshift({nameRender:"renderObjectID",attr:"oid",defaultValue:"",checkReadOnly:!0}),this.setState({inputs:d},()=>super.onTagChange(null,()=>{if(h){const p=JSON.parse(JSON.stringify(this.state.settings));Object.assign(p,h),this.setState(p),this.props.onChange(p)}}))}onValueChanged(s,i){this.onTagChange(void 0,void 0,void 0,i==="toggle"?s:void 0,i==="useTrigger"?s:void 0)}onUpdate(){this.onTagChange()}static getStaticData(){return{acceptedBy:"actions",name:"Set state action",id:"ActionSetState",icon:"PlayForWork",tagCardArray:["control","update"],title:"Control or update some state",helpDialog:"You can use %s in the value to use the current trigger value or %id to display the triggered object ID"}}getData(){return jc.getStaticData()}}class Fc extends at{constructor(s){super(s,Fc.getStaticData())}static compile(s,i){return`// exec "${s.exec}" + await setStateAsync("${s.oid}", subActionVar${s._id}, ${s.tagCard==="update"});`}renderDebug(s){return m.jsxs("span",{children:[x.I18n.t("Set:")," ",m.jsx("span",{style:s.data.ack?ww.valueAck:ww.valueNotAck,children:Ln(s.data.val)})]})}_setInputs(s,i){const r=this.isAllTriggersOnState();i=i===void 0?this.state.settings.toggle:i,s=s===void 0?this.state.settings.useTrigger:s;let l="",c;const{oidType:d,oidUnit:h,oidStates:p,oidMax:f,oidMin:b,oidRole:y,oidWrite:w,oidStep:v}=this.state.settings;let _;d&&(d==="number"?(l="number",f!==void 0&&b!==void 0&&(l="slider")):d==="boolean"?(l="boolean",y&&y.includes("button")&&w&&(l="button")):(l="",y&&y.includes("color")&&(l="color")),p&&(c=Object.keys(p).map(T=>({value:T,title:p[T]})),l="select"));let $;if(r&&s)$=[{backText:"use trigger value",nameRender:"renderCheckbox",attr:"useTrigger",defaultValue:!1}],l==="boolean"&&$.push({backText:"toggle value",attr:"toggle",nameRender:"renderCheckbox",defaultValue:!1});else{switch(l){case"number":$=[{backText:h||"",frontText:"with",nameRender:"renderNumber",defaultValue:f===void 0?0:f,attr:"value"}],this.state.settings.value!==void 0&&isNaN(parseFloat(this.state.settings.value))&&(_={value:f===void 0?0:f});break;case"slider":{$=[{nameRender:"renderSlider",defaultValue:f,min:b,max:f,unit:h,step:v,attr:"value"}];const T=parseFloat(this.state.settings.value);this.state.settings.value!==void 0&&(isNaN(T)||Tf)&&(_={value:f});break}case"select":$=[{nameRender:"renderSelect",frontText:"with",options:c,defaultValue:(c==null?void 0:c[0].value)||"",attr:"value"}],this.state.settings.value!==void 0&&!(c!=null&&c.find(T=>T.value===this.state.settings.value))&&(_={value:(c==null?void 0:c[0].value)||""});break;case"boolean":$=[{backText:"toggle value",attr:"toggle",nameRender:"renderCheckbox",defaultValue:!1}],i||$.push({backText:"true",frontText:"false",nameRender:"renderSwitch",defaultValue:!1,attr:"value"}),this.state.settings.value!==void 0&&this.state.settings.value!==!1&&this.state.settings.value!==!0&&(_={value:!1});break;case"button":$=[{nameRender:"renderButton",defaultValue:!0,attr:"value"}],this.state.settings.value!==void 0&&this.state.settings.value!==!0&&(_={value:!0});break;case"color":$=[{nameRender:"renderColor",frontText:"with",defaultValue:"#FFFFFF",attr:"value"}],this.state.settings.value!==void 0&&(typeof this.state.settings.value!="string"||!this.state.settings.value.startsWith("#")&&!this.state.settings.value.startsWith("rgb"))&&(_={value:"#FFFFFF"});break;default:$=[{backText:h||"",frontText:"with",nameRender:"renderText",defaultValue:"",attr:"value"}];break}r&&$.unshift({backText:"use trigger value",nameRender:"renderCheckbox",attr:"useTrigger"})}return{inputs:$,newSettings:_}}onTagChange(s,i,r,l,c){c=c===void 0?this.state.settings.useTrigger:c;const{inputs:d,newSettings:h}=this._setInputs(c,l);d.unshift({nameRender:"renderObjectID",attr:"oid",defaultValue:"",checkReadOnly:!0}),this.setState({inputs:d},()=>super.onTagChange(null,()=>{if(h){const p=JSON.parse(JSON.stringify(this.state.settings));Object.assign(p,h),this.setState(p),this.props.onChange(p)}}))}onValueChanged(s,i){this.onTagChange(void 0,void 0,void 0,i==="toggle"?s:void 0,i==="useTrigger"?s:void 0)}onUpdate(){this.onTagChange()}static getStaticData(){return{acceptedBy:"actions",name:"Set state action",id:"ActionSetState",icon:"PlayForWork",tagCardArray:["control","update"],title:"Control or update some state",helpDialog:"You can use %s in the value to use the current trigger value or %id to display the triggered object ID"}}getData(){return Fc.getStaticData()}}class zc extends at{constructor(s){super(s,zc.getStaticData())}static compile(s,i){return`// exec "${s.exec}" const subActionVar${s._id} = "${(s.exec||"").replace(/"/g,'\\"')}"${at.getReplacesInText(i)}; _sendToFrontEnd(${s._id}, {exec: subActionVar${s._id}}); - console.log(subActionVar${s._id});`}renderDebug(s){return`Exec: ${s.data.exec}`}onTagChange(s){this.setState({inputs:[{nameRender:"renderModalInput",attr:"exec",defaultValue:"ls /opt/iobroker",nameBlock:"Shell command"}]},()=>super.onTagChange(s))}static getStaticData(){return{acceptedBy:"actions",name:"Exec",id:"ActionExec",icon:"Apps",title:"Executes some shell command",helpDialog:"You can use %s in the command to use current trigger value or %id to use the triggered object ID"}}getData(){return Fc.getStaticData()}}class zc extends at{constructor(s){super(s,zc.getStaticData())}static compile(s,i){return`// HTTP request ${s.url} + console.log(subActionVar${s._id});`}renderDebug(s){return`Exec: ${s.data.exec}`}onTagChange(s){this.setState({inputs:[{nameRender:"renderModalInput",attr:"exec",defaultValue:"ls /opt/iobroker",nameBlock:"Shell command"}]},()=>super.onTagChange(s))}static getStaticData(){return{acceptedBy:"actions",name:"Exec",id:"ActionExec",icon:"Apps",title:"Executes some shell command",helpDialog:"You can use %s in the command to use current trigger value or %id to use the triggered object ID"}}getData(){return zc.getStaticData()}}class Uc extends at{constructor(s){super(s,Uc.getStaticData())}static compile(s,i){return`// HTTP request ${s.url} const subActionVar${s._id} = "${(s.url||"").replace(/"/g,'\\"')}"${at.getReplacesInText(i)}; _sendToFrontEnd(${s._id}, {url: subActionVar${s._id}}); - request(subActionVar${s._id});`}renderDebug(s){return`URL: ${s.data.url}`}onTagChange(s){this.setState({inputs:[{nameRender:"renderModalInput",attr:"url",defaultValue:"http://mydevice.com?...",nameBlock:"URL"}]},()=>super.onTagChange(s))}static getStaticData(){return{acceptedBy:"actions",name:"HTTP Call",id:"ActionHTTPCall",icon:"Language",title:"Make a HTTP get request",helpDialog:"You can use %s in the URL to use current trigger value or %id to use the triggered object ID"}}getData(){return zc.getStaticData()}}class Uc extends at{constructor(s){super(s,Uc.getStaticData())}static compile(s,i){return`// Log ${s.text} + request(subActionVar${s._id});`}renderDebug(s){return`URL: ${s.data.url}`}onTagChange(s){this.setState({inputs:[{nameRender:"renderModalInput",attr:"url",defaultValue:"http://mydevice.com?...",nameBlock:"URL"}]},()=>super.onTagChange(s))}static getStaticData(){return{acceptedBy:"actions",name:"HTTP Call",id:"ActionHTTPCall",icon:"Language",title:"Make a HTTP get request",helpDialog:"You can use %s in the URL to use current trigger value or %id to use the triggered object ID"}}getData(){return Uc.getStaticData()}}class Hc extends at{constructor(s){super(s,Hc.getStaticData())}static compile(s,i){return`// Log ${s.text} const subActionVar${s._id} = "${(s.text||"").replace(/"/g,'\\"')}"${at.getReplacesInText(i)}; _sendToFrontEnd(${s._id}, {text: subActionVar${s._id}}); - console.log(subActionVar${s._id});`}renderDebug(s){return x.I18n.t("Log: %s",s.data.text)}onTagChange(){this.setState({inputs:[{nameRender:"renderModalInput",attr:"text",defaultValue:"My device triggered",nameBlock:"Log text"}]},()=>super.onTagChange())}static getStaticData(){return{acceptedBy:"actions",name:"Log text",id:"ActionPrintText",icon:"Subject",title:"Print some text in log",helpDialog:"You can use %s in the text to display current trigger value or %id to display the triggered object ID"}}getData(){return Uc.getStaticData()}}class Hc extends at{constructor(s){super(s,Hc.getStaticData())}static compile(s){const i=s.unit==="ms"?1:s.unit==="s"?1e3:s.unit==="m"?6e4:36e5;return`// pause for ${i}ms + console.log(subActionVar${s._id});`}renderDebug(s){return x.I18n.t("Log: %s",s.data.text)}onTagChange(){this.setState({inputs:[{nameRender:"renderModalInput",attr:"text",defaultValue:"My device triggered",nameBlock:"Log text"}]},()=>super.onTagChange())}static getStaticData(){return{acceptedBy:"actions",name:"Log text",id:"ActionPrintText",icon:"Subject",title:"Print some text in log",helpDialog:"You can use %s in the text to display current trigger value or %id to display the triggered object ID"}}getData(){return Hc.getStaticData()}}class Wc extends at{constructor(s){super(s,Wc.getStaticData())}static compile(s){const i=s.unit==="ms"?1:s.unit==="s"?1e3:s.unit==="m"?6e4:36e5;return`// pause for ${i}ms _sendToFrontEnd(${s._id}, {paused: true}); await wait(${s.pause} * ${i}); - _sendToFrontEnd(${s._id}, {paused: false});`}renderDebug(s){return x.I18n.t("Paused: %s",s.data.paused)}_getOptions(s){return s=s===void 0?this.state.settings.pause:s,s===1||s==="1"?[{value:"ms",title:"millisecond"},{value:"s",title:"second"},{value:"m",title:"minute"},{value:"h",title:"hour"}]:[{value:"ms",title:"milliseconds"},{value:"s",title:"seconds"},{value:"m",title:"minutes"},{value:"h",title:"hours"}]}_setInputs(s){this.setState({inputs:[{nameRender:"renderNumber",attr:"pause",defaultValue:100,noHelperText:!0},{nameRender:"renderSelect",attr:"unit",defaultValue:"ms",options:this._getOptions(s)}]},()=>super.onTagChange())}onValueChanged(s,i){i==="pause"&&this._setInputs(s)}onTagChange(){this._setInputs()}static getStaticData(){return{acceptedBy:"actions",name:"Pause",id:"ActionPause",icon:"Pause",title:"Make a pause between actions"}}getData(){return Hc.getStaticData()}}class Wc extends at{constructor(s){super(s,Wc.getStaticData())}static compile(s){const i=(s.func||"").split(` + _sendToFrontEnd(${s._id}, {paused: false});`}renderDebug(s){return x.I18n.t("Paused: %s",s.data.paused)}_getOptions(s){return s=s===void 0?this.state.settings.pause:s,s===1||s==="1"?[{value:"ms",title:"millisecond"},{value:"s",title:"second"},{value:"m",title:"minute"},{value:"h",title:"hour"}]:[{value:"ms",title:"milliseconds"},{value:"s",title:"seconds"},{value:"m",title:"minutes"},{value:"h",title:"hours"}]}_setInputs(s){this.setState({inputs:[{nameRender:"renderNumber",attr:"pause",defaultValue:100,noHelperText:!0},{nameRender:"renderSelect",attr:"unit",defaultValue:"ms",options:this._getOptions(s)}]},()=>super.onTagChange())}onValueChanged(s,i){i==="pause"&&this._setInputs(s)}onTagChange(){this._setInputs()}static getStaticData(){return{acceptedBy:"actions",name:"Pause",id:"ActionPause",icon:"Pause",title:"Make a pause between actions"}}getData(){return Wc.getStaticData()}}class Gc extends at{constructor(s){super(s,Gc.getStaticData())}static compile(s){const i=(s.func||"").split(` `).map(r=>` ${r}`);return i.unshift(` _sendToFrontEnd(${s._id}, {func: 'executed'});`),i.unshift("// user function"),i.join(` -`)}renderDebug(){return x.I18n.t("Function: executed")}onTagChange(s){this.setState({inputs:[{nameRender:"renderModalInput",attr:"func",noTextEdit:!0,defaultValue:'console.log("Test")',nameBlock:"Function"}]},()=>super.onTagChange(s))}static getStaticData(){return{acceptedBy:"actions",name:"User function",id:"ActionFunction",icon:"Functions",title:"Write your own code",helpDialog:"This is advances option. You can write your own code here and it will be executed on trigger"}}getData(){return Wc.getStaticData()}}class Gc extends at{constructor(s){super(s,Gc.getStaticData())}isAllTriggersOnState(){var s,i,r,l;return!!((i=(s=this.props.userRules)==null?void 0:s.triggers)!=null&&i.find(c=>c.id==="TriggerState"))&&!((l=(r=this.props.userRules)==null?void 0:r.triggers)!=null&&l.find(c=>c.id!=="TriggerState"))}static compile(s,i){let r=s.value;s.useTrigger?r=s.toggle?"!obj.state.val":"obj.state.val":(r==null&&(r=""),typeof s.value=="string"&&parseFloat(s.value).toString()!==s.value&&s.value!=="true"&&s.value!=="false"&&(r=`"${r.replace(/"/g,'\\"')}"${at.getReplacesInText(i)}`));let l;return s.toggle&&!s.useTrigger?l=`const subActionVar${s._id} = !(await getStateAsync("${s.oid}")).val`:l=`const subActionVar${s._id} = ${r}`,`// set delayed state ${s.oid} to ${s.toggle&&!s.useTrigger?"toggle":r} with delay of ${s.delay}ms +`)}renderDebug(){return x.I18n.t("Function: executed")}onTagChange(s){this.setState({inputs:[{nameRender:"renderModalInput",attr:"func",noTextEdit:!0,defaultValue:'console.log("Test")',nameBlock:"Function"}]},()=>super.onTagChange(s))}static getStaticData(){return{acceptedBy:"actions",name:"User function",id:"ActionFunction",icon:"Functions",title:"Write your own code",helpDialog:"This is advances option. You can write your own code here and it will be executed on trigger"}}getData(){return Gc.getStaticData()}}class Vc extends at{constructor(s){super(s,Vc.getStaticData())}isAllTriggersOnState(){var s,i,r,l;return!!((i=(s=this.props.userRules)==null?void 0:s.triggers)!=null&&i.find(c=>c.id==="TriggerState"))&&!((l=(r=this.props.userRules)==null?void 0:r.triggers)!=null&&l.find(c=>c.id!=="TriggerState"))}static compile(s,i){let r=s.value;s.useTrigger?r=s.toggle?"!obj.state.val":"obj.state.val":(r==null&&(r=""),typeof s.value=="string"&&parseFloat(s.value).toString()!==s.value&&s.value!=="true"&&s.value!=="false"&&(r=`"${r.replace(/"/g,'\\"')}"${at.getReplacesInText(i)}`));let l;return s.toggle&&!s.useTrigger?l=`const subActionVar${s._id} = !(await getStateAsync("${s.oid}")).val`:l=`const subActionVar${s._id} = ${r}`,`// set delayed state ${s.oid} to ${s.toggle&&!s.useTrigger?"toggle":r} with delay of ${s.delay}ms ${l}; _sendToFrontEnd(${s._id}, {val: subActionVar${s._id}, ack: ${s.tagCard==="update"}}); - setStateDelayed("${s.oid}", subActionVar${s._id}, ${s.tagCard==="update"}, ${parseInt(s.delay,10)}, ${s.clearRunning?"true":"false"});`}renderDebug(s){var i,r;return m.jsxs("span",{children:[x.I18n.t("Set:")," ",m.jsx("span",{className:s.data.ack?(i=this.props.classes)==null?void 0:i.valueAck:(r=this.props.classes)==null?void 0:r.valueNotAck,children:Ln(s.data.val)})]})}_setInputs(s,i){const r=this.isAllTriggersOnState();i=i===void 0?this.state.settings.toggle:i,s=s===void 0?this.state.settings.useTrigger:s;let l="",c;const{oidType:d,oidUnit:h,oidStates:p,oidMax:f,oidMin:b,oidRole:y,oidWrite:w,oidStep:v}=this.state.settings;let _;d&&(d==="number"?(l="number",f!==void 0&&b!==void 0&&(l="slider")):d==="boolean"?(l="boolean",y&&y.includes("button")&&w&&(l="button")):(l="",y&&y.includes("color")&&(l="color")),p&&(c=Object.keys(p).map(S=>({value:S,title:p[S]})),l="select"));let $;if(r&&s)$=[{backText:"use trigger value",nameRender:"renderCheckbox",attr:"useTrigger",defaultValue:!1}],l==="boolean"&&$.push({backText:"toggle value",attr:"toggle",nameRender:"renderCheckbox",defaultValue:!1});else{switch(l){case"number":$=[{backText:h||"",frontText:"with",nameRender:"renderNumber",defaultValue:f===void 0?0:f,attr:"value"}],this.state.settings.value!==void 0&&isNaN(parseFloat(this.state.settings.value))&&(_={value:f===void 0?0:f});break;case"slider":{$=[{nameRender:"renderSlider",defaultValue:f,min:b,max:f,unit:h,step:v,attr:"value"}];const S=parseFloat(this.state.settings.value);this.state.settings.value!==void 0&&(isNaN(S)||Sf)&&(_={value:f});break}case"select":$=[{nameRender:"renderSelect",frontText:"with",options:c,defaultValue:(c==null?void 0:c[0].value)||"",attr:"value"}],this.state.settings.value!==void 0&&!(c!=null&&c.find(S=>S.value===this.state.settings.value))&&(_={value:(c==null?void 0:c[0].value)||""});break;case"boolean":$=[{backText:"toggle value",attr:"toggle",nameRender:"renderCheckbox",defaultValue:!1}],i||$.push({backText:"true",frontText:"false",nameRender:"renderSwitch",defaultValue:!1,attr:"value"}),this.state.settings.value!==void 0&&this.state.settings.value!==!1&&this.state.settings.value!==!0&&(_={value:!1});break;case"button":$=[{nameRender:"renderButton",defaultValue:!0,attr:"value"}],this.state.settings.value!==void 0&&this.state.settings.value!==!0&&(_={value:!0});break;case"color":$=[{nameRender:"renderColor",frontText:"with",defaultValue:"#FFFFFF",attr:"value"}],this.state.settings.value!==void 0&&(typeof this.state.settings.value!="string"||!this.state.settings.value.startsWith("#")&&!this.state.settings.value.startsWith("rgb"))&&(_={value:"#FFFFFF"});break;default:$=[{backText:h||"",frontText:"with",nameRender:"renderText",defaultValue:"",attr:"value"}];break}r&&$.unshift({backText:"use trigger value",nameRender:"renderCheckbox",attr:"useTrigger"})}return $.push({backText:"ms",frontText:"Delay",nameRender:"renderNumber",defaultValue:1e3,noHelperText:!0,attr:"delay"}),$.push({backText:"clear running",nameRender:"renderCheckbox",defaultValue:!0,attr:"clearRunning"}),{inputs:$,newSettings:_}}onTagChange(s,i,r,l,c){c=c===void 0?this.state.settings.useTrigger:c;const{inputs:d,newSettings:h}=this._setInputs(c,l);d.unshift({nameRender:"renderObjectID",attr:"oid",defaultValue:"",checkReadOnly:!0}),this.setState({inputs:d},()=>super.onTagChange(null,()=>{if(h){const p=JSON.parse(JSON.stringify(this.state.settings));Object.assign(p,h),this.setState(p),this.props.onChange(p)}}))}onValueChanged(s,i){this.onTagChange(void 0,void 0,void 0,i==="toggle"?s:void 0,i==="useTrigger"?s:void 0)}onUpdate(){this.onTagChange()}static getStaticData(){return{acceptedBy:"actions",name:"Set with delay",id:"ActionSetStateDelayed",icon:"PlayForWork",tagCardArray:["control","update"],title:"Control or update some state with delay",helpDialog:"You can use %s in the value to use the current trigger value or %id to display the triggered object ID"}}getData(){return Gc.getStaticData()}}class Vc extends at{constructor(s){super(s,Vc.getStaticData())}isAllTriggersOnState(){var s,i,r,l;return!!((i=(s=this.props.userRules)==null?void 0:s.triggers)!=null&&i.find(c=>c.id==="TriggerState"))&&!((l=(r=this.props.userRules)==null?void 0:r.triggers)!=null&&l.find(c=>c.id!=="TriggerState"))}static compile(s){const i=`const val2_${s._id} = (await getStateAsync("${s.oid1}")).val;`,r=`const val1_${s._id} = (await getStateAsync("${s.oid2}")).val;`;return`// ${s.oid1} ${s.operation} ${s.oid2} => ${s.oidResult} + setStateDelayed("${s.oid}", subActionVar${s._id}, ${s.tagCard==="update"}, ${parseInt(s.delay,10)}, ${s.clearRunning?"true":"false"});`}renderDebug(s){var i,r;return m.jsxs("span",{children:[x.I18n.t("Set:")," ",m.jsx("span",{className:s.data.ack?(i=this.props.classes)==null?void 0:i.valueAck:(r=this.props.classes)==null?void 0:r.valueNotAck,children:Ln(s.data.val)})]})}_setInputs(s,i){const r=this.isAllTriggersOnState();i=i===void 0?this.state.settings.toggle:i,s=s===void 0?this.state.settings.useTrigger:s;let l="",c;const{oidType:d,oidUnit:h,oidStates:p,oidMax:f,oidMin:b,oidRole:y,oidWrite:w,oidStep:v}=this.state.settings;let _;d&&(d==="number"?(l="number",f!==void 0&&b!==void 0&&(l="slider")):d==="boolean"?(l="boolean",y&&y.includes("button")&&w&&(l="button")):(l="",y&&y.includes("color")&&(l="color")),p&&(c=Object.keys(p).map(T=>({value:T,title:p[T]})),l="select"));let $;if(r&&s)$=[{backText:"use trigger value",nameRender:"renderCheckbox",attr:"useTrigger",defaultValue:!1}],l==="boolean"&&$.push({backText:"toggle value",attr:"toggle",nameRender:"renderCheckbox",defaultValue:!1});else{switch(l){case"number":$=[{backText:h||"",frontText:"with",nameRender:"renderNumber",defaultValue:f===void 0?0:f,attr:"value"}],this.state.settings.value!==void 0&&isNaN(parseFloat(this.state.settings.value))&&(_={value:f===void 0?0:f});break;case"slider":{$=[{nameRender:"renderSlider",defaultValue:f,min:b,max:f,unit:h,step:v,attr:"value"}];const T=parseFloat(this.state.settings.value);this.state.settings.value!==void 0&&(isNaN(T)||Tf)&&(_={value:f});break}case"select":$=[{nameRender:"renderSelect",frontText:"with",options:c,defaultValue:(c==null?void 0:c[0].value)||"",attr:"value"}],this.state.settings.value!==void 0&&!(c!=null&&c.find(T=>T.value===this.state.settings.value))&&(_={value:(c==null?void 0:c[0].value)||""});break;case"boolean":$=[{backText:"toggle value",attr:"toggle",nameRender:"renderCheckbox",defaultValue:!1}],i||$.push({backText:"true",frontText:"false",nameRender:"renderSwitch",defaultValue:!1,attr:"value"}),this.state.settings.value!==void 0&&this.state.settings.value!==!1&&this.state.settings.value!==!0&&(_={value:!1});break;case"button":$=[{nameRender:"renderButton",defaultValue:!0,attr:"value"}],this.state.settings.value!==void 0&&this.state.settings.value!==!0&&(_={value:!0});break;case"color":$=[{nameRender:"renderColor",frontText:"with",defaultValue:"#FFFFFF",attr:"value"}],this.state.settings.value!==void 0&&(typeof this.state.settings.value!="string"||!this.state.settings.value.startsWith("#")&&!this.state.settings.value.startsWith("rgb"))&&(_={value:"#FFFFFF"});break;default:$=[{backText:h||"",frontText:"with",nameRender:"renderText",defaultValue:"",attr:"value"}];break}r&&$.unshift({backText:"use trigger value",nameRender:"renderCheckbox",attr:"useTrigger"})}return $.push({backText:"ms",frontText:"Delay",nameRender:"renderNumber",defaultValue:1e3,noHelperText:!0,attr:"delay"}),$.push({backText:"clear running",nameRender:"renderCheckbox",defaultValue:!0,attr:"clearRunning"}),{inputs:$,newSettings:_}}onTagChange(s,i,r,l,c){c=c===void 0?this.state.settings.useTrigger:c;const{inputs:d,newSettings:h}=this._setInputs(c,l);d.unshift({nameRender:"renderObjectID",attr:"oid",defaultValue:"",checkReadOnly:!0}),this.setState({inputs:d},()=>super.onTagChange(null,()=>{if(h){const p=JSON.parse(JSON.stringify(this.state.settings));Object.assign(p,h),this.setState(p),this.props.onChange(p)}}))}onValueChanged(s,i){this.onTagChange(void 0,void 0,void 0,i==="toggle"?s:void 0,i==="useTrigger"?s:void 0)}onUpdate(){this.onTagChange()}static getStaticData(){return{acceptedBy:"actions",name:"Set with delay",id:"ActionSetStateDelayed",icon:"PlayForWork",tagCardArray:["control","update"],title:"Control or update some state with delay",helpDialog:"You can use %s in the value to use the current trigger value or %id to display the triggered object ID"}}getData(){return Vc.getStaticData()}}class Yc extends at{constructor(s){super(s,Yc.getStaticData())}isAllTriggersOnState(){var s,i,r,l;return!!((i=(s=this.props.userRules)==null?void 0:s.triggers)!=null&&i.find(c=>c.id==="TriggerState"))&&!((l=(r=this.props.userRules)==null?void 0:r.triggers)!=null&&l.find(c=>c.id!=="TriggerState"))}static compile(s){const i=`const val2_${s._id} = (await getStateAsync("${s.oid1}")).val;`,r=`const val1_${s._id} = (await getStateAsync("${s.oid2}")).val;`;return`// ${s.oid1} ${s.operation} ${s.oid2} => ${s.oidResult} ${i} ${r} _sendToFrontEnd(${s._id}, {val: val1_${s._id} ${s.operation} val2_${s._id}, ack: ${s.tagCard==="update"}}); - await setStateAsync("${s.oidResult}", val1_${s._id} ${s.operation} val2_${s._id}, ${s.tagCard==="update"});`}renderDebug(s){var i,r;return m.jsxs("span",{children:[x.I18n.t("Set:")," ",m.jsx("span",{className:s.data.ack?(i=this.props.classes)==null?void 0:i.valueAck:(r=this.props.classes)==null?void 0:r.valueNotAck,children:Ln(s.data.val)})]})}onTagChange(){const s=[];s.push({nameRender:"renderObjectID",title:"ID1",attr:"oid1",defaultValue:"",checkReadOnly:!1}),s.push({nameRender:"renderSelect",options:[{value:"+",title:"+"},{value:"-",title:"-"},{value:"*",title:"*"},{value:"/",title:"/"}],doNotTranslate:!0,defaultValue:"+",attr:"operation"}),s.push({nameRender:"renderObjectID",title:"ID2",attr:"oid2",defaultValue:"",checkReadOnly:!1}),s.push({nameRender:"renderNameText",defaultValue:"store in",attr:"textEqual"}),s.push({nameRender:"renderObjectID",attr:"oidResult",defaultValue:"",checkReadOnly:!0}),this.setState({inputs:s},()=>super.onTagChange(null,()=>{const i=JSON.parse(JSON.stringify(this.state.settings));this.props.onChange(i)}))}onValueChanged(s,i){this.onTagChange()}onUpdate(){this.onTagChange()}static getStaticData(){return{acceptedBy:"actions",name:"Operate two states",id:"ActionOperateStates",icon:"AddBox",tagCardArray:["control","update"],title:"Operations with two states"}}getData(){return Vc.getStaticData()}}const fO=[Ii,Pc,Bc,qr,Xr,Vo,jc,Fc,zc,Uc,Hc,Wc,Gc,Vc],hc={sayit:Oc,pushover:Nc,"whatsapp-cmb":Mc,pushsafer:Lc},$O=um({blocks:null,socket:null,onUpdate:!1,setOnUpdate:a=>{},setOnDebugMessage:a=>{},onDebugMessage:[],enableSimulation:!1,setEnableSimulation:a=>{},changedScripts:{},setChangedScripts:a=>{}}),bO=({children:a,socket:s})=>{const[i,r]=kt(null),[l,c]=kt(!1),[d,h]=kt([]),[p,f]=kt(!1),[b,y]=kt({});return Lt(()=>{l&&c(!1)},[l]),Lt(()=>{(async()=>{const w=await s.getAdapterInstances(),v=Object.keys(hc).filter(E=>w.find(D=>{var M;return((M=D==null?void 0:D.common)==null?void 0:M.name)===E})),_=[],$=w.filter(E=>E.common.javascriptRules),S=[];for(const E of $){if(S.includes(E.common.name)||!E.common.javascriptRules)continue;let D;if(E.common.javascriptRules.url.startsWith("http:")||E.common.javascriptRules.url.startsWith("https:")?D=E.common.javascriptRules.url:E.common.javascriptRules.url.startsWith("./")?D=`${window.location.protocol}//${window.location.host}${E.common.javascriptRules.url.replace(/^\./,"")}`:D=`${window.location.protocol}//${window.location.host}/adapter/${E.common.name}/${E.common.javascriptRules.url}`,E.common.javascriptRules.i18n===!0){const M=D.lastIndexOf("/");let P;M!==-1?P=D.substring(0,M):P=D;const W=x.I18n.getLanguage(),G=`${P}/i18n/${W}.json`;await fetch(G).then(z=>z.json()).then(z=>x.I18n.extendTranslations(z,W)).catch(z=>{if(W!=="en")return fetch(`${P}/i18n/en.json`).then(Z=>Z.json()).then(Z=>x.I18n.extendTranslations(Z,W)).catch(Z=>console.error(`Cannot load i18n "${G}": ${Z}`));console.log(`Cannot load i18n "${G}": ${z}`)})}else if(E.common.javascriptRules.i18n&&typeof E.common.javascriptRules.i18n=="object")try{x.I18n.extendTranslations(E.common.javascriptRules.i18n)}catch(M){console.error(`Cannot import i18n for "${E.common.javascriptRules.name}": ${M}`)}try{e_.registerRemotes([{name:E.common.javascriptRules.name,entry:D,type:E.common.javascriptRules.type}]);const M=(await e_.loadRemote(`${E.common.javascriptRules.name}/${E.common.javascriptRules.name}`)).default;M&&(_.push(M),S.push(E.common.name),hc[E.common.name]=null)}catch(M){console.error(`Cannot load component "${E.common.javascriptRules.name}": ${M}`)}}const T=v.filter(E=>hc[E]).map(E=>hc[E]);r([...fO,...T,..._])})()},[]),m.jsx($O.Provider,{value:{blocks:i,socket:s,onUpdate:l,setOnUpdate:c,onDebugMessage:d,setOnDebugMessage:h,enableSimulation:p,setEnableSimulation:f,changedScripts:b,setChangedScripts:y},children:a})},vO="Acknowledged",yO="Actions",_O="Add",wO="All",kO="Any",CO="Apply",TO="April",SO="Ask",EO="Astronomical",IO="August",xO="Cancel",DO="Close",AO="Condition",RO="Conditions",OO="Console",NO="Copied",MO="December",LO="Default",PO="Delay",BO="Delete",jO="Description",FO="Done",zO="Exec shell",UO="Explanation",HO="Export",WO="Februar",GO="February",VO="Filter",KO="Folder",YO="Fr",JO="Friday",qO="ID",XO="ID1",ZO="ID2",QO="Import",e1="Instance",t1="Instances",s1="Instructions",o1="Januar",i1="January",n1="July",r1="June",a1="Limit",l1="March",c1="May",u1="Menu",d1="Message",h1="Mo",p1="Model",g1="Monday",m1="Month",f1="More",$1="Name",b1="November",v1="OK",y1="October",_1="Ok",w1="Pause",k1="Pushover",C1="Pushsafer",T1="Reload",S1="Rename",E1="Repeat",I1="Restart",x1="Result",D1="Sa",A1="Saturday",R1="Save",O1="Schedule",N1="Script",M1="September",L1="Simulate",P1="Stack",B1="Start",j1="State",F1="Su",z1="Sunday",U1="Telegram",H1="Th",W1="Thursday",G1="Time",V1="Triggered",K1="Triggers",Y1="Tu",J1="Tuesday",q1="URL",X1="Value",Z1="Volume",Q1="We",eN="Wednesday",tN="Write",sN="Yes",oN="acknowledgment",iN="all",nN="and",rN="Astro",aN="at",lN="control",cN="copy",uN="CRON",dN="Dawn",hN="This is a special mode in which states and objects will not change. But only information about each planned change will be displayed in the protocol.",pN="Debug",gN="Dusk",mN="easy",fN="every",$N="Function",bN="ID",vN="Name",yN="Role",_N="Room",wN="Golden hour",kN="End of golden hour",CN='The code will be executed only every time when condition is true. E.g. if triggering on the temperature sensor value and the condition is "if temperature is greater than 20°C", the "then" actions will be executed every time when sensor sends the temperature and it is over 20°C. By 21°C, by 22°C and so on.',TN='The code will be executed only if the condition result changes. E.g. if triggering on the temperature sensor value and the condition is "if temperature is greater than 20°C", the "then" actions will be executed once when temperature is over 20. Next time the "then" actions will be executed when the temperature fails under 20 and then rises over 20 again.',SN="hours",EN="includes",IN="interval",xN="magic",DN="milliseconds",AN="minutes",RN="ms",ON="Nadir",NN="Nautical dawn",MN="Nautical dusk",LN="Next Sunrise",PN="Next sunset",BN="Night",jN="Night end",FN="normal",zN="offset",UN="one",HN="or",WN="quiet",GN="search",VN="seconds",KN="Solar noon",YN="sunrise",JN="Sunrise end",qN="Sunset",XN="Sunset start",ZN="then",QN="Acknowledge",eM="From",tM="Last changed",sM="Quality",oM="Timestamp",iM="User",nM="Value",rM="two",aM="update",lM="Adds debug output to the log for many system commands",cM="Verbose log outputs",uM="when",dM="Wizard",hM="Retry",pM={"%s not found":"%s not found","()":"()","(at %s)":"(at %s)","(optional)":"(optional)","-":"-",".":".","AI code generator":"AI code generator",Ack:vO,Actions:yO,"Actual time of day":"Actual time of day",Add:_O,"Add new script":"Add new script",All:wO,"All files will be accepted":"All files will be accepted",Any:kO,"Any month":"Any month",Apply:CO,April:TO,"Are you sure?":"Are you sure?",Ask:SO,Astronomical:EO,"Astronomical events today":"Astronomical events today",August:IO,"Blockly description":"Creating rules by graphic blocks","Body:":"Body:",Cancel:xO,"Cannot delete non empty item!":"Cannot delete non empty item!","Change layout":"Change layout",'Change theme (actual "%s")':'Change theme (now - "%s")',"Check blocks":"Check blocks","Check is not active, because javascript adapter is disabled":"Check is not active, because Javascript adapter is disabled","Clear search input":"Clear search input","Click on this icon":"Click on this icon",Close:DO,"Close all but current":"Close all but current","Collapse all":"Collapse all","Compares current time with astronomical event":"Compares current time with astronomical event","Compares current time with the user specific time":"Compares current time with the user specific time","Compares the state value with user defined value":"Compares the state value with user defined value",Condition:AO,Conditions:RO,"Configuration not saved.":"Configuration not saved.",Console:OO,"Control or update some state":"Control or update some state","Control or update some state with delay":"Control or update some state with delay","Convert blockly to javascript for ever.":"Permanently convert Blockly to Javascript.",Copied:NO,"Copy script":"Copy script","Copy to clipboard":"Copy to clipboard","Create new":"Create new","Create new folder":"Create new folder","Create new script":"Create new script","Create or edit CRON or time wizard":"Create or edit CRON or time wizard","Dark Theme":"Dark theme","Dark style":"Dark style",Date:"Date","Debug instance":"Debug instance","Debug options":"Debug options",December:MO,Default:LO,"Define cron...":"Define cron...","Define schedule...":"Define schedule...",Delay:PO,Delete:BO,"Delete %s":"Delete %s...","Delete folder":"Delete folder","Delete script":"Delete script",Description:jO,"Deselect all":"Deselect all","Discard changes for %s":"Discard changes for %s",Done:FO,"Double click to write value":"Double click to write value","Download as file":"Download as file","Drop some files here or click...":"Drop some files here or click...","Duplicate name":"Duplicate name","Edit script or just double click":"Edit script or just double click","Empty name is not allowed":"Empty name is not allowed","End search mode":"End search mode","Enter your question":"Enter your request",Error:"Error","Error formatting code":"Error formatting code","Error was found":"Error was found","Every day":"Every day",Exec:zO,"Executes some shell command":"Executes some shell command","Existing scripts will be overwritten.":"Existing scripts will be overwritten.","Expand all":"Expand all","Expert mode":"Expert mode",Explanation:UO,Export:HO,"Export all scripts":"Export all scripts","Export blocks":"Export blocks","Export selected blocks":"Export selected blocks",Februar:WO,February:GO,Filter:VO,Folder:KO,Fr:YO,Friday:JO,Function:"Function","Function editor":"Function editor","Function: executed":"Function: executed","Go to next line":"Go to next line","HTTP Call":"HTTP Call","Hide logs":"Hide logs",ID:qO,ID1:XO,ID2:ZO,Import:QO,"Import blocks":"Import blocks","Import error":"Import error","Import scripts":"Import scripts","Insert object ID":"Insert object ID",Instance:e1,"Instance is disabled":"Instance is disabled","Instance:":"Instance:",Instances:t1,Instructions:s1,"Invalid CRON":"Invalid CRON","It will not be possible to revert this operation.":"It will not be possible to revert this operation.","JS description":"Creating rules by writing Javascript",Januar:o1,January:i1,July:n1,June:r1,"Just check":"Just check","Keep my changes":"Keep my changes","Language:":"Language:","Learn More":"Learn More","Light style":"Light style",Limit:a1,"Local time":"Local time","Locate file":"Locate file","Log outputs":"Log outputs","Log text":"Log text","Log: %s":"Log: %s","Make a HTTP get request":"Make a HTTP get request","Make a pause between actions":"Make a pause between actions",March:l1,"March ":"March ",May:c1,Menu:u1,Message:d1,Mo:h1,Model:p1,Monday:g1,Month:m1,More:f1,Name:$1,"No API key found":"No API key found","No Chat GPT Key found":"No Chat GPT Key found","No active host found":"No active host found","Nothing found":"Nothing found",November:b1,OK:v1,October:y1,Ok:_1,"On condition change":"On condition result change","On script save or adapter start":"On script save or adapter start","On weekdays":"On weekdays","Open configuration":"Open configuration","Operate two states":"Operate two states","Operations with two states":"Operations with two states","Paste your blocks here":"Paste your blocks here",Pause:w1,"Pause execution":"Pause execution","Pause script":"Pause script","Phone:":"Phone:","Please select object ID...":"Please select object ID...","Press Ctrl+Enter to get the answer":"Press Ctrl+Enter to get the answer","Prettify the script":"Prettify the script","Print some text in log":"Print some text in log","Priority:":"Priority:",Pushover:k1,Pushsafer:C1,"Read only ID selected: %s":"Read only ID selected: %s",Reload:T1,Rename:S1,"Reorder scripts in folders":"Reorder scripts in folders",Repeat:E1,Restart:I1,Result:x1,"Resume execution":"Resume execution","Root folder":"Root folder","Rules description":"Create rules with IF, THEN, ELSE blocks","Run script":"Run script",Sa:D1,Saturday:A1,Save:R1,"Save all":"Save all","Say It":"Say It","Say some text via sayit adapter":"Say some text via sayit adapter",Schedule:O1,Script:N1,"Script %s was modified on disk":"Script %s was modified on disk","Script was modified externally":"Script was modified externally","Script is not running":"Script is not running","Search in scripts":"Search in scripts","Search...":"Search...","Select all":"Select all","Send email":"Send email","Sends an email":"Sends an email","Sends message via Pushsafer":"Sends message via Pushsafer","Sends message via pushover":"Sends message via pushover","Sends message via telegram":"Sends message via telegram","Sends message via whatsapp-cmb":"Sends message via whatsapp-cmb",September:M1,"Server time":"Server time","Set state action":"Set state action","Set with delay":"Set with delay","Shell command":"Shell command","Show astronomical events":"Show astronomical events","Show javascript code":"Show Javascript code","Show logs":"Show logs","Show only paused scripts":"Show only paused scripts","Show only running scripts":"Show only running scripts","Show only scripts with problems":"Show only scripts with problems",Simulate:L1,"Some files will be rejected":"Some files will be rejected","Sound:":"Sound:",Stack:P1,Start:B1,"Start script":"Start script",State:j1,"State condition":"State condition","Step into function":"Step into function","Step out from function":"Step out from function","Stop on exception":"Stop on exception",Su:F1,"Subject:":"Subject:",Sunday:z1,"TS description":"Creating rules by writing Typescript",Telegram:U1,"Text:":"Text:",Th:H1,'The script "%s" has been modified by another user or in another window. Do you want to reload the script or keep your local changes?':'The script "%s" has been modified by another user or in another window. Do you want to reload the script or keep your local changes?',"The script will be stopped and must be activated manually after debugging. Continue?":"The script will be stopped and must be activated manually after debugging. Continue?","This is advances option. You can write your own code here and it will be executed on trigger":"This is advances option. You can write your own code here and it will be executed on trigger",Thursday:W1,Time:G1,"Time condition":"Time condition","Title:":"Title:","To:":"To:","Trigger with value":"Trigger with value",Triggered:V1,Triggers:K1,"Triggers the on script saving or the javascript instance restart":"Triggers the on script saving or the javascript instance restart","Triggers the rule on update or change of some state":"Triggers the rule on update or change of some state","Triggers the rule periodically or on some specific time":"Triggers the rule periodically or on some specific time",Tu:Y1,Tuesday:J1,URL:q1,"Unknown error":"Unknown error","Unknown error!":"Unknown error!","Use generated code":"Use generated code","User function":"User function","User:":"User:",Value:X1,"Vibration:":"Vibration:",Volume:Z1,We:Q1,Wednesday:eN,"Whatsapp-cmb":"Whatsapp-cmb",Write:tN,"Write your own code":"Write your own code",Yes:sN,"Yet exists!":"Yet exists!","You can use %s in the URL to use current trigger value or %id to use the triggered object ID":"You can use %s in the URL to use current trigger value, %id to use the triggered object ID, %name to show triggered object ID name or %old to use old trigger value","You can use %s in the command to use current trigger value or %id to use the triggered object ID":"You can use %s in the command to use current trigger value, %id to use the triggered object ID, %name to show triggered object ID name or %old to use old trigger value","You can use %s in the text to display current trigger value or %id to display the triggered object ID":"You can use %s in the text to display current trigger value, %id to use the triggered object ID, %name to show triggered object ID name or %old to use old trigger value","You can use %s in the value to use the current trigger value or %id to display the triggered object ID":"You can use %s in the value to use the current trigger value, %id to use the triggered object ID, %name to show triggered object ID name or %old to use old trigger value","You have to enter OpenAI API key in the configuration of javascript adapter.":"You have to enter OpenAI API key in the configuration of javascript adapter.","You have to enter at least one API key in the configuration of javascript adapter.":"You have to enter at least one API key (OpenAI, Anthropic or Gemini) in the configuration of javascript adapter.","Please select a valid model":"Please select a valid model","[equal]":"[equal]","[greater or equal]":"[greater or equal]","[greater]":"[greater]","[hysteresis]":"[hysteresis]","[includes]":"[includes]","[less or equal]":"[less or equal]","[less]":"[less]","[not equal]":"[not equal]",acknowledgment:oN,all:iN,and:nN,"as JSON":"as JSON","as plain text":"as plain text",astro:rN,at:aN,"clear running":"clear running",control:lN,copy:cN,cron:uN,dawn:dN,debug_help:hN,debug_label:pN,default:"default",dusk:gN,easy:mN,else:"else","equal to":"equal to",every:fN,"every hour at 0 minutes":"every hour at 0 minutes",false:"false","file reading has failed: %s":"file reading has failed: %s","file reading was aborted":"file reading was aborted",filter_func:$N,filter_id:bN,filter_name:vN,filter_role:yN,filter_room:_N,"for edit or create script":"for edit or create a new script","for professionals":"for professionals","for programmers":"for programmers",goldenHour:wN,goldenHourEnd:kN,"greater or equal":"greater or equal","greater or equal to":"greater or equal to","greater than":"greater than",help_just_check:CN,help_on_change:TN,"high priority":"high priority","high-priority":"high-priority","highest priority":"highest priority",hours:SN,includes:EN,interval:IN,"just check":"just check","less or equal":"less or equal","less or equal to":"less or equal to","less than":"less than","lower priority":"lower priority","lowest priority":"lowest priority",magic:xN,milliseconds:DN,minutes:AN,ms:RN,nadir:ON,nauticalDawn:NN,nauticalDusk:MN,nextSunrise:LN,nextSunset:PN,night:BN,nightEnd:jN,"no blocks found":"No blocks found","no group":"NO GROUP",normal:FN,"normal priority":"normal priority","not running":"not running","not equal to":"not equal to","not properly connected":"This block is not properly connected to other blocks.",offset:zN,"on change":"on change","on condition change":"on condition change","on update":"on update",one:UN,or:HN,quiet:WN,"reset search":"reset search",search:GN,seconds:VN,solarNoon:KN,"store in":"store in",sunrise:YN,sunriseEnd:JN,sunset:qN,sunsetStart:XN,then:ZN,"toggle value":"toggle value",tooltip_ack:QN,tooltip_from:eM,tooltip_lc:tM,tooltip_quality:sM,tooltip_ts:oM,tooltip_user:iM,tooltip_value:nM,true:"true",two:rM,undefined:"undefined",update:aM,"use seconds":"use seconds","use trigger value":"use trigger value",verbose_help:lM,verbose_label:cM,when:uM,with:"with","with date":"with date","with offset":"with offset",wizard:dM,"Loading models...":"Loading models...","Could not connect to API at %s":"Could not connect to API at %s","Invalid API key":"Invalid API key","Access denied by API":"Access denied by API","API error: %s":"API error: %s",'Model "%s" not found':'Model "%s" not found',"Request failed: %s":"Request failed: %s",Retry:hM,"No running javascript instance found":"No running javascript instance found"},gM="Bestätigt",mM="Aktionen",fM="Hinzufügen",$M="Alle",bM="Egal",vM="Anwenden",yM="April",_M="Fragen",wM="Astronomisch",kM="August",CM="Abbrechen",TM="Schließen",SM="Bedingung",EM="Bedingungen",IM="Konsole",xM="Kopiert",DM="Dezember",AM="Standard",RM="Verzögerung",OM="Löschen",NM="Beschreibung",MM="Fertig",LM="Exec shell",PM="Erläuterung",BM="Export",jM="Februar",FM="Februar",zM="Filter",UM="Ordner",HM="Fr",WM="Freitag",GM="ID",VM="ID1",KM="ID2",YM="Import",JM="Instanz",qM="Instanzen",XM="Anleitung",ZM="Januar",QM="Januar",eL="Juli",tL="Juni",sL="Grenze",oL="März",iL="Mai",nL="Menü",rL="Nachricht",aL="Mo",lL="Modell",cL="Montag",uL="Monat",dL="Mehr",hL="Name",pL="November",gL="OK",mL="Oktober",fL="Ok",$L="Pause",bL="Pushover",vL="Pushsafer",yL="Neu laden",_L="Umbenennen",wL="Wiederholen",kL="Neustart",CL="Ergebnis",TL="Sa",SL="Samstag",EL="Speichern",IL="Zeitplan",xL="Skript",DL="September",AL="Simulieren",RL="Stack",OL="Start",NL="Zustand",ML="So",LL="Sonntag",PL="Telegram",BL="Do",jL="Donnerstag",FL="Zeit",zL="Ausgelöst",UL="Löst aus",HL="Di",WL="Dienstag",GL="URL",VL="Wert",KL="Volumen",YL="Mi",JL="Mittwoch",qL="Schreiben",XL="Ja",ZL="Wissen",QL="alle",eP="und",tP="Astro",sP="um",oP="Steuerung",iP="Kopie",nP="CRON",rP="Morgendämmerung",aP="Dies ist ein spezieller Modus, in dem sich Zustände und Objekte nicht ändern. Im Protokoll werden jedoch nur Informationen zu jeder geplanten Änderung angezeigt.",lP="Debuggen",cP="Abenddämmerung",uP="einfach",dP="jeder",hP="Funktion",pP="ID",gP="Name",mP="Rolle",fP="Raum",$P="Goldene Abendstunde",bP="Vormittag",vP='Der Code wird jedes Mal ausgeführt, wenn die Bedingung erfüllt ist. z.B. wenn der Temperatur wert sich ändert und die Bedingung "Wenn die Temperatur größer als 20°C ist" lautet, werden die "Dann" -Aktionen jedes Mal ausgeführt, wenn der Sensor die Temperatur sendet und diese über 20°C liegt. Bei 21°C, bei 22°C und so weiter.',yP='Der Code wird nur ausgeführt, wenn sich das Ergebnis der Bedingung ändert. z.B. wenn sich der Temperatur wert ändert und die Bedingung "Wenn die Temperatur größer als 20°C ist" lautet, werden die "Dann" -Aktionen einmal ausgeführt, wenn die Temperatur über 20°C liegt. Das nächste Mal werden die "Dann" -Aktionen ausgeführt, wenn die Temperatur unter 20°C gefallen ist und dann wieder über 20°C ansteigt.',_P="Stunden",wP="beinhaltet",kP="Intervall",CP="Magie",TP="Millisekunden",SP="Minuten",EP="ms",IP="Nadir",xP="nautische Morgendämmerung",DP="nautische Abenddämmerung",AP="Nächster Sonnenaufgang",RP="Nächster Sonnenuntergang",OP="Nacht",NP="astronomische Morgendämmerung",MP="Normal",LP="Versatz",PP="einer",BP="oder",jP="ruhig",FP="Suche",zP="Sekunden",UP="(Nach-)Mittag",HP="Sonnenaufgang",WP="Goldene Morgenstunde",GP="Sonnenuntergang",VP="Sonnenuntergang (Anfang)",KP="dann",YP="Bestätigen",JP="Von",qP="Zuletzt geändert",XP="Qualität",ZP="Zeitstempel",QP="Benutzer",eB="Wert",tB="zwei",sB="Aktualisieren",oB="Fügt Debug-Ausgaben für viele Systembefehle zum Protokoll hinzu",iB="Ausführliche Protokollausgaben",nB="falls",rB="Assistent",aB="Erneut versuchen",lB={"%s not found":"%s nicht gefunden","()":"()","(at %s)":"(um %s)","(optional)":"(optional)","-":"-",".":".","AI code generator":"KI-Codegenerator",Ack:gM,Actions:mM,"Actual time of day":"Tatsächliche Tageszeit",Add:fM,"Add new script":"Neues Skript hinzufügen",All:$M,"All files will be accepted":"Alle Dateien werden akzeptiert",Any:bM,"Any month":"Jeden Monat",Apply:vM,April:yM,"Are you sure?":"Wirklich sicher?",Ask:_M,Astronomical:wM,"Astronomical events today":"Astronomische Ereignisse heute",August:kM,"Blockly description":"Erstellen von Regeln durch Grafikblöcke","Body:":"Körper:",Cancel:CM,"Cannot delete non empty item!":"Kann nicht gelöscht werden, weil noch einige Elementen darin sind!","Change layout":"Layout ändern",'Change theme (actual "%s")':'Thema ändern (jetzt - "%s")',"Check blocks":"Blöcke prüfen","Check is not active, because javascript adapter is disabled":"Syntax-Check ist nicht aktiv, weil der Javascript Adapter nicht aktiv ist.","Clear search input":"Sucheingabe löschen","Click on this icon":"Auf dieses Symbol klicken",Close:TM,"Close all but current":"Alle anderen außer dem Aktiven schließen","Collapse all":"Alles einklappen","Compares current time with astronomical event":"Vergleicht die aktuelle Zeit mit einem astronomischen Ereignis","Compares current time with the user specific time":"Vergleicht die aktuelle Zeit mit der benutzerspezifischen Zeit","Compares the state value with user defined value":"Vergleicht den Zustandswert mit dem benutzerdefinierten Wert",Condition:SM,Conditions:EM,"Configuration not saved.":"Die Konfiguration ist nicht gespeichert.",Console:IM,"Control or update some state":"Zustand steuern oder aktualisieren","Control or update some state with delay":"Zustand mit Verzögerung steuern oder aktualisieren","Convert blockly to javascript for ever.":"Blockly dauerhaft in Javascript konvertieren.",Copied:xM,"Copy script":"Skript kopieren","Copy to clipboard":"In die Zwischenablage kopieren","Create new":"Neu erstellen","Create new folder":"Neuen Ordner erstellen","Create new script":"Neues Skript erstellen","Create or edit CRON or time wizard":"CRON- oder Zeit-Assistenten erstellen oder bearbeiten","Dark Theme":"Dunkles Thema","Dark style":"Dunkler Stil",Date:"Datum","Debug instance":"Debug-Instanz","Debug options":"Debug-Optionen",December:DM,Default:AM,"Define cron...":"Cron definieren ...","Define schedule...":"Zeitplan definieren ...",Delay:RM,Delete:OM,"Delete %s":"Löschen %s...","Delete folder":"Ordner löschen","Delete script":"Skript löschen",Description:NM,"Deselect all":"Alles abwählen","Discard changes for %s":"Änderungen für %s verwerfen",Done:MM,"Double click to write value":"Doppelklick zum Schreiben des Wertes","Download as file":"Download als Datei","Drop some files here or click...":"Dateien hier ablegen oder klicken ...","Duplicate name":"Doppelter Name","Edit script or just double click":"Skript bearbeiten oder einfach doppelklicken","Empty name is not allowed":"Leerer Name ist nicht zulässig","End search mode":"Suchmodus beenden","Enter your question":"Anfrage eingeben",Error:"Fehler","Error formatting code":"Fehler beim Formatieren des Codes","Error was found":"Fehler wurde gefunden","Every day":"Täglich",Exec:LM,"Executes some shell command":"Führt einen Shell-Befehl aus","Existing scripts will be overwritten.":"Vorhandene Skripte werden überschrieben.","Expand all":"Alle erweitern","Expert mode":"Expertenmodus",Explanation:PM,Export:BM,"Export all scripts":"Alle Skripte exportieren","Export blocks":"Blöcke exportieren","Export selected blocks":"Ausgewählte Blöcke exportieren",Februar:jM,February:FM,Filter:zM,Folder:UM,Fr:HM,Friday:WM,Function:"Funktion","Function editor":"Funktions-Editor","Function: executed":"Funktion: ausgeführt","Go to next line":"Gehe zur nächsten Zeile","HTTP Call":"HTTP-Aufruf","Hide logs":"Protokoll ausblenden",ID:GM,ID1:VM,ID2:KM,Import:YM,"Import blocks":"Blöcke importieren","Import error":"Fehler beim Importieren","Import scripts":"Skripte importieren","Insert object ID":"Objekt-ID einfügen",Instance:JM,"Instance is disabled":"Instanz ist deaktiviert","Instance:":"Instanz:",Instances:qM,Instructions:XM,"Invalid CRON":"Ungültiger CRON","It will not be possible to revert this operation.":"Dieser Vorgang kann nicht rückgängig gemacht werden.","JS description":"Regeln erstellen mit JavaScript",Januar:ZM,January:QM,July:eL,June:tL,"Just check":"Einfach überprüfen","Keep my changes":"Meine Änderungen behalten","Language:":"Sprache:","Learn More":"Mehr erfahren","Light style":"Heller Stil",Limit:sL,"Local time":"Lokale Zeit","Locate file":"Datei zeigen","Log outputs":"Protokoll","Log text":"Protokolltext","Log: %s":"Log: %s","Make a HTTP get request":"Eine HTTP-Abrufanforderung stellen","Make a pause between actions":"Eine Pause zwischen den Aktionen machen",March:oL,"March ":"März ",May:iL,Menu:nL,Message:rL,Mo:aL,Model:lL,Monday:cL,Month:uL,More:dL,Name:hL,"No API key found":"Kein API-Schlüssel gefunden","No Chat GPT Key found":"Kein Chat-GPT-Schlüssel gefunden","No active host found":"Kein aktiver Host gefunden","Nothing found":"Nichts gefunden",November:pL,OK:gL,October:mL,Ok:fL,"On condition change":"Bei Änderung des Ergebnis der Bedingung","On script save or adapter start":"Beim Speichern des Skripts oder beim Starten des Adapters","On weekdays":"An Wochentagen","Open configuration":"Konfiguration öffnen","Operate two states":"Zwei Zustände operieren","Operations with two states":"Operationen mit zwei Zuständen","Paste your blocks here":"Fügen Sie Ihre Blöcke hier ein",Pause:$L,"Pause execution":"Ausführung pausieren","Pause script":"Skript anhalten","Phone:":"Telefon:","Please select object ID...":"Objekt-ID auswählen ...","Press Ctrl+Enter to get the answer":"Strg+Eingabetaste, um die Antwort zu erhalten","Prettify the script":"Verschönern Sie das Skript","Print some text in log":"Einen Text im Protokoll ausdrucken","Priority:":"Priorität:",Pushover:bL,Pushsafer:vL,"Read only ID selected: %s":"Schreibgeschützte ID ausgewählt: %s",Reload:yL,Rename:_L,"Reorder scripts in folders":"Skripte in Ordnern neu ordnen",Repeat:wL,Restart:kL,Result:CL,"Resume execution":"Ausführung fortsetzen","Root folder":"Root-Verzeichnis","Rules description":"Regeln erstellen mit WENN-, DANN- und SONST-Blöcken","Run script":"Skript ausführen",Sa:TL,Saturday:SL,Save:EL,"Save all":"Alle speichern","Say It":"Say It","Say some text via sayit adapter":"Einen Text über den Sayit-Adapter sagen",Schedule:IL,Script:xL,"Script %s was modified on disk":'Skript "%s" wurde auf der Festplatte geändert',"Script was modified externally":"Skript wurde extern geändert","Script is not running":"Skript läuft nicht","Search in scripts":"Suche in Skripten","Search...":"Suche...","Select all":"Alles auswählen","Send email":"E-Mail senden","Sends an email":"Sendet eine E-Mail","Sends message via Pushsafer":"Sendet eine Nachricht über Pushsafer","Sends message via pushover":"Sendet eine Nachricht per Pushover","Sends message via telegram":"Sendet eine Nachricht per telegram","Sends message via whatsapp-cmb":"Sendet eine Nachricht über WhatsApp-Cmb",September:DL,"Server time":"Server-Zeit","Set state action":"Zustand setzten","Set with delay":"Setzen mit Verzögerung","Shell command":"Shell-Befehl","Show astronomical events":"Astronomische Ereignisse anzeigen","Show javascript code":"Javascript-Code zeigen","Show logs":"Protokoll anzeigen","Show only paused scripts":"Nur angehaltene Skripte zeigen","Show only running scripts":"Nur laufende Skripte zeigen","Show only scripts with problems":"Nur Skripte mit Problemen zeigen",Simulate:AL,"Some files will be rejected":"Einige Dateien werden abgelehnt","Sound:":"Klang:",Stack:RL,Start:OL,"Start script":"Skript starten",State:NL,"State condition":"Zustandsbedingung","Step into function":"Schritt in die Funktion","Step out from function":"Raus aus der Funktion","Stop on exception":"Bei Ausnahme anhalten",Su:ML,"Subject:":"Gegenstand:",Sunday:LL,"TS description":"Regeln erstellen mit TypeScript",Telegram:PL,"Text:":"Text:",Th:BL,'The script "%s" has been modified by another user or in another window. Do you want to reload the script or keep your local changes?':'Das Skript "%s" wurde von einem anderen Benutzer oder in einem anderen Fenster geändert. Möchten Sie das Skript neu laden oder Ihre lokalen Änderungen behalten?',"The script will be stopped and must be activated manually after debugging. Continue?":"Das Skript wird gestoppt und muss nach dem Debuggen manuell aktiviert werden. Fortsetzen?","This is advances option. You can write your own code here and it will be executed on trigger":"Dies ist eine erweiterte Option. Sie können hier Ihren eigenen Code schreiben, der beim Auslösen ausgeführt wird",Thursday:jL,Time:FL,"Time condition":"Zeitbedingung","Title:":"Titel:","To:":"Zu:","Trigger with value":"Trigger mit Wert",Triggered:zL,Triggers:UL,"Triggers the on script saving or the javascript instance restart":"Löst das Speichern des Skripts oder den Neustart der Javascript-Instanz aus","Triggers the rule on update or change of some state":"Löst die Regel beim Aktualisieren oder Ändern eines Zustands aus","Triggers the rule periodically or on some specific time":"Löst periodisch oder zu einem bestimmten Zeitpunkt aus",Tu:HL,Tuesday:WL,URL:GL,"Unknown error":"Unbekannter Fehler","Unknown error!":"Unbekannter Fehler!","Use generated code":"Code verwenden","User function":"Benutzerfunktion","User:":"Benutzer:",Value:VL,"Vibration:":"Vibration:",Volume:KL,We:YL,Wednesday:JL,"Whatsapp-cmb":"WhatsApp-cmb",Write:qL,"Write your own code":"Eigenen Code schreiben",Yes:XL,"Yet exists!":"Existiert schon!","You can use %s in the URL to use current trigger value or %id to use the triggered object ID":"Sie können %s in der URL verwenden, um den aktuellen Triggerwert zu verwenden, %id, um die ausgelöste Objekt-ID zu verwenden, %name, um den ID-Namen des ausgelösten Objekts anzuzeigen, oder %old, um den alten Triggerwert zu verwenden","You can use %s in the command to use current trigger value or %id to use the triggered object ID":"Sie können %s im Befehl verwenden, um den aktuellen Triggerwert zu verwenden, %id, um die ausgelöste Objekt-ID zu verwenden, %name, um den ID-Namen des ausgelösten Objekts anzuzeigen, oder %old, um den alten Triggerwert zu verwenden","You can use %s in the text to display current trigger value or %id to display the triggered object ID":"Sie können %s im Text verwenden, um den aktuellen Triggerwert anzuzeigen, %id, um die ausgelöste Objekt-ID zu verwenden, %name, um den ID-Namen des ausgelösten Objekts anzuzeigen, oder %old, um den alten Triggerwert zu verwenden","You can use %s in the value to use the current trigger value or %id to display the triggered object ID":"Sie können %s im Wert verwenden, um den aktuellen Triggerwert zu verwenden, %id, um die ID des ausgelösten Objekts zu verwenden, %name, um den ID-Namen des ausgelösten Objekts anzuzeigen, oder %old, um den alten Triggerwert zu verwenden","You have to enter OpenAI API key in the configuration of javascript adapter.":"Sie müssen den OpenAI-API-Schlüssel in der Konfiguration des Javascript-Adapters eingeben.","You have to enter at least one API key in the configuration of javascript adapter.":"Sie müssen mindestens einen API-Schlüssel (OpenAI, Anthropic oder Gemini) in der Konfiguration des Javascript-Adapters eingeben.","Please select a valid model":"Bitte wählen Sie ein gültiges Modell aus","[equal]":"[gleich]","[greater or equal]":"[größer oder gleich]","[greater]":"[größer]","[hysteresis]":"[Hysterese]","[includes]":"[enthält]","[less or equal]":"[kleiner oder gleich]","[less]":"[kleiner]","[not equal]":"[ungleich]",acknowledgment:ZL,all:QL,and:eP,"as JSON":"als JSON","as plain text":"als Klartext",astro:tP,at:sP,"clear running":"laufende abbrechen",control:oP,copy:iP,cron:nP,dawn:rP,debug_help:aP,debug_label:lP,default:"Standard",dusk:cP,easy:uP,else:"sonst","equal to":"gleich",every:dP,"every hour at 0 minutes":"jede Stunde bei 0 Minuten",false:"falsch","file reading has failed: %s":"Das Lesen der Datei ist fehlgeschlagen: %s","file reading was aborted":"Das Lesen der Datei wurde abgebrochen",filter_func:hP,filter_id:pP,filter_name:gP,filter_role:mP,filter_room:fP,"for edit or create script":"zum Bearbeiten oder zum Erstellen eines neues Skripts","for professionals":"für Profis","for programmers":"für Programmierer",goldenHour:$P,goldenHourEnd:bP,"greater or equal":"größer oder gleich","greater or equal to":"größer oder gleich","greater than":"größer als",help_just_check:vP,help_on_change:yP,"high priority":"hohe Priorität","high-priority":"hohe Priorität","highest priority":"höchste Priorität",hours:_P,includes:wP,interval:kP,"just check":"einfach prüfen","less or equal":"kleiner oder gleich","less or equal to":"kleiner oder gleich","less than":"kleiner als","lower priority":"geringere Priorität","lowest priority":"niedrigste Priorität",magic:CP,milliseconds:TP,minutes:SP,ms:EP,nadir:IP,nauticalDawn:xP,nauticalDusk:DP,nextSunrise:AP,nextSunset:RP,night:OP,nightEnd:NP,"no blocks found":"Keine Blöcke gefunden","no group":"KEINE GRUPPE",normal:MP,"normal priority":"normale Priorität","not running":"nicht gestartet","not equal to":"ungleich","not properly connected":"Dieser Block ist mit anderen nicht richtig verbunden.",offset:LP,"on change":"bei Änderung","on condition change":"bei Zustandsänderung","on update":"beim Aktualisieren",one:PP,or:BP,quiet:jP,"reset search":"Suche zurücksetzen",search:FP,seconds:zP,solarNoon:UP,"store in":"speichern in",sunrise:HP,sunriseEnd:WP,sunset:GP,sunsetStart:VP,then:KP,"toggle value":"Wert umschalten",tooltip_ack:YP,tooltip_from:JP,tooltip_lc:qP,tooltip_quality:XP,tooltip_ts:ZP,tooltip_user:QP,tooltip_value:eB,true:"wahr",two:tB,undefined:"nicht definiert",update:sB,"use seconds":"Sekunden verwenden","use trigger value":"Triggerwert benutzen",verbose_help:oB,verbose_label:iB,when:nB,with:"mit","with date":"mit Datum","with offset":"mit Versatz",wizard:rB,"Loading models...":"Modelle werden geladen...","Could not connect to API at %s":"Verbindung zur API unter %s nicht möglich","Invalid API key":"Ungültiger API-Schlüssel","Access denied by API":"Zugriff von der API verweigert","API error: %s":"API-Fehler: %s",'Model "%s" not found':'Modell "%s" nicht gefunden',"Request failed: %s":"Anfrage fehlgeschlagen: %s",Retry:aB,"No running javascript instance found":"Keine laufende JavaScript-Instanz gefunden"},cB="Admitido",uB="Comportamiento",dB="Añadir",hB="Todos",pB="Alguna",gB="Apply",mB="abril",fB="Preguntar",$B="Astronómico",bB="agosto",vB="Cancelar",yB="Cerrar",_B="Condición",wB="Condiciones",kB="Consola",CB="Copiado",TB="diciembre",SB="Defecto",EB="Demora",IB="Eliminar",xB="Descripción",DB="Hecho",AB="Ejecutivo shell",RB="Explicación",OB="Exportar",NB="Februar",MB="febrero",LB="Filtrar",PB="Carpeta",BB="P.",jB="viernes",FB="CARNÉ DE IDENTIDAD",zB="ID1",UB="ID2",HB="Importar",WB="Ejemplo",GB="Instancias",VB="Instrucciones",KB="Enero",YB="enero",JB="julio",qB="junio",XB="Límite",ZB="marzo",QB="Mayo",e2="Menú",t2="Mensaje",s2="Mes",o2="Modelo",i2="lunes",n2="Mes",r2="Más",a2="Nombre",l2="noviembre",c2="OK",u2="octubre",d2="Okay",h2="Pausa",p2="Persona fácil de convencer",g2="Pushsafer",m2="Recargar",f2="Rebautizar",$2="Repetir",b2="Reiniciar",v2="Resultado",y2="Sa",_2="sábado",w2="Salvar",k2="Calendario",C2="Guión",T2="septiembre",S2="Simular",E2="Stack",I2="Comienzo",x2="Expresar",D2="Su",A2="domingo",R2="Telegrama",O2="4",N2="jueves",M2="Tiempo",L2="Motivado",P2="Disparadores",B2="Tu",j2="martes",F2="URL",z2="Valor",U2="Volumen",H2="3",W2="miércoles",G2="Escribir",V2="sí",K2="Reconocimiento",Y2="todos",J2="y",q2="astro",X2="a",Z2="control",Q2="Copiar",ej="CRON",tj="Amanecer",sj="Este es un modo especial en el que los estados y los objetos no cambiarán. Pero solo se mostrará información sobre cada cambio planificado en el protocolo.",oj="Depurar",ij="Oscuridad",nj="fácil",rj="cada",aj="Función",lj="CARNÉ DE IDENTIDAD",cj="Nombre",uj="Papel",dj="Habitación",hj="hora dorada",pj="Fin de la hora dorada",gj='El código se ejecutará solo cada vez que la condición sea verdadera. P.ej. si se activa en el valor del sensor de temperatura y la condición es "si la temperatura es superior a 20 ° C", las acciones "entonces" se ejecutarán cada vez que el sensor envíe la temperatura y supere los 20 ° C. Por 21 ° C, por 22 ° C y así sucesivamente.',mj='El código se ejecutará solo si cambia el resultado de la condición. P.ej. si se activa en el valor del sensor de temperatura y la condición es "si la temperatura es superior a 20 ° C", las acciones "entonces" se ejecutarán una vez cuando la temperatura sea superior a 20. La próxima vez, las acciones "entonces" se ejecutarán cuando la temperatura falla por debajo de 20 y luego sube por encima de 20 nuevamente.',fj="horas",$j="incluye",bj="intervalo",vj="magia",yj="milisegundos",_j="minutos",wj="ms",kj="nadir",Cj="Amanecer náutico",Tj="Atardecer náutico",Sj="próximo amanecer",Ej="Próxima puesta de sol",Ij="Noche",xj="Fin de la noche",Dj="normal",Aj="compensar",Rj="uno",Oj="o",Nj="tranquilo",Mj="buscar",Lj="segundos",Pj="Mediodía solar",Bj="amanecer",jj="Final del amanecer",Fj="puesta de sol",zj="Inicio al atardecer",Uj="entonces",Hj="Reconocer",Wj="De",Gj="Último cambio",Vj="Calidad",Kj="Marca de tiempo",Yj="Usuario",Jj="Valor",qj="dos",Xj="actualizar",Zj="Agrega salida de depuración al registro para muchos comandos del sistema",Qj="Salidas de registro detalladas",eF="cuando",tF="Wizard",sF="Reintentar",oF={"%s not found":"%s no encontrado","()":"()","(at %s)":"(en %s)","(optional)":"(Opcional)","-":"-",".":".","AI code generator":"Generador de código de IA",Ack:cB,Actions:uB,"Actual time of day":"Hora real del día",Add:dB,"Add new script":"Agregar nuevo script",All:hB,"All files will be accepted":"Todos los archivos serán aceptados.",Any:pB,"Any month":"Cualquier mes",Apply:gB,April:mB,"Are you sure?":"¿Estás seguro?",Ask:fB,Astronomical:$B,"Astronomical events today":"Eventos astronómicos hoy",August:bB,"Blockly description":"Crear reglas por bloques gráficos","Body:":"Cuerpo:",Cancel:vB,"Cannot delete non empty item!":"¡No se puede eliminar un elemento no vacío!","Change layout":"Cambia el diseño",'Change theme (actual "%s")':'Cambiar tema (ahora - "%s")',"Check blocks":"Comprobar bloques","Check is not active, because javascript adapter is disabled":"La comprobación no está activa porque el adaptador Javascript está desactivado","Clear search input":"Borrar entrada de búsqueda","Click on this icon":"Haga clic en este ícono",Close:yB,"Close all but current":"Cerrar todo menos el actual","Collapse all":"Desplegar todo","Compares current time with astronomical event":"Compara la hora actual con un evento astronómico","Compares current time with the user specific time":"Compara la hora actual con la hora específica del usuario","Compares the state value with user defined value":"Compara el valor del estado con el valor definido por el usuario",Condition:_B,Conditions:wB,"Configuration not saved.":"Configuración no guardada.",Console:kB,"Control or update some state":"Controlar o actualizar algún estado","Control or update some state with delay":"Controlar o actualizar algún estado con retraso","Convert blockly to javascript for ever.":"Convierta instantáneamente en bloque a Javascript.",Copied:CB,"Copy script":"Copiar guion","Copy to clipboard":"Copiar al portapapeles","Create new":"Crear nuevo","Create new folder":"Crear nueva carpeta","Create new script":"Crear nuevo script","Create or edit CRON or time wizard":"Crear o editar CRON o asistente de tiempo","Dark Theme":"Tema oscuro","Dark style":"Estilo oscuro",Date:"Fecha","Debug instance":"Instancia de depuración","Debug options":"Opciones de depuración",December:TB,Default:SB,"Define cron...":"Definir cron ...","Define schedule...":"Definir horario ...",Delay:EB,Delete:IB,"Delete %s":"Eliminar %s ...","Delete folder":"Eliminar carpeta","Delete script":"Eliminar guión",Description:xB,"Deselect all":"Deseleccionar todo","Discard changes for %s":"Descartar cambios para %s",Done:DB,"Double click to write value":"Doble clic para escribir el valor","Download as file":"Descargar como archivo","Drop some files here or click...":"Suelta algunos archivos aquí o haz clic ...","Duplicate name":"Nombre duplicado","Edit script or just double click":"Editar guión o simplemente hacer doble clic","Empty name is not allowed":"No se permite el nombre vacío","End search mode":"Fin del modo de búsqueda","Enter your question":"Ingrese su solicitud",Error:"Error","Error formatting code":"Código de formato de error","Error was found":"Error encontrado","Every day":"Diario",Exec:AB,"Executes some shell command":"Ejecuta algún comando de shell","Existing scripts will be overwritten.":"Los guiones existentes se sobrescribirán.","Expand all":"Expandir todo","Expert mode":"Modo experto",Explanation:RB,Export:OB,"Export all scripts":"Exportar todos los scripts","Export blocks":"Exportar bloques","Export selected blocks":"Exportar bloques seleccionados",Februar:NB,February:MB,Filter:LB,Folder:PB,Fr:BB,Friday:jB,Function:"Función","Function editor":"Editor de funciones","Function: executed":"Función: ejecutada","Go to next line":"Ir a la siguiente línea","HTTP Call":"Llamada HTTP","Hide logs":"Ocultar registros",ID:FB,ID1:zB,ID2:UB,Import:HB,"Import blocks":"Importar bloques","Import error":"Error de importación","Import scripts":"Importar guiones","Insert object ID":"Insertar ID de objeto",Instance:WB,"Instance is disabled":"La instancia está deshabilitada","Instance:":"Ejemplo:",Instances:GB,Instructions:VB,"Invalid CRON":"CRON inválido","It will not be possible to revert this operation.":"No será posible revertir esta operación.","JS description":"Crear reglas escribiendo Javascript",Januar:KB,January:YB,July:JB,June:qB,"Just check":"Sólo revisa","Keep my changes":"Mantener mis cambios","Language:":"Idioma:","Learn More":"Aprende más","Light style":"Estilo ligero",Limit:XB,"Local time":"Hora local","Locate file":"Localizar el archivo","Log outputs":"Salidas de registro","Log text":"Texto de registro","Log: %s":"Log: %s","Make a HTTP get request":"Realizar una solicitud de obtención HTTP","Make a pause between actions":"Hacer una pausa entre acciones",March:ZB,"March ":"marzo",May:QB,Menu:e2,Message:t2,Mo:s2,Model:o2,Monday:i2,Month:n2,More:r2,Name:a2,"No API key found":"No se encontró ninguna clave API","No Chat GPT Key found":"No se ha encontrado ninguna clave GPT de chat","No active host found":"No se encontró un host activo","Nothing found":"Nada Encontrado",November:l2,OK:c2,October:u2,Ok:d2,"On condition change":"En condición de cambio","On script save or adapter start":"Al guardar el script o al iniciar el adaptador","On weekdays":"De lunes a viernes","Open configuration":"Configuración abierta","Operate two states":"Operar dos estados","Operations with two states":"Operaciones con dos estados","Paste your blocks here":"Pega tus bloques aquí",Pause:h2,"Pause execution":"Pausar ejecución","Pause script":"Pausar guion","Phone:":"Teléfono:","Please select object ID...":"Por favor, seleccione la ID del objeto ...","Press Ctrl+Enter to get the answer":"Presiona Ctrl+Enter para obtener la respuesta","Prettify the script":"Embellecer el guión","Print some text in log":"Imprime texto en el registro","Priority:":"Prioridad:",Pushover:p2,Pushsafer:g2,"Read only ID selected: %s":"ID de solo lectura seleccionado: %s",Reload:m2,Rename:f2,"Reorder scripts in folders":"Reordenar guiones en carpetas",Repeat:$2,Restart:b2,Result:v2,"Resume execution":"Reanudar ejecución","Root folder":"Carpeta raíz","Rules description":"Crea reglas con bloques IF, THEN, ELSE","Run script":"Ejecutar guión",Sa:y2,Saturday:_2,Save:w2,"Save all":"Salvar a todos","Say It":"Say It","Say some text via sayit adapter":"Di un mensaje de texto a través del adaptador sayit",Schedule:k2,Script:C2,"Script %s was modified on disk":"El script %s fue modificado en el disco","Script was modified externally":"El script fue modificado externamente","Script is not running":"El script no se está ejecutando","Search in scripts":"Buscar en guiones","Search...":"Buscar...","Select all":"Seleccionar todo","Send email":"Enviar correo electrónico","Sends an email":"Envía un correo electrónico","Sends message via Pushsafer":"Envía mensaje a través de Pushsafer","Sends message via pushover":"Envía un mensaje a través de un pushover","Sends message via telegram":"Envía mensaje por telegrama","Sends message via whatsapp-cmb":"Envía mensaje vía whatsapp-cmb",September:T2,"Server time":"Tiempo del servidor","Set state action":"Establecer acción estatal","Set with delay":"Establecer con retraso","Shell command":"Comando de Shell","Show astronomical events":"Mostrar eventos astronómicos","Show javascript code":"Mostrar código Javascript","Show logs":"Mostrar registros","Show only paused scripts":"Mostrar solo secuencias de comandos pausadas","Show only running scripts":"Mostrar solo scripts en ejecución","Show only scripts with problems":"Mostrar solo guiones con problemas",Simulate:S2,"Some files will be rejected":"Algunos archivos serán rechazados","Sound:":"Sonido:",Stack:E2,Start:I2,"Start script":"Iniciar guion",State:x2,"State condition":"Condición del estado","Step into function":"Entra en función","Step out from function":"Sal de la función","Stop on exception":"Deténgase en excepción",Su:D2,"Subject:":"Sujeto:",Sunday:A2,"TS description":"Crear reglas escribiendo el mecanografiado",Telegram:R2,"Text:":"Texto:",Th:O2,'The script "%s" has been modified by another user or in another window. Do you want to reload the script or keep your local changes?':'El script "%s" ha sido modificado por otro usuario o en otra ventana. ¿Desea recargar el script o mantener sus cambios locales?',"The script will be stopped and must be activated manually after debugging. Continue?":"El script se detendrá y deberá activarse manualmente después de la depuración. ¿Continuar?","This is advances option. You can write your own code here and it will be executed on trigger":"Esta es la opción de avances. Puede escribir su propio código aquí y se ejecutará en el disparador",Thursday:N2,Time:M2,"Time condition":"Condición de tiempo","Title:":"Título:","To:":"A:","Trigger with value":"Activar con valor",Triggered:L2,Triggers:P2,"Triggers the on script saving or the javascript instance restart":"Activa el guardado de la secuencia de comandos o el reinicio de la instancia de JavaScript","Triggers the rule on update or change of some state":"Activa la regla de actualización o cambio de algún estado","Triggers the rule periodically or on some specific time":"Activa la regla periódicamente o en un momento específico",Tu:B2,Tuesday:j2,URL:F2,"Unknown error":"Error desconocido","Unknown error!":"¡Error desconocido!","Use generated code":"Usar código generado","User function":"Función de usuario","User:":"Usuario:",Value:z2,"Vibration:":"Vibración:",Volume:U2,We:H2,Wednesday:W2,"Whatsapp-cmb":"Whatsapp-cmb",Write:G2,"Write your own code":"Escribe tu propio código",Yes:V2,"Yet exists!":"¡Sin embargo existe!","You can use %s in the URL to use current trigger value or %id to use the triggered object ID":"Puede usar %s en la URL para usar el valor de activación actual, %id para usar el ID de objeto activado, %name para mostrar el nombre de ID de objeto activado o %old para usar el valor de activación antiguo","You can use %s in the command to use current trigger value or %id to use the triggered object ID":"Puede usar %s en el comando para usar el valor de activación actual, %id para usar el ID de objeto activado, %name para mostrar el nombre de ID de objeto activado o %old para usar el valor de activación anterior","You can use %s in the text to display current trigger value or %id to display the triggered object ID":"Puede usar %s en el texto para mostrar el valor de activación actual, %id para usar el ID de objeto activado, %name para mostrar el nombre de ID de objeto activado o %old para usar el valor de activación antiguo","You can use %s in the value to use the current trigger value or %id to display the triggered object ID":"Puede usar %s en el valor para usar el valor de activación actual, %id para usar el ID de objeto activado, %name para mostrar el nombre de ID de objeto activado o %old para usar el valor de activación antiguo","You have to enter OpenAI API key in the configuration of javascript adapter.":"Debe ingresar la clave API de OpenAI en la configuración del adaptador de JavaScript.","You have to enter at least one API key in the configuration of javascript adapter.":"Debe ingresar al menos una clave API (OpenAI, Anthropic o Gemini) en la configuración del adaptador de JavaScript.","Please select a valid model":"Seleccione un modelo válido","[equal]":"[igual]","[greater or equal]":"[mayor o igual]","[greater]":"[mayor que]","[hysteresis]":"[histéresis]","[includes]":"[incluye]","[less or equal]":"[menor o igual]","[less]":"[menos]","[not equal]":"[no es igual]",acknowledgment:K2,all:Y2,and:J2,"as JSON":"como JSON","as plain text":"como texto plano",astro:q2,at:X2,"clear running":"carrera clara",control:Z2,copy:Q2,cron:ej,dawn:tj,debug_help:sj,debug_label:oj,default:"defecto",dusk:ij,easy:nj,else:"demás","equal to":"igual a",every:rj,"every hour at 0 minutes":"cada hora a los 0 minutos",false:"falso","file reading has failed: %s":"la lectura del archivo ha fallado: %s","file reading was aborted":"la lectura del archivo fue abortada",filter_func:aj,filter_id:lj,filter_name:cj,filter_role:uj,filter_room:dj,"for edit or create script":"para editar o crear un nuevo script","for professionals":"para profesionales","for programmers":"para programadores",goldenHour:hj,goldenHourEnd:pj,"greater or equal":"mayor o igual","greater or equal to":"mayor o igual a","greater than":"mas grande que",help_just_check:gj,help_on_change:mj,"high priority":"alta prioridad","high-priority":"alta prioridad","highest priority":"más alta prioridad",hours:fj,includes:$j,interval:bj,"just check":"Sólo revisa","less or equal":"menor o igual","less or equal to":"menor o igual a","less than":"menos que","lower priority":"prioridad más baja","lowest priority":"prioridad más baja",magic:vj,milliseconds:yj,minutes:_j,ms:wj,nadir:kj,nauticalDawn:Cj,nauticalDusk:Tj,nextSunrise:Sj,nextSunset:Ej,night:Ij,nightEnd:xj,"no blocks found":"No se encontraron bloques","no group":"NO GRUPO",normal:Dj,"normal priority":"prioridad normal","not running":"no está en ejecución","not equal to":"no igual a","not properly connected":"Este bloque no está conectado correctamente a otros bloques.",offset:Aj,"on change":"en el cambio","on condition change":"con cambio de condición","on update":"en actualización",one:Rj,or:Oj,quiet:Nj,"reset search":"restablecer la búsqueda",search:Mj,seconds:Lj,solarNoon:Pj,"store in":"almacenar en",sunrise:Bj,sunriseEnd:jj,sunset:Fj,sunsetStart:zj,then:Uj,"toggle value":"alternar valor",tooltip_ack:Hj,tooltip_from:Wj,tooltip_lc:Gj,tooltip_quality:Vj,tooltip_ts:Kj,tooltip_user:Yj,tooltip_value:Jj,true:"cierto",two:qj,undefined:"indefinido",update:Xj,"use seconds":"usar segundos","use trigger value":"usar valor de activación",verbose_help:Zj,verbose_label:Qj,when:eF,with:"con","with date":"con fecha","with offset":"con desplazamiento",wizard:tF,"Loading models...":"Cargando modelos...","Could not connect to API at %s":"No se pudo conectar a la API en %s","Invalid API key":"Clave API no válida","Access denied by API":"Acceso denegado por la API","API error: %s":"Error de API: %s",'Model "%s" not found':'Modelo "%s" no encontrado',"Request failed: %s":"Solicitud fallida: %s",Retry:sF,"No running javascript instance found":"No se encontró ninguna instancia de JavaScript en ejecución"},iF="Reconnu",nF="Actions",rF="Ajouter",aF="Tout",lF="Tout",cF="Postuler",uF="avril",dF="Demander",hF="Astronomique",pF="août",gF="Annuler",mF="proche",fF="État",$F="Conditions",bF="Console",vF="Copié",yF="décembre",_F="Défaut",wF="Retard",kF="Effacer",CF="Description",TF="Terminé",SF="Exec shell",EF="Explication",IF="Exportation",xF="Février",DF="février",AF="Filtre",RF="Dossier",OF="Fr",NF="Vendredi",MF="ID",LF="ID1",PF="ID2",BF="Importation",jF="Exemple",FF="Instances",zF="Instructions",UF="Janvier",HF="janvier",WF="juillet",GF="juin",VF="Limite",KF="Mars",YF="Mai",JF="M e n u",qF="Message",XF="Mo",ZF="Modèle",QF="Lundi",ez="Mois",tz="Plus",sz="Nom",oz="novembre",iz="OK",nz="octobre",rz="D'accord",az="Pause",lz="Pushover",cz="Pushsafer",uz="Recharger",dz="Renommer",hz="Répéter",pz="Redémarrer",gz="Résultat",mz="Sa",fz="samedi",$z="sauver",bz="Horaire",vz="Scénario",yz="septembre",_z="Simuler",wz="Stack",kz="Début",Cz="État",Tz="Su",Sz="dimanche",Ez="Télégramme",Iz="4",xz="Jeudi",Dz="Temps",Az="Déclenché",Rz="Déclencheurs",Oz="Tu",Nz="Mardi",Mz="URL",Lz="Valeur",Pz="Le volume",Bz="3",jz="Mercredi",Fz="Écrivez",zz="Oui",Uz="reconnaissance",Hz="tout",Wz="et",Gz="astro",Vz="à",Kz="contrôler",Yz="copie",Jz="CRON",qz="Aube",Xz="Il s'agit d'un mode spécial dans lequel les états et les objets ne changeront pas. Mais seules les informations sur chaque changement prévu seront affichées dans le protocole.",Zz="Déboguer",Qz="Crépuscule",eU="facile",tU="chaque",sU="Une fonction",oU="ID",iU="Nom",nU="Rôle",rU="Pièce",aU="Heure d'or",lU="Fin de l'heure d'or",cU="Le code ne sera exécuté que chaque fois que la condition est vraie. Par exemple. si déclenchement sur la valeur du capteur de température et que la condition est «si la température est supérieure à 20 ° C», les actions «alors» seront exécutées à chaque fois que le capteur envoie la température et qu'elle est supérieure à 20 ° C. À 21 ° C, à 22 ° C et ainsi de suite.",uU="Le code ne sera exécuté que si le résultat de la condition change. Par exemple. si le déclenchement sur la valeur du capteur de température et que la condition est «si la température est supérieure à 20 ° C», les actions «alors» seront exécutées une fois lorsque la température est supérieure à 20. La prochaine fois, les actions «alors» seront exécutées lorsque la température échoue sous 20 puis remonte au-dessus de 20.",dU="les heures",hU="comprend",pU="intervalle",gU="la magie",mU="millisecondes",fU="minutes",$U="ms",bU="nadir",vU="Aube nautique",yU="Crépuscule nautique",_U="Prochain lever de soleil",wU="Prochain coucher de soleil",kU="Nuit",CU="Fin de nuit",TU="Ordinaire",SU="décalage",EU="une",IU="ou",xU="calmer",DU="chercher",AU="secondes",RU="Midi solaire",OU="lever du soleil",NU="Fin du lever du soleil",MU="le coucher du soleil",LU="Début du coucher du soleil",PU="alors",BU="Reconnaître",jU="De",FU="Dernière modification",zU="Qualité",UU="Horodatage",HU="Utilisateur",WU="Valeur",GU="deux",VU="mettre à jour",KU="Ajoute une sortie de débogage au journal pour de nombreuses commandes système",YU="Sorties de journal détaillées",JU="lorsque",qU="Wizard",XU="Réessayer",ZU={"%s not found":"%s non trouvé","()":"()","(at %s)":"(à %s)","(optional)":"(optionnel)","-":"-",".":".","AI code generator":"Générateur de code IA",Ack:iF,Actions:nF,"Actual time of day":"Heure réelle de la journée",Add:rF,"Add new script":"Ajouter un nouveau script",All:aF,"All files will be accepted":"Tous les fichiers seront acceptés",Any:lF,"Any month":"N'importe quel mois",Apply:cF,April:uF,"Are you sure?":"Êtes-vous sûr?",Ask:dF,Astronomical:hF,"Astronomical events today":"Événements astronomiques aujourd'hui",August:pF,"Blockly description":"Création de règles par blocs graphiques","Body:":"Corps:",Cancel:gF,"Cannot delete non empty item!":"Impossible de supprimer un élément non vide!","Change layout":"Changer la disposition",'Change theme (actual "%s")':'Changer de thème (maintenant - "%s")',"Check blocks":"Vérifier les blocs","Check is not active, because javascript adapter is disabled":"La vérification n'est pas active, car l'adaptateur Javascript est désactivé","Clear search input":"Effacer la recherche","Click on this icon":"Cliquez sur cette icône",Close:mF,"Close all but current":"Ferme tout sauf courant","Collapse all":"Réduire tout","Compares current time with astronomical event":"Compare l'heure actuelle avec un événement astronomique","Compares current time with the user specific time":"Compare l'heure actuelle avec l'heure spécifique de l'utilisateur","Compares the state value with user defined value":"Compare la valeur d'état avec la valeur définie par l'utilisateur",Condition:fF,Conditions:$F,"Configuration not saved.":"Configuration non enregistrée.",Console:bF,"Control or update some state":"Contrôler ou mettre à jour un état","Control or update some state with delay":"Contrôler ou mettre à jour un état avec un délai","Convert blockly to javascript for ever.":"Convertissez instantanément en Javascript.",Copied:vF,"Copy script":"Copier le script","Copy to clipboard":"Copier dans le presse-papier","Create new":"Créer un nouveau","Create new folder":"Créer un nouveau dossier","Create new script":"Créer un nouveau script","Create or edit CRON or time wizard":"Créer ou éditer CRON ou un assistant de temps","Dark Theme":"Thème sombre","Dark style":"Style sombre",Date:"Date","Debug instance":"Instance de débogage","Debug options":"Options de débogage",December:yF,Default:_F,"Define cron...":"Définir le cron ...","Define schedule...":"Définir le calendrier ...",Delay:wF,Delete:kF,"Delete %s":"Supprimer %s ...","Delete folder":"Supprimer le dossier","Delete script":"Supprimer le script",Description:CF,"Deselect all":"Tout déselectionner","Discard changes for %s":"Ignorer les modifications pour %s",Done:TF,"Double click to write value":"Double clic pour écrire la valeur","Download as file":"Télécharger le fichier","Drop some files here or click...":"Déposer des fichiers ici ou cliquez sur ...","Duplicate name":"Nom en double","Edit script or just double click":"Modifiez le script ou double-cliquez simplement sur","Empty name is not allowed":"Le nom vide n'est pas autorisé","End search mode":"Fin du mode de recherche","Enter your question":"Entrez votre demande",Error:"Erreur","Error formatting code":"Erreur lors du formatage du code","Error was found":"Une erreur a été trouvée","Every day":"Tous les jours",Exec:SF,"Executes some shell command":"Exécute une commande shell","Existing scripts will be overwritten.":"Les scripts existants seront écrasés.","Expand all":"Développer tout","Expert mode":"Mode expert",Explanation:EF,Export:IF,"Export all scripts":"Exporter tous les scripts","Export blocks":"Blocs d'exportation","Export selected blocks":"Exporter les blocs sélectionnés",Februar:xF,February:DF,Filter:AF,Folder:RF,Fr:OF,Friday:NF,Function:"Fonction","Function editor":"Éditeur de fonction","Function: executed":"Fonction : exécutée","Go to next line":"Aller à la ligne suivante","HTTP Call":"Appel HTTP","Hide logs":"Masquer les journaux",ID:MF,ID1:LF,ID2:PF,Import:BF,"Import blocks":"Blocs d'importation","Import error":"Erreur d'importation","Import scripts":"Importer des scripts","Insert object ID":"Insérer un identifiant d'objet",Instance:jF,"Instance is disabled":"L'instance est désactivée","Instance:":"Exemple:",Instances:FF,Instructions:zF,"Invalid CRON":"CRON invalide","It will not be possible to revert this operation.":"Il ne sera pas possible de revenir sur cette opération.","JS description":"Créer des règles en écrivant du Javascript",Januar:UF,January:HF,July:WF,June:GF,"Just check":"Vérifiez simplement","Keep my changes":"Garder mes modifications","Language:":"Langue:","Learn More":"Apprendre encore plus","Light style":"Style de lumière",Limit:VF,"Local time":"Heure locale","Locate file":"Localiser le fichier","Log outputs":"Journal des sorties","Log text":"Texte du journal","Log: %s":"Log : %s","Make a HTTP get request":"Faire une requête HTTP Get","Make a pause between actions":"Faites une pause entre les actions",March:KF,"March ":"mars",May:YF,Menu:JF,Message:qF,Mo:XF,Model:ZF,Monday:QF,Month:ez,More:tz,Name:sz,"No API key found":"Aucune clé API trouvée","No Chat GPT Key found":"Aucune clé GPT de chat trouvée","No active host found":"Aucun hôte actif trouvé","Nothing found":"Rien n'a été trouvé",November:oz,OK:iz,October:nz,Ok:rz,"On condition change":"En cas de changement de condition","On script save or adapter start":"Lors de l'enregistrement du script ou du démarrage de l'adaptateur","On weekdays":"En semaine","Open configuration":"Configuration ouverte","Operate two states":"Opérer deux états","Operations with two states":"Opérations à deux états","Paste your blocks here":"Collez vos blocs ici",Pause:az,"Pause execution":"Suspendre l'exécution","Pause script":"Script de pause","Phone:":"Téléphone:","Please select object ID...":"Veuillez sélectionner l'ID d'objet ...","Press Ctrl+Enter to get the answer":"Appuyez sur Ctrl+Entrée pour obtenir la réponse","Prettify the script":"Embellir le scénario","Print some text in log":"Imprimer du texte dans le journal","Priority:":"Priorité:",Pushover:lz,Pushsafer:cz,"Read only ID selected: %s":"ID en lecture seule sélectionné: %s",Reload:uz,Rename:dz,"Reorder scripts in folders":"Réorganiser les scripts dans des dossiers",Repeat:hz,Restart:pz,Result:gz,"Resume execution":"Reprendre l'exécution","Root folder":"Dossier racine","Rules description":"Créer des règles avec des blocs IF, THEN, ELSE","Run script":"Script de lancement",Sa:mz,Saturday:fz,Save:$z,"Save all":"Sauver tous","Say It":"Say It","Say some text via sayit adapter":"Dites du texte via l'adaptateur sayit",Schedule:bz,Script:vz,"Script %s was modified on disk":"Le script %s a été modifié sur le disque","Script was modified externally":"Le script a été modifié en externe","Script is not running":"Le script n'est pas en cours d'exécution","Search in scripts":"Rechercher dans les scripts","Search...":"Chercher...","Select all":"Tout sélectionner","Send email":"Envoyer un e-mail","Sends an email":"Envoie un e-mail","Sends message via Pushsafer":"Envoie un message via Pushsafer","Sends message via pushover":"Envoie un message via pushover","Sends message via telegram":"Envoie un message par télégramme","Sends message via whatsapp-cmb":"Envoie un message via whatsapp-cmb",September:yz,"Server time":"Heure du serveur","Set state action":"Définir l'action de l'état","Set with delay":"Set avec retard","Shell command":"Commande Shell","Show astronomical events":"Afficher les événements astronomiques","Show javascript code":"Afficher le code Javascript","Show logs":"Afficher les journaux","Show only paused scripts":"Afficher uniquement les scripts en pause","Show only running scripts":"Afficher uniquement les scripts en cours d'exécution","Show only scripts with problems":"Afficher uniquement les scripts avec des problèmes",Simulate:_z,"Some files will be rejected":"Certains fichiers seront rejetés","Sound:":"Sonner:",Stack:wz,Start:kz,"Start script":"Lancer le script",State:Cz,"State condition":"État condition","Step into function":"Entrez dans la fonction","Step out from function":"Sortez de la fonction","Stop on exception":"Arrêt sur exception",Su:Tz,"Subject:":"Sujet:",Sunday:Sz,"TS description":"Créer des règles en écrivant des caractères dactylographiés",Telegram:Ez,"Text:":"Texte:",Th:Iz,'The script "%s" has been modified by another user or in another window. Do you want to reload the script or keep your local changes?':'Le script "%s" a été modifié par un autre utilisateur ou dans une autre fenêtre. Voulez-vous recharger le script ou garder vos modifications locales ?',"The script will be stopped and must be activated manually after debugging. Continue?":"Le script sera arrêté et doit être activé manuellement après le débogage. Continuez?","This is advances option. You can write your own code here and it will be executed on trigger":"C'est une option avancée. Vous pouvez écrire votre propre code ici et il sera exécuté au déclenchement",Thursday:xz,Time:Dz,"Time condition":"Condition de temps","Title:":"Titre:","To:":"À:","Trigger with value":"Déclencheur avec valeur",Triggered:Az,Triggers:Rz,"Triggers the on script saving or the javascript instance restart":"Déclenche l'enregistrement du script ou le redémarrage de l'instance javascript","Triggers the rule on update or change of some state":"Déclenche la règle sur la mise à jour ou le changement d'un état","Triggers the rule periodically or on some specific time":"Déclenche la règle périodiquement ou à une heure précise",Tu:Oz,Tuesday:Nz,URL:Mz,"Unknown error":"Erreur inconnue","Unknown error!":"Erreur inconnue!","Use generated code":"Utiliser le code généré","User function":"Fonction utilisateur","User:":"Utilisateur:",Value:Lz,"Vibration:":"Vibration:",Volume:Pz,We:Bz,Wednesday:jz,"Whatsapp-cmb":"Whatsapp-cmb",Write:Fz,"Write your own code":"Écrivez votre propre code",Yes:zz,"Yet exists!":"Pourtant existe!","You can use %s in the URL to use current trigger value or %id to use the triggered object ID":"Vous pouvez utiliser %s dans l'URL pour utiliser la valeur de déclenchement actuelle, %id pour utiliser l'ID de l'objet déclenché, %name pour afficher le nom de l'ID de l'objet déclenché ou %old pour utiliser l'ancienne valeur de déclenchement","You can use %s in the command to use current trigger value or %id to use the triggered object ID":"Vous pouvez utiliser %s dans la commande pour utiliser la valeur de déclenchement actuelle, %id pour utiliser l'ID de l'objet déclenché, %name pour afficher le nom de l'ID de l'objet déclenché ou %old pour utiliser l'ancienne valeur de déclenchement","You can use %s in the text to display current trigger value or %id to display the triggered object ID":"Vous pouvez utiliser %s dans le texte pour afficher la valeur de déclenchement actuelle, %id pour utiliser l'ID de l'objet déclenché, %name pour afficher le nom de l'ID de l'objet déclenché ou %old pour utiliser l'ancienne valeur de déclenchement","You can use %s in the value to use the current trigger value or %id to display the triggered object ID":"Vous pouvez utiliser %s dans la valeur pour utiliser la valeur de déclenchement actuelle, %id pour utiliser l'ID de l'objet déclenché, %name pour afficher le nom de l'ID de l'objet déclenché ou %old pour utiliser l'ancienne valeur de déclenchement","You have to enter OpenAI API key in the configuration of javascript adapter.":"Vous devez entrer la clé API OpenAI dans la configuration de l'adaptateur javascript.","You have to enter at least one API key in the configuration of javascript adapter.":"Vous devez entrer au moins une clé API (OpenAI, Anthropic ou Gemini) dans la configuration de l'adaptateur javascript.","Please select a valid model":"Veuillez sélectionner un modèle valide","[equal]":"[égal]","[greater or equal]":"[supérieur ou égal]","[greater]":"[plus grand]","[hysteresis]":"[hystérèse]","[includes]":"[comprend]","[less or equal]":"[inférieur ou égal]","[less]":"[moins]","[not equal]":"[inégal]",acknowledgment:Uz,all:Hz,and:Wz,"as JSON":"en JSON","as plain text":"en texte brut",astro:Gz,at:Vz,"clear running":"course claire",control:Kz,copy:Yz,cron:Jz,dawn:qz,debug_help:Xz,debug_label:Zz,default:"défaut",dusk:Qz,easy:eU,else:"autre","equal to":"égal à",every:tU,"every hour at 0 minutes":"toutes les heures à 0 minute",false:"faux","file reading has failed: %s":"La lecture du fichier a échoué: %s","file reading was aborted":"la lecture du fichier a été abandonnée",filter_func:sU,filter_id:oU,filter_name:iU,filter_role:nU,filter_room:rU,"for edit or create script":"pour éditer ou créer un nouveau script","for professionals":"pour les professionnels","for programmers":"pour les programmeurs",goldenHour:aU,goldenHourEnd:lU,"greater or equal":"supérieur ou égal","greater or equal to":"supérieur ou égal à","greater than":"plus grand que",help_just_check:cU,help_on_change:uU,"high priority":"haute priorité","high-priority":"haute priorité","highest priority":"priorité la plus élevée",hours:dU,includes:hU,interval:pU,"just check":"Vérifiez simplement","less or equal":"inférieur ou égal","less or equal to":"inférieur ou égal à","less than":"moins que","lower priority":"priorité inférieure","lowest priority":"priorité la plus basse",magic:gU,milliseconds:mU,minutes:fU,ms:$U,nadir:bU,nauticalDawn:vU,nauticalDusk:yU,nextSunrise:_U,nextSunset:wU,night:kU,nightEnd:CU,"no blocks found":"Aucun bloc trouvé","no group":"PAS DE GROUPE",normal:TU,"normal priority":"priorité normale","not running":"pas en cours d'exécution","not equal to":"pas égal à","not properly connected":"Ce bloc n'est pas correctement connecté à d'autres blocs.",offset:SU,"on change":"sur le changement","on condition change":"sur changement de condition","on update":"sur mise à jour",one:EU,or:IU,quiet:xU,"reset search":"Réinitialiser la recherche",search:DU,seconds:AU,solarNoon:RU,"store in":"stocker dans",sunrise:OU,sunriseEnd:NU,sunset:MU,sunsetStart:LU,then:PU,"toggle value":"valeur de bascule",tooltip_ack:BU,tooltip_from:jU,tooltip_lc:FU,tooltip_quality:zU,tooltip_ts:UU,tooltip_user:HU,tooltip_value:WU,true:"vrai",two:GU,undefined:"indéfini",update:VU,"use seconds":"utiliser les secondes","use trigger value":"use trigger value",verbose_help:KU,verbose_label:YU,when:JU,with:"avec","with date":"avec date","with offset":"avec offset",wizard:qU,"Loading models...":"Chargement des modèles...","Could not connect to API at %s":"Impossible de se connecter à l'API sur %s","Invalid API key":"Clé API invalide","Access denied by API":"Accès refusé par l'API","API error: %s":"Erreur API : %s",'Model "%s" not found':'Modèle "%s" introuvable',"Request failed: %s":"Requête échouée : %s",Retry:XU,"No running javascript instance found":"Aucune instance JavaScript en cours d'exécution trouvée"},QU="Riconosciuto",eH="Azioni",tH="Inserisci",sH="Tutti",oH="Qualunque",iH="Applica",nH="aprile",rH="Chiedere",aH="Astronomico",lH="agosto",cH="Annulla",uH="Vicino",dH="Condizione",hH="Condizioni",pH="Console",gH="Copiato",mH="dicembre",fH="Predefinito",$H="Ritardo",bH="Elimina",vH="Descrizione",yH="Fatto",_H="Execshell",wH="Spiegazione",kH="Esportare",CH="Februar",TH="febbraio",SH="Filtro",EH="Cartella",IH="P",xH="Venerdì",DH="ID",AH="ID1",RH="ID2",OH="Importare",NH="Esempio",MH="istanze",LH="Istruzioni",PH="Januar",BH="gennaio",jH="luglio",FH="giugno",zH="Limite",UH="marzo",HH="Maggio",WH="Menu",GH="Messaggio",VH="Mo",KH="Modello",YH="Lunedi",JH="Mese",qH="Di più",XH="Nome",ZH="novembre",QH="OK",eW="ottobre",tW="Ok",sW="Pausa",oW="Pushover",iW="Pushsafer",nW="Ricaricare",rW="Rinominare",aW="Ripetere",lW="Ricomincia",cW="Risultato",uW="Sa",dW="Sabato",hW="Salva",pW="Programma",gW="copione",mW="settembre",fW="Simulare",$W="Stack",bW="Cominciare",vW="Stato",yW="Su",_W="Domenica",wW="Telegramma",kW="4",CW="giovedi",TW="Tempo",SW="Innescato",EW="Trigger",IW="Tu",xW="martedì",DW="URL",AW="Valore",RW="Volume",OW="3",NW="mercoledì",MW="Scrivi",LW="sì",PW="riconoscimento",BW="tutti",jW="e",FW="astro",zW="a",UW="controllo",HW="copia",WW="CRON",GW="alba",VW="Questa è una modalità speciale in cui gli stati e gli oggetti non cambieranno. Ma nel protocollo verranno visualizzate solo le informazioni su ogni modifica pianificata.",KW="Debug",YW="crepuscolo",JW="facile",qW="ogni",XW="Funzione",ZW="ID",QW="Nome",e5="Ruolo",t5="Camera",s5="Ora d'oro",o5="Fine dell'ora d'oro",i5='Il codice verrà eseguito solo ogni volta che la condizione è vera. Per esempio. se si attiva il valore del sensore di temperatura e la condizione è "se la temperatura è maggiore di 20 ° C", le azioni "allora" verranno eseguite ogni volta che il sensore invia la temperatura e questa è superiore a 20 ° C. Di 21 ° C, di 22 ° C e così via.',n5='Il codice verrà eseguito solo se il risultato della condizione cambia. Per esempio. se si attiva il valore del sensore di temperatura e la condizione è "se la temperatura è maggiore di 20 ° C", le azioni "allora" verranno eseguite una volta quando la temperatura è superiore a 20. La prossima volta le azioni "allora" verranno eseguite quando la temperatura fallisce sotto 20 e poi sale di nuovo oltre 20.',r5="ore",a5="include",l5="intervallo",c5="Magia",u5="millisecondi",d5="minuti",h5="ms",p5="nadir",g5="Alba nautica",m5="Crepuscolo nautico",f5="Prossima alba",$5="Prossimo tramonto",b5="Notte",v5="Fine della notte",y5="normale",_5="compensare",w5="uno",k5="o",C5="silenzioso",T5="ricerca",S5="secondi",E5="Mezzogiorno solare",I5="Alba",x5="Fine dell'alba",D5="tramonto",A5="Inizio del tramonto",R5="poi",O5="Riconoscere",N5="A partire dal",M5="Ultima modifica",L5="Qualità",P5="timestamp",B5="Utente",j5="Valore",F5="Due",z5="aggiornare",U5="Aggiunge l'output di debug al registro per molti comandi di sistema",H5="Output di log dettagliati",W5="quando",G5="procedura guidata",V5="Riprova",K5={"%s not found":"%s non trovato","()":"()","(at %s)":"(a %s)","(optional)":"(opzionale)","-":"-",".":".","AI code generator":"Generatore di codice AI",Ack:QU,Actions:eH,"Actual time of day":"Ora effettiva della giornata",Add:tH,"Add new script":"Aggiungi nuovo script",All:sH,"All files will be accepted":"Tutti i file saranno accettati",Any:oH,"Any month":"Ogni mese",Apply:iH,April:nH,"Are you sure?":"Sei sicuro?",Ask:rH,Astronomical:aH,"Astronomical events today":"Eventi astronomici oggi",August:lH,"Blockly description":"Creazione di regole tramite blocchi grafici","Body:":"Corpo:",Cancel:cH,"Cannot delete non empty item!":"Impossibile eliminare l'elemento non vuoto!","Change layout":"Cambia layout",'Change theme (actual "%s")':'Cambia tema (ora - "%s")',"Check blocks":"Controlla i blocchi","Check is not active, because javascript adapter is disabled":"Il controllo non è attivo perché l'adattatore Javascript è disabilitato","Clear search input":"Cancella input di ricerca","Click on this icon":"Clicca su questa icona",Close:uH,"Close all but current":"Chiudi tutto tranne corrente","Collapse all":"Comprimi tutto","Compares current time with astronomical event":"Confronta l'ora corrente con l'evento astronomico","Compares current time with the user specific time":"Confronta l'ora corrente con l'ora specifica dell'utente","Compares the state value with user defined value":"Confronta il valore dello stato con il valore definito dall'utente",Condition:dH,Conditions:hH,"Configuration not saved.":"Configurazione non salvata.",Console:pH,"Control or update some state":"Controlla o aggiorna uno stato","Control or update some state with delay":"Controlla o aggiorna uno stato con ritardo","Convert blockly to javascript for ever.":"Converti istantaneamente a blocchi in Javascript.",Copied:gH,"Copy script":"Copia script","Copy to clipboard":"Copia negli appunti","Create new":"Creare nuovo","Create new folder":"Crea una nuova cartella","Create new script":"Crea nuovo script","Create or edit CRON or time wizard":"Crea o modifica la procedura guidata CRON o time","Dark Theme":"Tema scuro","Dark style":"Stile scuro",Date:"Data","Debug instance":"Istanza di debug","Debug options":"Opzioni di debug",December:mH,Default:fH,"Define cron...":"Definisci cron ...","Define schedule...":"Definisci programma ...",Delay:$H,Delete:bH,"Delete %s":"Elimina %s ...","Delete folder":"Elimina cartella","Delete script":"Elimina script",Description:vH,"Deselect all":"Deselezionare tutto","Discard changes for %s":"Annulla modifiche per %s",Done:yH,"Double click to write value":"Doppio clic per scrivere il valore","Download as file":"Scarica come file","Drop some files here or click...":"Trascina alcuni file qui o fai clic su ...","Duplicate name":"Nome duplicato","Edit script or just double click":"Modifica lo script o fai doppio clic","Empty name is not allowed":"Il nome vuoto non è consentito","End search mode":"Termina la modalità di ricerca","Enter your question":"Inserisci la tua richiesta",Error:"Errore","Error formatting code":"Errore di formattazione del codice","Error was found":"Errore trovato","Every day":"Ogni giorno",Exec:_H,"Executes some shell command":"Esegue alcuni comandi della shell","Existing scripts will be overwritten.":"Gli script esistenti verranno sovrascritti.","Expand all":"Espandi tutto","Expert mode":"Modalità esperto",Explanation:wH,Export:kH,"Export all scripts":"Esporta tutti gli script","Export blocks":"Esporta blocchi","Export selected blocks":"Esporta i blocchi selezionati",Februar:CH,February:TH,Filter:SH,Folder:EH,Fr:IH,Friday:xH,Function:"Funzione","Function editor":"Editor di funzioni","Function: executed":"Funzione: eseguita","Go to next line":"Vai alla riga successiva","HTTP Call":"Chiamata HTTP","Hide logs":"Nascondi i registri",ID:DH,ID1:AH,ID2:RH,Import:OH,"Import blocks":"Importa blocchi","Import error":"Errore di importazione","Import scripts":"Importa script","Insert object ID":"Inserisci l'ID oggetto",Instance:NH,"Instance is disabled":"L'istanza è disabilitata","Instance:":"Esempio:",Instances:MH,Instructions:LH,"Invalid CRON":"CRON non valido","It will not be possible to revert this operation.":"Non sarà possibile ripristinare questa operazione.","JS description":"Creare regole scrivendo Javascript",Januar:PH,January:BH,July:jH,June:FH,"Just check":"Controlla solamente","Keep my changes":"Mantieni le mie modifiche","Language:":"Linguaggio:","Learn More":"Per saperne di più","Light style":"Stile leggero",Limit:zH,"Local time":"Ora locale","Locate file":"Localizza file","Log outputs":"Registra le uscite","Log text":"Testo del registro","Log: %s":"Log: %s","Make a HTTP get request":"Effettua una richiesta get HTTP","Make a pause between actions":"Fai una pausa tra le azioni",March:UH,"March ":"marzo",May:HH,Menu:WH,Message:GH,Mo:VH,Model:KH,Monday:YH,Month:JH,More:qH,Name:XH,"No API key found":"Nessuna chiave API trovata","No Chat GPT Key found":"Nessuna chiave GPT chat trovata","No active host found":"Nessun host attivo trovato","Nothing found":"Non abbiamo trovato nulla",November:ZH,OK:QH,October:eW,Ok:tW,"On condition change":"A condizione che cambino","On script save or adapter start":"Al salvataggio dello script o all'avvio dell'adattatore","On weekdays":"Nei giorni della settimana","Open configuration":"Configurazione aperta","Operate two states":"Gestisci due stati","Operations with two states":"Operazioni con due stati","Paste your blocks here":"Incolla qui i tuoi blocchi",Pause:sW,"Pause execution":"Metti in pausa l'esecuzione","Pause script":"Metti in pausa lo script","Phone:":"Telefono:","Please select object ID...":"Seleziona l'ID oggetto ...","Press Ctrl+Enter to get the answer":"Premi Ctrl+Invio per ottenere la risposta","Prettify the script":"Abbellire la sceneggiatura","Print some text in log":"Stampa del testo nel registro","Priority:":"Priorità:",Pushover:oW,Pushsafer:iW,"Read only ID selected: %s":"ID di sola lettura selezionato: %s",Reload:nW,Rename:rW,"Reorder scripts in folders":"Riordina gli script nelle cartelle",Repeat:aW,Restart:lW,Result:cW,"Resume execution":"Riprendi esecuzione","Root folder":"Cartella root","Rules description":"Crea regole con i blocchi IF, THEN, ELSE","Run script":"Esegui script",Sa:uW,Saturday:dW,Save:hW,"Save all":"Salva tutto","Say It":"Say It","Say some text via sayit adapter":"Pronuncia del testo tramite l'adattatore sayit",Schedule:pW,Script:gW,"Script %s was modified on disk":"Lo script %s è stato modificato sul disco","Script was modified externally":"Lo script è stato modificato esternamente","Script is not running":"Lo script non è in esecuzione","Search in scripts":"Cerca negli script","Search...":"Ricerca...","Select all":"Seleziona tutto","Send email":"Invia una email","Sends an email":"Invia un'e-mail","Sends message via Pushsafer":"Invia messaggio tramite Pushsafer","Sends message via pushover":"Invia messaggio tramite pushover","Sends message via telegram":"Invia messaggio tramite telegramma","Sends message via whatsapp-cmb":"Invia messaggio tramite whatsapp-cmb",September:mW,"Server time":"Ora del server","Set state action":"Imposta l'azione dello stato","Set with delay":"Impostato con ritardo","Shell command":"Comando Shell","Show astronomical events":"Mostra eventi astronomici","Show javascript code":"Mostra codice Javascript","Show logs":"Mostra i log","Show only paused scripts":"Mostra solo script in pausa","Show only running scripts":"Mostra solo gli script in esecuzione","Show only scripts with problems":"Mostra solo script con problemi",Simulate:fW,"Some files will be rejected":"Alcuni file verranno rifiutati","Sound:":"Suono:",Stack:$W,Start:bW,"Start script":"Avvia script",State:vW,"State condition":"Condizione dello stato","Step into function":"Entra in funzione","Step out from function":"Esci dalla funzione","Stop on exception":"Ferma in caso di eccezione",Su:yW,"Subject:":"Soggetto:",Sunday:_W,"TS description":"Creare regole scrivendo dattiloscritto",Telegram:wW,"Text:":"Testo:",Th:kW,'The script "%s" has been modified by another user or in another window. Do you want to reload the script or keep your local changes?':`Lo script "%s" è stato modificato da un altro utente o in un'altra finestra. Vuoi ricaricare lo script o mantenere le tue modifiche locali?`,"The script will be stopped and must be activated manually after debugging. Continue?":"Lo script verrà interrotto e dovrà essere attivato manualmente dopo il debug. Continua?","This is advances option. You can write your own code here and it will be executed on trigger":"Questa è un'opzione anticipata. Puoi scrivere il tuo codice qui e verrà eseguito al trigger",Thursday:CW,Time:TW,"Time condition":"Condizione temporale","Title:":"Titolo:","To:":"Per:","Trigger with value":"Trigger con valore",Triggered:SW,Triggers:EW,"Triggers the on script saving or the javascript instance restart":"Attiva il salvataggio dello script o il riavvio dell'istanza javascript","Triggers the rule on update or change of some state":"Attiva la regola in caso di aggiornamento o modifica di uno stato","Triggers the rule periodically or on some specific time":"Attiva la regola periodicamente o in un momento specifico",Tu:IW,Tuesday:xW,URL:DW,"Unknown error":"Errore sconosciuto","Unknown error!":"Errore sconosciuto!","Use generated code":"Usa il codice generato","User function":"Funzione utente","User:":"Utente:",Value:AW,"Vibration:":"Vibrazione:",Volume:RW,We:OW,Wednesday:NW,"Whatsapp-cmb":"Whatsapp-cmb",Write:MW,"Write your own code":"Scrivi il tuo codice",Yes:LW,"Yet exists!":"Esiste ancora!","You can use %s in the URL to use current trigger value or %id to use the triggered object ID":"È possibile utilizzare %s nell'URL per utilizzare il valore di trigger corrente, %id per utilizzare l'ID dell'oggetto attivato, %name per mostrare il nome dell'ID dell'oggetto attivato o %old per utilizzare il vecchio valore di trigger","You can use %s in the command to use current trigger value or %id to use the triggered object ID":"È possibile utilizzare %s nel comando per utilizzare il valore di trigger corrente, %id per utilizzare l'ID dell'oggetto attivato, %name per mostrare il nome dell'ID dell'oggetto attivato o %old per utilizzare il vecchio valore di trigger","You can use %s in the text to display current trigger value or %id to display the triggered object ID":"È possibile utilizzare %s nel testo per visualizzare il valore di trigger corrente, %id per utilizzare l'ID dell'oggetto attivato, %name per mostrare il nome dell'ID dell'oggetto attivato o %old per utilizzare il vecchio valore di trigger","You can use %s in the value to use the current trigger value or %id to display the triggered object ID":"È possibile utilizzare %s nel valore per utilizzare il valore di trigger corrente, %id per utilizzare l'ID dell'oggetto attivato, %name per mostrare il nome dell'ID dell'oggetto attivato o %old per utilizzare il vecchio valore di trigger","You have to enter OpenAI API key in the configuration of javascript adapter.":"Devi inserire la chiave API OpenAI nella configurazione dell'adattatore javascript.","You have to enter at least one API key in the configuration of javascript adapter.":"Devi inserire almeno una chiave API (OpenAI, Anthropic o Gemini) nella configurazione dell'adattatore javascript.","Please select a valid model":"Seleziona un modello valido","[equal]":"[pari]","[greater or equal]":"[maggiore o uguale]","[greater]":"[maggiore]","[hysteresis]":"[isteresi]","[includes]":"[include]","[less or equal]":"[minore o uguale]","[less]":"[Di meno]","[not equal]":"[non uguale]",acknowledgment:PW,all:BW,and:jW,"as JSON":"come JSON","as plain text":"come testo",astro:FW,at:zW,"clear running":"chiara esecuzione",control:UW,copy:HW,cron:WW,dawn:GW,debug_help:VW,debug_label:KW,default:"predefinito",dusk:YW,easy:JW,else:"altro","equal to":"uguale a",every:qW,"every hour at 0 minutes":"ogni ora a 0 minuti",false:"falso","file reading has failed: %s":"lettura file non riuscita: %s","file reading was aborted":"la lettura del file è stata interrotta",filter_func:XW,filter_id:ZW,filter_name:QW,filter_role:e5,filter_room:t5,"for edit or create script":"per modificare o creare un nuovo script","for professionals":"per i professionisti","for programmers":"per i programmatori",goldenHour:s5,goldenHourEnd:o5,"greater or equal":"maggiore o uguale","greater or equal to":"maggiore o uguale a","greater than":"più grande di",help_just_check:i5,help_on_change:n5,"high priority":"priorità alta","high-priority":"priorità alta","highest priority":"massima priorità",hours:r5,includes:a5,interval:l5,"just check":"controlla solamente","less or equal":"inferiore o uguale","less or equal to":"minore o uguale a","less than":"meno di","lower priority":"priorità inferiore","lowest priority":"priorità più bassa",magic:c5,milliseconds:u5,minutes:d5,ms:h5,nadir:p5,nauticalDawn:g5,nauticalDusk:m5,nextSunrise:f5,nextSunset:$5,night:b5,nightEnd:v5,"no blocks found":"Nessun blocco trovato","no group":"NESSUN GRUPPO",normal:y5,"normal priority":"priorità normale","not running":"non in esecuzione","not equal to":"non uguale a","not properly connected":"Questo blocco non è correttamente collegato ad altri blocchi.",offset:_5,"on change":"sul cambiamento","on condition change":"a cambio di condizione","on update":"in aggiornamento",one:w5,or:k5,quiet:C5,"reset search":"resetta la ricerca",search:T5,seconds:S5,solarNoon:E5,"store in":"conservare in",sunrise:I5,sunriseEnd:x5,sunset:D5,sunsetStart:A5,then:R5,"toggle value":"alterna valore",tooltip_ack:O5,tooltip_from:N5,tooltip_lc:M5,tooltip_quality:L5,tooltip_ts:P5,tooltip_user:B5,tooltip_value:j5,true:"vero",two:F5,undefined:"non definito",update:z5,"use seconds":"usa i secondi","use trigger value":"usa il trigger",verbose_help:U5,verbose_label:H5,when:W5,with:"con","with date":"con data","with offset":"con offset",wizard:G5,"Loading models...":"Caricamento modelli...","Could not connect to API at %s":"Impossibile connettersi all'API su %s","Invalid API key":"Chiave API non valida","Access denied by API":"Accesso negato dall'API","API error: %s":"Errore API: %s",'Model "%s" not found':'Modello "%s" non trovato',"Request failed: %s":"Richiesta fallita: %s",Retry:V5,"No running javascript instance found":"Nessuna istanza JavaScript in esecuzione trovata"},Y5="Erkend",J5="Acties",q5="Toevoegen",X5="Alle",Z5="Ieder",Q5="Solliciteer",e3="april",t3="Vragen",s3="Astronomisch",o3="augustus",i3="annuleren",n3="Dichtbij",r3="Staat",a3="Voorwaarden",l3="Troosten",c3="Gekopieerd",u3="december",d3="Standaard",h3="Vertraging",p3="Verwijder",g3="Beschrijving",m3="Gedaan",f3="Exec shell",$3="Uitleg",b3="Exporteren",v3="Februari",y3="februari",_3="Filter",w3="Map",k3="Vr",C3="vrijdag",T3="ID kaart",S3="ID1",E3="ID2",I3="Importeren",x3="Voorbeeld",D3="Instanties",A3="Instructies",R3="Januar",O3="januari",N3="juli",M3="juni",L3="Begrenzing",P3="maart",B3="mei",j3="Menu",F3="Bericht",z3="Ma",U3="Model",H3="maandag",W3="Maand",G3="Meer",V3="Naam",K3="november",Y3="OK",J3="oktober",q3="OK",X3="Pauze",Z3="Pushover",Q3="Duwijzer",eG="Herladen",tG="andere naam geven",sG="Herhaling",oG="Herstarten",iG="Resultaat",nG="Za",rG="zaterdag",aG="Opslaan",lG="Schema",cG="Script",uG="september",dG="Simuleren",hG="Stack",pG="Begin",gG="Staat",mG="Zo",fG="zondag",$G="Telegram",bG="4",vG="donderdag",yG="Tijd",_G="Veroorzaakt",wG="Triggers",kG="Di",CG="dinsdag",TG="URL",SG="Waarde",EG="Volume",IG="3",xG="woensdag",DG="Schrijven",AG="Ja",RG="erkenning",OG="alle",NG="en",MG="astro",LG="Bij",PG="controle",BG="kopiëren",jG="cron",FG="dageraad",zG="Dit is een speciale modus waarin toestanden en objecten niet veranderen. Maar alleen informatie over elke geplande wijziging wordt in het protocol weergegeven.",UG="Debuggen",HG="schemer",WG="eenvoudig",GG="elke",VG="Functie",KG="ID kaart",YG="Naam",JG="Rol",qG="Kamer",XG="gouden uur",ZG="Einde van gouden uur",QG='De code wordt alleen uitgevoerd als de voorwaarde waar is. Bijv. als het triggeren op de temperatuursensorwaarde en de conditie is "als de temperatuur hoger is dan 20 ° C", zullen de "dan" acties worden uitgevoerd elke keer dat de sensor de temperatuur verzendt en deze hoger is dan 20 ° C. Bij 21 ° C, bij 22 ° C enzovoort.',eV='De code wordt alleen uitgevoerd als het conditieresultaat verandert. Bijv. als de temperatuursensor wordt geactiveerd en de conditie is "als de temperatuur hoger is dan 20 ° C", worden de "dan" -acties eenmaal uitgevoerd wanneer de temperatuur hoger is dan 20. De volgende keer worden de "dan" -acties uitgevoerd wanneer de temperatuur faalt onder de 20 en stijgt dan weer boven de 20.',tV="uren",sV="omvat",oV="interval",iV="magie",nV="milliseconden",rV="minuten",aV="ms",lV="nadir",cV="Nautische dageraad",uV="Nautische schemering",dV="Volgende zonsopgang",hV="Volgende zonsondergang",pV="nacht",gV="Einde van de nacht",mV="normaal",fV="compensatie",$V="een",bV="of",vV="stil",yV="zoeken",_V="seconden",wV="Zonne-middag",kV="zonsopkomst",CV="Einde zonsopgang",TV="zonsondergang",SV="Begin van de zonsondergang",EV="vervolgens",IV="Erkennen",xV="Van",DV="Laatst gewijzigd",AV="Kwaliteit",RV="tijdstempel",OV="Gebruiker",NV="Waarde",MV="twee",LV="bijwerken",PV="Voegt foutopsporingsuitvoer toe aan het logboek voor veel systeemopdrachten",BV="Uitgebreide log-uitgangen",jV="wanneer",FV="tovenaar",zV="Opnieuw proberen",UV={"%s not found":"%s niet gevonden","()":"()","(at %s)":"(op %s)","(optional)":"(optioneel)","-":"-",".":".","AI code generator":"AI-codegenerator",Ack:Y5,Actions:J5,"Actual time of day":"Werkelijke tijd van de dag",Add:q5,"Add new script":"Nieuw script toevoegen",All:X5,"All files will be accepted":"Alle bestanden worden geaccepteerd",Any:Z5,"Any month":"Elke maand",Apply:Q5,April:e3,"Are you sure?":"Weet je zeker dat?",Ask:t3,Astronomical:s3,"Astronomical events today":"Astronomische gebeurtenissen vandaag",August:o3,"Blockly description":"Regels maken door grafische blokken","Body:":"Lichaam:",Cancel:i3,"Cannot delete non empty item!":"Kan niet leeg item niet verwijderen!","Change layout":"Opmaak veranderen",'Change theme (actual "%s")':'Thema wijzigen (nu - "%s")',"Check blocks":"Controleer blokken","Check is not active, because javascript adapter is disabled":"Controle is niet actief, omdat Javascript-adapter is uitgeschakeld","Clear search input":"Zoekopdracht wissen","Click on this icon":"Klik op dit pictogram",Close:n3,"Close all but current":"Alles sluiten behalve huidig","Collapse all":"Alles inklappen","Compares current time with astronomical event":"Vergelijkt huidige tijd met astronomische gebeurtenis","Compares current time with the user specific time":"Vergelijkt de huidige tijd met de gebruikerspecifieke tijd","Compares the state value with user defined value":"Vergelijkt de statuswaarde met de door de gebruiker gedefinieerde waarde",Condition:r3,Conditions:a3,"Configuration not saved.":"Configuratie niet opgeslagen.",Console:l3,"Control or update some state":"Beheer of update een bepaalde staat","Control or update some state with delay":"Beheer of update een bepaalde staat met vertraging","Convert blockly to javascript for ever.":"Converteer direct blockly naar Javascript.",Copied:c3,"Copy script":"Kopieer script","Copy to clipboard":"Kopieer naar klembord","Create new":"Maak nieuw","Create new folder":"Maak een nieuwe map","Create new script":"Maak een nieuw script","Create or edit CRON or time wizard":"Creëer of bewerk CRON of tijdwizard","Dark Theme":"Donker thema","Dark style":"Donkere stijl",Date:"Datum","Debug instance":"Debug-instantie","Debug options":"Foutopsporingsopties",December:u3,Default:d3,"Define cron...":"Definieer cron ...","Define schedule...":"Definieer schema ...",Delay:h3,Delete:p3,"Delete %s":"%s verwijderen ...","Delete folder":"Verwijder map","Delete script":"Script verwijderen",Description:g3,"Deselect all":"Deselecteer alles","Discard changes for %s":"Wijzigingen voor %s annuleren",Done:m3,"Double click to write value":"Dubbelklikken om waarde te schrijven","Download as file":"Download","Drop some files here or click...":"Zet hier enkele bestanden neer of klik op ...","Duplicate name":"Dubbele naam","Edit script or just double click":"Bewerk het script of dubbelklik erop","Empty name is not allowed":"Lege naam is niet toegestaan","End search mode":"Zoekmodus beëindigen","Enter your question":"Voer uw verzoek in",Error:"Fout","Error formatting code":"Fout bij het opmaken van de code","Error was found":"Er is een fout gevonden","Every day":"Elke dag",Exec:f3,"Executes some shell command":"Voert een shell-commando uit","Existing scripts will be overwritten.":"Bestaande scripts worden overschreven.","Expand all":"Alles uitvouwen","Expert mode":"Expert modus",Explanation:$3,Export:b3,"Export all scripts":"Exporteer alle scripts","Export blocks":"Blokken exporteren","Export selected blocks":"Exporteer geselecteerde blokken",Februar:v3,February:y3,Filter:_3,Folder:w3,Fr:k3,Friday:C3,Function:"Functie","Function editor":"Functie-editor","Function: executed":"Functie: uitgevoerd","Go to next line":"Ga naar de volgende regel","HTTP Call":"HTTP-oproep","Hide logs":"Verberg logboeken",ID:T3,ID1:S3,ID2:E3,Import:I3,"Import blocks":"Blokken importeren","Import error":"Importfout","Import scripts":"Scripts importeren","Insert object ID":"Object-ID invoegen",Instance:x3,"Instance is disabled":"Exemplaar is uitgeschakeld","Instance:":"Voorbeeld:",Instances:D3,Instructions:A3,"Invalid CRON":"Ongeldige CRON","It will not be possible to revert this operation.":"Het is niet mogelijk om deze bewerking terug te zetten.","JS description":"Regels maken door Javascript te schrijven",Januar:R3,January:O3,July:N3,June:M3,"Just check":"Kijk maar","Keep my changes":"Mijn wijzigingen behouden","Language:":"Taal:","Learn More":"Leer meer","Light style":"Lichte stijl",Limit:L3,"Local time":"Lokale tijd","Locate file":"Vind het bestand","Log outputs":"Log uitgangen","Log text":"Log tekst","Log: %s":"Logboek: %s","Make a HTTP get request":"Maak een HTTP-ophaalverzoek","Make a pause between actions":"Pauzeer tussen acties",March:P3,"March ":"maart",May:B3,Menu:j3,Message:F3,Mo:z3,Model:U3,Monday:H3,Month:W3,More:G3,Name:V3,"No API key found":"Geen API-sleutel gevonden","No Chat GPT Key found":"Geen Chat GPT-sleutel gevonden","No active host found":"Geen actieve host gevonden","Nothing found":"Niets gevonden",November:K3,OK:Y3,October:J3,Ok:q3,"On condition change":"Op voorwaarde verandering","On script save or adapter start":"Bij het opslaan van het script of het starten van de adapter","On weekdays":"Op weekdagen","Open configuration":"Configuratie openen","Operate two states":"Bedien twee toestanden:","Operations with two states":"Bewerkingen met twee toestanden","Paste your blocks here":"Plak hier je blokken",Pause:X3,"Pause execution":"Uitvoering pauzeren","Pause script":"Pauzeer script","Phone:":"Telefoon:","Please select object ID...":"Selecteer object-ID ...","Press Ctrl+Enter to get the answer":"Druk op Ctrl+Enter om het antwoord te krijgen","Prettify the script":"Maak het script mooier","Print some text in log":"Druk wat tekst af in het logboek","Priority:":"Prioriteit:",Pushover:Z3,Pushsafer:Q3,"Read only ID selected: %s":"Alleen-lezen ID geselecteerd: %s",Reload:eG,Rename:tG,"Reorder scripts in folders":"Sorteer scripts in mappen opnieuw",Repeat:sG,Restart:oG,Result:iG,"Resume execution":"Uitvoering hervatten","Root folder":"Hoofdmap","Rules description":"Maak regels met IF, THEN, ELSE blokken","Run script":"Voer script uit",Sa:nG,Saturday:rG,Save:aG,"Save all":"Sla alles op","Say It":"Say It","Say some text via sayit adapter":"Zeg wat tekst via de sayit-adapter",Schedule:lG,Script:cG,"Script %s was modified on disk":"Script %s is gewijzigd op schijf","Script was modified externally":"Script is extern gewijzigd","Script is not running":"Script is niet actief","Search in scripts":"Zoeken in scripts","Search...":"Zoeken...","Select all":"Selecteer alles","Send email":"E-mail verzenden","Sends an email":"Stuurt een e-mail","Sends message via Pushsafer":"Stuurt bericht via Pushsafer","Sends message via pushover":"Stuurt bericht via pushover","Sends message via telegram":"Verzendt bericht via telegram","Sends message via whatsapp-cmb":"Stuurt bericht via whatsapp-cmb",September:uG,"Server time":"Servertijd","Set state action":"Stel statusactie in","Set with delay":"Met vertraging ingesteld","Shell command":"Shell-opdracht","Show astronomical events":"Laat astronomische gebeurtenissen zien","Show javascript code":"Javascript-code weergeven","Show logs":"Toon logboeken","Show only paused scripts":"Toon alleen onderbroken scripts","Show only running scripts":"Toon alleen actieve scripts","Show only scripts with problems":"Toon alleen scripts met problemen",Simulate:dG,"Some files will be rejected":"Sommige bestanden worden geweigerd","Sound:":"Geluid:",Stack:hG,Start:pG,"Start script":"Start het script",State:gG,"State condition":"Staat staat","Step into function":"Stap in functie","Step out from function":"Stap uit de functie","Stop on exception":"Stop bij uitzondering",Su:mG,"Subject:":"Onderwerpen:",Sunday:fG,"TS description":"Regels maken door Typescript te schrijven",Telegram:$G,"Text:":"Tekst:",Th:bG,'The script "%s" has been modified by another user or in another window. Do you want to reload the script or keep your local changes?':'Het script "%s" is gewijzigd door een andere gebruiker of in een ander venster. Wilt u het script herladen of uw lokale wijzigingen behouden?',"The script will be stopped and must be activated manually after debugging. Continue?":"Het script wordt gestopt en moet na het debuggen handmatig worden geactiveerd. Doorgaan met?","This is advances option. You can write your own code here and it will be executed on trigger":"Dit is een voorschotoptie. U kunt hier uw eigen code schrijven en deze wordt bij een trigger uitgevoerd",Thursday:vG,Time:yG,"Time condition":"Tijdsvoorwaarde","Title:":"Titel:","To:":"Naar:","Trigger with value":"Trigger met waarde",Triggered:_G,Triggers:wG,"Triggers the on script saving or the javascript instance restart":"Activeert het opslaan van het script of het opnieuw opstarten van de JavaScript-instantie","Triggers the rule on update or change of some state":"Activeert de regel voor het bijwerken of wijzigen van een bepaalde staat","Triggers the rule periodically or on some specific time":"Activeert de regel periodiek of op een specifieke tijd",Tu:kG,Tuesday:CG,URL:TG,"Unknown error":"Onbekende fout","Unknown error!":"Onbekende fout!","Use generated code":"Gebruik gegenereerde code","User function":"Gebruikersfunctie","User:":"Gebruiker:",Value:SG,"Vibration:":"Trilling:",Volume:EG,We:IG,Wednesday:xG,"Whatsapp-cmb":"Whatsapp-cmb",Write:DG,"Write your own code":"Schrijf je eigen code",Yes:AG,"Yet exists!":"Toch bestaat!","You can use %s in the URL to use current trigger value or %id to use the triggered object ID":"U kunt %s in de URL gebruiken om de huidige triggerwaarde te gebruiken, %id om de geactiveerde object-ID te gebruiken, %name om de geactiveerde object-ID-naam te tonen of %old om de oude triggerwaarde te gebruiken","You can use %s in the command to use current trigger value or %id to use the triggered object ID":"U kunt %s in de opdracht gebruiken om de huidige triggerwaarde te gebruiken, %id om de getriggerde object-ID te gebruiken, %name om de getriggerde object-ID-naam te tonen of %old om de oude triggerwaarde te gebruiken","You can use %s in the text to display current trigger value or %id to display the triggered object ID":"U kunt %s in de tekst gebruiken om de huidige triggerwaarde weer te geven, %id om de geactiveerde object-ID te gebruiken, %name om de geactiveerde object-ID-naam weer te geven of %old om de oude triggerwaarde te gebruiken","You can use %s in the value to use the current trigger value or %id to display the triggered object ID":"U kunt %s in de waarde gebruiken om de huidige triggerwaarde te gebruiken, %id om de geactiveerde object-ID te gebruiken, %name om de geactiveerde object-ID-naam te tonen of %old om de oude triggerwaarde te gebruiken","You have to enter OpenAI API key in the configuration of javascript adapter.":"U moet de OpenAI API-sleutel invoeren in de configuratie van de javascript-adapter.","You have to enter at least one API key in the configuration of javascript adapter.":"U moet ten minste één API-sleutel (OpenAI, Anthropic of Gemini) invoeren in de configuratie van de javascript-adapter.","Please select a valid model":"Selecteer een geldig model","[equal]":"[Gelijk]","[greater or equal]":"[groter of gelijk]","[greater]":"[groter]","[hysteresis]":"[hysterese]","[includes]":"[inclusief]","[less or equal]":"[minder of gelijk]","[less]":"[minder]","[not equal]":"[niet gelijk]",acknowledgment:RG,all:OG,and:NG,"as JSON":"als JSON","as plain text":"als platte tekst",astro:MG,at:LG,"clear running":"duidelijk rennen",control:PG,copy:BG,cron:jG,dawn:FG,debug_help:zG,debug_label:UG,default:"standaard",dusk:HG,easy:WG,else:"anders","equal to":"gelijk aan",every:GG,"every hour at 0 minutes":"elk uur op 0 minuten",false:"false","file reading has failed: %s":"bestands lezen is mislukt: %s","file reading was aborted":"bestands lezen is afgebroken",filter_func:VG,filter_id:KG,filter_name:YG,filter_role:JG,filter_room:qG,"for edit or create script":"voor bewerken of een nieuw script maken","for professionals":"voor professionals","for programmers":"voor programmeurs",goldenHour:XG,goldenHourEnd:ZG,"greater or equal":"groter of gelijk","greater or equal to":"groter of gelijk aan","greater than":"groter dan",help_just_check:QG,help_on_change:eV,"high priority":"hoge prioriteit","high-priority":"hoge prioriteit","highest priority":"hoogste prioriteit",hours:tV,includes:sV,interval:oV,"just check":"kijk maar","less or equal":"minder of gelijk","less or equal to":"minder of gelijk aan","less than":"minder dan","lower priority":"lagere prioriteit","lowest priority":"laagste prioriteit",magic:iV,milliseconds:nV,minutes:rV,ms:aV,nadir:lV,nauticalDawn:cV,nauticalDusk:uV,nextSunrise:dV,nextSunset:hV,night:pV,nightEnd:gV,"no blocks found":"Geen blokken gevonden","no group":"GEEN GROEP",normal:mV,"normal priority":"normale prioriteit","not running":"niet actief","not equal to":"niet gelijk aan","not properly connected":"Dit blok is niet correct verbonden met andere blokken.",offset:fV,"on change":"bij verandering","on condition change":"op voorwaarde verandering","on update":"bij update",one:$V,or:bV,quiet:vV,"reset search":"reset zoeken",search:yV,seconds:_V,solarNoon:wV,"store in":"opslaan in",sunrise:kV,sunriseEnd:CV,sunset:TV,sunsetStart:SV,then:EV,"toggle value":"schakelwaarde",tooltip_ack:IV,tooltip_from:xV,tooltip_lc:DV,tooltip_quality:AV,tooltip_ts:RV,tooltip_user:OV,tooltip_value:NV,true:"waar",two:MV,undefined:"ongedefinieerd",update:LV,"use seconds":"gebruik seconden","use trigger value":"triggerwaarde gebruiken",verbose_help:PV,verbose_label:BV,when:jV,with:"met","with date":"met datum","with offset":"met offset",wizard:FV,"Loading models...":"Modellen laden...","Could not connect to API at %s":"Kan geen verbinding maken met API op %s","Invalid API key":"Ongeldige API-sleutel","Access denied by API":"Toegang geweigerd door API","API error: %s":"API-fout: %s",'Model "%s" not found':'Model "%s" niet gevonden',"Request failed: %s":"Verzoek mislukt: %s",Retry:zV,"No running javascript instance found":"Geen draaiende JavaScript-instantie gevonden"},HV="Potwierdzony",WV="Działania",GV="Dodaj",VV="Wszystko",KV="Każdy",YV="Zastosuj",JV="Kwiecień",qV="Zapytać",XV="Astronomiczny",ZV="Sierpień",QV="Odwołaj",e4="Zamknij",t4="Stan",s4="Warunki",o4="Konsola",i4="Skopiowano",n4="Grudzień",r4="Domyślna",a4="Opóźnienie",l4="Usuń",c4="Opis",u4="Gotowe",d4="Uruchom shell",h4="Wyjaśnienie",p4="Eksport",g4="Luty",m4="Luty",f4="Filtr",$4="Folder",b4="Pt",v4="Piątek",y4="ID",_4="ID1",w4="ID2",k4="Import",C4="Instancja",T4="Instancje",S4="Instrukcje",E4="Styczeń",I4="Styczeń",x4="Lipiec",D4="Czerwiec",A4="Limit",R4="Marzec",O4="Maj",N4="Menu",M4="Wiadomość",L4="Po",P4="Model",B4="Poniedziałek",j4="Miesiąc",F4="Więcej",z4="Nazwa",U4="Listopad",H4="OK",W4="Październik",G4="Ok",V4="Pauza",K4="Pushover",Y4="Pushsafer",J4="Przeładuj",q4="Przemianuj",X4="Powtórz",Z4="Uruchom ponownie",Q4="Wynik",e8="So",t8="Sobota",s8="Zapisz",o8="Harmonogram",i8="Skrypt",n8="Wrzesień",r8="Symulacja",a8="Stos",l8="Początek",c8="Stan",u8="Nd",d8="Niedziela",h8="Telegram",p8="Cz",g8="Czwartek",m8="Czas",f8="Wyzwolony",$8="Wyzwalacze",b8="Wt",v8="Wtorek",y8="URL",_8="Wartość",w8="Wolumen",k8="Śr",C8="Środa",T8="Pisać",S8="Tak",E8="potwierdzenie",I8="wszystko",x8="i",D8="Astro",A8="w",R8="kontrola",O8="Kopiuj",N8="CRON",M8="Świt",L8="Jest to specjalny tryb, w którym stany i obiekty się nie zmieniają. Jednak w protokole będą wyświetlane tylko informacje o każdej planowanej zmianie.",P8="Odpluskwić",B8="Zmierzch",j8="łatwy",F8="każdy",z8="Funkcja",U8="ID",H8="Nazwa",W8="Rola",G8="Pokój",V8="Złota godzina",K8="Koniec złotej godziny",Y8="Kod zostanie wykonany tylko za każdym razem, gdy warunek będzie spełniony. Na przykład. jeśli wyzwalanie na wartość czujnika temperatury i warunek to „jeśli temperatura jest wyższa niż 20 ° C”, to działania „następnie” będą wykonywane za każdym razem, gdy czujnik wyśle temperaturę i jest powyżej 20 ° C. O 21 ° C, o 22 ° C i tak dalej.",J8="Kod zostanie wykonany tylko wtedy, gdy wynik warunku ulegnie zmianie. Na przykład. jeśli wyzwalanie na wartość czujnika temperatury i warunek „jeśli temperatura jest wyższa niż 20 ° C”, to akcje „następnie” zostaną wykonane raz, gdy temperatura przekroczy 20. Następnym razem działania „następnie” zostaną wykonane, gdy temperatura nie udaje się poniżej 20, a następnie ponownie wzrasta powyżej 20.",q8="godziny",X8="zawiera",Z8="interwał",Q8="magia",e6="milisekund",t6="minuty",s6="ms",o6="Północ słoneczna",i6="Żeglarski świt",n6="Żeglarski zmierzch",r6="Następny wschód słońca",a6="Następny zachód słońca",l6="Noc",c6="Koniec nocy",u6="normalny",d6="przesunięcie",h6="jeden",p6="lub",g6="cisza",m6="Szukaj",f6="sekundy",$6="Południe słoneczne",b6="Wschód słońca",v6="Koniec wschodu słońca",y6="Zachód słońca",_6="Początek zachodu słońca",w6="następnie",k6="Akceptuj",C6="Od",T6="Ostatnia zmiana",S6="Jakość",E6="Znacznik czasu",I6="Użytkownik",x6="Wartość",D6="dwa",A6="aktualizacja",R6="Dodaje wyniki debugowania do dziennika dla wielu poleceń systemowych",O6="Pełne dane wyjściowe dziennika",N6="gdy",M6="Wizard",L6="Ponów próbę",P6={"%s not found":"%s nie znaleziono","()":"()","(at %s)":"(w %s)","(optional)":"(opcjonalny)","-":"-",".":".","AI code generator":"Generator kodu AI",Ack:HV,Actions:WV,"Actual time of day":"Aktualna pora dnia",Add:GV,"Add new script":"Dodaj nowy skrypt",All:VV,"All files will be accepted":"Wszystkie pliki zostaną zaakceptowane",Any:KV,"Any month":"Dowolny miesiąc",Apply:YV,April:JV,"Are you sure?":"Jesteś pewny?",Ask:qV,Astronomical:XV,"Astronomical events today":"Wydarzenia astronomiczne dzisiaj",August:ZV,"Blockly description":"Tworzenie reguł za pomocą bloków graficznych","Body:":"Treść:",Cancel:QV,"Cannot delete non empty item!":"Nie można usunąć niepustego elementu!","Change layout":"Zmiana układu",'Change theme (actual "%s")':"Zmień motyw (obecnie - „%s”)","Check blocks":"Sprawdź bloki","Check is not active, because javascript adapter is disabled":"Sprawdzanie nie jest aktywne, ponieważ adapter Javascript jest wyłączony","Clear search input":"Wyczyść dane wyszukiwania","Click on this icon":"Kliknij tę ikonę",Close:e4,"Close all but current":"Zamknij wszystkie oprócz bieżących","Collapse all":"Zwinąć wszystkie","Compares current time with astronomical event":"Porównuje aktualny czas z wydarzeniem astronomicznym","Compares current time with the user specific time":"Porównuje aktualny czas z czasem określonym przez użytkownika","Compares the state value with user defined value":"Porównuje wartość stanu z wartością zdefiniowaną przez użytkownika",Condition:t4,Conditions:s4,"Configuration not saved.":"Konfiguracja nie została zapisana.",Console:o4,"Control or update some state":"Kontroluj lub aktualizuj stan","Control or update some state with delay":"Kontroluj lub aktualizuj jakiś stan z opóźnieniem","Convert blockly to javascript for ever.":"Bezpowrotna konwersja Blockly na Javascript.",Copied:i4,"Copy script":"Skopiuj skrypt","Copy to clipboard":"Skopiuj do schowka","Create new":"Utwórz nowy","Create new folder":"Utwórz nowy folder","Create new script":"Utwórz nowy skrypt","Create or edit CRON or time wizard":"Utwórz lub edytuj CRON lub kreator czasu","Dark Theme":"Ciemny schemat","Dark style":"Ciemny styl",Date:"Data","Debug instance":"Debuguj instancję","Debug options":"Opcje debugowania",December:n4,Default:r4,"Define cron...":"Zdefiniuj CRON ...","Define schedule...":"Zdefiniuj harmonogram ...",Delay:a4,Delete:l4,"Delete %s":"Usuń %s ...","Delete folder":"Usuń folder","Delete script":"Usuń skrypt",Description:c4,"Deselect all":"Odznacz wszystkie","Discard changes for %s":"Odrzuć zmiany dla %s",Done:u4,"Double click to write value":"Kliknij dwukrotnie, aby zapisać wartość","Download as file":"Download jako plik plik","Drop some files here or click...":"Upuść niektóre pliki tutaj lub kliknij ...","Duplicate name":"Duplikat nazwy","Edit script or just double click":"Edytuj skrypt lub po prostu kliknij dwukrotnie","Empty name is not allowed":"Pusta nazwa jest niedozwolona","End search mode":"Zakończ tryb wyszukiwania","Enter your question":"Wpisz swoją prośbę",Error:"Błąd","Error formatting code":"Błąd formatowania kodu","Error was found":"Błąd został znaleziony","Every day":"Codziennie",Exec:d4,"Executes some shell command":"Wykonuje polecenie powłoki","Existing scripts will be overwritten.":"Istniejące skrypty zostaną zastąpione.","Expand all":"Rozwiń wszystkie","Expert mode":"Tryb ekspercki",Explanation:h4,Export:p4,"Export all scripts":"Wyeksportuj wszystkie skrypty","Export blocks":"Eksportuj bloki","Export selected blocks":"Eksportuj wybrane bloki",Februar:g4,February:m4,Filter:f4,Folder:$4,Fr:b4,Friday:v4,Function:"Funkcja","Function editor":"Edytor funkcji","Function: executed":"Funkcja: wykonywana","Go to next line":"Przejdź do następnej linii","HTTP Call":"Połączenie HTTP","Hide logs":"Ukryj dzienniki",ID:y4,ID1:_4,ID2:w4,Import:k4,"Import blocks":"Importuj bloki","Import error":"Błąd importowania","Import scripts":"Importuj skrypty","Insert object ID":"Wstaw identyfikator obiektu",Instance:C4,"Instance is disabled":"Instancja jest wyłączona","Instance:":"Instancja:",Instances:T4,Instructions:S4,"Invalid CRON":"Nieprawidłowy CRON","It will not be possible to revert this operation.":"Cofnięcie tej operacji nie będzie możliwe.","JS description":"Tworzenie reguł w Javascript",Januar:E4,January:I4,July:x4,June:D4,"Just check":"Po prostu sprawdź","Keep my changes":"Zachowaj moje zmiany","Language:":"Język:","Learn More":"Ucz się więcej","Light style":"Lekki styl",Limit:A4,"Local time":"Czas lokalny","Locate file":"Znajdź plik","Log outputs":"Log dziennika","Log text":"Tekst dziennika","Log: %s":"Dziennik: %s","Make a HTTP get request":"Złóż żądanie HTTP get","Make a pause between actions":"Zrób przerwę między czynnościami",March:R4,"March ":"Marzec ",May:O4,Menu:N4,Message:M4,Mo:L4,Model:P4,Monday:B4,Month:j4,More:F4,Name:z4,"No API key found":"Nie znaleziono klucza API","No Chat GPT Key found":"Nie znaleziono klucza GPT czatu","No active host found":"Nie znaleziono aktywnego hosta","Nothing found":"Nic nie znaleziono",November:U4,OK:H4,October:W4,Ok:G4,"On condition change":"W przypadku zmiany warunków","On script save or adapter start":"Podczas zapisywania skryptu lub uruchamiania adaptera","On weekdays":"W dni powszednie","Open configuration":"Otwarta konfiguracja","Operate two states":"Obsługuj dwa stany","Operations with two states":"Operacje z dwoma stanami","Paste your blocks here":"Wklej tutaj swoje bloki",Pause:V4,"Pause execution":"Wstrzymaj wykonanie","Pause script":"Wstrzymaj skrypt","Phone:":"Telefon:","Please select object ID...":"Wybierz identyfikator obiektu ...","Press Ctrl+Enter to get the answer":"Naciśnij klawisze Ctrl+Enter, aby uzyskać odpowiedź","Prettify the script":"Upiększ skrypt","Print some text in log":"Wydrukuj tekst w dzienniku","Priority:":"Priorytet:",Pushover:K4,Pushsafer:Y4,"Read only ID selected: %s":"Wybrano identyfikator tylko do odczytu: %s",Reload:J4,Rename:q4,"Reorder scripts in folders":"Zmień kolejność skryptów w folderach",Repeat:X4,Restart:Z4,Result:Q4,"Resume execution":"Wznów wykonanie","Root folder":"Folder główny","Rules description":"Twórz reguły z blokami IF, THEN, ELSE","Run script":"Uruchom skrypt",Sa:e8,Saturday:t8,Save:s8,"Save all":"Zapisz wszystko","Say It":"Wypowiedz","Say some text via sayit adapter":"Powiedz tekst przez adapter sayit",Schedule:o8,Script:i8,"Script %s was modified on disk":"Skrypt %s został zmodyfikowany na dysku","Script was modified externally":"Skrypt został zmodyfikowany zewnętrznie","Script is not running":"Skrypt nie działa","Search in scripts":"Szukaj w skryptach","Search...":"Szukaj...","Select all":"Zaznacz wszystko","Send email":"Wysłać email","Sends an email":"Wysyła e-mail","Sends message via Pushsafer":"Wysyła wiadomość przez Pushsafer","Sends message via pushover":"Wysyła wiadomość przez pushover","Sends message via telegram":"Wysyła wiadomość telegramem","Sends message via whatsapp-cmb":"Wysyła wiadomość przez WhatsApp-cmb",September:n8,"Server time":"Czas serwera","Set state action":"Ustaw stan działania","Set with delay":"Ustaw z opóźnieniem","Shell command":"Polecenie powłoki","Show astronomical events":"Pokaż wydarzenia astronomiczne","Show javascript code":"Pokaż kod JavaScript","Show logs":"Pokaż dzienniki","Show only paused scripts":"Pokaż tylko wstrzymane skrypty","Show only running scripts":"Pokaż tylko działające skrypty","Show only scripts with problems":"Pokaż tylko skrypty z problemami",Simulate:r8,"Some files will be rejected":"Niektóre pliki zostaną odrzucone","Sound:":"Dźwięk:",Stack:a8,Start:l8,"Start script":"Uruchom skrypt",State:c8,"State condition":"Warunek stanu","Step into function":"Wejdź do funkcji","Step out from function":"Wyjdź z funkcji","Stop on exception":"Zatrzymaj się na wyjątku",Su:u8,"Subject:":"Temat:",Sunday:d8,"TS description":"Tworzenie reguł w Typescript",Telegram:h8,"Text:":"Tekst:",Th:p8,'The script "%s" has been modified by another user or in another window. Do you want to reload the script or keep your local changes?':'Skrypt "%s" został zmodyfikowany przez innego użytkownika lub w innym oknie. Czy chcesz przeładować skrypt, czy zachować lokalne zmiany?',"The script will be stopped and must be activated manually after debugging. Continue?":"Skrypt zostanie zatrzymany i należy go aktywować ręcznie po debugowaniu. Kontyntynuj?","This is advances option. You can write your own code here and it will be executed on trigger":"To jest opcja zaawansowana. Możesz tutaj napisać własny kod, który zostanie wykonany po wyzwoleniu",Thursday:g8,Time:m8,"Time condition":"Warunek czasowy","Title:":"Tytuł:","To:":"Do:","Trigger with value":"Wyzwalacz z wartością",Triggered:f8,Triggers:$8,"Triggers the on script saving or the javascript instance restart":"Uruchamia zapisywanie skryptu lub restart instancji javascript","Triggers the rule on update or change of some state":"Uruchamia regułę przy aktualizacji lub zmianie jakiegoś stanu","Triggers the rule periodically or on some specific time":"Uruchamia regułę okresowo lub w określonym czasie",Tu:b8,Tuesday:v8,URL:y8,"Unknown error":"Nieznany błąd","Unknown error!":"Nieznany błąd!","Use generated code":"Użyj wygenerowanego kodu","User function":"Funkcja użytkownika","User:":"Użytkownik:",Value:_8,"Vibration:":"Wibracja:",Volume:w8,We:k8,Wednesday:C8,"Whatsapp-cmb":"Whatsapp-cmb",Write:T8,"Write your own code":"Napisz swój własny kod",Yes:S8,"Yet exists!":"A jednak istnieje!","You can use %s in the URL to use current trigger value or %id to use the triggered object ID":"Możesz użyć %s w adresie URL, aby użyć bieżącej wartości wyzwalacza, %id, aby użyć wyzwalanego identyfikatora obiektu, %name, aby wyświetlić nazwę identyfikatora wyzwalanego obiektu, lub %old, aby użyć starej wartości wyzwalacza","You can use %s in the command to use current trigger value or %id to use the triggered object ID":"Możesz użyć %s w poleceniu, aby użyć bieżącej wartości wyzwalającej, %id, aby użyć identyfikatora wyzwalanego obiektu, %name, aby wyświetlić nazwę identyfikatora wyzwalanego obiektu, lub %old, aby użyć starej wartości wyzwalającej","You can use %s in the text to display current trigger value or %id to display the triggered object ID":"Możesz użyć %s w tekście, aby wyświetlić aktualną wartość wyzwalającą, %id, aby użyć identyfikatora wyzwolonego obiektu, %name, aby wyświetlić nazwę identyfikatora wyzwolonego obiektu lub %old, aby użyć starej wartości wyzwalającej","You can use %s in the value to use the current trigger value or %id to display the triggered object ID":"Możesz użyć %s w wartości, aby użyć bieżącej wartości wyzwalacza, %id, aby użyć identyfikatora wyzwalanego obiektu, %name, aby wyświetlić nazwę identyfikatora wyzwalanego obiektu, lub %old, aby użyć starej wartości wyzwalacza","You have to enter OpenAI API key in the configuration of javascript adapter.":"Należy wprowadzić klucz OpenAI API w konfiguracji adaptera javascript.","You have to enter at least one API key in the configuration of javascript adapter.":"Musisz wprowadzić co najmniej jeden klucz API (OpenAI, Anthropic lub Gemini) w konfiguracji adaptera javascript.","Please select a valid model":"Wybierz prawidłowy model","[equal]":"[równy]","[greater or equal]":"[większe lub równe]","[greater]":"[większe]","[hysteresis]":"[histereza]","[includes]":"[obejmuje]","[less or equal]":"[mniejsze lub równe]","[less]":"[mniejsze]","[not equal]":"[nie równe]",acknowledgment:E8,all:I8,and:x8,"as JSON":"jako JSON","as plain text":"jako zwykły tekst",astro:D8,at:A8,"clear running":"czyste uruchomienie",control:R8,copy:O8,cron:N8,dawn:M8,debug_help:L8,debug_label:P8,default:"domyślna",dusk:B8,easy:j8,else:"inaczej","equal to":"równy",every:F8,"every hour at 0 minutes":"co godzinę po 0 minutach",false:"fałsz","file reading has failed: %s":"odczyt pliku nie powiódł się: %s","file reading was aborted":"odczyt pliku został przerwany",filter_func:z8,filter_id:U8,filter_name:H8,filter_role:W8,filter_room:G8,"for edit or create script":"do edycji lub utwórz nowy skrypt","for professionals":"dla profesjonalistów","for programmers":"dla programistów",goldenHour:V8,goldenHourEnd:K8,"greater or equal":"większe lub równe","greater or equal to":"więcej lub równo","greater than":"więcej niż",help_just_check:Y8,help_on_change:J8,"high priority":"wysoki priorytet","high-priority":"wysoki priorytet","highest priority":"najwyższy priorytet",hours:q8,includes:X8,interval:Z8,"just check":"po prostu sprawdź","less or equal":"mniejsze lub równe","less or equal to":"mniej lub równo","less than":"mniej niż","lower priority":"niższy priorytet","lowest priority":"najniższy priorytet",magic:Q8,milliseconds:e6,minutes:t6,ms:s6,nadir:o6,nauticalDawn:i6,nauticalDusk:n6,nextSunrise:r6,nextSunset:a6,night:l6,nightEnd:c6,"no blocks found":"Nie znaleziono bloków","no group":"BRAK GRUPY",normal:u6,"normal priority":"normalny priorytet","not running":"nie uruchomiony","not equal to":"nie równa się","not properly connected":"Ten blok nie jest poprawnie podłączony do innych bloków.",offset:d6,"on change":"na zmianę","on condition change":"pod warunkiem zmiany warunków","on update":"po aktualizacji",one:h6,or:p6,quiet:g6,"reset search":"zresetuj wyszukiwanie",search:m6,seconds:f6,solarNoon:$6,"store in":"przechowaj w",sunrise:b6,sunriseEnd:v6,sunset:y6,sunsetStart:_6,then:w6,"toggle value":"wartość przełączania",tooltip_ack:k6,tooltip_from:C6,tooltip_lc:T6,tooltip_quality:S6,tooltip_ts:E6,tooltip_user:I6,tooltip_value:x6,true:"prawda",two:D6,undefined:"nieokreślony",update:A6,"use seconds":"użyj sekund","use trigger value":"użyj wartości wyzwalającej",verbose_help:R6,verbose_label:O6,when:N6,with:"z","with date":"z datą","with offset":"z przesunięciem",wizard:M6,"Loading models...":"Ładowanie modeli...","Could not connect to API at %s":"Nie można połączyć się z API pod adresem %s","Invalid API key":"Nieprawidłowy klucz API","Access denied by API":"Odmowa dostępu przez API","API error: %s":"Błąd API: %s",'Model "%s" not found':'Model "%s" nie znaleziony',"Request failed: %s":"Żądanie nie powiodło się: %s",Retry:L6,"No running javascript instance found":"Nie znaleziono uruchomionej instancji JavaScript"},B6="Reconhecido",j6="Ações",F6="Adicionar",z6="Todos",U6="Nenhum",H6="Aplique",W6="abril",G6="Perguntar",V6="Astronômico",K6="agosto",Y6="Cancelar",J6="Fechar",q6="Doença",X6="Condições",Z6="Console",Q6="Copiado",e9="dezembro",t9="Predefinição",s9="Atraso",o9="Deletar",i9="Descrição",n9="Pronto",r9="Exec shell",a9="Explicação",l9="Exportação",c9="Februar",u9="fevereiro",d9="Filtro",h9="Pasta",p9="Fr",g9="Sexta-feira",m9="ID",f9="ID1",$9="ID2",b9="Importar",v9="Instância",y9="Instâncias",_9="Instruções",w9="Januar",k9="janeiro",C9="julho",T9="junho",S9="Limite",E9="março",I9="maio",x9="Menu",D9="mensagem",A9="Mo",R9="Modelo",O9="Segunda-feira",N9="Mês",M9="Mais",L9="Nome",P9="novembro",B9="OK",j9="outubro",F9="Ok",z9="Pausa",U9="Pushover",H9="Pushsafer",W9="Recarregar",G9="Renomear",V9="Repetir",K9="Reiniciar",Y9="Resultado",J9="Sá",q9="Sábado",X9="Salve",Z9="Cronograma",Q9="Script",eK="setembro",tK="Simular",sK="Pilha",oK="Começar",iK="Estado",nK="Su",rK="Domingo",aK="Telegrama",lK="4",cK="Quinta-feira",uK="Tempo",dK="Provocado",hK="Gatilhos",pK="Tu",gK="terça",mK="URL",fK="Valor",$K="Volume",bK="3",vK="quarta",yK="Escrever",_K="sim",wK="reconhecimento",kK="todos",CK="e",TK="astro",SK="no",EK="ao controle",IK="copiar",xK="CRON",DK="alvorecer",AK="Este é um modo especial no qual estados e objetos não serão alterados. Mas apenas as informações sobre cada mudança planejada serão exibidas no protocolo.",RK="Depurar",OK="Crepúsculo",NK="fácil",MK="cada",LK="Função",PK="ID",BK="Nome",jK="Tipo",FK="Quarto",zK="Hora dourada",UK="Fim da hora de ouro",HK='O código será executado apenas sempre que a condição for verdadeira. Por exemplo. se disparar no valor do sensor de temperatura e a condição for "se a temperatura for maior que 20 ° C", as ações "então" serão executadas toda vez que o sensor enviar a temperatura e ela estiver acima de 20 ° C. Por 21 ° C, por 22 ° C e assim por diante.',WK='O código será executado apenas se o resultado da condição mudar. Por exemplo. se disparar no valor do sensor de temperatura e a condição for "se a temperatura for maior que 20 ° C", as ações "então" serão executadas uma vez quando a temperatura estiver acima de 20. Na próxima vez, as ações "então" serão executadas quando a temperatura falha abaixo de 20 e sobe acima de 20 novamente.',GK="horas",VK="inclui",KK="intervalo",YK="Magia",JK="milissegundos",qK="minutos",XK="ms",ZK="nadir",QK="Madrugada náutica",e7="Crepúsculo náutico",t7="próximo nascer do sol",s7="Próximo pôr do sol",o7="Noite",i7="Fim de noite",n7="normal",r7="Deslocamento",a7="1",l7="ou",c7="quieto",u7="procurar",d7="segundos",h7="Meio-dia solar",p7="nascer do sol",g7="Fim do nascer do sol",m7="pôr do sol",f7="Começo do pôr do sol",$7="então",b7="reconhecer",v7="de",y7="Última alteração",_7="Qualidade",w7="timestamp",k7="usuário",C7="valor",T7="dois",S7="atualizar",E7="Adiciona saída de depuração ao log para muitos comandos do sistema",I7="Saídas de log detalhadas",x7="quando",D7="Wizard",A7="Tentar novamente",R7={"%s not found":"%s não encontrado","()":"()","(at %s)":"(em %s)","(optional)":"(opcional)","-":"-",".":".","AI code generator":"Gerador de código de IA",Ack:B6,Actions:j6,"Actual time of day":"Hora real do dia",Add:F6,"Add new script":"Adicionar novo script",All:z6,"All files will be accepted":"Todos os arquivos serão aceitos",Any:U6,"Any month":"Qualquer mês",Apply:H6,April:W6,"Are you sure?":"Você tem certeza?",Ask:G6,Astronomical:V6,"Astronomical events today":"Eventos astronômicos hoje",August:K6,"Blockly description":"Criando regras por blocos gráficos","Body:":"Corpo:",Cancel:Y6,"Cannot delete non empty item!":"Não pode ser deletar, porque não está vazio!","Change layout":"Alterar layout",'Change theme (actual "%s")':'Alterar tema (agora - "%s")',"Check blocks":"Verificar blocos","Check is not active, because javascript adapter is disabled":"A verificação de sintaxe não está ativa porque o adaptador javascript não está rodando.","Clear search input":"Limpar entrada de pesquisa","Click on this icon":"Clique neste ícone",Close:J6,"Close all but current":"Fechar tudo, menos atual","Collapse all":"Recolher todos","Compares current time with astronomical event":"Compara o tempo atual com o evento astronômico","Compares current time with the user specific time":"Compara a hora atual com a hora específica do usuário","Compares the state value with user defined value":"Compara o valor do estado com o valor definido pelo usuário",Condition:q6,Conditions:X6,"Configuration not saved.":"Configuração não esta salva.",Console:Z6,"Control or update some state":"Controlar ou atualizar algum estado","Control or update some state with delay":"Controlar ou atualizar algum estado com atraso","Convert blockly to javascript for ever.":"Converter Blockly em Javascript permanentemente.",Copied:Q6,"Copy script":"Copiar script","Copy to clipboard":"Copiar para área de transferência","Create new":"Crie um novo","Create new folder":"Criar nova pasta","Create new script":"Criar novo script","Create or edit CRON or time wizard":"Criar ou editar o assistente cron ou o assistente de horário","Dark Theme":"Layout escuro","Dark style":"Estilo escuro",Date:"Encontro","Debug instance":"Instância de depuração","Debug options":"Opções de depuração",December:e9,Default:t9,"Define cron...":"Definir cron...","Define schedule...":"Definir agendamento ...",Delay:s9,Delete:o9,"Delete %s":"Deletar %s...","Delete folder":"Deletar pasta","Delete script":"Deletar script",Description:i9,"Deselect all":"Desmarcar todos","Discard changes for %s":"Descartar alterações para %s",Done:n9,"Double click to write value":"Clique duas vezes para escrever o valor","Download as file":"Baixar como arquivo","Drop some files here or click...":"Solte alguns arquivos aqui ou clique em...","Duplicate name":"Nome duplicado","Edit script or just double click":"Edite o script ou clique duas vezes","Empty name is not allowed":"Nome vazio não é permitido","End search mode":"Finalizar modo de pesquisa","Enter your question":"Digite sua solicitação",Error:"Erro","Error formatting code":"Erro de formatação de código","Error was found":"Erro foi encontrado","Every day":"Todos os dias",Exec:r9,"Executes some shell command":"Executa algum comando shell","Existing scripts will be overwritten.":"Os scripts existentes serão substituídos.","Expand all":"Expandir todos","Expert mode":"Modo de especialista",Explanation:a9,Export:l9,"Export all scripts":"Exportar todos os scripts","Export blocks":"Exportar blocos","Export selected blocks":"Exportar blocos selecionados",Februar:c9,February:u9,Filter:d9,Folder:h9,Fr:p9,Friday:g9,Function:"Função","Function editor":"Editor de funções","Function: executed":"Função: executado","Go to next line":"Vá para a próxima linha","HTTP Call":"Chamada HTTP","Hide logs":"Ocultar logs",ID:m9,ID1:f9,ID2:$9,Import:b9,"Import blocks":"Importar blocos","Import error":"Erro de importação","Import scripts":"Importar script","Insert object ID":"Inserir ID do objeto",Instance:v9,"Instance is disabled":"Instância está desativada","Instance:":"Instância:",Instances:y9,Instructions:_9,"Invalid CRON":"CRON inválido","It will not be possible to revert this operation.":"Não será possível reverter esta operação.","JS description":"Criando regras escrevendo Javascript",Januar:w9,January:k9,July:C9,June:T9,"Just check":"Apenas verifique","Keep my changes":"Manter minhas alterações","Language:":"Língua:","Learn More":"Aprender mais","Light style":"Estilo claro",Limit:S9,"Local time":"Hora local","Locate file":"Localize o arquivo","Log outputs":"Saídas de log","Log text":"Texto de registro","Log: %s":"Log: %s","Make a HTTP get request":"Faça uma solicitação HTTP get","Make a pause between actions":"Faça uma pausa entre as ações",March:E9,"March ":"Março",May:I9,Menu:x9,Message:D9,Mo:A9,Model:R9,Monday:O9,Month:N9,More:M9,Name:L9,"No API key found":"Nenhuma chave API encontrada","No Chat GPT Key found":"Nenhuma chave GPT de bate-papo encontrada","No active host found":"Nenhum host ativo encontrado","Nothing found":"Nada encontrado",November:P9,OK:B9,October:j9,Ok:F9,"On condition change":"Na mudança de condição","On script save or adapter start":"Ao salvar o script ou iniciar o adaptador","On weekdays":"Nos dias úteis","Open configuration":"Configuração aberta","Operate two states":"Operar dois estados","Operations with two states":"Operações com dois estados","Paste your blocks here":"Cole seus blocos aqui",Pause:z9,"Pause execution":"Pausar a execução","Pause script":"Pausar script","Phone:":"Telefone:","Please select object ID...":"Selecione o ID do objeto...","Press Ctrl+Enter to get the answer":"Pressione Ctrl+Enter para obter a resposta","Prettify the script":"Embeleze o roteiro","Print some text in log":"Imprimir algum texto no log","Priority:":"Prioridade:",Pushover:U9,Pushsafer:H9,"Read only ID selected: %s":"ID somente leitura selecionada: %s",Reload:W9,Rename:G9,"Reorder scripts in folders":"Reordenar scripts em pastas",Repeat:V9,Restart:K9,Result:Y9,"Resume execution":"Retomar execução","Root folder":"Pasta principal","Rules description":"Crie regras com blocos IF, THEN, ELSE","Run script":"Executar script",Sa:J9,Saturday:q9,Save:X9,"Save all":"Salvar tudo","Say It":"Say It","Say some text via sayit adapter":"Diga algum texto através do adaptador sayit",Schedule:Z9,Script:Q9,"Script %s was modified on disk":'O script "%s" foi modificado no disco rígido',"Script was modified externally":"O script foi modificado externamente","Script is not running":"Script não está sendo executado","Search in scripts":"Pesquisa em scripts","Search...":"Procurar...","Select all":"Selecionar tudo","Send email":"Enviar email","Sends an email":"Envia um email","Sends message via Pushsafer":"Envia mensagem via Pushsafer","Sends message via pushover":"Envia mensagem via pushover","Sends message via telegram":"Envia mensagem via telegrama","Sends message via whatsapp-cmb":"Envia mensagem via whatsapp-cmb",September:eK,"Server time":"Tempo de servidor","Set state action":"Definir ação de estado","Set with delay":"Definido com atraso","Shell command":"Comando shell","Show astronomical events":"Mostrar eventos astronômicos","Show javascript code":"Mostrar código Javascript","Show logs":"Mostrar logs","Show only paused scripts":"Mostrar apenas scripts pausados","Show only running scripts":"Mostrar apenas scripts em execução","Show only scripts with problems":"Mostrar apenas scripts com problemas",Simulate:tK,"Some files will be rejected":"Alguns arquivos serão rejeitados","Sound:":"Som:",Stack:sK,Start:oK,"Start script":"Iniciar script",State:iK,"State condition":"Condição de estado","Step into function":"Entre na função","Step out from function":"Saia da função","Stop on exception":"Pare na exceção",Su:nK,"Subject:":"Sujeito:",Sunday:rK,"TS description":"Criando regras escrevendo Typecript",Telegram:aK,"Text:":"Texto:",Th:lK,'The script "%s" has been modified by another user or in another window. Do you want to reload the script or keep your local changes?':'O script "%s" foi modificado por outro usuário ou em outra janela. Deseja recarregar o script ou manter suas alterações locais?',"The script will be stopped and must be activated manually after debugging. Continue?":"O script será interrompido e deve ser ativado manualmente após a depuração. Continuar?","This is advances option. You can write your own code here and it will be executed on trigger":"Esta é a opção de avanços. Você pode escrever seu próprio código aqui e ele será executado no gatilho",Thursday:cK,Time:uK,"Time condition":"Condição de tempo","Title:":"Título:","To:":"Para:","Trigger with value":"Trigger com valor",Triggered:dK,Triggers:hK,"Triggers the on script saving or the javascript instance restart":"Aciona o salvamento do script ou a reinicialização da instância javascript","Triggers the rule on update or change of some state":"Aciona a regra na atualização ou mudança de algum estado","Triggers the rule periodically or on some specific time":"Aciona a regra periodicamente ou em algum momento específico",Tu:pK,Tuesday:gK,URL:mK,"Unknown error":"Erro desconhecido","Unknown error!":"Erro desconhecido!","Use generated code":"Usar código gerado","User function":"Função do usuário","User:":"Do utilizador:",Value:fK,"Vibration:":"Vibração:",Volume:$K,We:bK,Wednesday:vK,"Whatsapp-cmb":"Whatsapp-cmb",Write:yK,"Write your own code":"Escreva seu próprio código",Yes:_K,"Yet exists!":"Ainda existe!","You can use %s in the URL to use current trigger value or %id to use the triggered object ID":"Você pode usar %s na URL para usar o valor do gatilho atual, %id para usar o ID do objeto acionado, %name para mostrar o nome do ID do objeto acionado ou %old para usar o valor do gatilho antigo","You can use %s in the command to use current trigger value or %id to use the triggered object ID":"Você pode usar %s no comando para usar o valor do acionador atual, %id para usar o ID do objeto acionado, %name para mostrar o nome do ID do objeto acionado ou %old para usar o valor do acionador antigo","You can use %s in the text to display current trigger value or %id to display the triggered object ID":"Você pode usar %s no texto para exibir o valor do acionador atual, %id para usar o ID do objeto acionado, %name para mostrar o nome do ID do objeto acionado ou %old para usar o valor do acionador antigo","You can use %s in the value to use the current trigger value or %id to display the triggered object ID":"Você pode usar %s no valor para usar o valor do acionador atual, %id para usar o ID do objeto acionado, %name para mostrar o nome do ID do objeto acionado ou %old para usar o valor do acionador antigo","You have to enter OpenAI API key in the configuration of javascript adapter.":"Você deve inserir a chave da API OpenAI na configuração do adaptador javascript.","You have to enter at least one API key in the configuration of javascript adapter.":"Você deve inserir pelo menos uma chave API (OpenAI, Anthropic ou Gemini) na configuração do adaptador javascript.","Please select a valid model":"Selecione um modelo válido","[equal]":"[igual]","[greater or equal]":"[maior ou igual]","[greater]":"[maior]","[hysteresis]":"[histerese]","[includes]":"[inclui]","[less or equal]":"[menor ou igual]","[less]":"[menos]","[not equal]":"[não igual]",acknowledgment:wK,all:kK,and:CK,"as JSON":"como JSON","as plain text":"como texto simples",astro:TK,at:SK,"clear running":"corrida limpa",control:EK,copy:IK,cron:xK,dawn:DK,debug_help:AK,debug_label:RK,default:"predefinição",dusk:OK,easy:NK,else:"outro","equal to":"igual a",every:MK,"every hour at 0 minutes":"a cada hora em 0 minutos",false:"falso","file reading has failed: %s":"a leitura do arquivo falhou: %s","file reading was aborted":"a leitura do arquivo foi abortada",filter_func:LK,filter_id:PK,filter_name:BK,filter_role:jK,filter_room:FK,"for edit or create script":"para editar ou criar um novo script","for professionals":"para profissionais","for programmers":"para programadores",goldenHour:zK,goldenHourEnd:UK,"greater or equal":"maior ou igual","greater or equal to":"maior ou igual a","greater than":"Maior que",help_just_check:HK,help_on_change:WK,"high priority":"prioridade máxima","high-priority":"prioridade máxima","highest priority":"Prioridade máxima",hours:GK,includes:VK,interval:KK,"just check":"Apenas verifique","less or equal":"menor ou igual","less or equal to":"menor ou igual a","less than":"Menor que","lower priority":"prioridade mais baixa","lowest priority":"prioridade mais baixa",magic:YK,milliseconds:JK,minutes:qK,ms:XK,nadir:ZK,nauticalDawn:QK,nauticalDusk:e7,nextSunrise:t7,nextSunset:s7,night:o7,nightEnd:i7,"no blocks found":"Nenhum bloco encontrado","no group":"SEM GRUPO",normal:n7,"normal priority":"prioridade normal","not running":"não está em execução","not equal to":"não é igual a","not properly connected":"Este bloco não está conectado corretamente com outros blocos.",offset:r7,"on change":"em mudança","on condition change":"na mudança de condição","on update":"em atualização",one:a7,or:l7,quiet:c7,"reset search":"redefinir pesquisa",search:u7,seconds:d7,solarNoon:h7,"store in":"armazenar em",sunrise:p7,sunriseEnd:g7,sunset:m7,sunsetStart:f7,then:$7,"toggle value":"valor de alternância",tooltip_ack:b7,tooltip_from:v7,tooltip_lc:y7,tooltip_quality:_7,tooltip_ts:w7,tooltip_user:k7,tooltip_value:C7,true:"verdade",two:T7,undefined:"Indefinido",update:S7,"use seconds":"use segundos","use trigger value":"use o gatilho",verbose_help:E7,verbose_label:I7,when:x7,with:"com","with date":"com data","with offset":"com deslocamento",wizard:D7,"Loading models...":"Carregando modelos...","Could not connect to API at %s":"Não foi possível conectar à API em %s","Invalid API key":"Chave API inválida","Access denied by API":"Acesso negado pela API","API error: %s":"Erro de API: %s",'Model "%s" not found':'Modelo "%s" não encontrado',"Request failed: %s":"Solicitação falhou: %s",Retry:A7,"No running javascript instance found":"Nenhuma instância JavaScript em execução encontrada"},O7="Подтверждение",N7="Действия",M7="Добавить",L7="Все",P7="Любая",B7="Применить",j7="Апрель",F7="Спросить",z7="Aстрономический",U7="Август",H7="Отмена",W7="Закрыть",G7="Условие",V7="Условия",K7="Приставка",Y7="Скопировано",J7="Декабрь",q7="Дефолт",X7="Задержка",Z7="Удалить",Q7="Описание",eY="Готово",tY="Исполнить shell",sY="Объяснение",oY="Экспорт",iY="Февраль",nY="Февраль",rY="Фильтр",aY="Папка",lY="Пт",cY="пятница",uY="ID",dY="ID1",hY="ID2",pY="Импорт",gY="Экземпляр",mY="Экземпляры",fY="Инструкции",$Y="Январь",bY="Январь",vY="Июль",yY="Июнь",_Y="Предел",wY="Март",kY="Май",CY="Меню",TY="Сообщение",SY="Пн",EY="Модель",IY="понедельник",xY="Месяц",DY="Более",AY="Имя",RY="Ноябрь",OY="Ок",NY="Октябрь",MY="Ok",LY="Пауза",PY="Pushover",BY="Pushsafer",jY="Перезагрузить",FY="Переименовать",zY="Повторение",UY="Перезапустить",HY="Результат",WY="Сб",GY="суббота",VY="Сохранить",KY="Расписание",YY="скрипт",JY="Сентябрь",qY="Симулировать",XY="Stack",ZY="Начинать",QY="Состояние",eJ="Вс",tJ="Воскресенье",sJ="Telegram",oJ="Чт",iJ="Четверг",nJ="Время",rJ="Срабатывает",aJ="Триггеры",lJ="Вт",cJ="вторник",uJ="URL",dJ="Значение",hJ="Громкость",pJ="Ср",gJ="среда",mJ="Напишите",fJ="Да",$J="подтверждение",bJ="все",vJ="и",yJ="Астро",_J="в",wJ="контроль",kJ="копия",CJ="CRON",TJ="Рассвет",SJ="Это особый режим, в котором состояния и объекты не будут меняться. Но в протоколе будет отображаться только информация о каждом планируемом изменении.",EJ="Отлаживать",IJ="Сумерки",xJ="легкий",DJ="каждые(ый)",AJ="Функция",RJ="ID",OJ="Название",NJ="Роль",MJ="Комната",LJ="Золотой час",PJ="Конец золотого часа",BJ="Код будет выполняться только каждый раз, когда условие истинно. Например. при срабатывании по значению датчика температуры и условию «если температура выше 20°C», действия «затем» будут выполняться каждый раз, когда датчик отправляет значение температуры, и оно превышает 20°C. На 21°С, на 22°С и так далее.",jJ="Код будет выполнен только в случае изменения результата условия. Например, при срабатывании по значению датчика температуры и условию «если температура больше 20°C», действия «затем» будут выполнены один раз, когда температура превысит 20°C. В следующий раз действия «затем» будут выполнены, когда температура опустится ниже 20°C, а затем снова поднимается выше 20°C.",FJ="час(ов)",zJ="содержит",UJ="интервал",HJ="магия",WJ="миллисекунды",GJ="минут(у)",VJ="мс",KJ="Надир",YJ="Морской рассвет",JJ="Морские сумерки",qJ="Следующий восход",XJ="Следующий закат",ZJ="Ночь",QJ="Конец ночи",eq="нормальный",tq="сдвиг",sq="один",oq="или",iq="тихий",nq="поиск",rq="секунд",aq="Солнечный полдень",lq="Восход солнца",cq="Конец восхода",uq="Закат солнца",dq="Начало заката",hq="тогда",pq="Подтверждено",gq="От",mq="Последнее изменение",fq="Качественный",$q="Время",bq="Пользователь",vq="Значение",yq="два",_q="обновить",wq="Добавляет вывод отладки в журнал для многих системных команд.",kq="Подробный протокол",Cq="если",Tq="Мастер",Sq="Повторить",Eq={"%s not found":"%s не найден","()":"()","(at %s)":"(в %s)","(optional)":"(необязательный)","-":"-",".":".","AI code generator":"ИИ Генератор кода",Ack:O7,Actions:N7,"Actual time of day":"Фактическое время суток",Add:M7,"Add new script":"Добавить новый скрипт",All:L7,"All files will be accepted":"Все файлы будут приняты",Any:P7,"Any month":"В любой месяц",Apply:B7,April:j7,"Are you sure?":"Вы уверены?",Ask:F7,Astronomical:z7,"Astronomical events today":"Астрономические события сегодня",August:U7,"Blockly description":"Создание правил графическими блоками","Body:":"Тело:",Cancel:H7,"Cannot delete non empty item!":"Не удается удалить непустой элемент!","Change layout":"Изменить макет",'Change theme (actual "%s")':'Сменить тему (сейчас - "%s")',"Check blocks":"Проверить блоки","Check is not active, because javascript adapter is disabled":"Проверка неактивна, потому что адаптер Javascript отключен","Clear search input":"Очистить ввод","Click on this icon":"Нажмите на этот значок",Close:W7,"Close all but current":"Закрыть все кроме текущего","Collapse all":"Свернуть все","Compares current time with astronomical event":"Сравнивает текущее время с астрономическим событием","Compares current time with the user specific time":"Сравнивает текущее время с конкретным временем пользователя","Compares the state value with user defined value":"Сравнивает значение состояния с пользовательским значением",Condition:G7,Conditions:V7,"Configuration not saved.":"Конфигурация не сохранена.",Console:K7,"Control or update some state":"Контролировать или обновлять какое-то состояние","Control or update some state with delay":"Контролировать или обновлять какое-либо состояние с задержкой","Convert blockly to javascript for ever.":"Преобразовать blockly в Javascript навсегда.",Copied:Y7,"Copy script":"Скопировать скрипт","Copy to clipboard":"Скопировать в буфер обмена","Create new":"Создать новый","Create new folder":"Создать новую папку","Create new script":"Создать новый скрипт","Create or edit CRON or time wizard":"Создание или редактирование CRON или мастера времени","Dark Theme":"Тёмная тема","Dark style":"Темный стиль",Date:"Дата","Debug instance":"Экземпляр отладки","Debug options":"Варианты отладки",December:J7,Default:q7,"Define cron...":"Задать правило ...","Define schedule...":"Задать расписание...",Delay:X7,Delete:Z7,"Delete %s":"Удалить %s...","Delete folder":"Удалить папку","Delete script":"Удалить скрипт",Description:Q7,"Deselect all":"Снять выбор со всех","Discard changes for %s":"Отменить изменения для %s",Done:eY,"Double click to write value":"Двойной щелчок для записи значения","Download as file":"Скачать как файл","Drop some files here or click...":"Перетыщите сюда файлы или нажмите ...","Duplicate name":"Повторяющееся имя","Edit script or just double click":"Редактировать скрипт или просто дважды щелкнуть","Empty name is not allowed":"Пустое имя не допускается","End search mode":"Закончить поиск","Enter your question":"Введи свою просьбу",Error:"Ошибка","Error formatting code":"Ошибка форматирования кода","Error was found":"Ошибка была найдена","Every day":"Каждый день",Exec:tY,"Executes some shell command":"Выполняет некоторую команду оболочки","Existing scripts will be overwritten.":"Существующие скрипты будут перезаписаны.","Expand all":"Открыть все","Expert mode":"Экспертный режим",Explanation:sY,Export:oY,"Export all scripts":"Экспорт всех скриптов","Export blocks":"Экспортировать блоки","Export selected blocks":"Экспортировать выбранные блоки",Februar:iY,February:nY,Filter:rY,Folder:aY,Fr:lY,Friday:cY,Function:"Функция","Function editor":"Редактор функции","Function: executed":"Функция: выполнено","Go to next line":"Перейти к следующей строке","HTTP Call":"HTTP-вызов","Hide logs":"Скрыть журналы",ID:uY,ID1:dY,ID2:hY,Import:pY,"Import blocks":"Импортировать блоки","Import error":"Ошибка импорта","Import scripts":"Импорт скриптов","Insert object ID":"Вставить ID объекта",Instance:gY,"Instance is disabled":"Экземпляр отключен","Instance:":"Пример:",Instances:mY,Instructions:fY,"Invalid CRON":"Неправильный CRON","It will not be possible to revert this operation.":"Невозможно вернуть эту операцию.","JS description":"Создание правил путём написания Javascript",Januar:$Y,January:bY,July:vY,June:yY,"Just check":"Просто проверить","Keep my changes":"Сохранить мои изменения","Language:":"Язык:","Learn More":"Узнать больше","Light style":"Светлый стиль",Limit:_Y,"Local time":"Местное время","Locate file":"Показать файл в дереве","Log outputs":"Журнал","Log text":"Текст журнала","Log: %s":"Журнал: %s","Make a HTTP get request":"Сделайте HTTP-запрос на получение","Make a pause between actions":"Сделайте паузу между действиями",March:wY,"March ":"Март ",May:kY,Menu:CY,Message:TY,Mo:SY,Model:EY,Monday:IY,Month:xY,More:DY,Name:AY,"No API key found":"API-ключ не найден","No Chat GPT Key found":"Ключ GPT для чата не найден","No active host found":"Активный host не найден","Nothing found":"Ничего не найдено",November:RY,OK:OY,October:NY,Ok:MY,"On condition change":"При изменении реузльтата условий","On script save or adapter start":"При сохранении скрипта или запуске адаптера","On weekdays":"По дням недели","Open configuration":"Открыть настройки","Operate two states":"Операции над двумя состояниями","Operations with two states":"Операции с двумя состояниями","Paste your blocks here":"Вставьте свои блоки сюда",Pause:LY,"Pause execution":"Приостановить выполнение","Pause script":"Остановить скрипт","Phone:":"Телефон:","Please select object ID...":"Пожалуйста, выберите ID объекта ...","Press Ctrl+Enter to get the answer":"Нажмите Ctrl+Enter, чтобы получить ответ","Prettify the script":"Украсьте сценарий","Print some text in log":"Напечатать текст в журнале","Priority:":"Приоритет:",Pushover:PY,Pushsafer:BY,"Read only ID selected: %s":"Выбран идентификатор только для чтения: %s",Reload:jY,Rename:FY,"Reorder scripts in folders":"Сортировать скрипты в папках",Repeat:zY,Restart:UY,Result:HY,"Resume execution":"Возобновить выполнение","Root folder":"Корневая папка","Rules description":"Создавайте правила с блоками ЕСЛИ, ТО, ИНАЧЕ","Run script":"Запустить скрипт",Sa:WY,Saturday:GY,Save:VY,"Save all":"Сохранить все","Say It":"Say It","Say some text via sayit adapter":"Произнесите текст через адаптер Sayit",Schedule:KY,Script:YY,"Script %s was modified on disk":'Скрипт "%s" был изменен на диске',"Script was modified externally":"Скрипт был изменён извне","Script is not running":"Сценарий не запущен","Search in scripts":"Поиск в скриптах","Search...":"Поиск...","Select all":"Выбрать все","Send email":"Отправить email","Sends an email":"Отправляет электронное письмо","Sends message via Pushsafer":"Отправляет сообщение через Pushsafer","Sends message via pushover":"Отправляет сообщение через пустышку","Sends message via telegram":"Отправляет сообщение в телеграмме","Sends message via whatsapp-cmb":"Отправляет сообщение через whatsapp-cmb",September:JY,"Server time":"Время сервера","Set state action":"Установить состояние","Set with delay":"Установить с задержкой","Shell command":"Команда оболочки","Show astronomical events":"Показать астрономические события","Show javascript code":"Показать код Javascript","Show logs":"Показать журналы","Show only paused scripts":"Показывать только приостановленные сценарии","Show only running scripts":"Показывать только запущенные скрипты","Show only scripts with problems":"Показывать только скрипты с проблемами",Simulate:qY,"Some files will be rejected":"Некоторые файлы будут отклонены","Sound:":"Звук:",Stack:XY,Start:ZY,"Start script":"Старт скрипта",State:QY,"State condition":"Сравнение состояния","Step into function":"Шаг в функционирование","Step out from function":"Выйти из функции","Stop on exception":"Остановить при исключении",Su:eJ,"Subject:":"Предмет:",Sunday:tJ,"TS description":"Создание правил путём написания Typescript",Telegram:sJ,"Text:":"Текст:",Th:oJ,'The script "%s" has been modified by another user or in another window. Do you want to reload the script or keep your local changes?':'Скрипт "%s" был изменён другим пользователем или в другом окне. Вы хотите перезагрузить скрипт или сохранить свои локальные изменения?',"The script will be stopped and must be activated manually after debugging. Continue?":"Cкрипт будет остановлен и должен быть активирован вручную после отладки. Продолжать?","This is advances option. You can write your own code here and it will be executed on trigger":"Это расширеный вариант. Вы можете написать здесь свой код и он будет выполняться по триггеру",Thursday:iJ,Time:nJ,"Time condition":"Условие времени","Title:":"Заголовок:","To:":"К:","Trigger with value":"Триггер со значением",Triggered:rJ,Triggers:aJ,"Triggers the on script saving or the javascript instance restart":"Запускает при сохранении скрипта или перезапуске экземпляра javascript","Triggers the rule on update or change of some state":"Запускает правило при обновлении или изменении какого-либо состояния","Triggers the rule periodically or on some specific time":"Срабатывает правило периодически или в определенное время",Tu:lJ,Tuesday:cJ,URL:uJ,"Unknown error":"Неизвестная ошибка","Unknown error!":"Неизвестная ошибка!","Use generated code":"Использовать сгенерированный код","User function":"Функция пользователя","User:":"Пользователь:",Value:dJ,"Vibration:":"Вибрация:",Volume:hJ,We:pJ,Wednesday:gJ,"Whatsapp-cmb":"Whatsapp-cmb",Write:mJ,"Write your own code":"Напишите свой код",Yes:fJ,"Yet exists!":"Имя уже существует!","You can use %s in the URL to use current trigger value or %id to use the triggered object ID":"Вы можете использовать %s в URL-адресе, чтобы использовать текущее значение триггера, %id, чтобы использовать идентификатор инициированного объекта, %name, чтобы показать имя идентификатора инициированного объекта, или %old, чтобы использовать старое значение триггера.","You can use %s in the command to use current trigger value or %id to use the triggered object ID":"Вы можете использовать %s в команде, чтобы использовать текущее значение триггера, %id, чтобы использовать идентификатор сработавшего объекта, %name, чтобы показать имя сработавшего идентификатора объекта, или %old, чтобы использовать старое значение триггера.","You can use %s in the text to display current trigger value or %id to display the triggered object ID":"Вы можете использовать %s в тексте для отображения текущего значения триггера, %id для использования идентификатора сработавшего объекта, %name для отображения имени сработавшего идентификатора объекта или %old для использования старого значения триггера.","You can use %s in the value to use the current trigger value or %id to display the triggered object ID":"Вы можете использовать %s в значении, чтобы использовать текущее значение триггера, %id, чтобы использовать идентификатор инициированного объекта, %name, чтобы показать имя идентификатора инициированного объекта, или %old, чтобы использовать старое значение триггера.","You have to enter OpenAI API key in the configuration of javascript adapter.":"Вы должны ввести ключ OpenAI API в конфигурации адаптера javascript.","You have to enter at least one API key in the configuration of javascript adapter.":"Необходимо ввести хотя бы один API-ключ (OpenAI, Anthropic или Gemini) в конфигурации адаптера javascript.","Please select a valid model":"Пожалуйста, выберите допустимую модель","[equal]":"[равно]","[greater or equal]":"[больше или равно]","[greater]":"[больше]","[hysteresis]":"[гистерезис]","[includes]":"[содержит]","[less or equal]":"[меньше или равно]","[less]":"[меньше]","[not equal]":"[не равно]",acknowledgment:$J,all:bJ,and:vJ,"as JSON":"как JSON","as plain text":"как текст",astro:yJ,at:_J,"clear running":"остановить уже бегущие",control:wJ,copy:kJ,cron:CJ,dawn:TJ,debug_help:SJ,debug_label:EJ,default:"дефолт",dusk:IJ,easy:xJ,else:"иначе","equal to":"равно",every:DJ,"every hour at 0 minutes":"каждый час через 0 минут",false:"false","file reading has failed: %s":"Ошибка чтения файла: %s","file reading was aborted":"Чтение файла было прервано",filter_func:AJ,filter_id:RJ,filter_name:OJ,filter_role:NJ,filter_room:MJ,"for edit or create script":"для редактирования или создайте новый скрипт","for professionals":"для профессионалов","for programmers":"для программистов",goldenHour:LJ,goldenHourEnd:PJ,"greater or equal":"больше или равно","greater or equal to":"больше или равно","greater than":"больше чем",help_just_check:BJ,help_on_change:jJ,"high priority":"высокий приоритет","high-priority":"высокий-приоритет","highest priority":"высший приоритет",hours:FJ,includes:zJ,interval:UJ,"just check":"просто проверить","less or equal":"меньше или равно","less or equal to":"меньше или равно","less than":"меньше, чем","lower priority":"более низкий приоритет","lowest priority":"самый низкий приоритет",magic:HJ,milliseconds:WJ,minutes:GJ,ms:VJ,nadir:KJ,nauticalDawn:YJ,nauticalDusk:JJ,nextSunrise:qJ,nextSunset:XJ,night:ZJ,nightEnd:QJ,"no blocks found":"Блоков нет","no group":"Нет группы",normal:eq,"normal priority":"нормальный приоритет","not running":"не запущен","not equal to":"не равно","not properly connected":"Этот блок неправильно соединён или не соединён с другими блоками.",offset:tq,"on change":"по изменению","on condition change":"при изменении результата условия","on update":"при обновлении",one:sq,or:oq,quiet:iq,"reset search":"Cбросить поиск",search:nq,seconds:rq,solarNoon:aq,"store in":"сохранить в",sunrise:lq,sunriseEnd:cq,sunset:uq,sunsetStart:dq,then:hq,"toggle value":"инвертировать текщее значение",tooltip_ack:pq,tooltip_from:gq,tooltip_lc:mq,tooltip_quality:fq,tooltip_ts:$q,tooltip_user:bq,tooltip_value:vq,true:"true",two:yq,undefined:"неопределенный",update:_q,"use seconds":"использовать секунды","use trigger value":"использовать значение триггера",verbose_help:wq,verbose_label:kq,when:Cq,with:"с","with date":"с датой","with offset":"со сдвигом",wizard:Tq,"Loading models...":"Загрузка моделей...","Could not connect to API at %s":"Не удалось подключиться к API по адресу %s","Invalid API key":"Недействительный ключ API","Access denied by API":"Доступ запрещён API","API error: %s":"Ошибка API: %s",'Model "%s" not found':'Модель "%s" не найдена',"Request failed: %s":"Запрос не удался: %s",Retry:Sq,"No running javascript instance found":"Не найден работающий экземпляр JavaScript"},Iq="Визнано",xq="Дії",Dq="додати",Aq="все",Rq="Будь-який",Oq="Застосувати",Nq="квітень",Mq="Запитуйте",Lq="Астрономічний",Pq="серпень",Bq="Скасувати",jq="Закрити",Fq="Хвороба",zq="Умови",Uq="Консоль",Hq="Скопійовано",Wq="Грудень",Gq="За замовчуванням",Vq="Затримка",Kq="Видалити",Yq="опис",Jq="Готово",qq="Виконавча оболонка",Xq="Пояснення",Zq="Експорт",Qq="Лютий",eX="Лютий",tX="фільтр",sX="Папка",oX="О",iX="П'ятниця",nX="ID",rX="ID1",aX="ID2",lX="Імпорт",cX="Екземпляр",uX="Примірники",dX="Інструкції",hX="січень",pX="січня",gX="липень",mX="червень",fX="Ліміт",$X="березень",bX="Може",vX="Меню",yX="повідомлення",_X="пн",wX="Модель",kX="понеділок",CX="місяць",TX="Більше",SX="Ім'я",EX="Листопад",IX="в порядку",xX="жовтень",DX="В порядку",AX="Пауза",RX="Pushover",OX="Pushsafer",NX="Перезавантажити",MX="Перейменувати",LX="Повторіть",PX="Перезапустіть",BX="Результат",jX="Sa",FX="Субота",zX="зберегти",UX="розклад",HX="Сценарій",WX="Вересень",GX="Симулювати",VX="Стек",KX="старт",YX="Держава",JX="Нд",qX="неділя",XX="Телеграма",ZX="чт",QX="четвер",eZ="час",tZ="Спрацьовує",sZ="Тригери",oZ="вт",iZ="вівторок",nZ="URL",rZ="Значення",aZ="Обсяг",lZ="ми",cZ="Середа",uZ="Напишіть",dZ="Так",hZ="підтвердження",pZ="все",gZ="і",mZ="Астро",fZ="в",$Z="КОНТРОЛЬ",bZ="копія",vZ="CRON",yZ="Світанок",_Z="Це особливий режим, в якому стану та об'єкти не змінюватимуться. Але в протоколі відображатиметься лише інформація про кожну заплановану зміну.",wZ="Відлагоджувати",kZ="Сутінки",CZ="легко",TZ="кожен",SZ="функція",EZ="ID",IZ="Ім'я",xZ="Роль",DZ="Кімната",AZ="Золота година",RZ="Кінець золотої години",OZ="Код буде виконуватися лише щоразу, коли умова виконується. наприклад якщо спрацьовує значення датчика температури та умова «якщо температура перевищує 20°C», дії «тоді» виконуватимуться щоразу, коли датчик надсилає температуру, і вона перевищує 20°C. На 21°C, на 22°C і так далі.",NZ="Код буде виконано лише у разі зміни результату умови. наприклад якщо спрацьовує значення датчика температури та умова «якщо температура перевищує 20°C», дії «тоді» будуть виконані один раз, коли температура буде вище 20. Наступного разу дії «тоді» буде виконано, коли температура падає нижче 20, а потім знову піднімається вище 20.",MZ="години",LZ="включає в себе",PZ="інтервал",BZ="магія",jZ="мілісекунд",FZ="хвилин",zZ="РС",UZ="Надір",HZ="Морський світанок",WZ="Морські сутінки",GZ="Наступний схід сонця",VZ="Наступний захід сонця",KZ="ніч",YZ="Кінець ночі",JZ="нормально",qZ="зсув",XZ="один",ZZ="або",QZ="тихо",eQ="пошук",tQ="секунд",sQ="Сонячний полудень",oQ="схід сонця",iQ="Кінець сходу сонця",nQ="Захід сонця",rQ="Початок заходу сонця",aQ="потім",lQ="Визнати",cQ="Від",uQ="Востаннє змінено",dQ="якість",hQ="Мітка часу",pQ="Користувач",gQ="Значення",mQ="два",fQ="оновлення",$Q="Додає вихідні дані налагодження до журналу для багатьох системних команд",bQ="Докладні результати журналу",vQ="коли",yQ="майстер",_Q="Повторити",wQ={"%s not found":"%s не знайдено","()":"()","(at %s)":"(у %s)","(optional)":"(необов'язково)","-":"-",".":".","AI code generator":"Генератор коду ШІ",Ack:Iq,Actions:xq,"Actual time of day":"Фактичний час доби",Add:Dq,"Add new script":"Додати новий сценарій",All:Aq,"All files will be accepted":"Усі файли будуть прийняті",Any:Rq,"Any month":"Будь-який місяць",Apply:Oq,April:Nq,"Are you sure?":"Ти впевнений?",Ask:Mq,Astronomical:Lq,"Astronomical events today":"Астрономічні події сьогодні",August:Pq,"Blockly description":"Створення правил за графічними блоками","Body:":"Тіло:",Cancel:Bq,"Cannot delete non empty item!":"Неможливо видалити непорожній елемент!","Change layout":"Змінити макет",'Change theme (actual "%s")':'Змінити тему (тепер - "%s")',"Check blocks":"Перевірте блоки","Check is not active, because javascript adapter is disabled":"Перевірка не активна, оскільки адаптер Javascript вимкнено","Clear search input":"Очистити пошуковий запит","Click on this icon":"Натисніть на цей значок",Close:jq,"Close all but current":"Закрити всі, крім поточних","Collapse all":"Закрити всі","Compares current time with astronomical event":"Порівнює поточний час з астрономічною подією","Compares current time with the user specific time":"Порівнює поточний час із конкретним часом користувача","Compares the state value with user defined value":"Порівнює значення стану з визначеним користувачем значенням",Condition:Fq,Conditions:zq,"Configuration not saved.":"Конфігурація не збережена.",Console:Uq,"Control or update some state":"Контролюйте або оновлюйте певний стан","Control or update some state with delay":"Контролюйте або оновлюйте деякий стан із затримкою","Convert blockly to javascript for ever.":"Назавжди конвертуйте Blockly у Javascript.",Copied:Hq,"Copy script":"Копіювати сценарій","Copy to clipboard":"Копіювати в буфер обміну","Create new":"Створити новий","Create new folder":"Створити нову папку","Create new script":"Створіть новий сценарій","Create or edit CRON or time wizard":"Створення або редагування CRON або майстра часу","Dark Theme":"Темна тема","Dark style":"Темний стиль",Date:"Дата","Debug instance":"Екземпляр налагодження","Debug options":"Параметри налагодження",December:Wq,Default:Gq,"Define cron...":"Визначити cron...","Define schedule...":"Визначити розклад...",Delay:Vq,Delete:Kq,"Delete %s":"Видалити %s...","Delete folder":"Видалити папку","Delete script":"Видалити сценарій",Description:Yq,"Deselect all":"Зняти вибір із усіх","Discard changes for %s":"Скасувати зміни для %s",Done:Jq,"Double click to write value":"Двічі клацніть, щоб записати значення","Download as file":"Завантажити файл","Drop some files here or click...":"Перетягніть кілька файлів сюди або натисніть...","Duplicate name":"Повторюване ім'я","Edit script or just double click":"Відредагуйте сценарій або просто двічі клацніть","Empty name is not allowed":"Порожнє ім'я не допускається","End search mode":"Завершити режим пошуку","Enter your question":"Введи своє прохання",Error:"Помилка","Error formatting code":"Помилка форматування коду","Error was found":"Виявлено помилку","Every day":"Кожен день",Exec:qq,"Executes some shell command":"Виконує певну команду оболонки","Existing scripts will be overwritten.":"Існуючі сценарії буде перезаписано.","Expand all":"Розгорнути все","Expert mode":"Експертний режим",Explanation:Xq,Export:Zq,"Export all scripts":"Експортувати всі сценарії","Export blocks":"Експорт блоків","Export selected blocks":"Експортувати вибрані блоки",Februar:Qq,February:eX,Filter:tX,Folder:sX,Fr:oX,Friday:iX,Function:"функція","Function editor":"Редактор функцій","Function: executed":"Функція: виконано","Go to next line":"Перейти до наступного рядка","HTTP Call":"Виклик HTTP","Hide logs":"Приховати журнали",ID:nX,ID1:rX,ID2:aX,Import:lX,"Import blocks":"Імпорт блоків","Import error":"Помилка імпорту","Import scripts":"Імпорт скриптів","Insert object ID":"Вставте ID об'єкта",Instance:cX,"Instance is disabled":"Примірник вимкнено","Instance:":"екземпляр:",Instances:uX,Instructions:dX,"Invalid CRON":"Недійсний CRON","It will not be possible to revert this operation.":"Скасувати цю операцію буде неможливо.","JS description":"Створення правил шляхом написання Javascript",Januar:hX,January:pX,July:gX,June:mX,"Just check":"Просто перевірте","Keep my changes":"Зберегти мої зміни","Language:":"Мову:","Learn More":"Вивчайте більше","Light style":"Легкий стиль",Limit:fX,"Local time":"Місцевий час","Locate file":"Знайти файл","Log outputs":"Виходи журналу","Log text":"Текст журналу","Log: %s":"Журнал: %s","Make a HTTP get request":"Зробіть HTTP-запит на отримання","Make a pause between actions":"Між діями робіть паузу",March:$X,"March ":"березень",May:bX,Menu:vX,Message:yX,Mo:_X,Model:wX,Monday:kX,Month:CX,More:TX,Name:SX,"No API key found":"API-ключ не знайдено","No Chat GPT Key found":"Ключ GPT для чату не знайдено","No active host found":"Активний хост не знайдено","Nothing found":"Нічого не знайдено",November:EX,OK:IX,October:xX,Ok:DX,"On condition change":"За умови зміни результату","On script save or adapter start":"Під час збереження сценарію або запуску адаптера","On weekdays":"В будні дні","Open configuration":"Відкрита конфігурація","Operate two states":"Керуйте двома станами","Operations with two states":"Операції з двома станами","Paste your blocks here":"Вставте сюди свої блоки",Pause:AX,"Pause execution":"Призупинити виконання","Pause script":"Призупинити сценарій","Phone:":"телефон:","Please select object ID...":"Виберіть ідентифікатор об'єкта...","Press Ctrl+Enter to get the answer":"Натисніть Ctrl+Enter, щоб отримати відповідь","Prettify the script":"Прикрасьте сценарій","Print some text in log":"Надрукувати текст у журналі","Priority:":"Пріоритет:",Pushover:RX,Pushsafer:OX,"Read only ID selected: %s":"Вибрано ідентифікатор лише для читання: %s",Reload:NX,Rename:MX,"Reorder scripts in folders":"Зміна порядку сценаріїв у папках",Repeat:LX,Restart:PX,Result:BX,"Resume execution":"Відновити виконання","Root folder":"Коренева папка","Rules description":"Створюйте правила з блоками IF, THEN, ELSE","Run script":"Запустіть сценарій",Sa:jX,Saturday:FX,Save:zX,"Save all":"Зберегти все","Say It":"Скажи це","Say some text via sayit adapter":"Скажіть текст через адаптер sayit",Schedule:UX,Script:HX,"Script %s was modified on disk":"Сценарій %s змінено на диску","Script was modified externally":"Скрипт було змінено ззовні","Script is not running":"Сценарій не працює","Search in scripts":"Пошук у скриптах","Search...":"пошук...","Select all":"Вибрати все","Send email":"Відправити лист","Sends an email":"Надсилає електронний лист","Sends message via Pushsafer":"Надсилає повідомлення через Pushsafer","Sends message via pushover":"Надсилає повідомлення через pushover","Sends message via telegram":"Надсилає повідомлення через телеграм","Sends message via whatsapp-cmb":"Надсилає повідомлення через whatsapp-cmb",September:WX,"Server time":"Час сервера","Set state action":"Встановити дію стану","Set with delay":"Встановити із затримкою","Shell command":"Команда оболонки","Show astronomical events":"Показати астрономічні події","Show javascript code":"Показати код Javascript","Show logs":"Показати журнали","Show only paused scripts":"Показувати лише призупинені сценарії","Show only running scripts":"Показувати лише запущені сценарії","Show only scripts with problems":"Показувати лише сценарії з проблемами",Simulate:GX,"Some files will be rejected":"Деякі файли буде відхилено","Sound:":"звук:",Stack:VX,Start:KX,"Start script":"Запустити сценарій",State:YX,"State condition":"Стан стану","Step into function":"Крок у функції","Step out from function":"Вийти з функції","Stop on exception":"Зупинка на винятках",Su:JX,"Subject:":"Тема:",Sunday:qX,"TS description":"Створення правил шляхом написання Typescript",Telegram:XX,"Text:":"Текст:",Th:ZX,'The script "%s" has been modified by another user or in another window. Do you want to reload the script or keep your local changes?':'Скрипт "%s" було змінено іншим користувачем або в іншому вікні. Бажаєте перезавантажити скрипт чи зберегти свої локальні зміни?',"The script will be stopped and must be activated manually after debugging. Continue?":"Сценарій буде зупинено, і його необхідно активувати вручну після налагодження. Продовжити?","This is advances option. You can write your own code here and it will be executed on trigger":"Це авансовий варіант. Ви можете написати тут свій власний код, і він буде виконано на тригері",Thursday:QX,Time:eZ,"Time condition":"Умова часу","Title:":"Назва:","To:":"до:","Trigger with value":"Тригер зі значенням",Triggered:tZ,Triggers:sZ,"Triggers the on script saving or the javascript instance restart":"Ініціює збереження сценарію або перезапуск екземпляра JavaScript","Triggers the rule on update or change of some state":"Запускає правило при оновленні або зміні якогось стану","Triggers the rule periodically or on some specific time":"Спрацьовує правило періодично або в певний час",Tu:oZ,Tuesday:iZ,URL:nZ,"Unknown error":"Невідома помилка","Unknown error!":"Невідома помилка!","Use generated code":"Використовуйте згенерований код","User function":"Функція користувача","User:":"Користувач:",Value:rZ,"Vibration:":"Вібрація:",Volume:aZ,We:lZ,Wednesday:cZ,"Whatsapp-cmb":"Whatsapp-cmb",Write:uZ,"Write your own code":"Напишіть власний код",Yes:dZ,"Yet exists!":"Все ж існує!","You can use %s in the URL to use current trigger value or %id to use the triggered object ID":"Ви можете використовувати %s в URL-адресі, щоб використовувати поточне значення тригера, %id, щоб використовувати ідентифікатор активованого об’єкта, %name, щоб показати назву ідентифікатора активованого об’єкта, або %old, щоб використовувати старе значення тригера","You can use %s in the command to use current trigger value or %id to use the triggered object ID":"Ви можете використовувати %s у команді, щоб використовувати поточне значення тригера, %id, щоб використовувати ідентифікатор активованого об’єкта, %name, щоб показати назву ідентифікатора активованого об’єкта, або %old, щоб використовувати старе значення тригера","You can use %s in the text to display current trigger value or %id to display the triggered object ID":"Ви можете використовувати %s у тексті для відображення поточного значення тригера, %id для використання ідентифікатора активованого об’єкта, %name для відображення імені ідентифікатора активованого об’єкта або %old для використання старого значення тригера","You can use %s in the value to use the current trigger value or %id to display the triggered object ID":"Ви можете використовувати %s у значенні, щоб використовувати поточне значення тригера, %id, щоб використовувати ідентифікатор активованого об’єкта, %name, щоб показати назву ідентифікатора активованого об’єкта, або %old, щоб використовувати старе значення тригера","You have to enter OpenAI API key in the configuration of javascript adapter.":"Ви повинні ввести ключ OpenAI API у конфігурації адаптера JavaScript.","You have to enter at least one API key in the configuration of javascript adapter.":"Необхідно ввести хоча б один API-ключ (OpenAI, Anthropic або Gemini) у конфігурації адаптера JavaScript.","Please select a valid model":"Будь ласка, виберіть дійсну модель","[equal]":"[рівний]","[greater or equal]":"[більше або дорівнює]","[greater]":"[більший]","[hysteresis]":"[гістерезис]","[includes]":"[включає]","[less or equal]":"[менше або рівно]","[less]":"[менше]","[not equal]":"[не дорівнює]",acknowledgment:hZ,all:pZ,and:gZ,"as JSON":"як JSON","as plain text":"як текст",astro:mZ,at:fZ,"clear running":"чіткий біг",control:$Z,copy:bZ,cron:vZ,dawn:yZ,debug_help:_Z,debug_label:wZ,default:"за замовчуванням",dusk:kZ,easy:CZ,else:"інше","equal to":"дорівнює",every:TZ,"every hour at 0 minutes":"щогодини о 0 хвилин",false:"помилковий","file reading has failed: %s":"не вдалося прочитати файл: %s","file reading was aborted":"читання файлу було перервано",filter_func:SZ,filter_id:EZ,filter_name:IZ,filter_role:xZ,filter_room:DZ,"for edit or create script":"для редагування або створення нового сценарію","for professionals":"для професіоналів","for programmers":"для програмістів",goldenHour:AZ,goldenHourEnd:RZ,"greater or equal":"більший або рівний","greater or equal to":"більше або дорівнює","greater than":"більше, ніж, величніше ніж, крутіший за",help_just_check:OZ,help_on_change:NZ,"high priority":"високий пріоритет","high-priority":"високий пріоритет","highest priority":"найвищий пріоритет",hours:MZ,includes:LZ,interval:PZ,"just check":"просто перевірте","less or equal":"менше або дорівнює","less or equal to":"менше або дорівнює","less than":"менше ніж","lower priority":"нижчий пріоритет","lowest priority":"найнижчий пріоритет",magic:BZ,milliseconds:jZ,minutes:FZ,ms:zZ,nadir:UZ,nauticalDawn:HZ,nauticalDusk:WZ,nextSunrise:GZ,nextSunset:VZ,night:KZ,nightEnd:YZ,"no blocks found":"Блоків не знайдено","no group":"НЕМАЄ ГРУПИ",normal:JZ,"normal priority":"нормальний пріоритет","not running":"не запущено","not equal to":"не дорівнює","not properly connected":"Цей блок неправильно з’єднаний з іншими блоками.",offset:qZ,"on change":"на зміну","on condition change":"про зміну умов","on update":"на оновлення",one:XZ,or:ZZ,quiet:QZ,"reset search":"скинути пошук",search:eQ,seconds:tQ,solarNoon:sQ,"store in":"зберігати в",sunrise:oQ,sunriseEnd:iQ,sunset:nQ,sunsetStart:rQ,then:aQ,"toggle value":"значення перемикання",tooltip_ack:lQ,tooltip_from:cQ,tooltip_lc:uQ,tooltip_quality:dQ,tooltip_ts:hQ,tooltip_user:pQ,tooltip_value:gQ,true:"правда",two:mQ,undefined:"невизначений",update:fQ,"use seconds":"використовуйте секунди","use trigger value":"використовувати значення тригера",verbose_help:$Q,verbose_label:bQ,when:vQ,with:"з","with date":"з датою","with offset":"зі зміщенням",wizard:yQ,"Loading models...":"Завантаження моделей...","Could not connect to API at %s":"Не вдалося підключитися до API за адресою %s","Invalid API key":"Недійсний ключ API","Access denied by API":"Доступ заборонено API","API error: %s":"Помилка API: %s",'Model "%s" not found':'Модель "%s" не знайдено',"Request failed: %s":"Запит не вдався: %s",Retry:_Q,"No running javascript instance found":"Не знайдено запущеного екземпляра JavaScript"},kQ="确认",CQ="动作",TQ="添加",SQ="所有",EQ="任何",IQ="申请",xQ="四月",DQ="问",AQ="天文",RQ="八月",OQ="取消",NQ="关闭",MQ="健康)状况",LQ="情况",PQ="安慰",BQ="复制的",jQ="十二月",FQ="默认",zQ="延迟",UQ="删除",HQ="描述",WQ="完成",GQ="执行力",VQ="解释",KQ="导出",YQ="二月",JQ="二月",qQ="筛选",XQ="文件夹",ZQ="r",QQ="星期五",eee="ID",tee="ID1",see="ID2",oee="导入",iee="实例",nee="实例",ree="指示",aee="亚努尔",lee="一月",cee="七月",uee="六月",dee="限制",hee="三月",pee="五月",gee="菜单",mee="信息",fee="莫",$ee="模型",bee="星期一",vee="月",yee="更多的",_ee="名称",wee="十一月",kee="好的",Cee="十月",Tee="确定",See="暂停",Eee="俯卧撑",Iee="推安全",xee="重新加载",Dee="重命名",Aee="重复",Ree="重启",Oee="结果",Nee="萨",Mee="星期六",Lee="保存",Pee="日程",Bee="脚本",jee="九月",Fee="模拟",zee="堆",Uee="开始",Hee="状态",Wee="苏",Gee="星期日",Vee="电报",Kee="4",Yee="星期四",Jee="时间",qee="触发",Xee="扳机",Zee="涂",Qee="星期二",ete="网址",tte="价值",ste="体积",ote="3",ite="星期三",nte="写",rte="是的",ate="致谢",lte="全部",cte="和",ute="天文",dte="在",hte="控制",pte="复制",gte="克朗",mte="黎明",fte="这是一种特殊模式,其中状态和对象不会改变。但只有有关每个计划更改的信息才会显示在协议中。",$te="调试",bte="黄昏",vte="简单的",yte="每一个",_te="功能",wte="ID",kte="名字",Cte="角色",Tte="房间",Ste="黄金时段",Ete="黄金时段结束",Ite="仅在条件为真时才执行代码。例如。如果触发温度传感器值并且条件为“如果温度大于20°C”,则每次传感器发送温度且温度超过20°C时,将执行“然后”动作。 21°C,22°C等。",xte="仅当条件结果更改时,代码才会执行。例如。如果触发温度传感器值且条件为“如果温度大于20°C”,则温度超过20时将执行一次“则”动作,下一次,当温度超过20时将执行“则”动作低于20失败,然后再次超过20。",Dte="小时",Ate="包括",Rte="间隔",Ote="魔法",Nte="毫秒",Mte="分钟",Lte="毫秒",Pte="最低点",Bte="航海黎明",jte="航海黄昏",Fte="下一个日出",zte="下一个日落",Ute="夜晚",Hte="夜晚结束",Wte="普通的",Gte="抵消",Vte="一",Kte="或",Yte="安静的",Jte="搜索",qte="秒",Xte="星期日正午",Zte="日出",Qte="日出结束",ese="日落",tse="日落开始",sse="然后",ose="确认",ise="从",nse="上一次改变",rse="质量",ase="时间戳",lse="用户",cse="值",use="二",dse="更新",hse="将调试输出添加到许多系统命令的日志中",pse="详细日志输出",gse="什么时候",mse="巫师",fse="重试",$se={"%s not found":"%s 未找到","()":"()","(at %s)":"(在 %s)","(optional)":"(选修的)","-":"-",".":".","AI code generator":"AI代码生成器",Ack:kQ,Actions:CQ,"Actual time of day":"一天中的实际时间",Add:TQ,"Add new script":"添加新脚本",All:SQ,"All files will be accepted":"所有文件都将被接受",Any:EQ,"Any month":"任何月份",Apply:IQ,April:xQ,"Are you sure?":"你确定吗?",Ask:DQ,Astronomical:AQ,"Astronomical events today":"今天的天文事件",August:RQ,"Blockly description":"按图形块创建规则","Body:":"身体:",Cancel:OQ,"Cannot delete non empty item!":"无法删除非空项目!","Change layout":"变更版面",'Change theme (actual "%s")':"更改主题(现在为“%s”)","Check blocks":"检查块","Check is not active, because javascript adapter is disabled":"检查未激活,因为禁用了Javascript适配器","Clear search input":"清除搜索输入","Click on this icon":"单击此图标",Close:NQ,"Close all but current":"关闭所有(当前除外)","Collapse all":"全部收缩","Compares current time with astronomical event":"将当前时间与天文事件进行比较","Compares current time with the user specific time":"将当前时间与用户特定时间进行比较","Compares the state value with user defined value":"比较状态值和用户定义的值",Condition:MQ,Conditions:LQ,"Configuration not saved.":"配置未保存。",Console:PQ,"Control or update some state":"控制或更新某些状态","Control or update some state with delay":"延迟控制或更新某些状态","Convert blockly to javascript for ever.":"立即将blockly转换为Javascript。",Copied:BQ,"Copy script":"复制脚本","Copy to clipboard":"复制到剪贴板","Create new":"创建新的","Create new folder":"创建新文件夹","Create new script":"创建新脚本","Create or edit CRON or time wizard":"创建或编辑周期任务或时间向导","Dark Theme":"深色调主题","Dark style":"深色调风格",Date:"日期","Debug instance":"调试实例","Debug options":"调试选项",December:jQ,Default:FQ,"Define cron...":"定义周期任务...","Define schedule...":"定义调度器......",Delay:zQ,Delete:UQ,"Delete %s":"删除%s...","Delete folder":"删除文件夹","Delete script":"删除脚本",Description:HQ,"Deselect all":"取消全选","Discard changes for %s":"放弃%s的更改",Done:WQ,"Double click to write value":"Double click to write value","Download as file":"档案","Drop some files here or click...":"将文件拖拽到这里或单击......","Duplicate name":"重名","Edit script or just double click":"双击编辑脚本","Empty name is not allowed":"不允许使用空名称","End search mode":"结束搜索模式","Enter your question":"输入您的要求",Error:"错误","Error formatting code":"代码格式错误","Error was found":"发现错误","Every day":"每天",Exec:GQ,"Executes some shell command":"执行一些shell命令","Existing scripts will be overwritten.":"现有脚本将被覆盖。","Expand all":"展开全部","Expert mode":"专家模式",Explanation:VQ,Export:KQ,"Export all scripts":"导出所有脚本","Export blocks":"导出块","Export selected blocks":"导出选定的块",Februar:YQ,February:JQ,Filter:qQ,Folder:XQ,Fr:ZQ,Friday:QQ,Function:"功能","Function editor":"功能编辑器","Function: executed":"功能:执行","Go to next line":"转到下一行","HTTP Call":"HTTP呼叫","Hide logs":"隐藏日志",ID:eee,ID1:tee,ID2:see,Import:oee,"Import blocks":"导入块","Import error":"导入错误","Import scripts":"导入脚本","Insert object ID":"插入对象ID",Instance:iee,"Instance is disabled":"实例已禁用","Instance:":"实例:",Instances:nee,Instructions:ree,"Invalid CRON":"无效的周期任务","It will not be possible to revert this operation.":"无法恢复此操作。","JS description":"通过编写Javascript来创建规则",Januar:aee,January:lee,July:cee,June:uee,"Just check":"只是检查","Keep my changes":"保留我的更改","Language:":"语言:","Learn More":"了解更多","Light style":"浅色调风格",Limit:dee,"Local time":"当地时间","Locate file":"定位文件","Log outputs":"记录输出","Log text":"记录文字","Log: %s":"日志:%s","Make a HTTP get request":"发出HTTP获取请求","Make a pause between actions":"在动作之间暂停",March:hee,"March ":"行进",May:pee,Menu:gee,Message:mee,Mo:fee,Model:$ee,Monday:bee,Month:vee,More:yee,Name:_ee,"No API key found":"未找到 API 密钥","No Chat GPT Key found":"找不到聊天 GPT 密钥","No active host found":"找不到活动主机","Nothing found":"没有发现",November:wee,OK:kee,October:Cee,Ok:Tee,"On condition change":"条件变化时","On script save or adapter start":"在脚本保存或适配器启动时","On weekdays":"在工作日","Open configuration":"开放配置","Operate two states":"操作两种状态","Operations with two states":"具有两种状态的操作","Paste your blocks here":"在此处粘贴您的区块",Pause:See,"Pause execution":"暂停执行","Pause script":"暂停脚本","Phone:":"电话:","Please select object ID...":"请选择对象ID...","Press Ctrl+Enter to get the answer":"按 Ctrl+Enter 即可得到答案","Prettify the script":"美化脚本","Print some text in log":"在日志中打印一些文本","Priority:":"优先:",Pushover:Eee,Pushsafer:Iee,"Read only ID selected: %s":"选择的只读ID:%s",Reload:xee,Rename:Dee,"Reorder scripts in folders":"重新排序文件夹中的脚本",Repeat:Aee,Restart:Ree,Result:Oee,"Resume execution":"恢复执行","Root folder":"根文件夹","Rules description":"使用IF,THEN,ELSE块创建规则","Run script":"运行脚本",Sa:Nee,Saturday:Mee,Save:Lee,"Save all":"保存全部","Say It":"Say It","Say some text via sayit adapter":"通过sayit适配器说一些文字",Schedule:Pee,Script:Bee,"Script %s was modified on disk":"脚本%s已在磁盘上修改","Script was modified externally":"脚本已被外部修改","Script is not running":"脚本没有运行","Search in scripts":"在脚本中搜索","Search...":"搜索...","Select all":"全选","Send email":"发送电子邮件","Sends an email":"发送邮件","Sends message via Pushsafer":"通过Pushsafer发送消息","Sends message via pushover":"通过推播发送消息","Sends message via telegram":"通过电报发送消息","Sends message via whatsapp-cmb":"通过whatsapp-cmb发送消息",September:jee,"Server time":"服务器时间","Set state action":"设定状态动作","Set with delay":"延迟设置","Shell command":"Shell命令","Show astronomical events":"显示天文事件","Show javascript code":"显示Javascript代码","Show logs":"显示记录","Show only paused scripts":"仅显示暂停的脚本","Show only running scripts":"仅显示正在运行的脚本","Show only scripts with problems":"仅显示有问题的脚本",Simulate:Fee,"Some files will be rejected":"有些文件将被拒绝","Sound:":"声音:",Stack:zee,Start:Uee,"Start script":"启动脚本",State:Hee,"State condition":"状态条件","Step into function":"进入功能","Step out from function":"退出函数","Stop on exception":"异常停止",Su:Wee,"Subject:":"学科:",Sunday:Gee,"TS description":"通过编写Typescript来创建规则",Telegram:Vee,"Text:":"文本:",Th:Kee,'The script "%s" has been modified by another user or in another window. Do you want to reload the script or keep your local changes?':'脚本 "%s" 已被其他用户或在其他窗口中修改。您想重新加载脚本还是保留您的本地更改?',"The script will be stopped and must be activated manually after debugging. Continue?":"该脚本将停止,并且必须在调试后手动激活。继续?","This is advances option. You can write your own code here and it will be executed on trigger":"这是高级选项。您可以在此处编写自己的代码,它将在触发器上执行",Thursday:Yee,Time:Jee,"Time condition":"时间条件","Title:":"标题:","To:":"到:","Trigger with value":"用值触发",Triggered:qee,Triggers:Xee,"Triggers the on script saving or the javascript instance restart":"触发脚本保存或javascript实例重启","Triggers the rule on update or change of some state":"在某些状态的更新或更改时触发规则","Triggers the rule periodically or on some specific time":"定期或在特定时间触发规则",Tu:Zee,Tuesday:Qee,URL:ete,"Unknown error":"未知错误","Unknown error!":"未知错误!","Use generated code":"使用生成的代码","User function":"用户功能","User:":"用户:",Value:tte,"Vibration:":"振动:",Volume:ste,We:ote,Wednesday:ite,"Whatsapp-cmb":"Whatsapp的cmb",Write:nte,"Write your own code":"编写自己的代码",Yes:rte,"Yet exists!":"不存在!","You can use %s in the URL to use current trigger value or %id to use the triggered object ID":"您可以在 URL 中使用 %s 以使用当前触发值,%id 以使用触发对象 ID,%name 以显示触发对象 ID 名称或 %old 以使用旧触发值","You can use %s in the command to use current trigger value or %id to use the triggered object ID":"您可以在命令中使用 %s 以使用当前触发值,%id 使用触发对象 ID,%name 显示触发对象 ID 名称或 %old 使用旧触发值","You can use %s in the text to display current trigger value or %id to display the triggered object ID":"您可以在文本中使用 %s 显示当前触发值,%id 使用触发对象 ID,%name 显示触发对象 ID 名称或 %old 使用旧触发值","You can use %s in the value to use the current trigger value or %id to display the triggered object ID":"您可以在值中使用 %s 以使用当前触发器值,%id 使用触发对象 ID,%name 显示触发对象 ID 名称或 %old 使用旧触发器值","You have to enter OpenAI API key in the configuration of javascript adapter.":"您必须在 javascript 适配器的配置中输入 OpenAI API 密钥。","You have to enter at least one API key in the configuration of javascript adapter.":"您必须在 javascript 适配器的配置中输入至少一个 API 密钥(OpenAI、Anthropic 或 Gemini)。","Please select a valid model":"请选择一个有效的模型","[equal]":"[平等的]","[greater or equal]":"[大于等于]","[greater]":"[更大]","[hysteresis]":"[磁滞]","[includes]":"[包括]","[less or equal]":"[小于或等于]","[less]":"[较少的]","[not equal]":"[不相等]",acknowledgment:ate,all:lte,and:cte,"as JSON":"为 JSON","as plain text":"为纯文本",astro:ute,at:dte,"clear running":"畅通无阻",control:hte,copy:pte,cron:gte,dawn:mte,debug_help:fte,debug_label:$te,default:"默认",dusk:bte,easy:vte,else:"别的","equal to":"等于",every:yte,"every hour at 0 minutes":"每小时0分钟",false:"错误的","file reading has failed: %s":"文件读取失败:%s","file reading was aborted":"文件读取中止",filter_func:_te,filter_id:wte,filter_name:kte,filter_role:Cte,filter_room:Tte,"for edit or create script":"用于编辑或创建脚本","for professionals":"对于专业人士","for programmers":"对于程序员",goldenHour:Ste,goldenHourEnd:Ete,"greater or equal":"大于或等于","greater or equal to":"大于或等于","greater than":"比...更棒",help_just_check:Ite,help_on_change:xte,"high priority":"高优先级","high-priority":"高优先级","highest priority":"最高优先级",hours:Dte,includes:Ate,interval:Rte,"just check":"只是检查","less or equal":"小于或等于","less or equal to":"小于或等于","less than":"少于","lower priority":"低优先级","lowest priority":"最低优先级",magic:Ote,milliseconds:Nte,minutes:Mte,ms:Lte,nadir:Pte,nauticalDawn:Bte,nauticalDusk:jte,nextSunrise:Fte,nextSunset:zte,night:Ute,nightEnd:Hte,"no blocks found":"找不到块","no group":"没有组",normal:Wte,"normal priority":"正常优先","not running":"未运行","not equal to":"不等于","not properly connected":"此块未正确连接到其他块。",offset:Gte,"on change":"在变化","on condition change":"在条件变化时","on update":"更新时",one:Vte,or:Kte,quiet:Yte,"reset search":"重置搜索",search:Jte,seconds:qte,solarNoon:Xte,"store in":"存放在",sunrise:Zte,sunriseEnd:Qte,sunset:ese,sunsetStart:tse,then:sse,"toggle value":"切换值",tooltip_ack:ose,tooltip_from:ise,tooltip_lc:nse,tooltip_quality:rse,tooltip_ts:ase,tooltip_user:lse,tooltip_value:cse,true:"真的",two:use,undefined:"不明确的",update:dse,"use seconds":"精确到秒","use trigger value":"使用触发值",verbose_help:hse,verbose_label:pse,when:gse,with:"和","with date":"有日期","with offset":"带偏移",wizard:mse,"Loading models...":"加载模型...","Could not connect to API at %s":"无法连接到 %s 的 API","Invalid API key":"无效的 API 密钥","Access denied by API":"API 拒绝访问","API error: %s":"API 错误:%s",'Model "%s" not found':'未找到模型 "%s"',"Request failed: %s":"请求失败:%s",Retry:fse,"No running javascript instance found":"未找到正在运行的 JavaScript 实例"};function pc(a){throw new Error('Could not dynamically require "'+a+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var RC={exports:{}};(function(a,s){(function(i){a.exports=i()})(function(){return(function i(r,l,c){function d(f,b){if(!l[f]){if(!r[f]){var y=typeof pc=="function"&&pc;if(!b&&y)return y(f,!0);if(h)return h(f,!0);var w=new Error("Cannot find module '"+f+"'");throw w.code="MODULE_NOT_FOUND",w}var v=l[f]={exports:{}};r[f][0].call(v.exports,function(_){var $=r[f][1][_];return d($||_)},v,v.exports,i,r,l,c)}return l[f].exports}for(var h=typeof pc=="function"&&pc,p=0;p>2,v=(3&f)<<4|b>>4,_=1>6:64,$=2>4,b=(15&w)<<4|(v=h.indexOf(p.charAt($++)))>>2,y=(3&v)<<6|(_=h.indexOf(p.charAt($++))),E[S++]=f,v!==64&&(E[S++]=b),_!==64&&(E[S++]=y);return E}},{"./support":30,"./utils":32}],2:[function(i,r,l){var c=i("./external"),d=i("./stream/DataWorker"),h=i("./stream/Crc32Probe"),p=i("./stream/DataLengthProbe");function f(b,y,w,v,_){this.compressedSize=b,this.uncompressedSize=y,this.crc32=w,this.compression=v,this.compressedContent=_}f.prototype={getContentWorker:function(){var b=new d(c.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new p("data_length")),y=this;return b.on("end",function(){if(this.streamInfo.data_length!==y.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),b},getCompressedWorker:function(){return new d(c.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},f.createWorkerFrom=function(b,y,w){return b.pipe(new h).pipe(new p("uncompressedSize")).pipe(y.compressWorker(w)).pipe(new p("compressedSize")).withStreamInfo("compression",y)},r.exports=f},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(i,r,l){var c=i("./stream/GenericWorker");l.STORE={magic:"\0\0",compressWorker:function(){return new c("STORE compression")},uncompressWorker:function(){return new c("STORE decompression")}},l.DEFLATE=i("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(i,r,l){var c=i("./utils"),d=(function(){for(var h,p=[],f=0;f<256;f++){h=f;for(var b=0;b<8;b++)h=1&h?3988292384^h>>>1:h>>>1;p[f]=h}return p})();r.exports=function(h,p){return h!==void 0&&h.length?c.getTypeOf(h)!=="string"?(function(f,b,y,w){var v=d,_=w+y;f^=-1;for(var $=w;$<_;$++)f=f>>>8^v[255&(f^b[$])];return-1^f})(0|p,h,h.length,0):(function(f,b,y,w){var v=d,_=w+y;f^=-1;for(var $=w;$<_;$++)f=f>>>8^v[255&(f^b.charCodeAt($))];return-1^f})(0|p,h,h.length,0):0}},{"./utils":32}],5:[function(i,r,l){l.base64=!1,l.binary=!1,l.dir=!1,l.createFolders=!0,l.date=null,l.compression=null,l.compressionOptions=null,l.comment=null,l.unixPermissions=null,l.dosPermissions=null},{}],6:[function(i,r,l){var c=null;c=typeof Promise<"u"?Promise:i("lie"),r.exports={Promise:c}},{lie:37}],7:[function(i,r,l){var c=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",d=i("pako"),h=i("./utils"),p=i("./stream/GenericWorker"),f=c?"uint8array":"array";function b(y,w){p.call(this,"FlateWorker/"+y),this._pako=null,this._pakoAction=y,this._pakoOptions=w,this.meta={}}l.magic="\b\0",h.inherits(b,p),b.prototype.processChunk=function(y){this.meta=y.meta,this._pako===null&&this._createPako(),this._pako.push(h.transformTo(f,y.data),!1)},b.prototype.flush=function(){p.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},b.prototype.cleanUp=function(){p.prototype.cleanUp.call(this),this._pako=null},b.prototype._createPako=function(){this._pako=new d[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var y=this;this._pako.onData=function(w){y.push({data:w,meta:y.meta})}},l.compressWorker=function(y){return new b("Deflate",y)},l.uncompressWorker=function(){return new b("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(i,r,l){function c(v,_){var $,S="";for($=0;$<_;$++)S+=String.fromCharCode(255&v),v>>>=8;return S}function d(v,_,$,S,T,E){var D,M,P=v.file,W=v.compression,G=E!==f.utf8encode,z=h.transformTo("string",E(P.name)),Z=h.transformTo("string",f.utf8encode(P.name)),he=P.comment,Ce=h.transformTo("string",E(he)),O=h.transformTo("string",f.utf8encode(he)),K=Z.length!==P.name.length,C=O.length!==he.length,Q="",ve="",ce="",ne=P.dir,me=P.date,re={crc32:0,compressedSize:0,uncompressedSize:0};_&&!$||(re.crc32=v.crc32,re.compressedSize=v.compressedSize,re.uncompressedSize=v.uncompressedSize);var B=0;_&&(B|=8),G||!K&&!C||(B|=2048);var N=0,te=0;ne&&(N|=16),T==="UNIX"?(te=798,N|=(function(se,F){var Te=se;return se||(Te=F?16893:33204),(65535&Te)<<16})(P.unixPermissions,ne)):(te=20,N|=(function(se){return 63&(se||0)})(P.dosPermissions)),D=me.getUTCHours(),D<<=6,D|=me.getUTCMinutes(),D<<=5,D|=me.getUTCSeconds()/2,M=me.getUTCFullYear()-1980,M<<=4,M|=me.getUTCMonth()+1,M<<=5,M|=me.getUTCDate(),K&&(ve=c(1,1)+c(b(z),4)+Z,Q+="up"+c(ve.length,2)+ve),C&&(ce=c(1,1)+c(b(Ce),4)+O,Q+="uc"+c(ce.length,2)+ce);var q="";return q+=` -\0`,q+=c(B,2),q+=W.magic,q+=c(D,2),q+=c(M,2),q+=c(re.crc32,4),q+=c(re.compressedSize,4),q+=c(re.uncompressedSize,4),q+=c(z.length,2),q+=c(Q.length,2),{fileRecord:y.LOCAL_FILE_HEADER+q+z+Q,dirRecord:y.CENTRAL_FILE_HEADER+c(te,2)+q+c(Ce.length,2)+"\0\0\0\0"+c(N,4)+c(S,4)+z+Q+Ce}}var h=i("../utils"),p=i("../stream/GenericWorker"),f=i("../utf8"),b=i("../crc32"),y=i("../signature");function w(v,_,$,S){p.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=_,this.zipPlatform=$,this.encodeFileName=S,this.streamFiles=v,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}h.inherits(w,p),w.prototype.push=function(v){var _=v.meta.percent||0,$=this.entriesCount,S=this._sources.length;this.accumulate?this.contentBuffer.push(v):(this.bytesWritten+=v.data.length,p.prototype.push.call(this,{data:v.data,meta:{currentFile:this.currentFile,percent:$?(_+100*($-S-1))/$:100}}))},w.prototype.openedSource=function(v){this.currentSourceOffset=this.bytesWritten,this.currentFile=v.file.name;var _=this.streamFiles&&!v.file.dir;if(_){var $=d(v,_,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:$.fileRecord,meta:{percent:0}})}else this.accumulate=!0},w.prototype.closedSource=function(v){this.accumulate=!1;var _=this.streamFiles&&!v.file.dir,$=d(v,_,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push($.dirRecord),_)this.push({data:(function(S){return y.DATA_DESCRIPTOR+c(S.crc32,4)+c(S.compressedSize,4)+c(S.uncompressedSize,4)})(v),meta:{percent:100}});else for(this.push({data:$.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},w.prototype.flush=function(){for(var v=this.bytesWritten,_=0;_=this.index;p--)f=(f<<8)+this.byteAt(p);return this.index+=h,f},readString:function(h){return c.transformTo("string",this.readData(h))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var h=this.readInt(4);return new Date(Date.UTC(1980+(h>>25&127),(h>>21&15)-1,h>>16&31,h>>11&31,h>>5&63,(31&h)<<1))}},r.exports=d},{"../utils":32}],19:[function(i,r,l){var c=i("./Uint8ArrayReader");function d(h){c.call(this,h)}i("../utils").inherits(d,c),d.prototype.readData=function(h){this.checkOffset(h);var p=this.data.slice(this.zero+this.index,this.zero+this.index+h);return this.index+=h,p},r.exports=d},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(i,r,l){var c=i("./DataReader");function d(h){c.call(this,h)}i("../utils").inherits(d,c),d.prototype.byteAt=function(h){return this.data.charCodeAt(this.zero+h)},d.prototype.lastIndexOfSignature=function(h){return this.data.lastIndexOf(h)-this.zero},d.prototype.readAndCheckSignature=function(h){return h===this.readData(4)},d.prototype.readData=function(h){this.checkOffset(h);var p=this.data.slice(this.zero+this.index,this.zero+this.index+h);return this.index+=h,p},r.exports=d},{"../utils":32,"./DataReader":18}],21:[function(i,r,l){var c=i("./ArrayReader");function d(h){c.call(this,h)}i("../utils").inherits(d,c),d.prototype.readData=function(h){if(this.checkOffset(h),h===0)return new Uint8Array(0);var p=this.data.subarray(this.zero+this.index,this.zero+this.index+h);return this.index+=h,p},r.exports=d},{"../utils":32,"./ArrayReader":17}],22:[function(i,r,l){var c=i("../utils"),d=i("../support"),h=i("./ArrayReader"),p=i("./StringReader"),f=i("./NodeBufferReader"),b=i("./Uint8ArrayReader");r.exports=function(y){var w=c.getTypeOf(y);return c.checkSupport(w),w!=="string"||d.uint8array?w==="nodebuffer"?new f(y):d.uint8array?new b(c.transformTo("uint8array",y)):new h(c.transformTo("array",y)):new p(y)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(i,r,l){l.LOCAL_FILE_HEADER="PK",l.CENTRAL_FILE_HEADER="PK",l.CENTRAL_DIRECTORY_END="PK",l.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK\x07",l.ZIP64_CENTRAL_DIRECTORY_END="PK",l.DATA_DESCRIPTOR="PK\x07\b"},{}],24:[function(i,r,l){var c=i("./GenericWorker"),d=i("../utils");function h(p){c.call(this,"ConvertWorker to "+p),this.destType=p}d.inherits(h,c),h.prototype.processChunk=function(p){this.push({data:d.transformTo(this.destType,p.data),meta:p.meta})},r.exports=h},{"../utils":32,"./GenericWorker":28}],25:[function(i,r,l){var c=i("./GenericWorker"),d=i("../crc32");function h(){c.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}i("../utils").inherits(h,c),h.prototype.processChunk=function(p){this.streamInfo.crc32=d(p.data,this.streamInfo.crc32||0),this.push(p)},r.exports=h},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(i,r,l){var c=i("../utils"),d=i("./GenericWorker");function h(p){d.call(this,"DataLengthProbe for "+p),this.propName=p,this.withStreamInfo(p,0)}c.inherits(h,d),h.prototype.processChunk=function(p){if(p){var f=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=f+p.data.length}d.prototype.processChunk.call(this,p)},r.exports=h},{"../utils":32,"./GenericWorker":28}],27:[function(i,r,l){var c=i("../utils"),d=i("./GenericWorker");function h(p){d.call(this,"DataWorker");var f=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,p.then(function(b){f.dataIsReady=!0,f.data=b,f.max=b&&b.length||0,f.type=c.getTypeOf(b),f.isPaused||f._tickAndRepeat()},function(b){f.error(b)})}c.inherits(h,d),h.prototype.cleanUp=function(){d.prototype.cleanUp.call(this),this.data=null},h.prototype.resume=function(){return!!d.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,c.delay(this._tickAndRepeat,[],this)),!0)},h.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(c.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},h.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var p=null,f=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":p=this.data.substring(this.index,f);break;case"uint8array":p=this.data.subarray(this.index,f);break;case"array":case"nodebuffer":p=this.data.slice(this.index,f)}return this.index=f,this.push({data:p,meta:{percent:this.max?this.index/this.max*100:0}})},r.exports=h},{"../utils":32,"./GenericWorker":28}],28:[function(i,r,l){function c(d){this.name=d||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}c.prototype={push:function(d){this.emit("data",d)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(d){this.emit("error",d)}return!0},error:function(d){return!this.isFinished&&(this.isPaused?this.generatedError=d:(this.isFinished=!0,this.emit("error",d),this.previous&&this.previous.error(d),this.cleanUp()),!0)},on:function(d,h){return this._listeners[d].push(h),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(d,h){if(this._listeners[d])for(var p=0;p "+d:d}},r.exports=c},{}],29:[function(i,r,l){var c=i("../utils"),d=i("./ConvertWorker"),h=i("./GenericWorker"),p=i("../base64"),f=i("../support"),b=i("../external"),y=null;if(f.nodestream)try{y=i("../nodejs/NodejsStreamOutputAdapter")}catch{}function w(_,$){return new b.Promise(function(S,T){var E=[],D=_._internalType,M=_._outputType,P=_._mimeType;_.on("data",function(W,G){E.push(W),$&&$(G)}).on("error",function(W){E=[],T(W)}).on("end",function(){try{var W=(function(G,z,Z){switch(G){case"blob":return c.newBlob(c.transformTo("arraybuffer",z),Z);case"base64":return p.encode(z);default:return c.transformTo(G,z)}})(M,(function(G,z){var Z,he=0,Ce=null,O=0;for(Z=0;Z"u")l.blob=!1;else{var c=new ArrayBuffer(0);try{l.blob=new Blob([c],{type:"application/zip"}).size===0}catch{try{var d=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);d.append(c),l.blob=d.getBlob("application/zip").size===0}catch{l.blob=!1}}}try{l.nodestream=!!i("readable-stream").Readable}catch{l.nodestream=!1}},{"readable-stream":16}],31:[function(i,r,l){for(var c=i("./utils"),d=i("./support"),h=i("./nodejsUtils"),p=i("./stream/GenericWorker"),f=new Array(256),b=0;b<256;b++)f[b]=252<=b?6:248<=b?5:240<=b?4:224<=b?3:192<=b?2:1;f[254]=f[254]=1;function y(){p.call(this,"utf-8 decode"),this.leftOver=null}function w(){p.call(this,"utf-8 encode")}l.utf8encode=function(v){return d.nodebuffer?h.newBufferFrom(v,"utf-8"):(function(_){var $,S,T,E,D,M=_.length,P=0;for(E=0;E>>6:(S<65536?$[D++]=224|S>>>12:($[D++]=240|S>>>18,$[D++]=128|S>>>12&63),$[D++]=128|S>>>6&63),$[D++]=128|63&S);return $})(v)},l.utf8decode=function(v){return d.nodebuffer?c.transformTo("nodebuffer",v).toString("utf-8"):(function(_){var $,S,T,E,D=_.length,M=new Array(2*D);for($=S=0;$>10&1023,M[S++]=56320|1023&T)}return M.length!==S&&(M.subarray?M=M.subarray(0,S):M.length=S),c.applyFromCharCode(M)})(v=c.transformTo(d.uint8array?"uint8array":"array",v))},c.inherits(y,p),y.prototype.processChunk=function(v){var _=c.transformTo(d.uint8array?"uint8array":"array",v.data);if(this.leftOver&&this.leftOver.length){if(d.uint8array){var $=_;(_=new Uint8Array($.length+this.leftOver.length)).set(this.leftOver,0),_.set($,this.leftOver.length)}else _=this.leftOver.concat(_);this.leftOver=null}var S=(function(E,D){var M;for((D=D||E.length)>E.length&&(D=E.length),M=D-1;0<=M&&(192&E[M])==128;)M--;return M<0||M===0?D:M+f[E[M]]>D?M:D})(_),T=_;S!==_.length&&(d.uint8array?(T=_.subarray(0,S),this.leftOver=_.subarray(S,_.length)):(T=_.slice(0,S),this.leftOver=_.slice(S,_.length))),this.push({data:l.utf8decode(T),meta:v.meta})},y.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:l.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},l.Utf8DecodeWorker=y,c.inherits(w,p),w.prototype.processChunk=function(v){this.push({data:l.utf8encode(v.data),meta:v.meta})},l.Utf8EncodeWorker=w},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(i,r,l){var c=i("./support"),d=i("./base64"),h=i("./nodejsUtils"),p=i("./external");function f($){return $}function b($,S){for(var T=0;T<$.length;++T)S[T]=255&$.charCodeAt(T);return S}i("setimmediate"),l.newBlob=function($,S){l.checkSupport("blob");try{return new Blob([$],{type:S})}catch{try{var T=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);return T.append($),T.getBlob(S)}catch{throw new Error("Bug : can't construct the Blob.")}}};var y={stringifyByChunk:function($,S,T){var E=[],D=0,M=$.length;if(M<=T)return String.fromCharCode.apply(null,$);for(;D>8;this.dir=!!(16&this.externalFileAttributes),v==0&&(this.dosPermissions=63&this.externalFileAttributes),v==3&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||this.fileNameStr.slice(-1)!=="/"||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var v=c(this.extraFields[1].value);this.uncompressedSize===d.MAX_VALUE_32BITS&&(this.uncompressedSize=v.readInt(8)),this.compressedSize===d.MAX_VALUE_32BITS&&(this.compressedSize=v.readInt(8)),this.localHeaderOffset===d.MAX_VALUE_32BITS&&(this.localHeaderOffset=v.readInt(8)),this.diskNumberStart===d.MAX_VALUE_32BITS&&(this.diskNumberStart=v.readInt(4))}},readExtraFields:function(v){var _,$,S,T=v.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});v.index+4>>6:(v<65536?w[S++]=224|v>>>12:(w[S++]=240|v>>>18,w[S++]=128|v>>>12&63),w[S++]=128|v>>>6&63),w[S++]=128|63&v);return w},l.buf2binstring=function(y){return b(y,y.length)},l.binstring2buf=function(y){for(var w=new c.Buf8(y.length),v=0,_=w.length;v<_;v++)w[v]=y.charCodeAt(v);return w},l.buf2string=function(y,w){var v,_,$,S,T=w||y.length,E=new Array(2*T);for(v=_=0;v>10&1023,E[_++]=56320|1023&$)}return b(E,_)},l.utf8border=function(y,w){var v;for((w=w||y.length)>y.length&&(w=y.length),v=w-1;0<=v&&(192&y[v])==128;)v--;return v<0||v===0?w:v+p[y[v]]>w?v:w}},{"./common":41}],43:[function(i,r,l){r.exports=function(c,d,h,p){for(var f=65535&c|0,b=c>>>16&65535|0,y=0;h!==0;){for(h-=y=2e3>>1:d>>>1;h[p]=d}return h})();r.exports=function(d,h,p,f){var b=c,y=f+p;d^=-1;for(var w=f;w>>8^b[255&(d^h[w])];return-1^d}},{}],46:[function(i,r,l){var c,d=i("../utils/common"),h=i("./trees"),p=i("./adler32"),f=i("./crc32"),b=i("./messages"),y=0,w=4,v=0,_=-2,$=-1,S=4,T=2,E=8,D=9,M=286,P=30,W=19,G=2*M+1,z=15,Z=3,he=258,Ce=he+Z+1,O=42,K=113,C=1,Q=2,ve=3,ce=4;function ne(k,X){return k.msg=b[X],X}function me(k){return(k<<1)-(4k.avail_out&&(Y=k.avail_out),Y!==0&&(d.arraySet(k.output,X.pending_buf,X.pending_out,Y,k.next_out),k.next_out+=Y,X.pending_out+=Y,k.total_out+=Y,k.avail_out-=Y,X.pending-=Y,X.pending===0&&(X.pending_out=0))}function N(k,X){h._tr_flush_block(k,0<=k.block_start?k.block_start:-1,k.strstart-k.block_start,X),k.block_start=k.strstart,B(k.strm)}function te(k,X){k.pending_buf[k.pending++]=X}function q(k,X){k.pending_buf[k.pending++]=X>>>8&255,k.pending_buf[k.pending++]=255&X}function se(k,X){var Y,R,A=k.max_chain_length,U=k.strstart,H=k.prev_length,ue=k.nice_match,V=k.strstart>k.w_size-Ce?k.strstart-(k.w_size-Ce):0,be=k.window,pe=k.w_mask,fe=k.prev,Le=k.strstart+he,He=be[U+H-1],Be=be[U+H];k.prev_length>=k.good_match&&(A>>=2),ue>k.lookahead&&(ue=k.lookahead);do if(be[(Y=X)+H]===Be&&be[Y+H-1]===He&&be[Y]===be[U]&&be[++Y]===be[U+1]){U+=2,Y++;do;while(be[++U]===be[++Y]&&be[++U]===be[++Y]&&be[++U]===be[++Y]&&be[++U]===be[++Y]&&be[++U]===be[++Y]&&be[++U]===be[++Y]&&be[++U]===be[++Y]&&be[++U]===be[++Y]&&UV&&--A!=0);return H<=k.lookahead?H:k.lookahead}function F(k){var X,Y,R,A,U,H,ue,V,be,pe,fe=k.w_size;do{if(A=k.window_size-k.lookahead-k.strstart,k.strstart>=fe+(fe-Ce)){for(d.arraySet(k.window,k.window,fe,fe,0),k.match_start-=fe,k.strstart-=fe,k.block_start-=fe,X=Y=k.hash_size;R=k.head[--X],k.head[X]=fe<=R?R-fe:0,--Y;);for(X=Y=fe;R=k.prev[--X],k.prev[X]=fe<=R?R-fe:0,--Y;);A+=fe}if(k.strm.avail_in===0)break;if(H=k.strm,ue=k.window,V=k.strstart+k.lookahead,be=A,pe=void 0,pe=H.avail_in,be=Z)for(U=k.strstart-k.insert,k.ins_h=k.window[U],k.ins_h=(k.ins_h<=Z&&(k.ins_h=(k.ins_h<=Z)if(R=h._tr_tally(k,k.strstart-k.match_start,k.match_length-Z),k.lookahead-=k.match_length,k.match_length<=k.max_lazy_match&&k.lookahead>=Z){for(k.match_length--;k.strstart++,k.ins_h=(k.ins_h<=Z&&(k.ins_h=(k.ins_h<=Z&&k.match_length<=k.prev_length){for(A=k.strstart+k.lookahead-Z,R=h._tr_tally(k,k.strstart-1-k.prev_match,k.prev_length-Z),k.lookahead-=k.prev_length-1,k.prev_length-=2;++k.strstart<=A&&(k.ins_h=(k.ins_h<k.pending_buf_size-5&&(Y=k.pending_buf_size-5);;){if(k.lookahead<=1){if(F(k),k.lookahead===0&&X===y)return C;if(k.lookahead===0)break}k.strstart+=k.lookahead,k.lookahead=0;var R=k.block_start+Y;if((k.strstart===0||k.strstart>=R)&&(k.lookahead=k.strstart-R,k.strstart=R,N(k,!1),k.strm.avail_out===0)||k.strstart-k.block_start>=k.w_size-Ce&&(N(k,!1),k.strm.avail_out===0))return C}return k.insert=0,X===w?(N(k,!0),k.strm.avail_out===0?ve:ce):(k.strstart>k.block_start&&(N(k,!1),k.strm.avail_out),C)}),new we(4,4,8,4,Te),new we(4,5,16,8,Te),new we(4,6,32,32,Te),new we(4,4,16,16,ae),new we(8,16,32,32,ae),new we(8,16,128,128,ae),new we(8,32,128,256,ae),new we(32,128,258,1024,ae),new we(32,258,258,4096,ae)],l.deflateInit=function(k,X){return We(k,X,E,15,8,0)},l.deflateInit2=We,l.deflateReset=Ae,l.deflateResetKeep=Ne,l.deflateSetHeader=function(k,X){return k&&k.state?k.state.wrap!==2?_:(k.state.gzhead=X,v):_},l.deflate=function(k,X){var Y,R,A,U;if(!k||!k.state||5>8&255),te(R,R.gzhead.time>>16&255),te(R,R.gzhead.time>>24&255),te(R,R.level===9?2:2<=R.strategy||R.level<2?4:0),te(R,255&R.gzhead.os),R.gzhead.extra&&R.gzhead.extra.length&&(te(R,255&R.gzhead.extra.length),te(R,R.gzhead.extra.length>>8&255)),R.gzhead.hcrc&&(k.adler=f(k.adler,R.pending_buf,R.pending,0)),R.gzindex=0,R.status=69):(te(R,0),te(R,0),te(R,0),te(R,0),te(R,0),te(R,R.level===9?2:2<=R.strategy||R.level<2?4:0),te(R,3),R.status=K);else{var H=E+(R.w_bits-8<<4)<<8;H|=(2<=R.strategy||R.level<2?0:R.level<6?1:R.level===6?2:3)<<6,R.strstart!==0&&(H|=32),H+=31-H%31,R.status=K,q(R,H),R.strstart!==0&&(q(R,k.adler>>>16),q(R,65535&k.adler)),k.adler=1}if(R.status===69)if(R.gzhead.extra){for(A=R.pending;R.gzindex<(65535&R.gzhead.extra.length)&&(R.pending!==R.pending_buf_size||(R.gzhead.hcrc&&R.pending>A&&(k.adler=f(k.adler,R.pending_buf,R.pending-A,A)),B(k),A=R.pending,R.pending!==R.pending_buf_size));)te(R,255&R.gzhead.extra[R.gzindex]),R.gzindex++;R.gzhead.hcrc&&R.pending>A&&(k.adler=f(k.adler,R.pending_buf,R.pending-A,A)),R.gzindex===R.gzhead.extra.length&&(R.gzindex=0,R.status=73)}else R.status=73;if(R.status===73)if(R.gzhead.name){A=R.pending;do{if(R.pending===R.pending_buf_size&&(R.gzhead.hcrc&&R.pending>A&&(k.adler=f(k.adler,R.pending_buf,R.pending-A,A)),B(k),A=R.pending,R.pending===R.pending_buf_size)){U=1;break}U=R.gzindexA&&(k.adler=f(k.adler,R.pending_buf,R.pending-A,A)),U===0&&(R.gzindex=0,R.status=91)}else R.status=91;if(R.status===91)if(R.gzhead.comment){A=R.pending;do{if(R.pending===R.pending_buf_size&&(R.gzhead.hcrc&&R.pending>A&&(k.adler=f(k.adler,R.pending_buf,R.pending-A,A)),B(k),A=R.pending,R.pending===R.pending_buf_size)){U=1;break}U=R.gzindexA&&(k.adler=f(k.adler,R.pending_buf,R.pending-A,A)),U===0&&(R.status=103)}else R.status=103;if(R.status===103&&(R.gzhead.hcrc?(R.pending+2>R.pending_buf_size&&B(k),R.pending+2<=R.pending_buf_size&&(te(R,255&k.adler),te(R,k.adler>>8&255),k.adler=0,R.status=K)):R.status=K),R.pending!==0){if(B(k),k.avail_out===0)return R.last_flush=-1,v}else if(k.avail_in===0&&me(X)<=me(Y)&&X!==w)return ne(k,-5);if(R.status===666&&k.avail_in!==0)return ne(k,-5);if(k.avail_in!==0||R.lookahead!==0||X!==y&&R.status!==666){var ue=R.strategy===2?(function(V,be){for(var pe;;){if(V.lookahead===0&&(F(V),V.lookahead===0)){if(be===y)return C;break}if(V.match_length=0,pe=h._tr_tally(V,0,V.window[V.strstart]),V.lookahead--,V.strstart++,pe&&(N(V,!1),V.strm.avail_out===0))return C}return V.insert=0,be===w?(N(V,!0),V.strm.avail_out===0?ve:ce):V.last_lit&&(N(V,!1),V.strm.avail_out===0)?C:Q})(R,X):R.strategy===3?(function(V,be){for(var pe,fe,Le,He,Be=V.window;;){if(V.lookahead<=he){if(F(V),V.lookahead<=he&&be===y)return C;if(V.lookahead===0)break}if(V.match_length=0,V.lookahead>=Z&&0V.lookahead&&(V.match_length=V.lookahead)}if(V.match_length>=Z?(pe=h._tr_tally(V,1,V.match_length-Z),V.lookahead-=V.match_length,V.strstart+=V.match_length,V.match_length=0):(pe=h._tr_tally(V,0,V.window[V.strstart]),V.lookahead--,V.strstart++),pe&&(N(V,!1),V.strm.avail_out===0))return C}return V.insert=0,be===w?(N(V,!0),V.strm.avail_out===0?ve:ce):V.last_lit&&(N(V,!1),V.strm.avail_out===0)?C:Q})(R,X):c[R.level].func(R,X);if(ue!==ve&&ue!==ce||(R.status=666),ue===C||ue===ve)return k.avail_out===0&&(R.last_flush=-1),v;if(ue===Q&&(X===1?h._tr_align(R):X!==5&&(h._tr_stored_block(R,0,0,!1),X===3&&(re(R.head),R.lookahead===0&&(R.strstart=0,R.block_start=0,R.insert=0))),B(k),k.avail_out===0))return R.last_flush=-1,v}return X!==w?v:R.wrap<=0?1:(R.wrap===2?(te(R,255&k.adler),te(R,k.adler>>8&255),te(R,k.adler>>16&255),te(R,k.adler>>24&255),te(R,255&k.total_in),te(R,k.total_in>>8&255),te(R,k.total_in>>16&255),te(R,k.total_in>>24&255)):(q(R,k.adler>>>16),q(R,65535&k.adler)),B(k),0=Y.w_size&&(U===0&&(re(Y.head),Y.strstart=0,Y.block_start=0,Y.insert=0),be=new d.Buf8(Y.w_size),d.arraySet(be,X,pe-Y.w_size,Y.w_size,0),X=be,pe=Y.w_size),H=k.avail_in,ue=k.next_in,V=k.input,k.avail_in=pe,k.next_in=0,k.input=X,F(Y);Y.lookahead>=Z;){for(R=Y.strstart,A=Y.lookahead-(Z-1);Y.ins_h=(Y.ins_h<>>=Z=z>>>24,D-=Z,(Z=z>>>16&255)===0)Q[b++]=65535&z;else{if(!(16&Z)){if((64&Z)==0){z=M[(65535&z)+(E&(1<>>=Z,D-=Z),D<15&&(E+=C[p++]<>>=Z=z>>>24,D-=Z,!(16&(Z=z>>>16&255))){if((64&Z)==0){z=P[(65535&z)+(E&(1<>>=Z,D-=Z,(Z=b-y)>3,E&=(1<<(D-=he<<3))-1,c.next_in=p,c.next_out=b,c.avail_in=p>>24&255)+(O>>>8&65280)+((65280&O)<<8)+((255&O)<<24)}function E(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new c.Buf16(320),this.work=new c.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function D(O){var K;return O&&O.state?(K=O.state,O.total_in=O.total_out=K.total=0,O.msg="",K.wrap&&(O.adler=1&K.wrap),K.mode=_,K.last=0,K.havedict=0,K.dmax=32768,K.head=null,K.hold=0,K.bits=0,K.lencode=K.lendyn=new c.Buf32($),K.distcode=K.distdyn=new c.Buf32(S),K.sane=1,K.back=-1,w):v}function M(O){var K;return O&&O.state?((K=O.state).wsize=0,K.whave=0,K.wnext=0,D(O)):v}function P(O,K){var C,Q;return O&&O.state?(Q=O.state,K<0?(C=0,K=-K):(C=1+(K>>4),K<48&&(K&=15)),K&&(K<8||15=ce.wsize?(c.arraySet(ce.window,K,C-ce.wsize,ce.wsize,0),ce.wnext=0,ce.whave=ce.wsize):(Q<(ve=ce.wsize-ce.wnext)&&(ve=Q),c.arraySet(ce.window,K,C-Q,ve,ce.wnext),(Q-=ve)?(c.arraySet(ce.window,K,C-Q,Q,0),ce.wnext=Q,ce.whave=ce.wsize):(ce.wnext+=ve,ce.wnext===ce.wsize&&(ce.wnext=0),ce.whave>>8&255,C.check=h(C.check,U,2,0),N=B=0,C.mode=2;break}if(C.flags=0,C.head&&(C.head.done=!1),!(1&C.wrap)||(((255&B)<<8)+(B>>8))%31){O.msg="incorrect header check",C.mode=30;break}if((15&B)!=8){O.msg="unknown compression method",C.mode=30;break}if(N-=4,k=8+(15&(B>>>=4)),C.wbits===0)C.wbits=k;else if(k>C.wbits){O.msg="invalid window size",C.mode=30;break}C.dmax=1<>8&1),512&C.flags&&(U[0]=255&B,U[1]=B>>>8&255,C.check=h(C.check,U,2,0)),N=B=0,C.mode=3;case 3:for(;N<32;){if(me===0)break e;me--,B+=Q[ce++]<>>8&255,U[2]=B>>>16&255,U[3]=B>>>24&255,C.check=h(C.check,U,4,0)),N=B=0,C.mode=4;case 4:for(;N<16;){if(me===0)break e;me--,B+=Q[ce++]<>8),512&C.flags&&(U[0]=255&B,U[1]=B>>>8&255,C.check=h(C.check,U,2,0)),N=B=0,C.mode=5;case 5:if(1024&C.flags){for(;N<16;){if(me===0)break e;me--,B+=Q[ce++]<>>8&255,C.check=h(C.check,U,2,0)),N=B=0}else C.head&&(C.head.extra=null);C.mode=6;case 6:if(1024&C.flags&&(me<(se=C.length)&&(se=me),se&&(C.head&&(k=C.head.extra_len-C.length,C.head.extra||(C.head.extra=new Array(C.head.extra_len)),c.arraySet(C.head.extra,Q,ce,se,k)),512&C.flags&&(C.check=h(C.check,Q,se,ce)),me-=se,ce+=se,C.length-=se),C.length))break e;C.length=0,C.mode=7;case 7:if(2048&C.flags){if(me===0)break e;for(se=0;k=Q[ce+se++],C.head&&k&&C.length<65536&&(C.head.name+=String.fromCharCode(k)),k&&se>9&1,C.head.done=!0),O.adler=C.check=0,C.mode=12;break;case 10:for(;N<32;){if(me===0)break e;me--,B+=Q[ce++]<>>=7&N,N-=7&N,C.mode=27;break}for(;N<3;){if(me===0)break e;me--,B+=Q[ce++]<>>=1)){case 0:C.mode=14;break;case 1:if(he(C),C.mode=20,K!==6)break;B>>>=2,N-=2;break e;case 2:C.mode=17;break;case 3:O.msg="invalid block type",C.mode=30}B>>>=2,N-=2;break;case 14:for(B>>>=7&N,N-=7&N;N<32;){if(me===0)break e;me--,B+=Q[ce++]<>>16^65535)){O.msg="invalid stored block lengths",C.mode=30;break}if(C.length=65535&B,N=B=0,C.mode=15,K===6)break e;case 15:C.mode=16;case 16:if(se=C.length){if(me>>=5,N-=5,C.ndist=1+(31&B),B>>>=5,N-=5,C.ncode=4+(15&B),B>>>=4,N-=4,286>>=3,N-=3}for(;C.have<19;)C.lens[H[C.have++]]=0;if(C.lencode=C.lendyn,C.lenbits=7,Y={bits:C.lenbits},X=f(0,C.lens,0,19,C.lencode,0,C.work,Y),C.lenbits=Y.bits,X){O.msg="invalid code lengths set",C.mode=30;break}C.have=0,C.mode=19;case 19:for(;C.have>>16&255,Ie=65535&A,!((ae=A>>>24)<=N);){if(me===0)break e;me--,B+=Q[ce++]<>>=ae,N-=ae,C.lens[C.have++]=Ie;else{if(Ie===16){for(R=ae+2;N>>=ae,N-=ae,C.have===0){O.msg="invalid bit length repeat",C.mode=30;break}k=C.lens[C.have-1],se=3+(3&B),B>>>=2,N-=2}else if(Ie===17){for(R=ae+3;N>>=ae)),B>>>=3,N-=3}else{for(R=ae+7;N>>=ae)),B>>>=7,N-=7}if(C.have+se>C.nlen+C.ndist){O.msg="invalid bit length repeat",C.mode=30;break}for(;se--;)C.lens[C.have++]=k}}if(C.mode===30)break;if(C.lens[256]===0){O.msg="invalid code -- missing end-of-block",C.mode=30;break}if(C.lenbits=9,Y={bits:C.lenbits},X=f(b,C.lens,0,C.nlen,C.lencode,0,C.work,Y),C.lenbits=Y.bits,X){O.msg="invalid literal/lengths set",C.mode=30;break}if(C.distbits=6,C.distcode=C.distdyn,Y={bits:C.distbits},X=f(y,C.lens,C.nlen,C.ndist,C.distcode,0,C.work,Y),C.distbits=Y.bits,X){O.msg="invalid distances set",C.mode=30;break}if(C.mode=20,K===6)break e;case 20:C.mode=21;case 21:if(6<=me&&258<=re){O.next_out=ne,O.avail_out=re,O.next_in=ce,O.avail_in=me,C.hold=B,C.bits=N,p(O,q),ne=O.next_out,ve=O.output,re=O.avail_out,ce=O.next_in,Q=O.input,me=O.avail_in,B=C.hold,N=C.bits,C.mode===12&&(C.back=-1);break}for(C.back=0;we=(A=C.lencode[B&(1<>>16&255,Ie=65535&A,!((ae=A>>>24)<=N);){if(me===0)break e;me--,B+=Q[ce++]<>Ne)])>>>16&255,Ie=65535&A,!(Ne+(ae=A>>>24)<=N);){if(me===0)break e;me--,B+=Q[ce++]<>>=Ne,N-=Ne,C.back+=Ne}if(B>>>=ae,N-=ae,C.back+=ae,C.length=Ie,we===0){C.mode=26;break}if(32&we){C.back=-1,C.mode=12;break}if(64&we){O.msg="invalid literal/length code",C.mode=30;break}C.extra=15&we,C.mode=22;case 22:if(C.extra){for(R=C.extra;N>>=C.extra,N-=C.extra,C.back+=C.extra}C.was=C.length,C.mode=23;case 23:for(;we=(A=C.distcode[B&(1<>>16&255,Ie=65535&A,!((ae=A>>>24)<=N);){if(me===0)break e;me--,B+=Q[ce++]<>Ne)])>>>16&255,Ie=65535&A,!(Ne+(ae=A>>>24)<=N);){if(me===0)break e;me--,B+=Q[ce++]<>>=Ne,N-=Ne,C.back+=Ne}if(B>>>=ae,N-=ae,C.back+=ae,64&we){O.msg="invalid distance code",C.mode=30;break}C.offset=Ie,C.extra=15&we,C.mode=24;case 24:if(C.extra){for(R=C.extra;N>>=C.extra,N-=C.extra,C.back+=C.extra}if(C.offset>C.dmax){O.msg="invalid distance too far back",C.mode=30;break}C.mode=25;case 25:if(re===0)break e;if(se=q-re,C.offset>se){if((se=C.offset-se)>C.whave&&C.sane){O.msg="invalid distance too far back",C.mode=30;break}F=se>C.wnext?(se-=C.wnext,C.wsize-se):C.wnext-se,se>C.length&&(se=C.length),Te=C.window}else Te=ve,F=ne-C.offset,se=C.length;for(reG?(Z=F[Te+S[K]],N[te+S[K]]):(Z=96,0),E=1<>ne)+(D-=E)]=z<<24|Z<<16|he|0,D!==0;);for(E=1<>=1;if(E!==0?(B&=E-1,B+=E):B=0,K++,--q[O]==0){if(O===Q)break;O=y[w+S[K]]}if(ve>>7)]}function te(A,U){A.pending_buf[A.pending++]=255&U,A.pending_buf[A.pending++]=U>>>8&255}function q(A,U,H){A.bi_valid>T-H?(A.bi_buf|=U<>T-A.bi_valid,A.bi_valid+=H-T):(A.bi_buf|=U<>>=1,H<<=1,0<--U;);return H>>>1}function Te(A,U,H){var ue,V,be=new Array(S+1),pe=0;for(ue=1;ue<=S;ue++)be[ue]=pe=pe+H[ue-1]<<1;for(V=0;V<=U;V++){var fe=A[2*V+1];fe!==0&&(A[2*V]=F(be[fe]++,fe))}}function ae(A){var U;for(U=0;U>1;1<=H;H--)Ne(A,be,H);for(V=Le;H=A.heap[1],A.heap[1]=A.heap[A.heap_len--],Ne(A,be,1),ue=A.heap[1],A.heap[--A.heap_max]=H,A.heap[--A.heap_max]=ue,be[2*V]=be[2*H]+be[2*ue],A.depth[V]=(A.depth[H]>=A.depth[ue]?A.depth[H]:A.depth[ue])+1,be[2*H+1]=be[2*ue+1]=V,A.heap[1]=V++,Ne(A,be,1),2<=A.heap_len;);A.heap[--A.heap_max]=A.heap[1],(function(Be,jt){var ie,Re,Ps,ze,Zo,Ze,At=jt.dyn_tree,Qo=jt.max_code,io=jt.stat_desc.static_tree,no=jt.stat_desc.has_stree,Un=jt.stat_desc.extra_bits,Io=jt.stat_desc.extra_base,Bs=jt.stat_desc.max_length,ro=0;for(ze=0;ze<=S;ze++)Be.bl_count[ze]=0;for(At[2*Be.heap[Be.heap_max]+1]=0,ie=Be.heap_max+1;ie<$;ie++)Bs<(ze=At[2*At[2*(Re=Be.heap[ie])+1]+1]+1)&&(ze=Bs,ro++),At[2*Re+1]=ze,Qo>=7;V>>=1)if(1&He&&fe.dyn_ltree[2*Le]!==0)return d;if(fe.dyn_ltree[18]!==0||fe.dyn_ltree[20]!==0||fe.dyn_ltree[26]!==0)return h;for(Le=32;Le>>3,(be=A.static_len+3+7>>>3)<=V&&(V=be)):V=be=H+5,H+4<=V&&U!==-1?R(A,U,H,ue):A.strategy===4||be===V?(q(A,2+(ue?1:0),3),Ae(A,Ce,O)):(q(A,4+(ue?1:0),3),(function(fe,Le,He,Be){var jt;for(q(fe,Le-257,5),q(fe,He-1,5),q(fe,Be-4,4),jt=0;jt>>8&255,A.pending_buf[A.d_buf+2*A.last_lit+1]=255&U,A.pending_buf[A.l_buf+A.last_lit]=255&H,A.last_lit++,U===0?A.dyn_ltree[2*H]++:(A.matches++,U--,A.dyn_ltree[2*(C[H]+y+1)]++,A.dyn_dtree[2*N(U)]++),A.last_lit===A.lit_bufsize-1},l._tr_align=function(A){q(A,2,3),se(A,D,Ce),(function(U){U.bi_valid===16?(te(U,U.bi_buf),U.bi_buf=0,U.bi_valid=0):8<=U.bi_valid&&(U.pending_buf[U.pending++]=255&U.bi_buf,U.bi_buf>>=8,U.bi_valid-=8)})(A)}},{"../utils/common":41}],53:[function(i,r,l){r.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(i,r,l){(function(c){(function(d,h){if(!d.setImmediate){var p,f,b,y,w=1,v={},_=!1,$=d.document,S=Object.getPrototypeOf&&Object.getPrototypeOf(d);S=S&&S.setTimeout?S:d,p={}.toString.call(d.process)==="[object process]"?function(M){process.nextTick(function(){E(M)})}:(function(){if(d.postMessage&&!d.importScripts){var M=!0,P=d.onmessage;return d.onmessage=function(){M=!1},d.postMessage("","*"),d.onmessage=P,M}})()?(y="setImmediate$"+Math.random()+"$",d.addEventListener?d.addEventListener("message",D,!1):d.attachEvent("onmessage",D),function(M){d.postMessage(y+M,"*")}):d.MessageChannel?((b=new MessageChannel).port1.onmessage=function(M){E(M.data)},function(M){b.port2.postMessage(M)}):$&&"onreadystatechange"in $.createElement("script")?(f=$.documentElement,function(M){var P=$.createElement("script");P.onreadystatechange=function(){E(M),P.onreadystatechange=null,f.removeChild(P),P=null},f.appendChild(P)}):function(M){setTimeout(E,0,M)},S.setImmediate=function(M){typeof M!="function"&&(M=new Function(""+M));for(var P=new Array(arguments.length-1),W=0;W"u"?c===void 0?this:c:self)}).call(this,typeof eo<"u"?eo:typeof self<"u"?self:typeof window<"u"?window:{})},{}]},{},[10])(10)})})(RC);var bse=RC.exports;const ww=Xo(bse);function vse(a){const[s,i]=_e.useState(""),[r,l]=_e.useState("");return Lt(()=>{a.socket.decrypt(a.systemConfig.native.javascriptPassword).then(c=>l(c))},[a.systemConfig,a.socket]),m.jsxs(Pt,{open:!0,onClose:()=>a.onEntered(null),fullWidth:!0,maxWidth:"sm",children:[m.jsx(Xt,{children:x.I18n.t("Please enter a password for expert mode")}),m.jsx(Wt,{children:m.jsx(Eo,{autoFocus:!0,margin:"dense",variant:"standard",label:x.I18n.t("Password"),type:"password",fullWidth:!0,value:s,onKeyDown:c=>{c.key==="Enter"&&s&&(c.preventDefault(),c.stopPropagation(),r===s?a.onEntered(s):a.onEntered(""))},onChange:c=>i(c.target.value)})}),m.jsxs(Bt,{children:[m.jsx(Ue,{variant:"contained",disabled:!s,onClick:()=>{r===s?a.onEntered(s):a.onEntered("")},startIcon:m.jsx(qo,{}),children:x.I18n.t("Ok")}),m.jsx(Ue,{color:"grey",variant:"contained",onClick:()=>a.onEntered(null),startIcon:m.jsx(so,{}),children:x.I18n.t("Cancel")})]})]})}const Gr={root:{flexGrow:1,display:"flex",width:"100%",height:"100%"},mainDiv:{width:"100%",height:"100%",overflow:"hidden"},content:a=>({width:"100%",height:"100%",backgroundColor:a.palette.background&&a.palette.background.default,position:"relative"}),menuOpenCloseButton:a=>({position:"absolute",left:0,borderRadius:"0 5px 5px 0",top:6,pt:1,cursor:"pointer",zIndex:1,height:25,width:20,background:a.palette.secondary.main,color:a.palette.primary.main,pl:"3px","&:hover":{color:"white"}}),showLogButton:a=>({position:"absolute",right:3,borderRadius:"5px 5px 0 0",bottom:0,pt:"3px",cursor:"pointer",zIndex:10,height:20,width:25,background:a.palette.secondary.main,color:a.palette.primary.main,pl:1,"&:hover":{color:"white"}})};class yse extends x.GenericApp{hosts=[];importFile=null;importFileName=null;scripts={};confirmCallback=null;changedScripts={};javascriptPassword="";constructor(s){super(s,{Connection:x.AdminConnection,translations:{en:pM,de:lB,es:oF,fr:ZU,it:K5,nl:UV,pl:P6,pt:R7,ru:Eq,uk:wQ,"zh-cn":$se},bottomButtons:!1,socket:{autoSubscribeLog:!0},sentryDSN:window.sentryDSN});const i=window.localStorage.getItem("JS.logSizes");let r=[80,20];if(i)try{r=JSON.parse(i)}catch{}const l=window.localStorage.getItem("JS.splitSizes");let c=[20,80];if(l)try{c=JSON.parse(l)}catch{}this.state={...this.state,splitSizes:c,logSizes:r},window.alert=d=>{console.error(d),this.showJsError(d.toString())}}onScriptsChanged=(s,i)=>{if(!s)return;let r=!1;const l={};s.startsWith("script.js.")&&(i?JSON.stringify(this.scripts[s])!==JSON.stringify(i)&&(this.scripts[s]=i,r=!0,l.scriptsHash=this.state.scriptsHash+1):this.scripts[s]&&(delete this.scripts[s],r=!0,l.scriptsHash=this.state.scriptsHash+1)),r&&this.setState(l)};onInstanceChanged=(s,i)=>{var c;if(!s)return;let r=!1;const l={};if(s.match(/^system\.adapter\.[-_\w\d]+\$/)){if(s.startsWith(`system.adapter.${this.adapterName}.`)){const d=parseInt(s.split(".").pop()||"0",10)||0;if((i==null?void 0:i.type)==="instance")this.state.instances.includes(d)||(l.instances=[...this.state.instances],l.instances.push(d),l.instances.sort(),r=!0,this.socket.subscribeState(`${i._id}.alive`,this.onInstanceAliveChange));else if(!i&&this.state.instances.includes(d)){this.socket.unsubscribeState(`${s}.alive`,this.onInstanceAliveChange),l.instances=[...this.state.instances];const h=l.instances.indexOf(d);l.instances.splice(h,1),r=!0}}(c=i==null?void 0:i.common)!=null&&c.blockly&&(this.confirmCallback=d=>d&&window.location.reload(),l.confirm=x.I18n.t("Some blocks were updated. Reload admin?"),r=!0)}r&&this.setState(l)};onHostChanged=(s,i)=>{if(s&&s.startsWith("system.host.")){if((i==null?void 0:i.type)==="host")this.hosts.includes(s)||(this.hosts.push(s),this.hosts.sort());else if(!i&&this.hosts.includes(s)){const r=this.hosts.indexOf(s);this.hosts.splice(r,1)}}};onConnectionReady(){window.systemLang=this.socket.systemLang,this.setState({ready:!1,scriptsHash:0,instances:[],updating:!1,resizing:!1,selected:null,logMessage:{},editing:[],menuOpened:window.localStorage.getItem("App.menuOpened")!=="false",menuSelectId:"",expertMode:window.localStorage.getItem("App.expertMode")==="true",logHorzLayout:window.localStorage.getItem("App.logHorzLayout")==="true",runningInstances:{},confirm:"",importFile:!1,message:"",searchText:"",hideLog:window.localStorage.getItem("App.hideLog")==="true",debugMode:!1,debugInstance:null,splitSizes:[20,80],password:""},async()=>{var d;const s={},i=await this.subscribeOnInstances();s.instances=i.instances,s.runningInstances=i.runningInstances,this.javascriptPassword=((d=this.socket.systemConfig)==null?void 0:d.native.javascriptPassword)||"",await this.readAdaptersWithBlockly();const r=await this.socket.getHosts();this.hosts=r.map(h=>h._id);const l=await this.readAllScripts();window.localStorage.getItem("App.expertMode")!=="true"&&window.localStorage.getItem("App.expertMode")!=="false"&&!this.javascriptPassword?Object.keys(l).find(h=>h.startsWith("script.js.global.")&&l[h].type==="script")&&(s.expertMode=!0):this.javascriptPassword&&(s.expertMode=!1),this.scripts=l;let c=this.state.scriptsHash;this.compareScripts(l)&&c++,s.scriptsHash=c,s.ready=!0,this.setState(s),await this.socket.subscribeObject("script.*",this.onScriptsChanged),await this.socket.subscribeObject("system.adapter.*",this.onInstanceChanged),await this.socket.subscribeObject("system.host.*",this.onHostChanged)})}async subscribeOnInstances(){const i=(await this.socket.getAdapterInstances(this.adapterName)).map(l=>parseInt(l._id.split(".").pop()||"0")).sort(),r={};i.forEach(l=>r[`system.adapter.${this.adapterName}.${l}`]=!1);for(let l=0;ls[r]=i[r]),s}async readAdaptersWithBlockly(){const s=await this.socket.getObjectViewSystem("adapter","system.adapter.","system.adapter.香");return new Promise(i=>et.loadCustomBlockly(s,()=>i()))}onInstanceAliveChange=(s,i)=>{if(s&&(s=s?s.substring(0,s.length-6):"",this.state.runningInstances[s]!==(i?i.val:!1))){const r=JSON.parse(JSON.stringify(this.state.runningInstances));r[s]=i?!!i.val:!1,this.setState({runningInstances:r})}};compareScripts(s){const i=Object.keys(this.scripts),r=Object.keys(s);if(i.length!==r.length)return this.scripts=s,!0;if(JSON.stringify(i)!==JSON.stringify(r))return this.scripts=s,!0;for(let l=0;l ${i}`),this.setState({updating:!0});try{if(((c=this.scripts[s])==null?void 0:c.type)==="script"){const d=JSON.parse(JSON.stringify(this.scripts[s].common));d.name=r||d.name,l!==void 0&&(d.engine=`system.adapter.javascript.${l}`);const h=i.split(".");h.pop();const p=h.join(".");this.scripts[p]&&this.scripts[p].type==="script"&&(h.pop(),i=`${h.join(".")}.${i.split(".").pop()}`),await this.updateScript(s,i,d)}else await this.renameGroup(s,i,r)}catch(d){d.toString().includes("canceled")||this.showJsError(d)}this.setState({updating:!1})}async renameGroup(s,i,r,l){if(l){if(l.length){let c=l.pop();if(c){const d=await this.socket.getObject(c);if(d){try{await this.socket.delObject(c)}catch{}c=i+c.substring(s.length),d._id=c,d.common=d.common||{},d.common.expert=!0,await this.socket.setObject(c,d),await this.renameGroup(s,i,r,l)}}}}else{l=[],l=Object.keys(this.scripts).filter(d=>d.startsWith(`${s}.`));let c=await this.socket.getObject(s);c=c||{common:{},type:"channel"},c.common.name=r||c.common.name||s.split(".").pop()||"",c._id=i;try{await this.socket.delObject(s)}catch{}try{await this.socket.setObject(i,c),await this.renameGroup(s,i,r,l)}catch(d){console.log(d);const h={_id:i,type:"channel",common:{name:r||s.split(".").pop()||"",expert:!0},native:{}};await this.socket.setObject(i,h),await this.renameGroup(s,i,r,l)}}}async onUpdateScript(s,i){var r;if(((r=this.scripts[s])==null?void 0:r.type)==="script")try{await this.updateScript(s,s,i)}catch(l){l.toString().includes("canceled")||this.showJsError(l)}}onSelect(s){this.scripts[s]&&this.scripts[s].common&&this.scripts[s].type==="script"&&this.setState({selected:s,menuSelectId:s},()=>setTimeout(()=>this.setState({menuSelectId:""}),300))}renderPasswordDialog(){return this.state.showPasswordDialog?m.jsx(vse,{socket:this.socket,systemConfig:this.socket.systemConfig,onEntered:s=>{s===null?this.setState({showPasswordDialog:!1,expertMode:!1,password:""}):s?this.setState({expertMode:!0,showPasswordDialog:!1,password:s}):this.setState({showPasswordDialog:!1,expertMode:!1,message:x.I18n.t("Wrong password"),password:""})}},"passwordDialog"):null}onExpertModeChange(s){var i;if(this.state.expertMode!==s)if(s&&this.javascriptPassword)this.setState({showPasswordDialog:!0});else{let r=this.state.selected;r&&!s&&((i=this.scripts[r].native)!=null&&i.protected)&&(r=this.state.editing.find(l=>{var c;return this.scripts[l]&&!((c=this.scripts[l].native)!=null&&c.protected)})||null),window.localStorage.setItem("App.expertMode",s?"true":"false"),this.setState({expertMode:s,password:"",selected:r})}}showJsError(s){this.setState({errorText:s?s.toString():""})}showMessage(s){this.setState({message:s?s.toString():""})}onDelete(s){this.socket.delObject(s).catch(i=>this.showJsError(i))}onEdit(s){this.state.selected!==s&&this.setState({selected:s})}onAddNew(s,i,r,l,c,d){const h=new RegExp(`^${s}\\.`);if(Object.keys(this.scripts).find(p=>s===p||h.test(s)))return this.showJsError(x.I18n.t("Yet exists!"));r?this.socket.setObject(s,{_id:s,type:"channel",common:{name:i,expert:!0},native:{}}).then(()=>setTimeout(()=>this.setState({menuSelectId:s},()=>setTimeout(()=>this.setState({menuSelectId:""}),300)),1e3)).catch(p=>this.showJsError(p)):(c==="Blockly"&&!d&&(d=` -//${btoa(encodeURIComponent(''))}`),this.socket.setObject(s,{_id:s,type:"script",common:{name:i,expert:!0,engineType:c||"Javascript/js",enabled:!1,engine:`system.adapter.javascript.${l||0}`,source:d||"",debug:!1,verbose:!1},native:{}}).then(()=>setTimeout(()=>this.onSelect(s),1e3)).catch(p=>this.showJsError(p)))}async updateScript(s,i,r){let l=await this.socket.getObject(s);const c={common:{}};if(r.engine!==void 0&&(c.common.engine=r.engine),r.enabled!==void 0&&(c.common.enabled=r.enabled),r.source!==void 0&&(c.common.source=r.source),r.debug!==void 0&&(c.common.debug=r.debug),r.verbose!==void 0&&(c.common.verbose=r.verbose),c.from="system.adapter.admin.0",s===i&&(l!=null&&l.common)&&r.name===l.common.name){(!r.engineType||r.engineType!==l.common.engineType)&&r.engineType!==void 0&&(c.common.engineType=r.engineType||"Javascript/js"),c.type="script",await this.socket.extendObject(s,c);return}if(l!=null&&l.common){l.common.engineType=r.engineType||l.common.engineType||"Javascript/js",await this.socket.delObject(s),c.common.engine!==void 0&&(l.common.engine=c.common.engine),c.common.enabled!==void 0&&(l.common.enabled=c.common.enabled),c.common.source!==void 0&&(l.common.source=c.common.source),c.common.name!==void 0&&(l.common.name=c.common.name),c.common.debug!==void 0&&(l.common.debug=c.common.debug),c.common.verbose!==void 0&&(l.common.verbose=c.common.verbose),l._rev!==void 0&&delete l._rev,l.common.name=r.name,l.common.expert=!0,l.type="script",l._id=i,await this.socket.setObject(i,l);return}l=c,l.common.name=r.name,l.common.expert=!0,l.type="script",l._id=i,await this.socket.setObject(i,l)}onEnableDisable(s,i){var r;if(((r=this.scripts[s])==null?void 0:r.type)==="script"){const l=this.scripts[s].common;l.enabled=i,l.expert=!0,this.updateScript(s,s,l).catch(c=>c!=="canceled"&&this.showJsError(c))}}async getLiveHost(){for(let s=0;s{if(typeof d=="string"){const h=document.createElement("a");h.href=`../../files/${d}`,document.body.appendChild(h),h.click(),h.remove()}else if(d.error&&this.showJsError(d.error),d.data){const h=document.createElement("a");h.href=`data: application/zip;base64,${d.data}`,h.download=`${r}scripts.zip`,document.body.appendChild(h),h.click(),h.remove()}})}else{const c=new ww;for(const[d,h]of Object.entries(this.scripts))if(h.type==="script"){const p=h,f=p.common.engineType==="TypeScript/ts"?"ts":p.common.engineType==="Blockly"?"blockly":p.common.engineType==="Rules"?"rules":"js";let b=`/******* (ext=${f}/engine=${p.common.engine}/debug=${p.common.debug}/verbose=${p.common.verbose}/enabled=${p.common.enabled}) *******/ -`;b+=p.common.source||"";const y=`${d.substring(10).replace(/\./g,"/")}.${f}`;c.file(y,b)}c.generateAsync({type:"blob"}).then(d=>{const h=document.createElement("a");h.href=URL.createObjectURL(d),h.download=`${r}scripts_plain.zip`,document.body.appendChild(h),h.click(),h.remove(),URL.revokeObjectURL(h.href)})}}onImport(s,i){this.importFile=s||null,this.importFileName=i||null,s?(this.confirmCallback=this.onImportConfirmed.bind(this),this.setState({importFile:!1,confirm:x.I18n.t("Existing scripts will be overwritten.")})):this.setState({importFile:!1})}async onImportConfirmed(s){let i=this.importFile;const r=this.importFileName;if(this.importFile=null,this.importFileName=null,s&&i)if(r&&/_(plain|text)\.zip$/i.test(r)){i=i.split(",")[1];try{const c=await ww.loadAsync(i,{base64:!0}),d=[];c.forEach((h,p)=>{p.dir||d.push(p.async("string").then(async f=>{const b=f.split(` + await setStateAsync("${s.oidResult}", val1_${s._id} ${s.operation} val2_${s._id}, ${s.tagCard==="update"});`}renderDebug(s){var i,r;return m.jsxs("span",{children:[x.I18n.t("Set:")," ",m.jsx("span",{className:s.data.ack?(i=this.props.classes)==null?void 0:i.valueAck:(r=this.props.classes)==null?void 0:r.valueNotAck,children:Ln(s.data.val)})]})}onTagChange(){const s=[];s.push({nameRender:"renderObjectID",title:"ID1",attr:"oid1",defaultValue:"",checkReadOnly:!1}),s.push({nameRender:"renderSelect",options:[{value:"+",title:"+"},{value:"-",title:"-"},{value:"*",title:"*"},{value:"/",title:"/"}],doNotTranslate:!0,defaultValue:"+",attr:"operation"}),s.push({nameRender:"renderObjectID",title:"ID2",attr:"oid2",defaultValue:"",checkReadOnly:!1}),s.push({nameRender:"renderNameText",defaultValue:"store in",attr:"textEqual"}),s.push({nameRender:"renderObjectID",attr:"oidResult",defaultValue:"",checkReadOnly:!0}),this.setState({inputs:s},()=>super.onTagChange(null,()=>{const i=JSON.parse(JSON.stringify(this.state.settings));this.props.onChange(i)}))}onValueChanged(s,i){this.onTagChange()}onUpdate(){this.onTagChange()}static getStaticData(){return{acceptedBy:"actions",name:"Operate two states",id:"ActionOperateStates",icon:"AddBox",tagCardArray:["control","update"],title:"Operations with two states"}}getData(){return Yc.getStaticData()}}const _R=[Ii,Bc,jc,qr,Zr,Vo,Fc,zc,Uc,Hc,Wc,Gc,Vc,Yc],pc={sayit:Mc,pushover:Nc,"whatsapp-cmb":Lc,pushsafer:Pc},wR=pm({blocks:null,socket:null,onUpdate:!1,setOnUpdate:a=>{},setOnDebugMessage:a=>{},onDebugMessage:[],enableSimulation:!1,setEnableSimulation:a=>{},changedScripts:{},setChangedScripts:a=>{}}),kR=({children:a,socket:s})=>{const[i,r]=kt(null),[l,c]=kt(!1),[d,h]=kt([]),[p,f]=kt(!1),[b,y]=kt({});return Lt(()=>{l&&c(!1)},[l]),Lt(()=>{(async()=>{const w=await s.getAdapterInstances(),v=Object.keys(pc).filter(E=>w.find(D=>{var R;return((R=D==null?void 0:D.common)==null?void 0:R.name)===E})),_=[],$=w.filter(E=>E.common.javascriptRules),T=[];for(const E of $){if(T.includes(E.common.name)||!E.common.javascriptRules)continue;let D;if(E.common.javascriptRules.url.startsWith("http:")||E.common.javascriptRules.url.startsWith("https:")?D=E.common.javascriptRules.url:E.common.javascriptRules.url.startsWith("./")?D=`${window.location.protocol}//${window.location.host}${E.common.javascriptRules.url.replace(/^\./,"")}`:D=`${window.location.protocol}//${window.location.host}/adapter/${E.common.name}/${E.common.javascriptRules.url}`,E.common.javascriptRules.i18n===!0){const R=D.lastIndexOf("/");let L;R!==-1?L=D.substring(0,R):L=D;const H=x.I18n.getLanguage(),G=`${L}/i18n/${H}.json`;await fetch(G).then(z=>z.json()).then(z=>x.I18n.extendTranslations(z,H)).catch(z=>{if(H!=="en")return fetch(`${L}/i18n/en.json`).then(Z=>Z.json()).then(Z=>x.I18n.extendTranslations(Z,H)).catch(Z=>console.error(`Cannot load i18n "${G}": ${Z}`));console.log(`Cannot load i18n "${G}": ${z}`)})}else if(E.common.javascriptRules.i18n&&typeof E.common.javascriptRules.i18n=="object")try{x.I18n.extendTranslations(E.common.javascriptRules.i18n)}catch(R){console.error(`Cannot import i18n for "${E.common.javascriptRules.name}": ${R}`)}try{s_.registerRemotes([{name:E.common.javascriptRules.name,entry:D,type:E.common.javascriptRules.type}]);const R=(await s_.loadRemote(`${E.common.javascriptRules.name}/${E.common.javascriptRules.name}`)).default;R&&(_.push(R),T.push(E.common.name),pc[E.common.name]=null)}catch(R){console.error(`Cannot load component "${E.common.javascriptRules.name}": ${R}`)}}const S=v.filter(E=>pc[E]).map(E=>pc[E]);r([..._R,...S,..._])})()},[]),m.jsx(wR.Provider,{value:{blocks:i,socket:s,onUpdate:l,setOnUpdate:c,onDebugMessage:d,setOnDebugMessage:h,enableSimulation:p,setEnableSimulation:f,changedScripts:b,setChangedScripts:y},children:a})},CR="Acknowledged",TR="Actions",SR="Add",ER="All",IR="Any",xR="Apply",DR="April",AR="Ask",OR="Astronomical",RR="August",MR="Cancel",NR="Close",LR="Condition",PR="Conditions",BR="Console",jR="Copied",FR="December",zR="Default",UR="Delay",HR="Delete",WR="Description",GR="Done",VR="Exec shell",YR="Explanation",KR="Export",JR="Februar",XR="February",qR="Filter",ZR="Folder",QR="Fr",e1="Friday",t1="ID",s1="ID1",o1="ID2",i1="Import",n1="Instance",r1="Instances",a1="Instructions",l1="Januar",c1="January",u1="July",d1="June",h1="Limit",p1="March",g1="May",m1="Menu",f1="Message",$1="Mo",b1="Model",v1="Monday",y1="Month",_1="More",w1="Name",k1="November",C1="OK",T1="October",S1="Ok",E1="Pause",I1="Pushover",x1="Pushsafer",D1="Reload",A1="Rename",O1="Repeat",R1="Restart",M1="Result",N1="Sa",L1="Saturday",P1="Save",B1="Schedule",j1="Script",F1="September",z1="Simulate",U1="Stack",H1="Start",W1="State",G1="Su",V1="Sunday",Y1="Telegram",K1="Th",J1="Thursday",X1="Time",q1="Triggered",Z1="Triggers",Q1="Tu",eM="Tuesday",tM="URL",sM="Value",oM="Volume",iM="We",nM="Wednesday",rM="Write",aM="Yes",lM="acknowledgment",cM="all",uM="and",dM="Astro",hM="at",pM="control",gM="copy",mM="CRON",fM="Dawn",$M="This is a special mode in which states and objects will not change. But only information about each planned change will be displayed in the protocol.",bM="Debug",vM="Dusk",yM="easy",_M="every",wM="Function",kM="ID",CM="Name",TM="Role",SM="Room",EM="Golden hour",IM="End of golden hour",xM='The code will be executed only every time when condition is true. E.g. if triggering on the temperature sensor value and the condition is "if temperature is greater than 20°C", the "then" actions will be executed every time when sensor sends the temperature and it is over 20°C. By 21°C, by 22°C and so on.',DM='The code will be executed only if the condition result changes. E.g. if triggering on the temperature sensor value and the condition is "if temperature is greater than 20°C", the "then" actions will be executed once when temperature is over 20. Next time the "then" actions will be executed when the temperature fails under 20 and then rises over 20 again.',AM="hours",OM="includes",RM="interval",MM="magic",NM="milliseconds",LM="minutes",PM="ms",BM="Nadir",jM="Nautical dawn",FM="Nautical dusk",zM="Next Sunrise",UM="Next sunset",HM="Night",WM="Night end",GM="normal",VM="offset",YM="one",KM="or",JM="quiet",XM="search",qM="seconds",ZM="Solar noon",QM="sunrise",eN="Sunrise end",tN="Sunset",sN="Sunset start",oN="then",iN="Acknowledge",nN="From",rN="Last changed",aN="Quality",lN="Timestamp",cN="User",uN="Value",dN="two",hN="update",pN="Adds debug output to the log for many system commands",gN="Verbose log outputs",mN="when",fN="Wizard",$N="Retry",bN={"%s not found":"%s not found","()":"()","(at %s)":"(at %s)","(optional)":"(optional)","-":"-",".":".","AI code generator":"AI code generator","Planning...":"Planning...","Generating code...":"Generating code...","Show plan":"Show plan",Ack:CR,Actions:TR,"Actual time of day":"Actual time of day",Add:SR,"Add new script":"Add new script",All:ER,"All files will be accepted":"All files will be accepted",Any:IR,"Any month":"Any month",Apply:xR,April:DR,"Are you sure?":"Are you sure?",Ask:AR,Astronomical:OR,"Astronomical events today":"Astronomical events today",August:RR,"Blockly description":"Creating rules by graphic blocks","Body:":"Body:",Cancel:MR,"Cannot delete non empty item!":"Cannot delete non empty item!","Change layout":"Change layout",'Change theme (actual "%s")':'Change theme (now - "%s")',"Check blocks":"Check blocks","Check is not active, because javascript adapter is disabled":"Check is not active, because Javascript adapter is disabled","Clear search input":"Clear search input","Click on this icon":"Click on this icon",Close:NR,"Close all but current":"Close all but current","Collapse all":"Collapse all","Compares current time with astronomical event":"Compares current time with astronomical event","Compares current time with the user specific time":"Compares current time with the user specific time","Compares the state value with user defined value":"Compares the state value with user defined value",Condition:LR,Conditions:PR,"Configuration not saved.":"Configuration not saved.",Console:BR,"Control or update some state":"Control or update some state","Control or update some state with delay":"Control or update some state with delay","Convert blockly to javascript for ever.":"Permanently convert Blockly to Javascript.",Copied:jR,"Copy script":"Copy script","Copy to clipboard":"Copy to clipboard","Create new":"Create new","Create new folder":"Create new folder","Create new script":"Create new script","Create or edit CRON or time wizard":"Create or edit CRON or time wizard","Dark Theme":"Dark theme","Dark style":"Dark style",Date:"Date","Debug instance":"Debug instance","Debug options":"Debug options",December:FR,Default:zR,"Define cron...":"Define cron...","Define schedule...":"Define schedule...",Delay:UR,Delete:HR,"Delete %s":"Delete %s...","Delete folder":"Delete folder","Delete script":"Delete script",Description:WR,"Deselect all":"Deselect all","Discard changes for %s":"Discard changes for %s",Done:GR,"Double click to write value":"Double click to write value","Download as file":"Download as file","Drop some files here or click...":"Drop some files here or click...","Duplicate name":"Duplicate name","Edit script or just double click":"Edit script or just double click","Empty name is not allowed":"Empty name is not allowed","End search mode":"End search mode","Enter your question":"Enter your request",Error:"Error","Error formatting code":"Error formatting code","Error was found":"Error was found","Every day":"Every day",Exec:VR,"Executes some shell command":"Executes some shell command","Existing scripts will be overwritten.":"Existing scripts will be overwritten.","Expand all":"Expand all","Expert mode":"Expert mode",Explanation:YR,Export:KR,"Export all scripts":"Export all scripts","Export blocks":"Export blocks","Export selected blocks":"Export selected blocks",Februar:JR,February:XR,Filter:qR,Folder:ZR,Fr:QR,Friday:e1,Function:"Function","Function editor":"Function editor","Function: executed":"Function: executed","Go to next line":"Go to next line","HTTP Call":"HTTP Call","Hide logs":"Hide logs",ID:t1,ID1:s1,ID2:o1,Import:i1,"Import blocks":"Import blocks","Import error":"Import error","Import scripts":"Import scripts","Insert object ID":"Insert object ID",Instance:n1,"Instance is disabled":"Instance is disabled","Instance:":"Instance:",Instances:r1,Instructions:a1,"Invalid CRON":"Invalid CRON","It will not be possible to revert this operation.":"It will not be possible to revert this operation.","JS description":"Creating rules by writing Javascript",Januar:l1,January:c1,July:u1,June:d1,"Just check":"Just check","Keep my changes":"Keep my changes","Language:":"Language:","Learn More":"Learn More","Light style":"Light style",Limit:h1,"Local time":"Local time","Locate file":"Locate file","Log outputs":"Log outputs","Log text":"Log text","Log: %s":"Log: %s","Make a HTTP get request":"Make a HTTP get request","Make a pause between actions":"Make a pause between actions",March:p1,"March ":"March ",May:g1,Menu:m1,Message:f1,Mo:$1,Model:b1,Monday:v1,Month:y1,More:_1,Name:w1,"No API key found":"No API key found","No Chat GPT Key found":"No Chat GPT Key found","No active host found":"No active host found","Nothing found":"Nothing found",November:k1,OK:C1,October:T1,Ok:S1,"On condition change":"On condition result change","On script save or adapter start":"On script save or adapter start","On weekdays":"On weekdays","Open configuration":"Open configuration","Operate two states":"Operate two states","Operations with two states":"Operations with two states","Paste your blocks here":"Paste your blocks here",Pause:E1,"Pause execution":"Pause execution","Pause script":"Pause script","Phone:":"Phone:","Please select object ID...":"Please select object ID...","Press Ctrl+Enter to get the answer":"Press Ctrl+Enter to get the answer","Prettify the script":"Prettify the script","Print some text in log":"Print some text in log","Priority:":"Priority:",Pushover:I1,Pushsafer:x1,"Read only ID selected: %s":"Read only ID selected: %s",Reload:D1,Rename:A1,"Reorder scripts in folders":"Reorder scripts in folders",Repeat:O1,Restart:R1,Result:M1,"Resume execution":"Resume execution","Root folder":"Root folder","Rules description":"Create rules with IF, THEN, ELSE blocks","Run script":"Run script",Sa:N1,Saturday:L1,Save:P1,"Save all":"Save all","Say It":"Say It","Say some text via sayit adapter":"Say some text via sayit adapter",Schedule:B1,Script:j1,"Script %s was modified on disk":"Script %s was modified on disk","Script was modified externally":"Script was modified externally","Script is not running":"Script is not running","Search in scripts":"Search in scripts","Search...":"Search...","Select all":"Select all","Send email":"Send email","Sends an email":"Sends an email","Sends message via Pushsafer":"Sends message via Pushsafer","Sends message via pushover":"Sends message via pushover","Sends message via telegram":"Sends message via telegram","Sends message via whatsapp-cmb":"Sends message via whatsapp-cmb",September:F1,"Server time":"Server time","Set state action":"Set state action","Set with delay":"Set with delay","Shell command":"Shell command","Show astronomical events":"Show astronomical events","Show javascript code":"Show Javascript code","Show logs":"Show logs","Show only paused scripts":"Show only paused scripts","Show only running scripts":"Show only running scripts","Show only scripts with problems":"Show only scripts with problems",Simulate:z1,"Some files will be rejected":"Some files will be rejected","Sound:":"Sound:",Stack:U1,Start:H1,"Start script":"Start script",State:W1,"State condition":"State condition","Step into function":"Step into function","Step out from function":"Step out from function","Stop on exception":"Stop on exception",Su:G1,"Subject:":"Subject:",Sunday:V1,"TS description":"Creating rules by writing Typescript",Telegram:Y1,"Text:":"Text:",Th:K1,'The script "%s" has been modified by another user or in another window. Do you want to reload the script or keep your local changes?':'The script "%s" has been modified by another user or in another window. Do you want to reload the script or keep your local changes?',"The script will be stopped and must be activated manually after debugging. Continue?":"The script will be stopped and must be activated manually after debugging. Continue?","This is advances option. You can write your own code here and it will be executed on trigger":"This is advances option. You can write your own code here and it will be executed on trigger",Thursday:J1,Time:X1,"Time condition":"Time condition","Title:":"Title:","To:":"To:","Trigger with value":"Trigger with value",Triggered:q1,Triggers:Z1,"Triggers the on script saving or the javascript instance restart":"Triggers the on script saving or the javascript instance restart","Triggers the rule on update or change of some state":"Triggers the rule on update or change of some state","Triggers the rule periodically or on some specific time":"Triggers the rule periodically or on some specific time",Tu:Q1,Tuesday:eM,URL:tM,"Unknown error":"Unknown error","Unknown error!":"Unknown error!","Use generated code":"Use generated code","User function":"User function","User:":"User:",Value:sM,"Vibration:":"Vibration:",Volume:oM,We:iM,Wednesday:nM,"Whatsapp-cmb":"Whatsapp-cmb",Write:rM,"Write your own code":"Write your own code",Yes:aM,"Yet exists!":"Yet exists!","You can use %s in the URL to use current trigger value or %id to use the triggered object ID":"You can use %s in the URL to use current trigger value, %id to use the triggered object ID, %name to show triggered object ID name or %old to use old trigger value","You can use %s in the command to use current trigger value or %id to use the triggered object ID":"You can use %s in the command to use current trigger value, %id to use the triggered object ID, %name to show triggered object ID name or %old to use old trigger value","You can use %s in the text to display current trigger value or %id to display the triggered object ID":"You can use %s in the text to display current trigger value, %id to use the triggered object ID, %name to show triggered object ID name or %old to use old trigger value","You can use %s in the value to use the current trigger value or %id to display the triggered object ID":"You can use %s in the value to use the current trigger value, %id to use the triggered object ID, %name to show triggered object ID name or %old to use old trigger value","You have to enter OpenAI API key in the configuration of javascript adapter.":"You have to enter OpenAI API key in the configuration of javascript adapter.","You have to enter at least one API key in the configuration of javascript adapter.":"You have to enter at least one API key (OpenAI, Anthropic or Gemini) in the configuration of javascript adapter.","Please select a valid model":"Please select a valid model","[equal]":"[equal]","[greater or equal]":"[greater or equal]","[greater]":"[greater]","[hysteresis]":"[hysteresis]","[includes]":"[includes]","[less or equal]":"[less or equal]","[less]":"[less]","[not equal]":"[not equal]",acknowledgment:lM,all:cM,and:uM,"as JSON":"as JSON","as plain text":"as plain text",astro:dM,at:hM,"clear running":"clear running",control:pM,copy:gM,cron:mM,dawn:fM,debug_help:$M,debug_label:bM,default:"default",dusk:vM,easy:yM,else:"else","equal to":"equal to",every:_M,"every hour at 0 minutes":"every hour at 0 minutes",false:"false","file reading has failed: %s":"file reading has failed: %s","file reading was aborted":"file reading was aborted",filter_func:wM,filter_id:kM,filter_name:CM,filter_role:TM,filter_room:SM,"for edit or create script":"for edit or create a new script","for professionals":"for professionals","for programmers":"for programmers",goldenHour:EM,goldenHourEnd:IM,"greater or equal":"greater or equal","greater or equal to":"greater or equal to","greater than":"greater than",help_just_check:xM,help_on_change:DM,"high priority":"high priority","high-priority":"high-priority","highest priority":"highest priority",hours:AM,includes:OM,interval:RM,"just check":"just check","less or equal":"less or equal","less or equal to":"less or equal to","less than":"less than","lower priority":"lower priority","lowest priority":"lowest priority",magic:MM,milliseconds:NM,minutes:LM,ms:PM,nadir:BM,nauticalDawn:jM,nauticalDusk:FM,nextSunrise:zM,nextSunset:UM,night:HM,nightEnd:WM,"no blocks found":"No blocks found","no group":"NO GROUP",normal:GM,"normal priority":"normal priority","not running":"not running","not equal to":"not equal to","not properly connected":"This block is not properly connected to other blocks.",offset:VM,"on change":"on change","on condition change":"on condition change","on update":"on update",one:YM,or:KM,quiet:JM,"reset search":"reset search",search:XM,seconds:qM,solarNoon:ZM,"store in":"store in",sunrise:QM,sunriseEnd:eN,sunset:tN,sunsetStart:sN,then:oN,"toggle value":"toggle value",tooltip_ack:iN,tooltip_from:nN,tooltip_lc:rN,tooltip_quality:aN,tooltip_ts:lN,tooltip_user:cN,tooltip_value:uN,true:"true",two:dN,undefined:"undefined",update:hN,"use seconds":"use seconds","use trigger value":"use trigger value",verbose_help:pN,verbose_label:gN,when:mN,with:"with","with date":"with date","with offset":"with offset",wizard:fN,"Loading models...":"Loading models...","Could not connect to API at %s":"Could not connect to API at %s","Invalid API key":"Invalid API key","Access denied by API":"Access denied by API","API error: %s":"API error: %s",'Model "%s" not found':'Model "%s" not found',"Request failed: %s":"Request failed: %s",Retry:$N,"No running javascript instance found":"No running javascript instance found","OID display mode":"OID display mode"},vN="Bestätigt",yN="Aktionen",_N="Hinzufügen",wN="Alle",kN="Egal",CN="Anwenden",TN="April",SN="Fragen",EN="Astronomisch",IN="August",xN="Abbrechen",DN="Schließen",AN="Bedingung",ON="Bedingungen",RN="Konsole",MN="Kopiert",NN="Dezember",LN="Standard",PN="Verzögerung",BN="Löschen",jN="Beschreibung",FN="Fertig",zN="Exec shell",UN="Erläuterung",HN="Export",WN="Februar",GN="Februar",VN="Filter",YN="Ordner",KN="Fr",JN="Freitag",XN="ID",qN="ID1",ZN="ID2",QN="Import",eL="Instanz",tL="Instanzen",sL="Anleitung",oL="Januar",iL="Januar",nL="Juli",rL="Juni",aL="Grenze",lL="März",cL="Mai",uL="Menü",dL="Nachricht",hL="Mo",pL="Modell",gL="Montag",mL="Monat",fL="Mehr",$L="Name",bL="November",vL="OK",yL="Oktober",_L="Ok",wL="Pause",kL="Pushover",CL="Pushsafer",TL="Neu laden",SL="Umbenennen",EL="Wiederholen",IL="Neustart",xL="Ergebnis",DL="Sa",AL="Samstag",OL="Speichern",RL="Zeitplan",ML="Skript",NL="September",LL="Simulieren",PL="Stack",BL="Start",jL="Zustand",FL="So",zL="Sonntag",UL="Telegram",HL="Do",WL="Donnerstag",GL="Zeit",VL="Ausgelöst",YL="Löst aus",KL="Di",JL="Dienstag",XL="URL",qL="Wert",ZL="Volumen",QL="Mi",eP="Mittwoch",tP="Schreiben",sP="Ja",oP="Wissen",iP="alle",nP="und",rP="Astro",aP="um",lP="Steuerung",cP="Kopie",uP="CRON",dP="Morgendämmerung",hP="Dies ist ein spezieller Modus, in dem sich Zustände und Objekte nicht ändern. Im Protokoll werden jedoch nur Informationen zu jeder geplanten Änderung angezeigt.",pP="Debuggen",gP="Abenddämmerung",mP="einfach",fP="jeder",$P="Funktion",bP="ID",vP="Name",yP="Rolle",_P="Raum",wP="Goldene Abendstunde",kP="Vormittag",CP='Der Code wird jedes Mal ausgeführt, wenn die Bedingung erfüllt ist. z.B. wenn der Temperatur wert sich ändert und die Bedingung "Wenn die Temperatur größer als 20°C ist" lautet, werden die "Dann" -Aktionen jedes Mal ausgeführt, wenn der Sensor die Temperatur sendet und diese über 20°C liegt. Bei 21°C, bei 22°C und so weiter.',TP='Der Code wird nur ausgeführt, wenn sich das Ergebnis der Bedingung ändert. z.B. wenn sich der Temperatur wert ändert und die Bedingung "Wenn die Temperatur größer als 20°C ist" lautet, werden die "Dann" -Aktionen einmal ausgeführt, wenn die Temperatur über 20°C liegt. Das nächste Mal werden die "Dann" -Aktionen ausgeführt, wenn die Temperatur unter 20°C gefallen ist und dann wieder über 20°C ansteigt.',SP="Stunden",EP="beinhaltet",IP="Intervall",xP="Magie",DP="Millisekunden",AP="Minuten",OP="ms",RP="Nadir",MP="nautische Morgendämmerung",NP="nautische Abenddämmerung",LP="Nächster Sonnenaufgang",PP="Nächster Sonnenuntergang",BP="Nacht",jP="astronomische Morgendämmerung",FP="Normal",zP="Versatz",UP="einer",HP="oder",WP="ruhig",GP="Suche",VP="Sekunden",YP="(Nach-)Mittag",KP="Sonnenaufgang",JP="Goldene Morgenstunde",XP="Sonnenuntergang",qP="Sonnenuntergang (Anfang)",ZP="dann",QP="Bestätigen",eB="Von",tB="Zuletzt geändert",sB="Qualität",oB="Zeitstempel",iB="Benutzer",nB="Wert",rB="zwei",aB="Aktualisieren",lB="Fügt Debug-Ausgaben für viele Systembefehle zum Protokoll hinzu",cB="Ausführliche Protokollausgaben",uB="falls",dB="Assistent",hB="Erneut versuchen",pB={"%s not found":"%s nicht gefunden","()":"()","(at %s)":"(um %s)","(optional)":"(optional)","-":"-",".":".","AI code generator":"KI-Codegenerator","Planning...":"Plane...","Generating code...":"Generiere Code...","Show plan":"Plan anzeigen",Ack:vN,Actions:yN,"Actual time of day":"Tatsächliche Tageszeit",Add:_N,"Add new script":"Neues Skript hinzufügen",All:wN,"All files will be accepted":"Alle Dateien werden akzeptiert",Any:kN,"Any month":"Jeden Monat",Apply:CN,April:TN,"Are you sure?":"Wirklich sicher?",Ask:SN,Astronomical:EN,"Astronomical events today":"Astronomische Ereignisse heute",August:IN,"Blockly description":"Erstellen von Regeln durch Grafikblöcke","Body:":"Körper:",Cancel:xN,"Cannot delete non empty item!":"Kann nicht gelöscht werden, weil noch einige Elementen darin sind!","Change layout":"Layout ändern",'Change theme (actual "%s")':'Thema ändern (jetzt - "%s")',"Check blocks":"Blöcke prüfen","Check is not active, because javascript adapter is disabled":"Syntax-Check ist nicht aktiv, weil der Javascript Adapter nicht aktiv ist.","Clear search input":"Sucheingabe löschen","Click on this icon":"Auf dieses Symbol klicken",Close:DN,"Close all but current":"Alle anderen außer dem Aktiven schließen","Collapse all":"Alles einklappen","Compares current time with astronomical event":"Vergleicht die aktuelle Zeit mit einem astronomischen Ereignis","Compares current time with the user specific time":"Vergleicht die aktuelle Zeit mit der benutzerspezifischen Zeit","Compares the state value with user defined value":"Vergleicht den Zustandswert mit dem benutzerdefinierten Wert",Condition:AN,Conditions:ON,"Configuration not saved.":"Die Konfiguration ist nicht gespeichert.",Console:RN,"Control or update some state":"Zustand steuern oder aktualisieren","Control or update some state with delay":"Zustand mit Verzögerung steuern oder aktualisieren","Convert blockly to javascript for ever.":"Blockly dauerhaft in Javascript konvertieren.",Copied:MN,"Copy script":"Skript kopieren","Copy to clipboard":"In die Zwischenablage kopieren","Create new":"Neu erstellen","Create new folder":"Neuen Ordner erstellen","Create new script":"Neues Skript erstellen","Create or edit CRON or time wizard":"CRON- oder Zeit-Assistenten erstellen oder bearbeiten","Dark Theme":"Dunkles Thema","Dark style":"Dunkler Stil",Date:"Datum","Debug instance":"Debug-Instanz","Debug options":"Debug-Optionen",December:NN,Default:LN,"Define cron...":"Cron definieren ...","Define schedule...":"Zeitplan definieren ...",Delay:PN,Delete:BN,"Delete %s":"Löschen %s...","Delete folder":"Ordner löschen","Delete script":"Skript löschen",Description:jN,"Deselect all":"Alles abwählen","Discard changes for %s":"Änderungen für %s verwerfen",Done:FN,"Double click to write value":"Doppelklick zum Schreiben des Wertes","Download as file":"Download als Datei","Drop some files here or click...":"Dateien hier ablegen oder klicken ...","Duplicate name":"Doppelter Name","Edit script or just double click":"Skript bearbeiten oder einfach doppelklicken","Empty name is not allowed":"Leerer Name ist nicht zulässig","End search mode":"Suchmodus beenden","Enter your question":"Anfrage eingeben",Error:"Fehler","Error formatting code":"Fehler beim Formatieren des Codes","Error was found":"Fehler wurde gefunden","Every day":"Täglich",Exec:zN,"Executes some shell command":"Führt einen Shell-Befehl aus","Existing scripts will be overwritten.":"Vorhandene Skripte werden überschrieben.","Expand all":"Alle erweitern","Expert mode":"Expertenmodus",Explanation:UN,Export:HN,"Export all scripts":"Alle Skripte exportieren","Export blocks":"Blöcke exportieren","Export selected blocks":"Ausgewählte Blöcke exportieren",Februar:WN,February:GN,Filter:VN,Folder:YN,Fr:KN,Friday:JN,Function:"Funktion","Function editor":"Funktions-Editor","Function: executed":"Funktion: ausgeführt","Go to next line":"Gehe zur nächsten Zeile","HTTP Call":"HTTP-Aufruf","Hide logs":"Protokoll ausblenden",ID:XN,ID1:qN,ID2:ZN,Import:QN,"Import blocks":"Blöcke importieren","Import error":"Fehler beim Importieren","Import scripts":"Skripte importieren","Insert object ID":"Objekt-ID einfügen",Instance:eL,"Instance is disabled":"Instanz ist deaktiviert","Instance:":"Instanz:",Instances:tL,Instructions:sL,"Invalid CRON":"Ungültiger CRON","It will not be possible to revert this operation.":"Dieser Vorgang kann nicht rückgängig gemacht werden.","JS description":"Regeln erstellen mit JavaScript",Januar:oL,January:iL,July:nL,June:rL,"Just check":"Einfach überprüfen","Keep my changes":"Meine Änderungen behalten","Language:":"Sprache:","Learn More":"Mehr erfahren","Light style":"Heller Stil",Limit:aL,"Local time":"Lokale Zeit","Locate file":"Datei zeigen","Log outputs":"Protokoll","Log text":"Protokolltext","Log: %s":"Log: %s","Make a HTTP get request":"Eine HTTP-Abrufanforderung stellen","Make a pause between actions":"Eine Pause zwischen den Aktionen machen",March:lL,"March ":"März ",May:cL,Menu:uL,Message:dL,Mo:hL,Model:pL,Monday:gL,Month:mL,More:fL,Name:$L,"No API key found":"Kein API-Schlüssel gefunden","No Chat GPT Key found":"Kein Chat-GPT-Schlüssel gefunden","No active host found":"Kein aktiver Host gefunden","Nothing found":"Nichts gefunden",November:bL,OK:vL,October:yL,Ok:_L,"On condition change":"Bei Änderung des Ergebnis der Bedingung","On script save or adapter start":"Beim Speichern des Skripts oder beim Starten des Adapters","On weekdays":"An Wochentagen","Open configuration":"Konfiguration öffnen","Operate two states":"Zwei Zustände operieren","Operations with two states":"Operationen mit zwei Zuständen","Paste your blocks here":"Fügen Sie Ihre Blöcke hier ein",Pause:wL,"Pause execution":"Ausführung pausieren","Pause script":"Skript anhalten","Phone:":"Telefon:","Please select object ID...":"Objekt-ID auswählen ...","Press Ctrl+Enter to get the answer":"Strg+Eingabetaste, um die Antwort zu erhalten","Prettify the script":"Verschönern Sie das Skript","Print some text in log":"Einen Text im Protokoll ausdrucken","Priority:":"Priorität:",Pushover:kL,Pushsafer:CL,"Read only ID selected: %s":"Schreibgeschützte ID ausgewählt: %s",Reload:TL,Rename:SL,"Reorder scripts in folders":"Skripte in Ordnern neu ordnen",Repeat:EL,Restart:IL,Result:xL,"Resume execution":"Ausführung fortsetzen","Root folder":"Root-Verzeichnis","Rules description":"Regeln erstellen mit WENN-, DANN- und SONST-Blöcken","Run script":"Skript ausführen",Sa:DL,Saturday:AL,Save:OL,"Save all":"Alle speichern","Say It":"Say It","Say some text via sayit adapter":"Einen Text über den Sayit-Adapter sagen",Schedule:RL,Script:ML,"Script %s was modified on disk":'Skript "%s" wurde auf der Festplatte geändert',"Script was modified externally":"Skript wurde extern geändert","Script is not running":"Skript läuft nicht","Search in scripts":"Suche in Skripten","Search...":"Suche...","Select all":"Alles auswählen","Send email":"E-Mail senden","Sends an email":"Sendet eine E-Mail","Sends message via Pushsafer":"Sendet eine Nachricht über Pushsafer","Sends message via pushover":"Sendet eine Nachricht per Pushover","Sends message via telegram":"Sendet eine Nachricht per telegram","Sends message via whatsapp-cmb":"Sendet eine Nachricht über WhatsApp-Cmb",September:NL,"Server time":"Server-Zeit","Set state action":"Zustand setzten","Set with delay":"Setzen mit Verzögerung","Shell command":"Shell-Befehl","Show astronomical events":"Astronomische Ereignisse anzeigen","Show javascript code":"Javascript-Code zeigen","Show logs":"Protokoll anzeigen","Show only paused scripts":"Nur angehaltene Skripte zeigen","Show only running scripts":"Nur laufende Skripte zeigen","Show only scripts with problems":"Nur Skripte mit Problemen zeigen",Simulate:LL,"Some files will be rejected":"Einige Dateien werden abgelehnt","Sound:":"Klang:",Stack:PL,Start:BL,"Start script":"Skript starten",State:jL,"State condition":"Zustandsbedingung","Step into function":"Schritt in die Funktion","Step out from function":"Raus aus der Funktion","Stop on exception":"Bei Ausnahme anhalten",Su:FL,"Subject:":"Gegenstand:",Sunday:zL,"TS description":"Regeln erstellen mit TypeScript",Telegram:UL,"Text:":"Text:",Th:HL,'The script "%s" has been modified by another user or in another window. Do you want to reload the script or keep your local changes?':'Das Skript "%s" wurde von einem anderen Benutzer oder in einem anderen Fenster geändert. Möchten Sie das Skript neu laden oder Ihre lokalen Änderungen behalten?',"The script will be stopped and must be activated manually after debugging. Continue?":"Das Skript wird gestoppt und muss nach dem Debuggen manuell aktiviert werden. Fortsetzen?","This is advances option. You can write your own code here and it will be executed on trigger":"Dies ist eine erweiterte Option. Sie können hier Ihren eigenen Code schreiben, der beim Auslösen ausgeführt wird",Thursday:WL,Time:GL,"Time condition":"Zeitbedingung","Title:":"Titel:","To:":"Zu:","Trigger with value":"Trigger mit Wert",Triggered:VL,Triggers:YL,"Triggers the on script saving or the javascript instance restart":"Löst das Speichern des Skripts oder den Neustart der Javascript-Instanz aus","Triggers the rule on update or change of some state":"Löst die Regel beim Aktualisieren oder Ändern eines Zustands aus","Triggers the rule periodically or on some specific time":"Löst periodisch oder zu einem bestimmten Zeitpunkt aus",Tu:KL,Tuesday:JL,URL:XL,"Unknown error":"Unbekannter Fehler","Unknown error!":"Unbekannter Fehler!","Use generated code":"Code verwenden","User function":"Benutzerfunktion","User:":"Benutzer:",Value:qL,"Vibration:":"Vibration:",Volume:ZL,We:QL,Wednesday:eP,"Whatsapp-cmb":"WhatsApp-cmb",Write:tP,"Write your own code":"Eigenen Code schreiben",Yes:sP,"Yet exists!":"Existiert schon!","You can use %s in the URL to use current trigger value or %id to use the triggered object ID":"Sie können %s in der URL verwenden, um den aktuellen Triggerwert zu verwenden, %id, um die ausgelöste Objekt-ID zu verwenden, %name, um den ID-Namen des ausgelösten Objekts anzuzeigen, oder %old, um den alten Triggerwert zu verwenden","You can use %s in the command to use current trigger value or %id to use the triggered object ID":"Sie können %s im Befehl verwenden, um den aktuellen Triggerwert zu verwenden, %id, um die ausgelöste Objekt-ID zu verwenden, %name, um den ID-Namen des ausgelösten Objekts anzuzeigen, oder %old, um den alten Triggerwert zu verwenden","You can use %s in the text to display current trigger value or %id to display the triggered object ID":"Sie können %s im Text verwenden, um den aktuellen Triggerwert anzuzeigen, %id, um die ausgelöste Objekt-ID zu verwenden, %name, um den ID-Namen des ausgelösten Objekts anzuzeigen, oder %old, um den alten Triggerwert zu verwenden","You can use %s in the value to use the current trigger value or %id to display the triggered object ID":"Sie können %s im Wert verwenden, um den aktuellen Triggerwert zu verwenden, %id, um die ID des ausgelösten Objekts zu verwenden, %name, um den ID-Namen des ausgelösten Objekts anzuzeigen, oder %old, um den alten Triggerwert zu verwenden","You have to enter OpenAI API key in the configuration of javascript adapter.":"Sie müssen den OpenAI-API-Schlüssel in der Konfiguration des Javascript-Adapters eingeben.","You have to enter at least one API key in the configuration of javascript adapter.":"Sie müssen mindestens einen API-Schlüssel (OpenAI, Anthropic oder Gemini) in der Konfiguration des Javascript-Adapters eingeben.","Please select a valid model":"Bitte wählen Sie ein gültiges Modell aus","[equal]":"[gleich]","[greater or equal]":"[größer oder gleich]","[greater]":"[größer]","[hysteresis]":"[Hysterese]","[includes]":"[enthält]","[less or equal]":"[kleiner oder gleich]","[less]":"[kleiner]","[not equal]":"[ungleich]",acknowledgment:oP,all:iP,and:nP,"as JSON":"als JSON","as plain text":"als Klartext",astro:rP,at:aP,"clear running":"laufende abbrechen",control:lP,copy:cP,cron:uP,dawn:dP,debug_help:hP,debug_label:pP,default:"Standard",dusk:gP,easy:mP,else:"sonst","equal to":"gleich",every:fP,"every hour at 0 minutes":"jede Stunde bei 0 Minuten",false:"falsch","file reading has failed: %s":"Das Lesen der Datei ist fehlgeschlagen: %s","file reading was aborted":"Das Lesen der Datei wurde abgebrochen",filter_func:$P,filter_id:bP,filter_name:vP,filter_role:yP,filter_room:_P,"for edit or create script":"zum Bearbeiten oder zum Erstellen eines neues Skripts","for professionals":"für Profis","for programmers":"für Programmierer",goldenHour:wP,goldenHourEnd:kP,"greater or equal":"größer oder gleich","greater or equal to":"größer oder gleich","greater than":"größer als",help_just_check:CP,help_on_change:TP,"high priority":"hohe Priorität","high-priority":"hohe Priorität","highest priority":"höchste Priorität",hours:SP,includes:EP,interval:IP,"just check":"einfach prüfen","less or equal":"kleiner oder gleich","less or equal to":"kleiner oder gleich","less than":"kleiner als","lower priority":"geringere Priorität","lowest priority":"niedrigste Priorität",magic:xP,milliseconds:DP,minutes:AP,ms:OP,nadir:RP,nauticalDawn:MP,nauticalDusk:NP,nextSunrise:LP,nextSunset:PP,night:BP,nightEnd:jP,"no blocks found":"Keine Blöcke gefunden","no group":"KEINE GRUPPE",normal:FP,"normal priority":"normale Priorität","not running":"nicht gestartet","not equal to":"ungleich","not properly connected":"Dieser Block ist mit anderen nicht richtig verbunden.",offset:zP,"on change":"bei Änderung","on condition change":"bei Zustandsänderung","on update":"beim Aktualisieren",one:UP,or:HP,quiet:WP,"reset search":"Suche zurücksetzen",search:GP,seconds:VP,solarNoon:YP,"store in":"speichern in",sunrise:KP,sunriseEnd:JP,sunset:XP,sunsetStart:qP,then:ZP,"toggle value":"Wert umschalten",tooltip_ack:QP,tooltip_from:eB,tooltip_lc:tB,tooltip_quality:sB,tooltip_ts:oB,tooltip_user:iB,tooltip_value:nB,true:"wahr",two:rB,undefined:"nicht definiert",update:aB,"use seconds":"Sekunden verwenden","use trigger value":"Triggerwert benutzen",verbose_help:lB,verbose_label:cB,when:uB,with:"mit","with date":"mit Datum","with offset":"mit Versatz",wizard:dB,"Loading models...":"Modelle werden geladen...","Could not connect to API at %s":"Verbindung zur API unter %s nicht möglich","Invalid API key":"Ungültiger API-Schlüssel","Access denied by API":"Zugriff von der API verweigert","API error: %s":"API-Fehler: %s",'Model "%s" not found':'Modell "%s" nicht gefunden',"Request failed: %s":"Anfrage fehlgeschlagen: %s",Retry:hB,"No running javascript instance found":"Keine laufende JavaScript-Instanz gefunden","OID display mode":"OID-Anzeigemodus"},gB="Admitido",mB="Comportamiento",fB="Añadir",$B="Todos",bB="Alguna",vB="Apply",yB="abril",_B="Preguntar",wB="Astronómico",kB="agosto",CB="Cancelar",TB="Cerrar",SB="Condición",EB="Condiciones",IB="Consola",xB="Copiado",DB="diciembre",AB="Defecto",OB="Demora",RB="Eliminar",MB="Descripción",NB="Hecho",LB="Ejecutivo shell",PB="Explicación",BB="Exportar",jB="Februar",FB="febrero",zB="Filtrar",UB="Carpeta",HB="P.",WB="viernes",GB="CARNÉ DE IDENTIDAD",VB="ID1",YB="ID2",KB="Importar",JB="Ejemplo",XB="Instancias",qB="Instrucciones",ZB="Enero",QB="enero",e2="julio",t2="junio",s2="Límite",o2="marzo",i2="Mayo",n2="Menú",r2="Mensaje",a2="Mes",l2="Modelo",c2="lunes",u2="Mes",d2="Más",h2="Nombre",p2="noviembre",g2="OK",m2="octubre",f2="Okay",$2="Pausa",b2="Persona fácil de convencer",v2="Pushsafer",y2="Recargar",_2="Rebautizar",w2="Repetir",k2="Reiniciar",C2="Resultado",T2="Sa",S2="sábado",E2="Salvar",I2="Calendario",x2="Guión",D2="septiembre",A2="Simular",O2="Stack",R2="Comienzo",M2="Expresar",N2="Su",L2="domingo",P2="Telegrama",B2="4",j2="jueves",F2="Tiempo",z2="Motivado",U2="Disparadores",H2="Tu",W2="martes",G2="URL",V2="Valor",Y2="Volumen",K2="3",J2="miércoles",X2="Escribir",q2="sí",Z2="Reconocimiento",Q2="todos",ej="y",tj="astro",sj="a",oj="control",ij="Copiar",nj="CRON",rj="Amanecer",aj="Este es un modo especial en el que los estados y los objetos no cambiarán. Pero solo se mostrará información sobre cada cambio planificado en el protocolo.",lj="Depurar",cj="Oscuridad",uj="fácil",dj="cada",hj="Función",pj="CARNÉ DE IDENTIDAD",gj="Nombre",mj="Papel",fj="Habitación",$j="hora dorada",bj="Fin de la hora dorada",vj='El código se ejecutará solo cada vez que la condición sea verdadera. P.ej. si se activa en el valor del sensor de temperatura y la condición es "si la temperatura es superior a 20 ° C", las acciones "entonces" se ejecutarán cada vez que el sensor envíe la temperatura y supere los 20 ° C. Por 21 ° C, por 22 ° C y así sucesivamente.',yj='El código se ejecutará solo si cambia el resultado de la condición. P.ej. si se activa en el valor del sensor de temperatura y la condición es "si la temperatura es superior a 20 ° C", las acciones "entonces" se ejecutarán una vez cuando la temperatura sea superior a 20. La próxima vez, las acciones "entonces" se ejecutarán cuando la temperatura falla por debajo de 20 y luego sube por encima de 20 nuevamente.',_j="horas",wj="incluye",kj="intervalo",Cj="magia",Tj="milisegundos",Sj="minutos",Ej="ms",Ij="nadir",xj="Amanecer náutico",Dj="Atardecer náutico",Aj="próximo amanecer",Oj="Próxima puesta de sol",Rj="Noche",Mj="Fin de la noche",Nj="normal",Lj="compensar",Pj="uno",Bj="o",jj="tranquilo",Fj="buscar",zj="segundos",Uj="Mediodía solar",Hj="amanecer",Wj="Final del amanecer",Gj="puesta de sol",Vj="Inicio al atardecer",Yj="entonces",Kj="Reconocer",Jj="De",Xj="Último cambio",qj="Calidad",Zj="Marca de tiempo",Qj="Usuario",eF="Valor",tF="dos",sF="actualizar",oF="Agrega salida de depuración al registro para muchos comandos del sistema",iF="Salidas de registro detalladas",nF="cuando",rF="Wizard",aF="Reintentar",lF={"%s not found":"%s no encontrado","()":"()","(at %s)":"(en %s)","(optional)":"(Opcional)","-":"-",".":".","AI code generator":"Generador de código de IA","Planning...":"Planificando...","Generating code...":"Generando código...","Show plan":"Mostrar plan",Ack:gB,Actions:mB,"Actual time of day":"Hora real del día",Add:fB,"Add new script":"Agregar nuevo script",All:$B,"All files will be accepted":"Todos los archivos serán aceptados.",Any:bB,"Any month":"Cualquier mes",Apply:vB,April:yB,"Are you sure?":"¿Estás seguro?",Ask:_B,Astronomical:wB,"Astronomical events today":"Eventos astronómicos hoy",August:kB,"Blockly description":"Crear reglas por bloques gráficos","Body:":"Cuerpo:",Cancel:CB,"Cannot delete non empty item!":"¡No se puede eliminar un elemento no vacío!","Change layout":"Cambia el diseño",'Change theme (actual "%s")':'Cambiar tema (ahora - "%s")',"Check blocks":"Comprobar bloques","Check is not active, because javascript adapter is disabled":"La comprobación no está activa porque el adaptador Javascript está desactivado","Clear search input":"Borrar entrada de búsqueda","Click on this icon":"Haga clic en este ícono",Close:TB,"Close all but current":"Cerrar todo menos el actual","Collapse all":"Desplegar todo","Compares current time with astronomical event":"Compara la hora actual con un evento astronómico","Compares current time with the user specific time":"Compara la hora actual con la hora específica del usuario","Compares the state value with user defined value":"Compara el valor del estado con el valor definido por el usuario",Condition:SB,Conditions:EB,"Configuration not saved.":"Configuración no guardada.",Console:IB,"Control or update some state":"Controlar o actualizar algún estado","Control or update some state with delay":"Controlar o actualizar algún estado con retraso","Convert blockly to javascript for ever.":"Convierta instantáneamente en bloque a Javascript.",Copied:xB,"Copy script":"Copiar guion","Copy to clipboard":"Copiar al portapapeles","Create new":"Crear nuevo","Create new folder":"Crear nueva carpeta","Create new script":"Crear nuevo script","Create or edit CRON or time wizard":"Crear o editar CRON o asistente de tiempo","Dark Theme":"Tema oscuro","Dark style":"Estilo oscuro",Date:"Fecha","Debug instance":"Instancia de depuración","Debug options":"Opciones de depuración",December:DB,Default:AB,"Define cron...":"Definir cron ...","Define schedule...":"Definir horario ...",Delay:OB,Delete:RB,"Delete %s":"Eliminar %s ...","Delete folder":"Eliminar carpeta","Delete script":"Eliminar guión",Description:MB,"Deselect all":"Deseleccionar todo","Discard changes for %s":"Descartar cambios para %s",Done:NB,"Double click to write value":"Doble clic para escribir el valor","Download as file":"Descargar como archivo","Drop some files here or click...":"Suelta algunos archivos aquí o haz clic ...","Duplicate name":"Nombre duplicado","Edit script or just double click":"Editar guión o simplemente hacer doble clic","Empty name is not allowed":"No se permite el nombre vacío","End search mode":"Fin del modo de búsqueda","Enter your question":"Ingrese su solicitud",Error:"Error","Error formatting code":"Código de formato de error","Error was found":"Error encontrado","Every day":"Diario",Exec:LB,"Executes some shell command":"Ejecuta algún comando de shell","Existing scripts will be overwritten.":"Los guiones existentes se sobrescribirán.","Expand all":"Expandir todo","Expert mode":"Modo experto",Explanation:PB,Export:BB,"Export all scripts":"Exportar todos los scripts","Export blocks":"Exportar bloques","Export selected blocks":"Exportar bloques seleccionados",Februar:jB,February:FB,Filter:zB,Folder:UB,Fr:HB,Friday:WB,Function:"Función","Function editor":"Editor de funciones","Function: executed":"Función: ejecutada","Go to next line":"Ir a la siguiente línea","HTTP Call":"Llamada HTTP","Hide logs":"Ocultar registros",ID:GB,ID1:VB,ID2:YB,Import:KB,"Import blocks":"Importar bloques","Import error":"Error de importación","Import scripts":"Importar guiones","Insert object ID":"Insertar ID de objeto",Instance:JB,"Instance is disabled":"La instancia está deshabilitada","Instance:":"Ejemplo:",Instances:XB,Instructions:qB,"Invalid CRON":"CRON inválido","It will not be possible to revert this operation.":"No será posible revertir esta operación.","JS description":"Crear reglas escribiendo Javascript",Januar:ZB,January:QB,July:e2,June:t2,"Just check":"Sólo revisa","Keep my changes":"Mantener mis cambios","Language:":"Idioma:","Learn More":"Aprende más","Light style":"Estilo ligero",Limit:s2,"Local time":"Hora local","Locate file":"Localizar el archivo","Log outputs":"Salidas de registro","Log text":"Texto de registro","Log: %s":"Log: %s","Make a HTTP get request":"Realizar una solicitud de obtención HTTP","Make a pause between actions":"Hacer una pausa entre acciones",March:o2,"March ":"marzo",May:i2,Menu:n2,Message:r2,Mo:a2,Model:l2,Monday:c2,Month:u2,More:d2,Name:h2,"No API key found":"No se encontró ninguna clave API","No Chat GPT Key found":"No se ha encontrado ninguna clave GPT de chat","No active host found":"No se encontró un host activo","Nothing found":"Nada Encontrado",November:p2,OK:g2,October:m2,Ok:f2,"On condition change":"En condición de cambio","On script save or adapter start":"Al guardar el script o al iniciar el adaptador","On weekdays":"De lunes a viernes","Open configuration":"Configuración abierta","Operate two states":"Operar dos estados","Operations with two states":"Operaciones con dos estados","Paste your blocks here":"Pega tus bloques aquí",Pause:$2,"Pause execution":"Pausar ejecución","Pause script":"Pausar guion","Phone:":"Teléfono:","Please select object ID...":"Por favor, seleccione la ID del objeto ...","Press Ctrl+Enter to get the answer":"Presiona Ctrl+Enter para obtener la respuesta","Prettify the script":"Embellecer el guión","Print some text in log":"Imprime texto en el registro","Priority:":"Prioridad:",Pushover:b2,Pushsafer:v2,"Read only ID selected: %s":"ID de solo lectura seleccionado: %s",Reload:y2,Rename:_2,"Reorder scripts in folders":"Reordenar guiones en carpetas",Repeat:w2,Restart:k2,Result:C2,"Resume execution":"Reanudar ejecución","Root folder":"Carpeta raíz","Rules description":"Crea reglas con bloques IF, THEN, ELSE","Run script":"Ejecutar guión",Sa:T2,Saturday:S2,Save:E2,"Save all":"Salvar a todos","Say It":"Say It","Say some text via sayit adapter":"Di un mensaje de texto a través del adaptador sayit",Schedule:I2,Script:x2,"Script %s was modified on disk":"El script %s fue modificado en el disco","Script was modified externally":"El script fue modificado externamente","Script is not running":"El script no se está ejecutando","Search in scripts":"Buscar en guiones","Search...":"Buscar...","Select all":"Seleccionar todo","Send email":"Enviar correo electrónico","Sends an email":"Envía un correo electrónico","Sends message via Pushsafer":"Envía mensaje a través de Pushsafer","Sends message via pushover":"Envía un mensaje a través de un pushover","Sends message via telegram":"Envía mensaje por telegrama","Sends message via whatsapp-cmb":"Envía mensaje vía whatsapp-cmb",September:D2,"Server time":"Tiempo del servidor","Set state action":"Establecer acción estatal","Set with delay":"Establecer con retraso","Shell command":"Comando de Shell","Show astronomical events":"Mostrar eventos astronómicos","Show javascript code":"Mostrar código Javascript","Show logs":"Mostrar registros","Show only paused scripts":"Mostrar solo secuencias de comandos pausadas","Show only running scripts":"Mostrar solo scripts en ejecución","Show only scripts with problems":"Mostrar solo guiones con problemas",Simulate:A2,"Some files will be rejected":"Algunos archivos serán rechazados","Sound:":"Sonido:",Stack:O2,Start:R2,"Start script":"Iniciar guion",State:M2,"State condition":"Condición del estado","Step into function":"Entra en función","Step out from function":"Sal de la función","Stop on exception":"Deténgase en excepción",Su:N2,"Subject:":"Sujeto:",Sunday:L2,"TS description":"Crear reglas escribiendo el mecanografiado",Telegram:P2,"Text:":"Texto:",Th:B2,'The script "%s" has been modified by another user or in another window. Do you want to reload the script or keep your local changes?':'El script "%s" ha sido modificado por otro usuario o en otra ventana. ¿Desea recargar el script o mantener sus cambios locales?',"The script will be stopped and must be activated manually after debugging. Continue?":"El script se detendrá y deberá activarse manualmente después de la depuración. ¿Continuar?","This is advances option. You can write your own code here and it will be executed on trigger":"Esta es la opción de avances. Puede escribir su propio código aquí y se ejecutará en el disparador",Thursday:j2,Time:F2,"Time condition":"Condición de tiempo","Title:":"Título:","To:":"A:","Trigger with value":"Activar con valor",Triggered:z2,Triggers:U2,"Triggers the on script saving or the javascript instance restart":"Activa el guardado de la secuencia de comandos o el reinicio de la instancia de JavaScript","Triggers the rule on update or change of some state":"Activa la regla de actualización o cambio de algún estado","Triggers the rule periodically or on some specific time":"Activa la regla periódicamente o en un momento específico",Tu:H2,Tuesday:W2,URL:G2,"Unknown error":"Error desconocido","Unknown error!":"¡Error desconocido!","Use generated code":"Usar código generado","User function":"Función de usuario","User:":"Usuario:",Value:V2,"Vibration:":"Vibración:",Volume:Y2,We:K2,Wednesday:J2,"Whatsapp-cmb":"Whatsapp-cmb",Write:X2,"Write your own code":"Escribe tu propio código",Yes:q2,"Yet exists!":"¡Sin embargo existe!","You can use %s in the URL to use current trigger value or %id to use the triggered object ID":"Puede usar %s en la URL para usar el valor de activación actual, %id para usar el ID de objeto activado, %name para mostrar el nombre de ID de objeto activado o %old para usar el valor de activación antiguo","You can use %s in the command to use current trigger value or %id to use the triggered object ID":"Puede usar %s en el comando para usar el valor de activación actual, %id para usar el ID de objeto activado, %name para mostrar el nombre de ID de objeto activado o %old para usar el valor de activación anterior","You can use %s in the text to display current trigger value or %id to display the triggered object ID":"Puede usar %s en el texto para mostrar el valor de activación actual, %id para usar el ID de objeto activado, %name para mostrar el nombre de ID de objeto activado o %old para usar el valor de activación antiguo","You can use %s in the value to use the current trigger value or %id to display the triggered object ID":"Puede usar %s en el valor para usar el valor de activación actual, %id para usar el ID de objeto activado, %name para mostrar el nombre de ID de objeto activado o %old para usar el valor de activación antiguo","You have to enter OpenAI API key in the configuration of javascript adapter.":"Debe ingresar la clave API de OpenAI en la configuración del adaptador de JavaScript.","You have to enter at least one API key in the configuration of javascript adapter.":"Debe ingresar al menos una clave API (OpenAI, Anthropic o Gemini) en la configuración del adaptador de JavaScript.","Please select a valid model":"Seleccione un modelo válido","[equal]":"[igual]","[greater or equal]":"[mayor o igual]","[greater]":"[mayor que]","[hysteresis]":"[histéresis]","[includes]":"[incluye]","[less or equal]":"[menor o igual]","[less]":"[menos]","[not equal]":"[no es igual]",acknowledgment:Z2,all:Q2,and:ej,"as JSON":"como JSON","as plain text":"como texto plano",astro:tj,at:sj,"clear running":"carrera clara",control:oj,copy:ij,cron:nj,dawn:rj,debug_help:aj,debug_label:lj,default:"defecto",dusk:cj,easy:uj,else:"demás","equal to":"igual a",every:dj,"every hour at 0 minutes":"cada hora a los 0 minutos",false:"falso","file reading has failed: %s":"la lectura del archivo ha fallado: %s","file reading was aborted":"la lectura del archivo fue abortada",filter_func:hj,filter_id:pj,filter_name:gj,filter_role:mj,filter_room:fj,"for edit or create script":"para editar o crear un nuevo script","for professionals":"para profesionales","for programmers":"para programadores",goldenHour:$j,goldenHourEnd:bj,"greater or equal":"mayor o igual","greater or equal to":"mayor o igual a","greater than":"mas grande que",help_just_check:vj,help_on_change:yj,"high priority":"alta prioridad","high-priority":"alta prioridad","highest priority":"más alta prioridad",hours:_j,includes:wj,interval:kj,"just check":"Sólo revisa","less or equal":"menor o igual","less or equal to":"menor o igual a","less than":"menos que","lower priority":"prioridad más baja","lowest priority":"prioridad más baja",magic:Cj,milliseconds:Tj,minutes:Sj,ms:Ej,nadir:Ij,nauticalDawn:xj,nauticalDusk:Dj,nextSunrise:Aj,nextSunset:Oj,night:Rj,nightEnd:Mj,"no blocks found":"No se encontraron bloques","no group":"NO GRUPO",normal:Nj,"normal priority":"prioridad normal","not running":"no está en ejecución","not equal to":"no igual a","not properly connected":"Este bloque no está conectado correctamente a otros bloques.",offset:Lj,"on change":"en el cambio","on condition change":"con cambio de condición","on update":"en actualización",one:Pj,or:Bj,quiet:jj,"reset search":"restablecer la búsqueda",search:Fj,seconds:zj,solarNoon:Uj,"store in":"almacenar en",sunrise:Hj,sunriseEnd:Wj,sunset:Gj,sunsetStart:Vj,then:Yj,"toggle value":"alternar valor",tooltip_ack:Kj,tooltip_from:Jj,tooltip_lc:Xj,tooltip_quality:qj,tooltip_ts:Zj,tooltip_user:Qj,tooltip_value:eF,true:"cierto",two:tF,undefined:"indefinido",update:sF,"use seconds":"usar segundos","use trigger value":"usar valor de activación",verbose_help:oF,verbose_label:iF,when:nF,with:"con","with date":"con fecha","with offset":"con desplazamiento",wizard:rF,"Loading models...":"Cargando modelos...","Could not connect to API at %s":"No se pudo conectar a la API en %s","Invalid API key":"Clave API no válida","Access denied by API":"Acceso denegado por la API","API error: %s":"Error de API: %s",'Model "%s" not found':'Modelo "%s" no encontrado',"Request failed: %s":"Solicitud fallida: %s",Retry:aF,"No running javascript instance found":"No se encontró ninguna instancia de JavaScript en ejecución","OID display mode":"Modo de visualización OID"},cF="Reconnu",uF="Actions",dF="Ajouter",hF="Tout",pF="Tout",gF="Postuler",mF="avril",fF="Demander",$F="Astronomique",bF="août",vF="Annuler",yF="proche",_F="État",wF="Conditions",kF="Console",CF="Copié",TF="décembre",SF="Défaut",EF="Retard",IF="Effacer",xF="Description",DF="Terminé",AF="Exec shell",OF="Explication",RF="Exportation",MF="Février",NF="février",LF="Filtre",PF="Dossier",BF="Fr",jF="Vendredi",FF="ID",zF="ID1",UF="ID2",HF="Importation",WF="Exemple",GF="Instances",VF="Instructions",YF="Janvier",KF="janvier",JF="juillet",XF="juin",qF="Limite",ZF="Mars",QF="Mai",ez="M e n u",tz="Message",sz="Mo",oz="Modèle",iz="Lundi",nz="Mois",rz="Plus",az="Nom",lz="novembre",cz="OK",uz="octobre",dz="D'accord",hz="Pause",pz="Pushover",gz="Pushsafer",mz="Recharger",fz="Renommer",$z="Répéter",bz="Redémarrer",vz="Résultat",yz="Sa",_z="samedi",wz="sauver",kz="Horaire",Cz="Scénario",Tz="septembre",Sz="Simuler",Ez="Stack",Iz="Début",xz="État",Dz="Su",Az="dimanche",Oz="Télégramme",Rz="4",Mz="Jeudi",Nz="Temps",Lz="Déclenché",Pz="Déclencheurs",Bz="Tu",jz="Mardi",Fz="URL",zz="Valeur",Uz="Le volume",Hz="3",Wz="Mercredi",Gz="Écrivez",Vz="Oui",Yz="reconnaissance",Kz="tout",Jz="et",Xz="astro",qz="à",Zz="contrôler",Qz="copie",eU="CRON",tU="Aube",sU="Il s'agit d'un mode spécial dans lequel les états et les objets ne changeront pas. Mais seules les informations sur chaque changement prévu seront affichées dans le protocole.",oU="Déboguer",iU="Crépuscule",nU="facile",rU="chaque",aU="Une fonction",lU="ID",cU="Nom",uU="Rôle",dU="Pièce",hU="Heure d'or",pU="Fin de l'heure d'or",gU="Le code ne sera exécuté que chaque fois que la condition est vraie. Par exemple. si déclenchement sur la valeur du capteur de température et que la condition est «si la température est supérieure à 20 ° C», les actions «alors» seront exécutées à chaque fois que le capteur envoie la température et qu'elle est supérieure à 20 ° C. À 21 ° C, à 22 ° C et ainsi de suite.",mU="Le code ne sera exécuté que si le résultat de la condition change. Par exemple. si le déclenchement sur la valeur du capteur de température et que la condition est «si la température est supérieure à 20 ° C», les actions «alors» seront exécutées une fois lorsque la température est supérieure à 20. La prochaine fois, les actions «alors» seront exécutées lorsque la température échoue sous 20 puis remonte au-dessus de 20.",fU="les heures",$U="comprend",bU="intervalle",vU="la magie",yU="millisecondes",_U="minutes",wU="ms",kU="nadir",CU="Aube nautique",TU="Crépuscule nautique",SU="Prochain lever de soleil",EU="Prochain coucher de soleil",IU="Nuit",xU="Fin de nuit",DU="Ordinaire",AU="décalage",OU="une",RU="ou",MU="calmer",NU="chercher",LU="secondes",PU="Midi solaire",BU="lever du soleil",jU="Fin du lever du soleil",FU="le coucher du soleil",zU="Début du coucher du soleil",UU="alors",HU="Reconnaître",WU="De",GU="Dernière modification",VU="Qualité",YU="Horodatage",KU="Utilisateur",JU="Valeur",XU="deux",qU="mettre à jour",ZU="Ajoute une sortie de débogage au journal pour de nombreuses commandes système",QU="Sorties de journal détaillées",eH="lorsque",tH="Wizard",sH="Réessayer",oH={"%s not found":"%s non trouvé","()":"()","(at %s)":"(à %s)","(optional)":"(optionnel)","-":"-",".":".","AI code generator":"Générateur de code IA","Planning...":"Planification...","Generating code...":"Génération du code...","Show plan":"Afficher le plan",Ack:cF,Actions:uF,"Actual time of day":"Heure réelle de la journée",Add:dF,"Add new script":"Ajouter un nouveau script",All:hF,"All files will be accepted":"Tous les fichiers seront acceptés",Any:pF,"Any month":"N'importe quel mois",Apply:gF,April:mF,"Are you sure?":"Êtes-vous sûr?",Ask:fF,Astronomical:$F,"Astronomical events today":"Événements astronomiques aujourd'hui",August:bF,"Blockly description":"Création de règles par blocs graphiques","Body:":"Corps:",Cancel:vF,"Cannot delete non empty item!":"Impossible de supprimer un élément non vide!","Change layout":"Changer la disposition",'Change theme (actual "%s")':'Changer de thème (maintenant - "%s")',"Check blocks":"Vérifier les blocs","Check is not active, because javascript adapter is disabled":"La vérification n'est pas active, car l'adaptateur Javascript est désactivé","Clear search input":"Effacer la recherche","Click on this icon":"Cliquez sur cette icône",Close:yF,"Close all but current":"Ferme tout sauf courant","Collapse all":"Réduire tout","Compares current time with astronomical event":"Compare l'heure actuelle avec un événement astronomique","Compares current time with the user specific time":"Compare l'heure actuelle avec l'heure spécifique de l'utilisateur","Compares the state value with user defined value":"Compare la valeur d'état avec la valeur définie par l'utilisateur",Condition:_F,Conditions:wF,"Configuration not saved.":"Configuration non enregistrée.",Console:kF,"Control or update some state":"Contrôler ou mettre à jour un état","Control or update some state with delay":"Contrôler ou mettre à jour un état avec un délai","Convert blockly to javascript for ever.":"Convertissez instantanément en Javascript.",Copied:CF,"Copy script":"Copier le script","Copy to clipboard":"Copier dans le presse-papier","Create new":"Créer un nouveau","Create new folder":"Créer un nouveau dossier","Create new script":"Créer un nouveau script","Create or edit CRON or time wizard":"Créer ou éditer CRON ou un assistant de temps","Dark Theme":"Thème sombre","Dark style":"Style sombre",Date:"Date","Debug instance":"Instance de débogage","Debug options":"Options de débogage",December:TF,Default:SF,"Define cron...":"Définir le cron ...","Define schedule...":"Définir le calendrier ...",Delay:EF,Delete:IF,"Delete %s":"Supprimer %s ...","Delete folder":"Supprimer le dossier","Delete script":"Supprimer le script",Description:xF,"Deselect all":"Tout déselectionner","Discard changes for %s":"Ignorer les modifications pour %s",Done:DF,"Double click to write value":"Double clic pour écrire la valeur","Download as file":"Télécharger le fichier","Drop some files here or click...":"Déposer des fichiers ici ou cliquez sur ...","Duplicate name":"Nom en double","Edit script or just double click":"Modifiez le script ou double-cliquez simplement sur","Empty name is not allowed":"Le nom vide n'est pas autorisé","End search mode":"Fin du mode de recherche","Enter your question":"Entrez votre demande",Error:"Erreur","Error formatting code":"Erreur lors du formatage du code","Error was found":"Une erreur a été trouvée","Every day":"Tous les jours",Exec:AF,"Executes some shell command":"Exécute une commande shell","Existing scripts will be overwritten.":"Les scripts existants seront écrasés.","Expand all":"Développer tout","Expert mode":"Mode expert",Explanation:OF,Export:RF,"Export all scripts":"Exporter tous les scripts","Export blocks":"Blocs d'exportation","Export selected blocks":"Exporter les blocs sélectionnés",Februar:MF,February:NF,Filter:LF,Folder:PF,Fr:BF,Friday:jF,Function:"Fonction","Function editor":"Éditeur de fonction","Function: executed":"Fonction : exécutée","Go to next line":"Aller à la ligne suivante","HTTP Call":"Appel HTTP","Hide logs":"Masquer les journaux",ID:FF,ID1:zF,ID2:UF,Import:HF,"Import blocks":"Blocs d'importation","Import error":"Erreur d'importation","Import scripts":"Importer des scripts","Insert object ID":"Insérer un identifiant d'objet",Instance:WF,"Instance is disabled":"L'instance est désactivée","Instance:":"Exemple:",Instances:GF,Instructions:VF,"Invalid CRON":"CRON invalide","It will not be possible to revert this operation.":"Il ne sera pas possible de revenir sur cette opération.","JS description":"Créer des règles en écrivant du Javascript",Januar:YF,January:KF,July:JF,June:XF,"Just check":"Vérifiez simplement","Keep my changes":"Garder mes modifications","Language:":"Langue:","Learn More":"Apprendre encore plus","Light style":"Style de lumière",Limit:qF,"Local time":"Heure locale","Locate file":"Localiser le fichier","Log outputs":"Journal des sorties","Log text":"Texte du journal","Log: %s":"Log : %s","Make a HTTP get request":"Faire une requête HTTP Get","Make a pause between actions":"Faites une pause entre les actions",March:ZF,"March ":"mars",May:QF,Menu:ez,Message:tz,Mo:sz,Model:oz,Monday:iz,Month:nz,More:rz,Name:az,"No API key found":"Aucune clé API trouvée","No Chat GPT Key found":"Aucune clé GPT de chat trouvée","No active host found":"Aucun hôte actif trouvé","Nothing found":"Rien n'a été trouvé",November:lz,OK:cz,October:uz,Ok:dz,"On condition change":"En cas de changement de condition","On script save or adapter start":"Lors de l'enregistrement du script ou du démarrage de l'adaptateur","On weekdays":"En semaine","Open configuration":"Configuration ouverte","Operate two states":"Opérer deux états","Operations with two states":"Opérations à deux états","Paste your blocks here":"Collez vos blocs ici",Pause:hz,"Pause execution":"Suspendre l'exécution","Pause script":"Script de pause","Phone:":"Téléphone:","Please select object ID...":"Veuillez sélectionner l'ID d'objet ...","Press Ctrl+Enter to get the answer":"Appuyez sur Ctrl+Entrée pour obtenir la réponse","Prettify the script":"Embellir le scénario","Print some text in log":"Imprimer du texte dans le journal","Priority:":"Priorité:",Pushover:pz,Pushsafer:gz,"Read only ID selected: %s":"ID en lecture seule sélectionné: %s",Reload:mz,Rename:fz,"Reorder scripts in folders":"Réorganiser les scripts dans des dossiers",Repeat:$z,Restart:bz,Result:vz,"Resume execution":"Reprendre l'exécution","Root folder":"Dossier racine","Rules description":"Créer des règles avec des blocs IF, THEN, ELSE","Run script":"Script de lancement",Sa:yz,Saturday:_z,Save:wz,"Save all":"Sauver tous","Say It":"Say It","Say some text via sayit adapter":"Dites du texte via l'adaptateur sayit",Schedule:kz,Script:Cz,"Script %s was modified on disk":"Le script %s a été modifié sur le disque","Script was modified externally":"Le script a été modifié en externe","Script is not running":"Le script n'est pas en cours d'exécution","Search in scripts":"Rechercher dans les scripts","Search...":"Chercher...","Select all":"Tout sélectionner","Send email":"Envoyer un e-mail","Sends an email":"Envoie un e-mail","Sends message via Pushsafer":"Envoie un message via Pushsafer","Sends message via pushover":"Envoie un message via pushover","Sends message via telegram":"Envoie un message par télégramme","Sends message via whatsapp-cmb":"Envoie un message via whatsapp-cmb",September:Tz,"Server time":"Heure du serveur","Set state action":"Définir l'action de l'état","Set with delay":"Set avec retard","Shell command":"Commande Shell","Show astronomical events":"Afficher les événements astronomiques","Show javascript code":"Afficher le code Javascript","Show logs":"Afficher les journaux","Show only paused scripts":"Afficher uniquement les scripts en pause","Show only running scripts":"Afficher uniquement les scripts en cours d'exécution","Show only scripts with problems":"Afficher uniquement les scripts avec des problèmes",Simulate:Sz,"Some files will be rejected":"Certains fichiers seront rejetés","Sound:":"Sonner:",Stack:Ez,Start:Iz,"Start script":"Lancer le script",State:xz,"State condition":"État condition","Step into function":"Entrez dans la fonction","Step out from function":"Sortez de la fonction","Stop on exception":"Arrêt sur exception",Su:Dz,"Subject:":"Sujet:",Sunday:Az,"TS description":"Créer des règles en écrivant des caractères dactylographiés",Telegram:Oz,"Text:":"Texte:",Th:Rz,'The script "%s" has been modified by another user or in another window. Do you want to reload the script or keep your local changes?':'Le script "%s" a été modifié par un autre utilisateur ou dans une autre fenêtre. Voulez-vous recharger le script ou garder vos modifications locales ?',"The script will be stopped and must be activated manually after debugging. Continue?":"Le script sera arrêté et doit être activé manuellement après le débogage. Continuez?","This is advances option. You can write your own code here and it will be executed on trigger":"C'est une option avancée. Vous pouvez écrire votre propre code ici et il sera exécuté au déclenchement",Thursday:Mz,Time:Nz,"Time condition":"Condition de temps","Title:":"Titre:","To:":"À:","Trigger with value":"Déclencheur avec valeur",Triggered:Lz,Triggers:Pz,"Triggers the on script saving or the javascript instance restart":"Déclenche l'enregistrement du script ou le redémarrage de l'instance javascript","Triggers the rule on update or change of some state":"Déclenche la règle sur la mise à jour ou le changement d'un état","Triggers the rule periodically or on some specific time":"Déclenche la règle périodiquement ou à une heure précise",Tu:Bz,Tuesday:jz,URL:Fz,"Unknown error":"Erreur inconnue","Unknown error!":"Erreur inconnue!","Use generated code":"Utiliser le code généré","User function":"Fonction utilisateur","User:":"Utilisateur:",Value:zz,"Vibration:":"Vibration:",Volume:Uz,We:Hz,Wednesday:Wz,"Whatsapp-cmb":"Whatsapp-cmb",Write:Gz,"Write your own code":"Écrivez votre propre code",Yes:Vz,"Yet exists!":"Pourtant existe!","You can use %s in the URL to use current trigger value or %id to use the triggered object ID":"Vous pouvez utiliser %s dans l'URL pour utiliser la valeur de déclenchement actuelle, %id pour utiliser l'ID de l'objet déclenché, %name pour afficher le nom de l'ID de l'objet déclenché ou %old pour utiliser l'ancienne valeur de déclenchement","You can use %s in the command to use current trigger value or %id to use the triggered object ID":"Vous pouvez utiliser %s dans la commande pour utiliser la valeur de déclenchement actuelle, %id pour utiliser l'ID de l'objet déclenché, %name pour afficher le nom de l'ID de l'objet déclenché ou %old pour utiliser l'ancienne valeur de déclenchement","You can use %s in the text to display current trigger value or %id to display the triggered object ID":"Vous pouvez utiliser %s dans le texte pour afficher la valeur de déclenchement actuelle, %id pour utiliser l'ID de l'objet déclenché, %name pour afficher le nom de l'ID de l'objet déclenché ou %old pour utiliser l'ancienne valeur de déclenchement","You can use %s in the value to use the current trigger value or %id to display the triggered object ID":"Vous pouvez utiliser %s dans la valeur pour utiliser la valeur de déclenchement actuelle, %id pour utiliser l'ID de l'objet déclenché, %name pour afficher le nom de l'ID de l'objet déclenché ou %old pour utiliser l'ancienne valeur de déclenchement","You have to enter OpenAI API key in the configuration of javascript adapter.":"Vous devez entrer la clé API OpenAI dans la configuration de l'adaptateur javascript.","You have to enter at least one API key in the configuration of javascript adapter.":"Vous devez entrer au moins une clé API (OpenAI, Anthropic ou Gemini) dans la configuration de l'adaptateur javascript.","Please select a valid model":"Veuillez sélectionner un modèle valide","[equal]":"[égal]","[greater or equal]":"[supérieur ou égal]","[greater]":"[plus grand]","[hysteresis]":"[hystérèse]","[includes]":"[comprend]","[less or equal]":"[inférieur ou égal]","[less]":"[moins]","[not equal]":"[inégal]",acknowledgment:Yz,all:Kz,and:Jz,"as JSON":"en JSON","as plain text":"en texte brut",astro:Xz,at:qz,"clear running":"course claire",control:Zz,copy:Qz,cron:eU,dawn:tU,debug_help:sU,debug_label:oU,default:"défaut",dusk:iU,easy:nU,else:"autre","equal to":"égal à",every:rU,"every hour at 0 minutes":"toutes les heures à 0 minute",false:"faux","file reading has failed: %s":"La lecture du fichier a échoué: %s","file reading was aborted":"la lecture du fichier a été abandonnée",filter_func:aU,filter_id:lU,filter_name:cU,filter_role:uU,filter_room:dU,"for edit or create script":"pour éditer ou créer un nouveau script","for professionals":"pour les professionnels","for programmers":"pour les programmeurs",goldenHour:hU,goldenHourEnd:pU,"greater or equal":"supérieur ou égal","greater or equal to":"supérieur ou égal à","greater than":"plus grand que",help_just_check:gU,help_on_change:mU,"high priority":"haute priorité","high-priority":"haute priorité","highest priority":"priorité la plus élevée",hours:fU,includes:$U,interval:bU,"just check":"Vérifiez simplement","less or equal":"inférieur ou égal","less or equal to":"inférieur ou égal à","less than":"moins que","lower priority":"priorité inférieure","lowest priority":"priorité la plus basse",magic:vU,milliseconds:yU,minutes:_U,ms:wU,nadir:kU,nauticalDawn:CU,nauticalDusk:TU,nextSunrise:SU,nextSunset:EU,night:IU,nightEnd:xU,"no blocks found":"Aucun bloc trouvé","no group":"PAS DE GROUPE",normal:DU,"normal priority":"priorité normale","not running":"pas en cours d'exécution","not equal to":"pas égal à","not properly connected":"Ce bloc n'est pas correctement connecté à d'autres blocs.",offset:AU,"on change":"sur le changement","on condition change":"sur changement de condition","on update":"sur mise à jour",one:OU,or:RU,quiet:MU,"reset search":"Réinitialiser la recherche",search:NU,seconds:LU,solarNoon:PU,"store in":"stocker dans",sunrise:BU,sunriseEnd:jU,sunset:FU,sunsetStart:zU,then:UU,"toggle value":"valeur de bascule",tooltip_ack:HU,tooltip_from:WU,tooltip_lc:GU,tooltip_quality:VU,tooltip_ts:YU,tooltip_user:KU,tooltip_value:JU,true:"vrai",two:XU,undefined:"indéfini",update:qU,"use seconds":"utiliser les secondes","use trigger value":"use trigger value",verbose_help:ZU,verbose_label:QU,when:eH,with:"avec","with date":"avec date","with offset":"avec offset",wizard:tH,"Loading models...":"Chargement des modèles...","Could not connect to API at %s":"Impossible de se connecter à l'API sur %s","Invalid API key":"Clé API invalide","Access denied by API":"Accès refusé par l'API","API error: %s":"Erreur API : %s",'Model "%s" not found':'Modèle "%s" introuvable',"Request failed: %s":"Requête échouée : %s",Retry:sH,"No running javascript instance found":"Aucune instance JavaScript en cours d'exécution trouvée","OID display mode":"Mode d'affichage OID"},iH="Riconosciuto",nH="Azioni",rH="Inserisci",aH="Tutti",lH="Qualunque",cH="Applica",uH="aprile",dH="Chiedere",hH="Astronomico",pH="agosto",gH="Annulla",mH="Vicino",fH="Condizione",$H="Condizioni",bH="Console",vH="Copiato",yH="dicembre",_H="Predefinito",wH="Ritardo",kH="Elimina",CH="Descrizione",TH="Fatto",SH="Execshell",EH="Spiegazione",IH="Esportare",xH="Februar",DH="febbraio",AH="Filtro",OH="Cartella",RH="P",MH="Venerdì",NH="ID",LH="ID1",PH="ID2",BH="Importare",jH="Esempio",FH="istanze",zH="Istruzioni",UH="Januar",HH="gennaio",WH="luglio",GH="giugno",VH="Limite",YH="marzo",KH="Maggio",JH="Menu",XH="Messaggio",qH="Mo",ZH="Modello",QH="Lunedi",eW="Mese",tW="Di più",sW="Nome",oW="novembre",iW="OK",nW="ottobre",rW="Ok",aW="Pausa",lW="Pushover",cW="Pushsafer",uW="Ricaricare",dW="Rinominare",hW="Ripetere",pW="Ricomincia",gW="Risultato",mW="Sa",fW="Sabato",$W="Salva",bW="Programma",vW="copione",yW="settembre",_W="Simulare",wW="Stack",kW="Cominciare",CW="Stato",TW="Su",SW="Domenica",EW="Telegramma",IW="4",xW="giovedi",DW="Tempo",AW="Innescato",OW="Trigger",RW="Tu",MW="martedì",NW="URL",LW="Valore",PW="Volume",BW="3",jW="mercoledì",FW="Scrivi",zW="sì",UW="riconoscimento",HW="tutti",WW="e",GW="astro",VW="a",YW="controllo",KW="copia",JW="CRON",XW="alba",qW="Questa è una modalità speciale in cui gli stati e gli oggetti non cambieranno. Ma nel protocollo verranno visualizzate solo le informazioni su ogni modifica pianificata.",ZW="Debug",QW="crepuscolo",e5="facile",t5="ogni",s5="Funzione",o5="ID",i5="Nome",n5="Ruolo",r5="Camera",a5="Ora d'oro",l5="Fine dell'ora d'oro",c5='Il codice verrà eseguito solo ogni volta che la condizione è vera. Per esempio. se si attiva il valore del sensore di temperatura e la condizione è "se la temperatura è maggiore di 20 ° C", le azioni "allora" verranno eseguite ogni volta che il sensore invia la temperatura e questa è superiore a 20 ° C. Di 21 ° C, di 22 ° C e così via.',u5='Il codice verrà eseguito solo se il risultato della condizione cambia. Per esempio. se si attiva il valore del sensore di temperatura e la condizione è "se la temperatura è maggiore di 20 ° C", le azioni "allora" verranno eseguite una volta quando la temperatura è superiore a 20. La prossima volta le azioni "allora" verranno eseguite quando la temperatura fallisce sotto 20 e poi sale di nuovo oltre 20.',d5="ore",h5="include",p5="intervallo",g5="Magia",m5="millisecondi",f5="minuti",$5="ms",b5="nadir",v5="Alba nautica",y5="Crepuscolo nautico",_5="Prossima alba",w5="Prossimo tramonto",k5="Notte",C5="Fine della notte",T5="normale",S5="compensare",E5="uno",I5="o",x5="silenzioso",D5="ricerca",A5="secondi",O5="Mezzogiorno solare",R5="Alba",M5="Fine dell'alba",N5="tramonto",L5="Inizio del tramonto",P5="poi",B5="Riconoscere",j5="A partire dal",F5="Ultima modifica",z5="Qualità",U5="timestamp",H5="Utente",W5="Valore",G5="Due",V5="aggiornare",Y5="Aggiunge l'output di debug al registro per molti comandi di sistema",K5="Output di log dettagliati",J5="quando",X5="procedura guidata",q5="Riprova",Z5={"%s not found":"%s non trovato","()":"()","(at %s)":"(a %s)","(optional)":"(opzionale)","-":"-",".":".","AI code generator":"Generatore di codice AI","Planning...":"Pianificazione...","Generating code...":"Generazione codice...","Show plan":"Mostra piano",Ack:iH,Actions:nH,"Actual time of day":"Ora effettiva della giornata",Add:rH,"Add new script":"Aggiungi nuovo script",All:aH,"All files will be accepted":"Tutti i file saranno accettati",Any:lH,"Any month":"Ogni mese",Apply:cH,April:uH,"Are you sure?":"Sei sicuro?",Ask:dH,Astronomical:hH,"Astronomical events today":"Eventi astronomici oggi",August:pH,"Blockly description":"Creazione di regole tramite blocchi grafici","Body:":"Corpo:",Cancel:gH,"Cannot delete non empty item!":"Impossibile eliminare l'elemento non vuoto!","Change layout":"Cambia layout",'Change theme (actual "%s")':'Cambia tema (ora - "%s")',"Check blocks":"Controlla i blocchi","Check is not active, because javascript adapter is disabled":"Il controllo non è attivo perché l'adattatore Javascript è disabilitato","Clear search input":"Cancella input di ricerca","Click on this icon":"Clicca su questa icona",Close:mH,"Close all but current":"Chiudi tutto tranne corrente","Collapse all":"Comprimi tutto","Compares current time with astronomical event":"Confronta l'ora corrente con l'evento astronomico","Compares current time with the user specific time":"Confronta l'ora corrente con l'ora specifica dell'utente","Compares the state value with user defined value":"Confronta il valore dello stato con il valore definito dall'utente",Condition:fH,Conditions:$H,"Configuration not saved.":"Configurazione non salvata.",Console:bH,"Control or update some state":"Controlla o aggiorna uno stato","Control or update some state with delay":"Controlla o aggiorna uno stato con ritardo","Convert blockly to javascript for ever.":"Converti istantaneamente a blocchi in Javascript.",Copied:vH,"Copy script":"Copia script","Copy to clipboard":"Copia negli appunti","Create new":"Creare nuovo","Create new folder":"Crea una nuova cartella","Create new script":"Crea nuovo script","Create or edit CRON or time wizard":"Crea o modifica la procedura guidata CRON o time","Dark Theme":"Tema scuro","Dark style":"Stile scuro",Date:"Data","Debug instance":"Istanza di debug","Debug options":"Opzioni di debug",December:yH,Default:_H,"Define cron...":"Definisci cron ...","Define schedule...":"Definisci programma ...",Delay:wH,Delete:kH,"Delete %s":"Elimina %s ...","Delete folder":"Elimina cartella","Delete script":"Elimina script",Description:CH,"Deselect all":"Deselezionare tutto","Discard changes for %s":"Annulla modifiche per %s",Done:TH,"Double click to write value":"Doppio clic per scrivere il valore","Download as file":"Scarica come file","Drop some files here or click...":"Trascina alcuni file qui o fai clic su ...","Duplicate name":"Nome duplicato","Edit script or just double click":"Modifica lo script o fai doppio clic","Empty name is not allowed":"Il nome vuoto non è consentito","End search mode":"Termina la modalità di ricerca","Enter your question":"Inserisci la tua richiesta",Error:"Errore","Error formatting code":"Errore di formattazione del codice","Error was found":"Errore trovato","Every day":"Ogni giorno",Exec:SH,"Executes some shell command":"Esegue alcuni comandi della shell","Existing scripts will be overwritten.":"Gli script esistenti verranno sovrascritti.","Expand all":"Espandi tutto","Expert mode":"Modalità esperto",Explanation:EH,Export:IH,"Export all scripts":"Esporta tutti gli script","Export blocks":"Esporta blocchi","Export selected blocks":"Esporta i blocchi selezionati",Februar:xH,February:DH,Filter:AH,Folder:OH,Fr:RH,Friday:MH,Function:"Funzione","Function editor":"Editor di funzioni","Function: executed":"Funzione: eseguita","Go to next line":"Vai alla riga successiva","HTTP Call":"Chiamata HTTP","Hide logs":"Nascondi i registri",ID:NH,ID1:LH,ID2:PH,Import:BH,"Import blocks":"Importa blocchi","Import error":"Errore di importazione","Import scripts":"Importa script","Insert object ID":"Inserisci l'ID oggetto",Instance:jH,"Instance is disabled":"L'istanza è disabilitata","Instance:":"Esempio:",Instances:FH,Instructions:zH,"Invalid CRON":"CRON non valido","It will not be possible to revert this operation.":"Non sarà possibile ripristinare questa operazione.","JS description":"Creare regole scrivendo Javascript",Januar:UH,January:HH,July:WH,June:GH,"Just check":"Controlla solamente","Keep my changes":"Mantieni le mie modifiche","Language:":"Linguaggio:","Learn More":"Per saperne di più","Light style":"Stile leggero",Limit:VH,"Local time":"Ora locale","Locate file":"Localizza file","Log outputs":"Registra le uscite","Log text":"Testo del registro","Log: %s":"Log: %s","Make a HTTP get request":"Effettua una richiesta get HTTP","Make a pause between actions":"Fai una pausa tra le azioni",March:YH,"March ":"marzo",May:KH,Menu:JH,Message:XH,Mo:qH,Model:ZH,Monday:QH,Month:eW,More:tW,Name:sW,"No API key found":"Nessuna chiave API trovata","No Chat GPT Key found":"Nessuna chiave GPT chat trovata","No active host found":"Nessun host attivo trovato","Nothing found":"Non abbiamo trovato nulla",November:oW,OK:iW,October:nW,Ok:rW,"On condition change":"A condizione che cambino","On script save or adapter start":"Al salvataggio dello script o all'avvio dell'adattatore","On weekdays":"Nei giorni della settimana","Open configuration":"Configurazione aperta","Operate two states":"Gestisci due stati","Operations with two states":"Operazioni con due stati","Paste your blocks here":"Incolla qui i tuoi blocchi",Pause:aW,"Pause execution":"Metti in pausa l'esecuzione","Pause script":"Metti in pausa lo script","Phone:":"Telefono:","Please select object ID...":"Seleziona l'ID oggetto ...","Press Ctrl+Enter to get the answer":"Premi Ctrl+Invio per ottenere la risposta","Prettify the script":"Abbellire la sceneggiatura","Print some text in log":"Stampa del testo nel registro","Priority:":"Priorità:",Pushover:lW,Pushsafer:cW,"Read only ID selected: %s":"ID di sola lettura selezionato: %s",Reload:uW,Rename:dW,"Reorder scripts in folders":"Riordina gli script nelle cartelle",Repeat:hW,Restart:pW,Result:gW,"Resume execution":"Riprendi esecuzione","Root folder":"Cartella root","Rules description":"Crea regole con i blocchi IF, THEN, ELSE","Run script":"Esegui script",Sa:mW,Saturday:fW,Save:$W,"Save all":"Salva tutto","Say It":"Say It","Say some text via sayit adapter":"Pronuncia del testo tramite l'adattatore sayit",Schedule:bW,Script:vW,"Script %s was modified on disk":"Lo script %s è stato modificato sul disco","Script was modified externally":"Lo script è stato modificato esternamente","Script is not running":"Lo script non è in esecuzione","Search in scripts":"Cerca negli script","Search...":"Ricerca...","Select all":"Seleziona tutto","Send email":"Invia una email","Sends an email":"Invia un'e-mail","Sends message via Pushsafer":"Invia messaggio tramite Pushsafer","Sends message via pushover":"Invia messaggio tramite pushover","Sends message via telegram":"Invia messaggio tramite telegramma","Sends message via whatsapp-cmb":"Invia messaggio tramite whatsapp-cmb",September:yW,"Server time":"Ora del server","Set state action":"Imposta l'azione dello stato","Set with delay":"Impostato con ritardo","Shell command":"Comando Shell","Show astronomical events":"Mostra eventi astronomici","Show javascript code":"Mostra codice Javascript","Show logs":"Mostra i log","Show only paused scripts":"Mostra solo script in pausa","Show only running scripts":"Mostra solo gli script in esecuzione","Show only scripts with problems":"Mostra solo script con problemi",Simulate:_W,"Some files will be rejected":"Alcuni file verranno rifiutati","Sound:":"Suono:",Stack:wW,Start:kW,"Start script":"Avvia script",State:CW,"State condition":"Condizione dello stato","Step into function":"Entra in funzione","Step out from function":"Esci dalla funzione","Stop on exception":"Ferma in caso di eccezione",Su:TW,"Subject:":"Soggetto:",Sunday:SW,"TS description":"Creare regole scrivendo dattiloscritto",Telegram:EW,"Text:":"Testo:",Th:IW,'The script "%s" has been modified by another user or in another window. Do you want to reload the script or keep your local changes?':`Lo script "%s" è stato modificato da un altro utente o in un'altra finestra. Vuoi ricaricare lo script o mantenere le tue modifiche locali?`,"The script will be stopped and must be activated manually after debugging. Continue?":"Lo script verrà interrotto e dovrà essere attivato manualmente dopo il debug. Continua?","This is advances option. You can write your own code here and it will be executed on trigger":"Questa è un'opzione anticipata. Puoi scrivere il tuo codice qui e verrà eseguito al trigger",Thursday:xW,Time:DW,"Time condition":"Condizione temporale","Title:":"Titolo:","To:":"Per:","Trigger with value":"Trigger con valore",Triggered:AW,Triggers:OW,"Triggers the on script saving or the javascript instance restart":"Attiva il salvataggio dello script o il riavvio dell'istanza javascript","Triggers the rule on update or change of some state":"Attiva la regola in caso di aggiornamento o modifica di uno stato","Triggers the rule periodically or on some specific time":"Attiva la regola periodicamente o in un momento specifico",Tu:RW,Tuesday:MW,URL:NW,"Unknown error":"Errore sconosciuto","Unknown error!":"Errore sconosciuto!","Use generated code":"Usa il codice generato","User function":"Funzione utente","User:":"Utente:",Value:LW,"Vibration:":"Vibrazione:",Volume:PW,We:BW,Wednesday:jW,"Whatsapp-cmb":"Whatsapp-cmb",Write:FW,"Write your own code":"Scrivi il tuo codice",Yes:zW,"Yet exists!":"Esiste ancora!","You can use %s in the URL to use current trigger value or %id to use the triggered object ID":"È possibile utilizzare %s nell'URL per utilizzare il valore di trigger corrente, %id per utilizzare l'ID dell'oggetto attivato, %name per mostrare il nome dell'ID dell'oggetto attivato o %old per utilizzare il vecchio valore di trigger","You can use %s in the command to use current trigger value or %id to use the triggered object ID":"È possibile utilizzare %s nel comando per utilizzare il valore di trigger corrente, %id per utilizzare l'ID dell'oggetto attivato, %name per mostrare il nome dell'ID dell'oggetto attivato o %old per utilizzare il vecchio valore di trigger","You can use %s in the text to display current trigger value or %id to display the triggered object ID":"È possibile utilizzare %s nel testo per visualizzare il valore di trigger corrente, %id per utilizzare l'ID dell'oggetto attivato, %name per mostrare il nome dell'ID dell'oggetto attivato o %old per utilizzare il vecchio valore di trigger","You can use %s in the value to use the current trigger value or %id to display the triggered object ID":"È possibile utilizzare %s nel valore per utilizzare il valore di trigger corrente, %id per utilizzare l'ID dell'oggetto attivato, %name per mostrare il nome dell'ID dell'oggetto attivato o %old per utilizzare il vecchio valore di trigger","You have to enter OpenAI API key in the configuration of javascript adapter.":"Devi inserire la chiave API OpenAI nella configurazione dell'adattatore javascript.","You have to enter at least one API key in the configuration of javascript adapter.":"Devi inserire almeno una chiave API (OpenAI, Anthropic o Gemini) nella configurazione dell'adattatore javascript.","Please select a valid model":"Seleziona un modello valido","[equal]":"[pari]","[greater or equal]":"[maggiore o uguale]","[greater]":"[maggiore]","[hysteresis]":"[isteresi]","[includes]":"[include]","[less or equal]":"[minore o uguale]","[less]":"[Di meno]","[not equal]":"[non uguale]",acknowledgment:UW,all:HW,and:WW,"as JSON":"come JSON","as plain text":"come testo",astro:GW,at:VW,"clear running":"chiara esecuzione",control:YW,copy:KW,cron:JW,dawn:XW,debug_help:qW,debug_label:ZW,default:"predefinito",dusk:QW,easy:e5,else:"altro","equal to":"uguale a",every:t5,"every hour at 0 minutes":"ogni ora a 0 minuti",false:"falso","file reading has failed: %s":"lettura file non riuscita: %s","file reading was aborted":"la lettura del file è stata interrotta",filter_func:s5,filter_id:o5,filter_name:i5,filter_role:n5,filter_room:r5,"for edit or create script":"per modificare o creare un nuovo script","for professionals":"per i professionisti","for programmers":"per i programmatori",goldenHour:a5,goldenHourEnd:l5,"greater or equal":"maggiore o uguale","greater or equal to":"maggiore o uguale a","greater than":"più grande di",help_just_check:c5,help_on_change:u5,"high priority":"priorità alta","high-priority":"priorità alta","highest priority":"massima priorità",hours:d5,includes:h5,interval:p5,"just check":"controlla solamente","less or equal":"inferiore o uguale","less or equal to":"minore o uguale a","less than":"meno di","lower priority":"priorità inferiore","lowest priority":"priorità più bassa",magic:g5,milliseconds:m5,minutes:f5,ms:$5,nadir:b5,nauticalDawn:v5,nauticalDusk:y5,nextSunrise:_5,nextSunset:w5,night:k5,nightEnd:C5,"no blocks found":"Nessun blocco trovato","no group":"NESSUN GRUPPO",normal:T5,"normal priority":"priorità normale","not running":"non in esecuzione","not equal to":"non uguale a","not properly connected":"Questo blocco non è correttamente collegato ad altri blocchi.",offset:S5,"on change":"sul cambiamento","on condition change":"a cambio di condizione","on update":"in aggiornamento",one:E5,or:I5,quiet:x5,"reset search":"resetta la ricerca",search:D5,seconds:A5,solarNoon:O5,"store in":"conservare in",sunrise:R5,sunriseEnd:M5,sunset:N5,sunsetStart:L5,then:P5,"toggle value":"alterna valore",tooltip_ack:B5,tooltip_from:j5,tooltip_lc:F5,tooltip_quality:z5,tooltip_ts:U5,tooltip_user:H5,tooltip_value:W5,true:"vero",two:G5,undefined:"non definito",update:V5,"use seconds":"usa i secondi","use trigger value":"usa il trigger",verbose_help:Y5,verbose_label:K5,when:J5,with:"con","with date":"con data","with offset":"con offset",wizard:X5,"Loading models...":"Caricamento modelli...","Could not connect to API at %s":"Impossibile connettersi all'API su %s","Invalid API key":"Chiave API non valida","Access denied by API":"Accesso negato dall'API","API error: %s":"Errore API: %s",'Model "%s" not found':'Modello "%s" non trovato',"Request failed: %s":"Richiesta fallita: %s",Retry:q5,"No running javascript instance found":"Nessuna istanza JavaScript in esecuzione trovata","OID display mode":"Modalità di visualizzazione OID"},Q5="Erkend",eG="Acties",tG="Toevoegen",sG="Alle",oG="Ieder",iG="Solliciteer",nG="april",rG="Vragen",aG="Astronomisch",lG="augustus",cG="annuleren",uG="Dichtbij",dG="Staat",hG="Voorwaarden",pG="Troosten",gG="Gekopieerd",mG="december",fG="Standaard",$G="Vertraging",bG="Verwijder",vG="Beschrijving",yG="Gedaan",_G="Exec shell",wG="Uitleg",kG="Exporteren",CG="Februari",TG="februari",SG="Filter",EG="Map",IG="Vr",xG="vrijdag",DG="ID kaart",AG="ID1",OG="ID2",RG="Importeren",MG="Voorbeeld",NG="Instanties",LG="Instructies",PG="Januar",BG="januari",jG="juli",FG="juni",zG="Begrenzing",UG="maart",HG="mei",WG="Menu",GG="Bericht",VG="Ma",YG="Model",KG="maandag",JG="Maand",XG="Meer",qG="Naam",ZG="november",QG="OK",e3="oktober",t3="OK",s3="Pauze",o3="Pushover",i3="Duwijzer",n3="Herladen",r3="andere naam geven",a3="Herhaling",l3="Herstarten",c3="Resultaat",u3="Za",d3="zaterdag",h3="Opslaan",p3="Schema",g3="Script",m3="september",f3="Simuleren",$3="Stack",b3="Begin",v3="Staat",y3="Zo",_3="zondag",w3="Telegram",k3="4",C3="donderdag",T3="Tijd",S3="Veroorzaakt",E3="Triggers",I3="Di",x3="dinsdag",D3="URL",A3="Waarde",O3="Volume",R3="3",M3="woensdag",N3="Schrijven",L3="Ja",P3="erkenning",B3="alle",j3="en",F3="astro",z3="Bij",U3="controle",H3="kopiëren",W3="cron",G3="dageraad",V3="Dit is een speciale modus waarin toestanden en objecten niet veranderen. Maar alleen informatie over elke geplande wijziging wordt in het protocol weergegeven.",Y3="Debuggen",K3="schemer",J3="eenvoudig",X3="elke",q3="Functie",Z3="ID kaart",Q3="Naam",eV="Rol",tV="Kamer",sV="gouden uur",oV="Einde van gouden uur",iV='De code wordt alleen uitgevoerd als de voorwaarde waar is. Bijv. als het triggeren op de temperatuursensorwaarde en de conditie is "als de temperatuur hoger is dan 20 ° C", zullen de "dan" acties worden uitgevoerd elke keer dat de sensor de temperatuur verzendt en deze hoger is dan 20 ° C. Bij 21 ° C, bij 22 ° C enzovoort.',nV='De code wordt alleen uitgevoerd als het conditieresultaat verandert. Bijv. als de temperatuursensor wordt geactiveerd en de conditie is "als de temperatuur hoger is dan 20 ° C", worden de "dan" -acties eenmaal uitgevoerd wanneer de temperatuur hoger is dan 20. De volgende keer worden de "dan" -acties uitgevoerd wanneer de temperatuur faalt onder de 20 en stijgt dan weer boven de 20.',rV="uren",aV="omvat",lV="interval",cV="magie",uV="milliseconden",dV="minuten",hV="ms",pV="nadir",gV="Nautische dageraad",mV="Nautische schemering",fV="Volgende zonsopgang",$V="Volgende zonsondergang",bV="nacht",vV="Einde van de nacht",yV="normaal",_V="compensatie",wV="een",kV="of",CV="stil",TV="zoeken",SV="seconden",EV="Zonne-middag",IV="zonsopkomst",xV="Einde zonsopgang",DV="zonsondergang",AV="Begin van de zonsondergang",OV="vervolgens",RV="Erkennen",MV="Van",NV="Laatst gewijzigd",LV="Kwaliteit",PV="tijdstempel",BV="Gebruiker",jV="Waarde",FV="twee",zV="bijwerken",UV="Voegt foutopsporingsuitvoer toe aan het logboek voor veel systeemopdrachten",HV="Uitgebreide log-uitgangen",WV="wanneer",GV="tovenaar",VV="Opnieuw proberen",YV={"%s not found":"%s niet gevonden","()":"()","(at %s)":"(op %s)","(optional)":"(optioneel)","-":"-",".":".","AI code generator":"AI-codegenerator","Planning...":"Planning...","Generating code...":"Code genereren...","Show plan":"Plan weergeven",Ack:Q5,Actions:eG,"Actual time of day":"Werkelijke tijd van de dag",Add:tG,"Add new script":"Nieuw script toevoegen",All:sG,"All files will be accepted":"Alle bestanden worden geaccepteerd",Any:oG,"Any month":"Elke maand",Apply:iG,April:nG,"Are you sure?":"Weet je zeker dat?",Ask:rG,Astronomical:aG,"Astronomical events today":"Astronomische gebeurtenissen vandaag",August:lG,"Blockly description":"Regels maken door grafische blokken","Body:":"Lichaam:",Cancel:cG,"Cannot delete non empty item!":"Kan niet leeg item niet verwijderen!","Change layout":"Opmaak veranderen",'Change theme (actual "%s")':'Thema wijzigen (nu - "%s")',"Check blocks":"Controleer blokken","Check is not active, because javascript adapter is disabled":"Controle is niet actief, omdat Javascript-adapter is uitgeschakeld","Clear search input":"Zoekopdracht wissen","Click on this icon":"Klik op dit pictogram",Close:uG,"Close all but current":"Alles sluiten behalve huidig","Collapse all":"Alles inklappen","Compares current time with astronomical event":"Vergelijkt huidige tijd met astronomische gebeurtenis","Compares current time with the user specific time":"Vergelijkt de huidige tijd met de gebruikerspecifieke tijd","Compares the state value with user defined value":"Vergelijkt de statuswaarde met de door de gebruiker gedefinieerde waarde",Condition:dG,Conditions:hG,"Configuration not saved.":"Configuratie niet opgeslagen.",Console:pG,"Control or update some state":"Beheer of update een bepaalde staat","Control or update some state with delay":"Beheer of update een bepaalde staat met vertraging","Convert blockly to javascript for ever.":"Converteer direct blockly naar Javascript.",Copied:gG,"Copy script":"Kopieer script","Copy to clipboard":"Kopieer naar klembord","Create new":"Maak nieuw","Create new folder":"Maak een nieuwe map","Create new script":"Maak een nieuw script","Create or edit CRON or time wizard":"Creëer of bewerk CRON of tijdwizard","Dark Theme":"Donker thema","Dark style":"Donkere stijl",Date:"Datum","Debug instance":"Debug-instantie","Debug options":"Foutopsporingsopties",December:mG,Default:fG,"Define cron...":"Definieer cron ...","Define schedule...":"Definieer schema ...",Delay:$G,Delete:bG,"Delete %s":"%s verwijderen ...","Delete folder":"Verwijder map","Delete script":"Script verwijderen",Description:vG,"Deselect all":"Deselecteer alles","Discard changes for %s":"Wijzigingen voor %s annuleren",Done:yG,"Double click to write value":"Dubbelklikken om waarde te schrijven","Download as file":"Download","Drop some files here or click...":"Zet hier enkele bestanden neer of klik op ...","Duplicate name":"Dubbele naam","Edit script or just double click":"Bewerk het script of dubbelklik erop","Empty name is not allowed":"Lege naam is niet toegestaan","End search mode":"Zoekmodus beëindigen","Enter your question":"Voer uw verzoek in",Error:"Fout","Error formatting code":"Fout bij het opmaken van de code","Error was found":"Er is een fout gevonden","Every day":"Elke dag",Exec:_G,"Executes some shell command":"Voert een shell-commando uit","Existing scripts will be overwritten.":"Bestaande scripts worden overschreven.","Expand all":"Alles uitvouwen","Expert mode":"Expert modus",Explanation:wG,Export:kG,"Export all scripts":"Exporteer alle scripts","Export blocks":"Blokken exporteren","Export selected blocks":"Exporteer geselecteerde blokken",Februar:CG,February:TG,Filter:SG,Folder:EG,Fr:IG,Friday:xG,Function:"Functie","Function editor":"Functie-editor","Function: executed":"Functie: uitgevoerd","Go to next line":"Ga naar de volgende regel","HTTP Call":"HTTP-oproep","Hide logs":"Verberg logboeken",ID:DG,ID1:AG,ID2:OG,Import:RG,"Import blocks":"Blokken importeren","Import error":"Importfout","Import scripts":"Scripts importeren","Insert object ID":"Object-ID invoegen",Instance:MG,"Instance is disabled":"Exemplaar is uitgeschakeld","Instance:":"Voorbeeld:",Instances:NG,Instructions:LG,"Invalid CRON":"Ongeldige CRON","It will not be possible to revert this operation.":"Het is niet mogelijk om deze bewerking terug te zetten.","JS description":"Regels maken door Javascript te schrijven",Januar:PG,January:BG,July:jG,June:FG,"Just check":"Kijk maar","Keep my changes":"Mijn wijzigingen behouden","Language:":"Taal:","Learn More":"Leer meer","Light style":"Lichte stijl",Limit:zG,"Local time":"Lokale tijd","Locate file":"Vind het bestand","Log outputs":"Log uitgangen","Log text":"Log tekst","Log: %s":"Logboek: %s","Make a HTTP get request":"Maak een HTTP-ophaalverzoek","Make a pause between actions":"Pauzeer tussen acties",March:UG,"March ":"maart",May:HG,Menu:WG,Message:GG,Mo:VG,Model:YG,Monday:KG,Month:JG,More:XG,Name:qG,"No API key found":"Geen API-sleutel gevonden","No Chat GPT Key found":"Geen Chat GPT-sleutel gevonden","No active host found":"Geen actieve host gevonden","Nothing found":"Niets gevonden",November:ZG,OK:QG,October:e3,Ok:t3,"On condition change":"Op voorwaarde verandering","On script save or adapter start":"Bij het opslaan van het script of het starten van de adapter","On weekdays":"Op weekdagen","Open configuration":"Configuratie openen","Operate two states":"Bedien twee toestanden:","Operations with two states":"Bewerkingen met twee toestanden","Paste your blocks here":"Plak hier je blokken",Pause:s3,"Pause execution":"Uitvoering pauzeren","Pause script":"Pauzeer script","Phone:":"Telefoon:","Please select object ID...":"Selecteer object-ID ...","Press Ctrl+Enter to get the answer":"Druk op Ctrl+Enter om het antwoord te krijgen","Prettify the script":"Maak het script mooier","Print some text in log":"Druk wat tekst af in het logboek","Priority:":"Prioriteit:",Pushover:o3,Pushsafer:i3,"Read only ID selected: %s":"Alleen-lezen ID geselecteerd: %s",Reload:n3,Rename:r3,"Reorder scripts in folders":"Sorteer scripts in mappen opnieuw",Repeat:a3,Restart:l3,Result:c3,"Resume execution":"Uitvoering hervatten","Root folder":"Hoofdmap","Rules description":"Maak regels met IF, THEN, ELSE blokken","Run script":"Voer script uit",Sa:u3,Saturday:d3,Save:h3,"Save all":"Sla alles op","Say It":"Say It","Say some text via sayit adapter":"Zeg wat tekst via de sayit-adapter",Schedule:p3,Script:g3,"Script %s was modified on disk":"Script %s is gewijzigd op schijf","Script was modified externally":"Script is extern gewijzigd","Script is not running":"Script is niet actief","Search in scripts":"Zoeken in scripts","Search...":"Zoeken...","Select all":"Selecteer alles","Send email":"E-mail verzenden","Sends an email":"Stuurt een e-mail","Sends message via Pushsafer":"Stuurt bericht via Pushsafer","Sends message via pushover":"Stuurt bericht via pushover","Sends message via telegram":"Verzendt bericht via telegram","Sends message via whatsapp-cmb":"Stuurt bericht via whatsapp-cmb",September:m3,"Server time":"Servertijd","Set state action":"Stel statusactie in","Set with delay":"Met vertraging ingesteld","Shell command":"Shell-opdracht","Show astronomical events":"Laat astronomische gebeurtenissen zien","Show javascript code":"Javascript-code weergeven","Show logs":"Toon logboeken","Show only paused scripts":"Toon alleen onderbroken scripts","Show only running scripts":"Toon alleen actieve scripts","Show only scripts with problems":"Toon alleen scripts met problemen",Simulate:f3,"Some files will be rejected":"Sommige bestanden worden geweigerd","Sound:":"Geluid:",Stack:$3,Start:b3,"Start script":"Start het script",State:v3,"State condition":"Staat staat","Step into function":"Stap in functie","Step out from function":"Stap uit de functie","Stop on exception":"Stop bij uitzondering",Su:y3,"Subject:":"Onderwerpen:",Sunday:_3,"TS description":"Regels maken door Typescript te schrijven",Telegram:w3,"Text:":"Tekst:",Th:k3,'The script "%s" has been modified by another user or in another window. Do you want to reload the script or keep your local changes?':'Het script "%s" is gewijzigd door een andere gebruiker of in een ander venster. Wilt u het script herladen of uw lokale wijzigingen behouden?',"The script will be stopped and must be activated manually after debugging. Continue?":"Het script wordt gestopt en moet na het debuggen handmatig worden geactiveerd. Doorgaan met?","This is advances option. You can write your own code here and it will be executed on trigger":"Dit is een voorschotoptie. U kunt hier uw eigen code schrijven en deze wordt bij een trigger uitgevoerd",Thursday:C3,Time:T3,"Time condition":"Tijdsvoorwaarde","Title:":"Titel:","To:":"Naar:","Trigger with value":"Trigger met waarde",Triggered:S3,Triggers:E3,"Triggers the on script saving or the javascript instance restart":"Activeert het opslaan van het script of het opnieuw opstarten van de JavaScript-instantie","Triggers the rule on update or change of some state":"Activeert de regel voor het bijwerken of wijzigen van een bepaalde staat","Triggers the rule periodically or on some specific time":"Activeert de regel periodiek of op een specifieke tijd",Tu:I3,Tuesday:x3,URL:D3,"Unknown error":"Onbekende fout","Unknown error!":"Onbekende fout!","Use generated code":"Gebruik gegenereerde code","User function":"Gebruikersfunctie","User:":"Gebruiker:",Value:A3,"Vibration:":"Trilling:",Volume:O3,We:R3,Wednesday:M3,"Whatsapp-cmb":"Whatsapp-cmb",Write:N3,"Write your own code":"Schrijf je eigen code",Yes:L3,"Yet exists!":"Toch bestaat!","You can use %s in the URL to use current trigger value or %id to use the triggered object ID":"U kunt %s in de URL gebruiken om de huidige triggerwaarde te gebruiken, %id om de geactiveerde object-ID te gebruiken, %name om de geactiveerde object-ID-naam te tonen of %old om de oude triggerwaarde te gebruiken","You can use %s in the command to use current trigger value or %id to use the triggered object ID":"U kunt %s in de opdracht gebruiken om de huidige triggerwaarde te gebruiken, %id om de getriggerde object-ID te gebruiken, %name om de getriggerde object-ID-naam te tonen of %old om de oude triggerwaarde te gebruiken","You can use %s in the text to display current trigger value or %id to display the triggered object ID":"U kunt %s in de tekst gebruiken om de huidige triggerwaarde weer te geven, %id om de geactiveerde object-ID te gebruiken, %name om de geactiveerde object-ID-naam weer te geven of %old om de oude triggerwaarde te gebruiken","You can use %s in the value to use the current trigger value or %id to display the triggered object ID":"U kunt %s in de waarde gebruiken om de huidige triggerwaarde te gebruiken, %id om de geactiveerde object-ID te gebruiken, %name om de geactiveerde object-ID-naam te tonen of %old om de oude triggerwaarde te gebruiken","You have to enter OpenAI API key in the configuration of javascript adapter.":"U moet de OpenAI API-sleutel invoeren in de configuratie van de javascript-adapter.","You have to enter at least one API key in the configuration of javascript adapter.":"U moet ten minste één API-sleutel (OpenAI, Anthropic of Gemini) invoeren in de configuratie van de javascript-adapter.","Please select a valid model":"Selecteer een geldig model","[equal]":"[Gelijk]","[greater or equal]":"[groter of gelijk]","[greater]":"[groter]","[hysteresis]":"[hysterese]","[includes]":"[inclusief]","[less or equal]":"[minder of gelijk]","[less]":"[minder]","[not equal]":"[niet gelijk]",acknowledgment:P3,all:B3,and:j3,"as JSON":"als JSON","as plain text":"als platte tekst",astro:F3,at:z3,"clear running":"duidelijk rennen",control:U3,copy:H3,cron:W3,dawn:G3,debug_help:V3,debug_label:Y3,default:"standaard",dusk:K3,easy:J3,else:"anders","equal to":"gelijk aan",every:X3,"every hour at 0 minutes":"elk uur op 0 minuten",false:"false","file reading has failed: %s":"bestands lezen is mislukt: %s","file reading was aborted":"bestands lezen is afgebroken",filter_func:q3,filter_id:Z3,filter_name:Q3,filter_role:eV,filter_room:tV,"for edit or create script":"voor bewerken of een nieuw script maken","for professionals":"voor professionals","for programmers":"voor programmeurs",goldenHour:sV,goldenHourEnd:oV,"greater or equal":"groter of gelijk","greater or equal to":"groter of gelijk aan","greater than":"groter dan",help_just_check:iV,help_on_change:nV,"high priority":"hoge prioriteit","high-priority":"hoge prioriteit","highest priority":"hoogste prioriteit",hours:rV,includes:aV,interval:lV,"just check":"kijk maar","less or equal":"minder of gelijk","less or equal to":"minder of gelijk aan","less than":"minder dan","lower priority":"lagere prioriteit","lowest priority":"laagste prioriteit",magic:cV,milliseconds:uV,minutes:dV,ms:hV,nadir:pV,nauticalDawn:gV,nauticalDusk:mV,nextSunrise:fV,nextSunset:$V,night:bV,nightEnd:vV,"no blocks found":"Geen blokken gevonden","no group":"GEEN GROEP",normal:yV,"normal priority":"normale prioriteit","not running":"niet actief","not equal to":"niet gelijk aan","not properly connected":"Dit blok is niet correct verbonden met andere blokken.",offset:_V,"on change":"bij verandering","on condition change":"op voorwaarde verandering","on update":"bij update",one:wV,or:kV,quiet:CV,"reset search":"reset zoeken",search:TV,seconds:SV,solarNoon:EV,"store in":"opslaan in",sunrise:IV,sunriseEnd:xV,sunset:DV,sunsetStart:AV,then:OV,"toggle value":"schakelwaarde",tooltip_ack:RV,tooltip_from:MV,tooltip_lc:NV,tooltip_quality:LV,tooltip_ts:PV,tooltip_user:BV,tooltip_value:jV,true:"waar",two:FV,undefined:"ongedefinieerd",update:zV,"use seconds":"gebruik seconden","use trigger value":"triggerwaarde gebruiken",verbose_help:UV,verbose_label:HV,when:WV,with:"met","with date":"met datum","with offset":"met offset",wizard:GV,"Loading models...":"Modellen laden...","Could not connect to API at %s":"Kan geen verbinding maken met API op %s","Invalid API key":"Ongeldige API-sleutel","Access denied by API":"Toegang geweigerd door API","API error: %s":"API-fout: %s",'Model "%s" not found':'Model "%s" niet gevonden',"Request failed: %s":"Verzoek mislukt: %s",Retry:VV,"No running javascript instance found":"Geen draaiende JavaScript-instantie gevonden","OID display mode":"OID-weergavemodus"},KV="Potwierdzony",JV="Działania",XV="Dodaj",qV="Wszystko",ZV="Każdy",QV="Zastosuj",e4="Kwiecień",t4="Zapytać",s4="Astronomiczny",o4="Sierpień",i4="Odwołaj",n4="Zamknij",r4="Stan",a4="Warunki",l4="Konsola",c4="Skopiowano",u4="Grudzień",d4="Domyślna",h4="Opóźnienie",p4="Usuń",g4="Opis",m4="Gotowe",f4="Uruchom shell",$4="Wyjaśnienie",b4="Eksport",v4="Luty",y4="Luty",_4="Filtr",w4="Folder",k4="Pt",C4="Piątek",T4="ID",S4="ID1",E4="ID2",I4="Import",x4="Instancja",D4="Instancje",A4="Instrukcje",O4="Styczeń",R4="Styczeń",M4="Lipiec",N4="Czerwiec",L4="Limit",P4="Marzec",B4="Maj",j4="Menu",F4="Wiadomość",z4="Po",U4="Model",H4="Poniedziałek",W4="Miesiąc",G4="Więcej",V4="Nazwa",Y4="Listopad",K4="OK",J4="Październik",X4="Ok",q4="Pauza",Z4="Pushover",Q4="Pushsafer",e8="Przeładuj",t8="Przemianuj",s8="Powtórz",o8="Uruchom ponownie",i8="Wynik",n8="So",r8="Sobota",a8="Zapisz",l8="Harmonogram",c8="Skrypt",u8="Wrzesień",d8="Symulacja",h8="Stos",p8="Początek",g8="Stan",m8="Nd",f8="Niedziela",$8="Telegram",b8="Cz",v8="Czwartek",y8="Czas",_8="Wyzwolony",w8="Wyzwalacze",k8="Wt",C8="Wtorek",T8="URL",S8="Wartość",E8="Wolumen",I8="Śr",x8="Środa",D8="Pisać",A8="Tak",O8="potwierdzenie",R8="wszystko",M8="i",N8="Astro",L8="w",P8="kontrola",B8="Kopiuj",j8="CRON",F8="Świt",z8="Jest to specjalny tryb, w którym stany i obiekty się nie zmieniają. Jednak w protokole będą wyświetlane tylko informacje o każdej planowanej zmianie.",U8="Odpluskwić",H8="Zmierzch",W8="łatwy",G8="każdy",V8="Funkcja",Y8="ID",K8="Nazwa",J8="Rola",X8="Pokój",q8="Złota godzina",Z8="Koniec złotej godziny",Q8="Kod zostanie wykonany tylko za każdym razem, gdy warunek będzie spełniony. Na przykład. jeśli wyzwalanie na wartość czujnika temperatury i warunek to „jeśli temperatura jest wyższa niż 20 ° C”, to działania „następnie” będą wykonywane za każdym razem, gdy czujnik wyśle temperaturę i jest powyżej 20 ° C. O 21 ° C, o 22 ° C i tak dalej.",e6="Kod zostanie wykonany tylko wtedy, gdy wynik warunku ulegnie zmianie. Na przykład. jeśli wyzwalanie na wartość czujnika temperatury i warunek „jeśli temperatura jest wyższa niż 20 ° C”, to akcje „następnie” zostaną wykonane raz, gdy temperatura przekroczy 20. Następnym razem działania „następnie” zostaną wykonane, gdy temperatura nie udaje się poniżej 20, a następnie ponownie wzrasta powyżej 20.",t6="godziny",s6="zawiera",o6="interwał",i6="magia",n6="milisekund",r6="minuty",a6="ms",l6="Północ słoneczna",c6="Żeglarski świt",u6="Żeglarski zmierzch",d6="Następny wschód słońca",h6="Następny zachód słońca",p6="Noc",g6="Koniec nocy",m6="normalny",f6="przesunięcie",$6="jeden",b6="lub",v6="cisza",y6="Szukaj",_6="sekundy",w6="Południe słoneczne",k6="Wschód słońca",C6="Koniec wschodu słońca",T6="Zachód słońca",S6="Początek zachodu słońca",E6="następnie",I6="Akceptuj",x6="Od",D6="Ostatnia zmiana",A6="Jakość",O6="Znacznik czasu",R6="Użytkownik",M6="Wartość",N6="dwa",L6="aktualizacja",P6="Dodaje wyniki debugowania do dziennika dla wielu poleceń systemowych",B6="Pełne dane wyjściowe dziennika",j6="gdy",F6="Wizard",z6="Ponów próbę",U6={"%s not found":"%s nie znaleziono","()":"()","(at %s)":"(w %s)","(optional)":"(opcjonalny)","-":"-",".":".","AI code generator":"Generator kodu AI","Planning...":"Planowanie...","Generating code...":"Generowanie kodu...","Show plan":"Pokaż plan",Ack:KV,Actions:JV,"Actual time of day":"Aktualna pora dnia",Add:XV,"Add new script":"Dodaj nowy skrypt",All:qV,"All files will be accepted":"Wszystkie pliki zostaną zaakceptowane",Any:ZV,"Any month":"Dowolny miesiąc",Apply:QV,April:e4,"Are you sure?":"Jesteś pewny?",Ask:t4,Astronomical:s4,"Astronomical events today":"Wydarzenia astronomiczne dzisiaj",August:o4,"Blockly description":"Tworzenie reguł za pomocą bloków graficznych","Body:":"Treść:",Cancel:i4,"Cannot delete non empty item!":"Nie można usunąć niepustego elementu!","Change layout":"Zmiana układu",'Change theme (actual "%s")':"Zmień motyw (obecnie - „%s”)","Check blocks":"Sprawdź bloki","Check is not active, because javascript adapter is disabled":"Sprawdzanie nie jest aktywne, ponieważ adapter Javascript jest wyłączony","Clear search input":"Wyczyść dane wyszukiwania","Click on this icon":"Kliknij tę ikonę",Close:n4,"Close all but current":"Zamknij wszystkie oprócz bieżących","Collapse all":"Zwinąć wszystkie","Compares current time with astronomical event":"Porównuje aktualny czas z wydarzeniem astronomicznym","Compares current time with the user specific time":"Porównuje aktualny czas z czasem określonym przez użytkownika","Compares the state value with user defined value":"Porównuje wartość stanu z wartością zdefiniowaną przez użytkownika",Condition:r4,Conditions:a4,"Configuration not saved.":"Konfiguracja nie została zapisana.",Console:l4,"Control or update some state":"Kontroluj lub aktualizuj stan","Control or update some state with delay":"Kontroluj lub aktualizuj jakiś stan z opóźnieniem","Convert blockly to javascript for ever.":"Bezpowrotna konwersja Blockly na Javascript.",Copied:c4,"Copy script":"Skopiuj skrypt","Copy to clipboard":"Skopiuj do schowka","Create new":"Utwórz nowy","Create new folder":"Utwórz nowy folder","Create new script":"Utwórz nowy skrypt","Create or edit CRON or time wizard":"Utwórz lub edytuj CRON lub kreator czasu","Dark Theme":"Ciemny schemat","Dark style":"Ciemny styl",Date:"Data","Debug instance":"Debuguj instancję","Debug options":"Opcje debugowania",December:u4,Default:d4,"Define cron...":"Zdefiniuj CRON ...","Define schedule...":"Zdefiniuj harmonogram ...",Delay:h4,Delete:p4,"Delete %s":"Usuń %s ...","Delete folder":"Usuń folder","Delete script":"Usuń skrypt",Description:g4,"Deselect all":"Odznacz wszystkie","Discard changes for %s":"Odrzuć zmiany dla %s",Done:m4,"Double click to write value":"Kliknij dwukrotnie, aby zapisać wartość","Download as file":"Download jako plik plik","Drop some files here or click...":"Upuść niektóre pliki tutaj lub kliknij ...","Duplicate name":"Duplikat nazwy","Edit script or just double click":"Edytuj skrypt lub po prostu kliknij dwukrotnie","Empty name is not allowed":"Pusta nazwa jest niedozwolona","End search mode":"Zakończ tryb wyszukiwania","Enter your question":"Wpisz swoją prośbę",Error:"Błąd","Error formatting code":"Błąd formatowania kodu","Error was found":"Błąd został znaleziony","Every day":"Codziennie",Exec:f4,"Executes some shell command":"Wykonuje polecenie powłoki","Existing scripts will be overwritten.":"Istniejące skrypty zostaną zastąpione.","Expand all":"Rozwiń wszystkie","Expert mode":"Tryb ekspercki",Explanation:$4,Export:b4,"Export all scripts":"Wyeksportuj wszystkie skrypty","Export blocks":"Eksportuj bloki","Export selected blocks":"Eksportuj wybrane bloki",Februar:v4,February:y4,Filter:_4,Folder:w4,Fr:k4,Friday:C4,Function:"Funkcja","Function editor":"Edytor funkcji","Function: executed":"Funkcja: wykonywana","Go to next line":"Przejdź do następnej linii","HTTP Call":"Połączenie HTTP","Hide logs":"Ukryj dzienniki",ID:T4,ID1:S4,ID2:E4,Import:I4,"Import blocks":"Importuj bloki","Import error":"Błąd importowania","Import scripts":"Importuj skrypty","Insert object ID":"Wstaw identyfikator obiektu",Instance:x4,"Instance is disabled":"Instancja jest wyłączona","Instance:":"Instancja:",Instances:D4,Instructions:A4,"Invalid CRON":"Nieprawidłowy CRON","It will not be possible to revert this operation.":"Cofnięcie tej operacji nie będzie możliwe.","JS description":"Tworzenie reguł w Javascript",Januar:O4,January:R4,July:M4,June:N4,"Just check":"Po prostu sprawdź","Keep my changes":"Zachowaj moje zmiany","Language:":"Język:","Learn More":"Ucz się więcej","Light style":"Lekki styl",Limit:L4,"Local time":"Czas lokalny","Locate file":"Znajdź plik","Log outputs":"Log dziennika","Log text":"Tekst dziennika","Log: %s":"Dziennik: %s","Make a HTTP get request":"Złóż żądanie HTTP get","Make a pause between actions":"Zrób przerwę między czynnościami",March:P4,"March ":"Marzec ",May:B4,Menu:j4,Message:F4,Mo:z4,Model:U4,Monday:H4,Month:W4,More:G4,Name:V4,"No API key found":"Nie znaleziono klucza API","No Chat GPT Key found":"Nie znaleziono klucza GPT czatu","No active host found":"Nie znaleziono aktywnego hosta","Nothing found":"Nic nie znaleziono",November:Y4,OK:K4,October:J4,Ok:X4,"On condition change":"W przypadku zmiany warunków","On script save or adapter start":"Podczas zapisywania skryptu lub uruchamiania adaptera","On weekdays":"W dni powszednie","Open configuration":"Otwarta konfiguracja","Operate two states":"Obsługuj dwa stany","Operations with two states":"Operacje z dwoma stanami","Paste your blocks here":"Wklej tutaj swoje bloki",Pause:q4,"Pause execution":"Wstrzymaj wykonanie","Pause script":"Wstrzymaj skrypt","Phone:":"Telefon:","Please select object ID...":"Wybierz identyfikator obiektu ...","Press Ctrl+Enter to get the answer":"Naciśnij klawisze Ctrl+Enter, aby uzyskać odpowiedź","Prettify the script":"Upiększ skrypt","Print some text in log":"Wydrukuj tekst w dzienniku","Priority:":"Priorytet:",Pushover:Z4,Pushsafer:Q4,"Read only ID selected: %s":"Wybrano identyfikator tylko do odczytu: %s",Reload:e8,Rename:t8,"Reorder scripts in folders":"Zmień kolejność skryptów w folderach",Repeat:s8,Restart:o8,Result:i8,"Resume execution":"Wznów wykonanie","Root folder":"Folder główny","Rules description":"Twórz reguły z blokami IF, THEN, ELSE","Run script":"Uruchom skrypt",Sa:n8,Saturday:r8,Save:a8,"Save all":"Zapisz wszystko","Say It":"Wypowiedz","Say some text via sayit adapter":"Powiedz tekst przez adapter sayit",Schedule:l8,Script:c8,"Script %s was modified on disk":"Skrypt %s został zmodyfikowany na dysku","Script was modified externally":"Skrypt został zmodyfikowany zewnętrznie","Script is not running":"Skrypt nie działa","Search in scripts":"Szukaj w skryptach","Search...":"Szukaj...","Select all":"Zaznacz wszystko","Send email":"Wysłać email","Sends an email":"Wysyła e-mail","Sends message via Pushsafer":"Wysyła wiadomość przez Pushsafer","Sends message via pushover":"Wysyła wiadomość przez pushover","Sends message via telegram":"Wysyła wiadomość telegramem","Sends message via whatsapp-cmb":"Wysyła wiadomość przez WhatsApp-cmb",September:u8,"Server time":"Czas serwera","Set state action":"Ustaw stan działania","Set with delay":"Ustaw z opóźnieniem","Shell command":"Polecenie powłoki","Show astronomical events":"Pokaż wydarzenia astronomiczne","Show javascript code":"Pokaż kod JavaScript","Show logs":"Pokaż dzienniki","Show only paused scripts":"Pokaż tylko wstrzymane skrypty","Show only running scripts":"Pokaż tylko działające skrypty","Show only scripts with problems":"Pokaż tylko skrypty z problemami",Simulate:d8,"Some files will be rejected":"Niektóre pliki zostaną odrzucone","Sound:":"Dźwięk:",Stack:h8,Start:p8,"Start script":"Uruchom skrypt",State:g8,"State condition":"Warunek stanu","Step into function":"Wejdź do funkcji","Step out from function":"Wyjdź z funkcji","Stop on exception":"Zatrzymaj się na wyjątku",Su:m8,"Subject:":"Temat:",Sunday:f8,"TS description":"Tworzenie reguł w Typescript",Telegram:$8,"Text:":"Tekst:",Th:b8,'The script "%s" has been modified by another user or in another window. Do you want to reload the script or keep your local changes?':'Skrypt "%s" został zmodyfikowany przez innego użytkownika lub w innym oknie. Czy chcesz przeładować skrypt, czy zachować lokalne zmiany?',"The script will be stopped and must be activated manually after debugging. Continue?":"Skrypt zostanie zatrzymany i należy go aktywować ręcznie po debugowaniu. Kontyntynuj?","This is advances option. You can write your own code here and it will be executed on trigger":"To jest opcja zaawansowana. Możesz tutaj napisać własny kod, który zostanie wykonany po wyzwoleniu",Thursday:v8,Time:y8,"Time condition":"Warunek czasowy","Title:":"Tytuł:","To:":"Do:","Trigger with value":"Wyzwalacz z wartością",Triggered:_8,Triggers:w8,"Triggers the on script saving or the javascript instance restart":"Uruchamia zapisywanie skryptu lub restart instancji javascript","Triggers the rule on update or change of some state":"Uruchamia regułę przy aktualizacji lub zmianie jakiegoś stanu","Triggers the rule periodically or on some specific time":"Uruchamia regułę okresowo lub w określonym czasie",Tu:k8,Tuesday:C8,URL:T8,"Unknown error":"Nieznany błąd","Unknown error!":"Nieznany błąd!","Use generated code":"Użyj wygenerowanego kodu","User function":"Funkcja użytkownika","User:":"Użytkownik:",Value:S8,"Vibration:":"Wibracja:",Volume:E8,We:I8,Wednesday:x8,"Whatsapp-cmb":"Whatsapp-cmb",Write:D8,"Write your own code":"Napisz swój własny kod",Yes:A8,"Yet exists!":"A jednak istnieje!","You can use %s in the URL to use current trigger value or %id to use the triggered object ID":"Możesz użyć %s w adresie URL, aby użyć bieżącej wartości wyzwalacza, %id, aby użyć wyzwalanego identyfikatora obiektu, %name, aby wyświetlić nazwę identyfikatora wyzwalanego obiektu, lub %old, aby użyć starej wartości wyzwalacza","You can use %s in the command to use current trigger value or %id to use the triggered object ID":"Możesz użyć %s w poleceniu, aby użyć bieżącej wartości wyzwalającej, %id, aby użyć identyfikatora wyzwalanego obiektu, %name, aby wyświetlić nazwę identyfikatora wyzwalanego obiektu, lub %old, aby użyć starej wartości wyzwalającej","You can use %s in the text to display current trigger value or %id to display the triggered object ID":"Możesz użyć %s w tekście, aby wyświetlić aktualną wartość wyzwalającą, %id, aby użyć identyfikatora wyzwolonego obiektu, %name, aby wyświetlić nazwę identyfikatora wyzwolonego obiektu lub %old, aby użyć starej wartości wyzwalającej","You can use %s in the value to use the current trigger value or %id to display the triggered object ID":"Możesz użyć %s w wartości, aby użyć bieżącej wartości wyzwalacza, %id, aby użyć identyfikatora wyzwalanego obiektu, %name, aby wyświetlić nazwę identyfikatora wyzwalanego obiektu, lub %old, aby użyć starej wartości wyzwalacza","You have to enter OpenAI API key in the configuration of javascript adapter.":"Należy wprowadzić klucz OpenAI API w konfiguracji adaptera javascript.","You have to enter at least one API key in the configuration of javascript adapter.":"Musisz wprowadzić co najmniej jeden klucz API (OpenAI, Anthropic lub Gemini) w konfiguracji adaptera javascript.","Please select a valid model":"Wybierz prawidłowy model","[equal]":"[równy]","[greater or equal]":"[większe lub równe]","[greater]":"[większe]","[hysteresis]":"[histereza]","[includes]":"[obejmuje]","[less or equal]":"[mniejsze lub równe]","[less]":"[mniejsze]","[not equal]":"[nie równe]",acknowledgment:O8,all:R8,and:M8,"as JSON":"jako JSON","as plain text":"jako zwykły tekst",astro:N8,at:L8,"clear running":"czyste uruchomienie",control:P8,copy:B8,cron:j8,dawn:F8,debug_help:z8,debug_label:U8,default:"domyślna",dusk:H8,easy:W8,else:"inaczej","equal to":"równy",every:G8,"every hour at 0 minutes":"co godzinę po 0 minutach",false:"fałsz","file reading has failed: %s":"odczyt pliku nie powiódł się: %s","file reading was aborted":"odczyt pliku został przerwany",filter_func:V8,filter_id:Y8,filter_name:K8,filter_role:J8,filter_room:X8,"for edit or create script":"do edycji lub utwórz nowy skrypt","for professionals":"dla profesjonalistów","for programmers":"dla programistów",goldenHour:q8,goldenHourEnd:Z8,"greater or equal":"większe lub równe","greater or equal to":"więcej lub równo","greater than":"więcej niż",help_just_check:Q8,help_on_change:e6,"high priority":"wysoki priorytet","high-priority":"wysoki priorytet","highest priority":"najwyższy priorytet",hours:t6,includes:s6,interval:o6,"just check":"po prostu sprawdź","less or equal":"mniejsze lub równe","less or equal to":"mniej lub równo","less than":"mniej niż","lower priority":"niższy priorytet","lowest priority":"najniższy priorytet",magic:i6,milliseconds:n6,minutes:r6,ms:a6,nadir:l6,nauticalDawn:c6,nauticalDusk:u6,nextSunrise:d6,nextSunset:h6,night:p6,nightEnd:g6,"no blocks found":"Nie znaleziono bloków","no group":"BRAK GRUPY",normal:m6,"normal priority":"normalny priorytet","not running":"nie uruchomiony","not equal to":"nie równa się","not properly connected":"Ten blok nie jest poprawnie podłączony do innych bloków.",offset:f6,"on change":"na zmianę","on condition change":"pod warunkiem zmiany warunków","on update":"po aktualizacji",one:$6,or:b6,quiet:v6,"reset search":"zresetuj wyszukiwanie",search:y6,seconds:_6,solarNoon:w6,"store in":"przechowaj w",sunrise:k6,sunriseEnd:C6,sunset:T6,sunsetStart:S6,then:E6,"toggle value":"wartość przełączania",tooltip_ack:I6,tooltip_from:x6,tooltip_lc:D6,tooltip_quality:A6,tooltip_ts:O6,tooltip_user:R6,tooltip_value:M6,true:"prawda",two:N6,undefined:"nieokreślony",update:L6,"use seconds":"użyj sekund","use trigger value":"użyj wartości wyzwalającej",verbose_help:P6,verbose_label:B6,when:j6,with:"z","with date":"z datą","with offset":"z przesunięciem",wizard:F6,"Loading models...":"Ładowanie modeli...","Could not connect to API at %s":"Nie można połączyć się z API pod adresem %s","Invalid API key":"Nieprawidłowy klucz API","Access denied by API":"Odmowa dostępu przez API","API error: %s":"Błąd API: %s",'Model "%s" not found':'Model "%s" nie znaleziony',"Request failed: %s":"Żądanie nie powiodło się: %s",Retry:z6,"No running javascript instance found":"Nie znaleziono uruchomionej instancji JavaScript","OID display mode":"Tryb wyświetlania OID"},H6="Reconhecido",W6="Ações",G6="Adicionar",V6="Todos",Y6="Nenhum",K6="Aplique",J6="abril",X6="Perguntar",q6="Astronômico",Z6="agosto",Q6="Cancelar",e9="Fechar",t9="Doença",s9="Condições",o9="Console",i9="Copiado",n9="dezembro",r9="Predefinição",a9="Atraso",l9="Deletar",c9="Descrição",u9="Pronto",d9="Exec shell",h9="Explicação",p9="Exportação",g9="Februar",m9="fevereiro",f9="Filtro",$9="Pasta",b9="Fr",v9="Sexta-feira",y9="ID",_9="ID1",w9="ID2",k9="Importar",C9="Instância",T9="Instâncias",S9="Instruções",E9="Januar",I9="janeiro",x9="julho",D9="junho",A9="Limite",O9="março",R9="maio",M9="Menu",N9="mensagem",L9="Mo",P9="Modelo",B9="Segunda-feira",j9="Mês",F9="Mais",z9="Nome",U9="novembro",H9="OK",W9="outubro",G9="Ok",V9="Pausa",Y9="Pushover",K9="Pushsafer",J9="Recarregar",X9="Renomear",q9="Repetir",Z9="Reiniciar",Q9="Resultado",eY="Sá",tY="Sábado",sY="Salve",oY="Cronograma",iY="Script",nY="setembro",rY="Simular",aY="Pilha",lY="Começar",cY="Estado",uY="Su",dY="Domingo",hY="Telegrama",pY="4",gY="Quinta-feira",mY="Tempo",fY="Provocado",$Y="Gatilhos",bY="Tu",vY="terça",yY="URL",_Y="Valor",wY="Volume",kY="3",CY="quarta",TY="Escrever",SY="sim",EY="reconhecimento",IY="todos",xY="e",DY="astro",AY="no",OY="ao controle",RY="copiar",MY="CRON",NY="alvorecer",LY="Este é um modo especial no qual estados e objetos não serão alterados. Mas apenas as informações sobre cada mudança planejada serão exibidas no protocolo.",PY="Depurar",BY="Crepúsculo",jY="fácil",FY="cada",zY="Função",UY="ID",HY="Nome",WY="Tipo",GY="Quarto",VY="Hora dourada",YY="Fim da hora de ouro",KY='O código será executado apenas sempre que a condição for verdadeira. Por exemplo. se disparar no valor do sensor de temperatura e a condição for "se a temperatura for maior que 20 ° C", as ações "então" serão executadas toda vez que o sensor enviar a temperatura e ela estiver acima de 20 ° C. Por 21 ° C, por 22 ° C e assim por diante.',JY='O código será executado apenas se o resultado da condição mudar. Por exemplo. se disparar no valor do sensor de temperatura e a condição for "se a temperatura for maior que 20 ° C", as ações "então" serão executadas uma vez quando a temperatura estiver acima de 20. Na próxima vez, as ações "então" serão executadas quando a temperatura falha abaixo de 20 e sobe acima de 20 novamente.',XY="horas",qY="inclui",ZY="intervalo",QY="Magia",eK="milissegundos",tK="minutos",sK="ms",oK="nadir",iK="Madrugada náutica",nK="Crepúsculo náutico",rK="próximo nascer do sol",aK="Próximo pôr do sol",lK="Noite",cK="Fim de noite",uK="normal",dK="Deslocamento",hK="1",pK="ou",gK="quieto",mK="procurar",fK="segundos",$K="Meio-dia solar",bK="nascer do sol",vK="Fim do nascer do sol",yK="pôr do sol",_K="Começo do pôr do sol",wK="então",kK="reconhecer",CK="de",TK="Última alteração",SK="Qualidade",EK="timestamp",IK="usuário",xK="valor",DK="dois",AK="atualizar",OK="Adiciona saída de depuração ao log para muitos comandos do sistema",RK="Saídas de log detalhadas",MK="quando",NK="Wizard",LK="Tentar novamente",PK={"%s not found":"%s não encontrado","()":"()","(at %s)":"(em %s)","(optional)":"(opcional)","-":"-",".":".","AI code generator":"Gerador de código de IA","Planning...":"Planejando...","Generating code...":"Gerando código...","Show plan":"Mostrar plano",Ack:H6,Actions:W6,"Actual time of day":"Hora real do dia",Add:G6,"Add new script":"Adicionar novo script",All:V6,"All files will be accepted":"Todos os arquivos serão aceitos",Any:Y6,"Any month":"Qualquer mês",Apply:K6,April:J6,"Are you sure?":"Você tem certeza?",Ask:X6,Astronomical:q6,"Astronomical events today":"Eventos astronômicos hoje",August:Z6,"Blockly description":"Criando regras por blocos gráficos","Body:":"Corpo:",Cancel:Q6,"Cannot delete non empty item!":"Não pode ser deletar, porque não está vazio!","Change layout":"Alterar layout",'Change theme (actual "%s")':'Alterar tema (agora - "%s")',"Check blocks":"Verificar blocos","Check is not active, because javascript adapter is disabled":"A verificação de sintaxe não está ativa porque o adaptador javascript não está rodando.","Clear search input":"Limpar entrada de pesquisa","Click on this icon":"Clique neste ícone",Close:e9,"Close all but current":"Fechar tudo, menos atual","Collapse all":"Recolher todos","Compares current time with astronomical event":"Compara o tempo atual com o evento astronômico","Compares current time with the user specific time":"Compara a hora atual com a hora específica do usuário","Compares the state value with user defined value":"Compara o valor do estado com o valor definido pelo usuário",Condition:t9,Conditions:s9,"Configuration not saved.":"Configuração não esta salva.",Console:o9,"Control or update some state":"Controlar ou atualizar algum estado","Control or update some state with delay":"Controlar ou atualizar algum estado com atraso","Convert blockly to javascript for ever.":"Converter Blockly em Javascript permanentemente.",Copied:i9,"Copy script":"Copiar script","Copy to clipboard":"Copiar para área de transferência","Create new":"Crie um novo","Create new folder":"Criar nova pasta","Create new script":"Criar novo script","Create or edit CRON or time wizard":"Criar ou editar o assistente cron ou o assistente de horário","Dark Theme":"Layout escuro","Dark style":"Estilo escuro",Date:"Encontro","Debug instance":"Instância de depuração","Debug options":"Opções de depuração",December:n9,Default:r9,"Define cron...":"Definir cron...","Define schedule...":"Definir agendamento ...",Delay:a9,Delete:l9,"Delete %s":"Deletar %s...","Delete folder":"Deletar pasta","Delete script":"Deletar script",Description:c9,"Deselect all":"Desmarcar todos","Discard changes for %s":"Descartar alterações para %s",Done:u9,"Double click to write value":"Clique duas vezes para escrever o valor","Download as file":"Baixar como arquivo","Drop some files here or click...":"Solte alguns arquivos aqui ou clique em...","Duplicate name":"Nome duplicado","Edit script or just double click":"Edite o script ou clique duas vezes","Empty name is not allowed":"Nome vazio não é permitido","End search mode":"Finalizar modo de pesquisa","Enter your question":"Digite sua solicitação",Error:"Erro","Error formatting code":"Erro de formatação de código","Error was found":"Erro foi encontrado","Every day":"Todos os dias",Exec:d9,"Executes some shell command":"Executa algum comando shell","Existing scripts will be overwritten.":"Os scripts existentes serão substituídos.","Expand all":"Expandir todos","Expert mode":"Modo de especialista",Explanation:h9,Export:p9,"Export all scripts":"Exportar todos os scripts","Export blocks":"Exportar blocos","Export selected blocks":"Exportar blocos selecionados",Februar:g9,February:m9,Filter:f9,Folder:$9,Fr:b9,Friday:v9,Function:"Função","Function editor":"Editor de funções","Function: executed":"Função: executado","Go to next line":"Vá para a próxima linha","HTTP Call":"Chamada HTTP","Hide logs":"Ocultar logs",ID:y9,ID1:_9,ID2:w9,Import:k9,"Import blocks":"Importar blocos","Import error":"Erro de importação","Import scripts":"Importar script","Insert object ID":"Inserir ID do objeto",Instance:C9,"Instance is disabled":"Instância está desativada","Instance:":"Instância:",Instances:T9,Instructions:S9,"Invalid CRON":"CRON inválido","It will not be possible to revert this operation.":"Não será possível reverter esta operação.","JS description":"Criando regras escrevendo Javascript",Januar:E9,January:I9,July:x9,June:D9,"Just check":"Apenas verifique","Keep my changes":"Manter minhas alterações","Language:":"Língua:","Learn More":"Aprender mais","Light style":"Estilo claro",Limit:A9,"Local time":"Hora local","Locate file":"Localize o arquivo","Log outputs":"Saídas de log","Log text":"Texto de registro","Log: %s":"Log: %s","Make a HTTP get request":"Faça uma solicitação HTTP get","Make a pause between actions":"Faça uma pausa entre as ações",March:O9,"March ":"Março",May:R9,Menu:M9,Message:N9,Mo:L9,Model:P9,Monday:B9,Month:j9,More:F9,Name:z9,"No API key found":"Nenhuma chave API encontrada","No Chat GPT Key found":"Nenhuma chave GPT de bate-papo encontrada","No active host found":"Nenhum host ativo encontrado","Nothing found":"Nada encontrado",November:U9,OK:H9,October:W9,Ok:G9,"On condition change":"Na mudança de condição","On script save or adapter start":"Ao salvar o script ou iniciar o adaptador","On weekdays":"Nos dias úteis","Open configuration":"Configuração aberta","Operate two states":"Operar dois estados","Operations with two states":"Operações com dois estados","Paste your blocks here":"Cole seus blocos aqui",Pause:V9,"Pause execution":"Pausar a execução","Pause script":"Pausar script","Phone:":"Telefone:","Please select object ID...":"Selecione o ID do objeto...","Press Ctrl+Enter to get the answer":"Pressione Ctrl+Enter para obter a resposta","Prettify the script":"Embeleze o roteiro","Print some text in log":"Imprimir algum texto no log","Priority:":"Prioridade:",Pushover:Y9,Pushsafer:K9,"Read only ID selected: %s":"ID somente leitura selecionada: %s",Reload:J9,Rename:X9,"Reorder scripts in folders":"Reordenar scripts em pastas",Repeat:q9,Restart:Z9,Result:Q9,"Resume execution":"Retomar execução","Root folder":"Pasta principal","Rules description":"Crie regras com blocos IF, THEN, ELSE","Run script":"Executar script",Sa:eY,Saturday:tY,Save:sY,"Save all":"Salvar tudo","Say It":"Say It","Say some text via sayit adapter":"Diga algum texto através do adaptador sayit",Schedule:oY,Script:iY,"Script %s was modified on disk":'O script "%s" foi modificado no disco rígido',"Script was modified externally":"O script foi modificado externamente","Script is not running":"Script não está sendo executado","Search in scripts":"Pesquisa em scripts","Search...":"Procurar...","Select all":"Selecionar tudo","Send email":"Enviar email","Sends an email":"Envia um email","Sends message via Pushsafer":"Envia mensagem via Pushsafer","Sends message via pushover":"Envia mensagem via pushover","Sends message via telegram":"Envia mensagem via telegrama","Sends message via whatsapp-cmb":"Envia mensagem via whatsapp-cmb",September:nY,"Server time":"Tempo de servidor","Set state action":"Definir ação de estado","Set with delay":"Definido com atraso","Shell command":"Comando shell","Show astronomical events":"Mostrar eventos astronômicos","Show javascript code":"Mostrar código Javascript","Show logs":"Mostrar logs","Show only paused scripts":"Mostrar apenas scripts pausados","Show only running scripts":"Mostrar apenas scripts em execução","Show only scripts with problems":"Mostrar apenas scripts com problemas",Simulate:rY,"Some files will be rejected":"Alguns arquivos serão rejeitados","Sound:":"Som:",Stack:aY,Start:lY,"Start script":"Iniciar script",State:cY,"State condition":"Condição de estado","Step into function":"Entre na função","Step out from function":"Saia da função","Stop on exception":"Pare na exceção",Su:uY,"Subject:":"Sujeito:",Sunday:dY,"TS description":"Criando regras escrevendo Typecript",Telegram:hY,"Text:":"Texto:",Th:pY,'The script "%s" has been modified by another user or in another window. Do you want to reload the script or keep your local changes?':'O script "%s" foi modificado por outro usuário ou em outra janela. Deseja recarregar o script ou manter suas alterações locais?',"The script will be stopped and must be activated manually after debugging. Continue?":"O script será interrompido e deve ser ativado manualmente após a depuração. Continuar?","This is advances option. You can write your own code here and it will be executed on trigger":"Esta é a opção de avanços. Você pode escrever seu próprio código aqui e ele será executado no gatilho",Thursday:gY,Time:mY,"Time condition":"Condição de tempo","Title:":"Título:","To:":"Para:","Trigger with value":"Trigger com valor",Triggered:fY,Triggers:$Y,"Triggers the on script saving or the javascript instance restart":"Aciona o salvamento do script ou a reinicialização da instância javascript","Triggers the rule on update or change of some state":"Aciona a regra na atualização ou mudança de algum estado","Triggers the rule periodically or on some specific time":"Aciona a regra periodicamente ou em algum momento específico",Tu:bY,Tuesday:vY,URL:yY,"Unknown error":"Erro desconhecido","Unknown error!":"Erro desconhecido!","Use generated code":"Usar código gerado","User function":"Função do usuário","User:":"Do utilizador:",Value:_Y,"Vibration:":"Vibração:",Volume:wY,We:kY,Wednesday:CY,"Whatsapp-cmb":"Whatsapp-cmb",Write:TY,"Write your own code":"Escreva seu próprio código",Yes:SY,"Yet exists!":"Ainda existe!","You can use %s in the URL to use current trigger value or %id to use the triggered object ID":"Você pode usar %s na URL para usar o valor do gatilho atual, %id para usar o ID do objeto acionado, %name para mostrar o nome do ID do objeto acionado ou %old para usar o valor do gatilho antigo","You can use %s in the command to use current trigger value or %id to use the triggered object ID":"Você pode usar %s no comando para usar o valor do acionador atual, %id para usar o ID do objeto acionado, %name para mostrar o nome do ID do objeto acionado ou %old para usar o valor do acionador antigo","You can use %s in the text to display current trigger value or %id to display the triggered object ID":"Você pode usar %s no texto para exibir o valor do acionador atual, %id para usar o ID do objeto acionado, %name para mostrar o nome do ID do objeto acionado ou %old para usar o valor do acionador antigo","You can use %s in the value to use the current trigger value or %id to display the triggered object ID":"Você pode usar %s no valor para usar o valor do acionador atual, %id para usar o ID do objeto acionado, %name para mostrar o nome do ID do objeto acionado ou %old para usar o valor do acionador antigo","You have to enter OpenAI API key in the configuration of javascript adapter.":"Você deve inserir a chave da API OpenAI na configuração do adaptador javascript.","You have to enter at least one API key in the configuration of javascript adapter.":"Você deve inserir pelo menos uma chave API (OpenAI, Anthropic ou Gemini) na configuração do adaptador javascript.","Please select a valid model":"Selecione um modelo válido","[equal]":"[igual]","[greater or equal]":"[maior ou igual]","[greater]":"[maior]","[hysteresis]":"[histerese]","[includes]":"[inclui]","[less or equal]":"[menor ou igual]","[less]":"[menos]","[not equal]":"[não igual]",acknowledgment:EY,all:IY,and:xY,"as JSON":"como JSON","as plain text":"como texto simples",astro:DY,at:AY,"clear running":"corrida limpa",control:OY,copy:RY,cron:MY,dawn:NY,debug_help:LY,debug_label:PY,default:"predefinição",dusk:BY,easy:jY,else:"outro","equal to":"igual a",every:FY,"every hour at 0 minutes":"a cada hora em 0 minutos",false:"falso","file reading has failed: %s":"a leitura do arquivo falhou: %s","file reading was aborted":"a leitura do arquivo foi abortada",filter_func:zY,filter_id:UY,filter_name:HY,filter_role:WY,filter_room:GY,"for edit or create script":"para editar ou criar um novo script","for professionals":"para profissionais","for programmers":"para programadores",goldenHour:VY,goldenHourEnd:YY,"greater or equal":"maior ou igual","greater or equal to":"maior ou igual a","greater than":"Maior que",help_just_check:KY,help_on_change:JY,"high priority":"prioridade máxima","high-priority":"prioridade máxima","highest priority":"Prioridade máxima",hours:XY,includes:qY,interval:ZY,"just check":"Apenas verifique","less or equal":"menor ou igual","less or equal to":"menor ou igual a","less than":"Menor que","lower priority":"prioridade mais baixa","lowest priority":"prioridade mais baixa",magic:QY,milliseconds:eK,minutes:tK,ms:sK,nadir:oK,nauticalDawn:iK,nauticalDusk:nK,nextSunrise:rK,nextSunset:aK,night:lK,nightEnd:cK,"no blocks found":"Nenhum bloco encontrado","no group":"SEM GRUPO",normal:uK,"normal priority":"prioridade normal","not running":"não está em execução","not equal to":"não é igual a","not properly connected":"Este bloco não está conectado corretamente com outros blocos.",offset:dK,"on change":"em mudança","on condition change":"na mudança de condição","on update":"em atualização",one:hK,or:pK,quiet:gK,"reset search":"redefinir pesquisa",search:mK,seconds:fK,solarNoon:$K,"store in":"armazenar em",sunrise:bK,sunriseEnd:vK,sunset:yK,sunsetStart:_K,then:wK,"toggle value":"valor de alternância",tooltip_ack:kK,tooltip_from:CK,tooltip_lc:TK,tooltip_quality:SK,tooltip_ts:EK,tooltip_user:IK,tooltip_value:xK,true:"verdade",two:DK,undefined:"Indefinido",update:AK,"use seconds":"use segundos","use trigger value":"use o gatilho",verbose_help:OK,verbose_label:RK,when:MK,with:"com","with date":"com data","with offset":"com deslocamento",wizard:NK,"Loading models...":"Carregando modelos...","Could not connect to API at %s":"Não foi possível conectar à API em %s","Invalid API key":"Chave API inválida","Access denied by API":"Acesso negado pela API","API error: %s":"Erro de API: %s",'Model "%s" not found':'Modelo "%s" não encontrado',"Request failed: %s":"Solicitação falhou: %s",Retry:LK,"No running javascript instance found":"Nenhuma instância JavaScript em execução encontrada","OID display mode":"Modo de exibição OID"},BK="Подтверждение",jK="Действия",FK="Добавить",zK="Все",UK="Любая",HK="Применить",WK="Апрель",GK="Спросить",VK="Aстрономический",YK="Август",KK="Отмена",JK="Закрыть",XK="Условие",qK="Условия",ZK="Приставка",QK="Скопировано",e7="Декабрь",t7="Дефолт",s7="Задержка",o7="Удалить",i7="Описание",n7="Готово",r7="Исполнить shell",a7="Объяснение",l7="Экспорт",c7="Февраль",u7="Февраль",d7="Фильтр",h7="Папка",p7="Пт",g7="пятница",m7="ID",f7="ID1",$7="ID2",b7="Импорт",v7="Экземпляр",y7="Экземпляры",_7="Инструкции",w7="Январь",k7="Январь",C7="Июль",T7="Июнь",S7="Предел",E7="Март",I7="Май",x7="Меню",D7="Сообщение",A7="Пн",O7="Модель",R7="понедельник",M7="Месяц",N7="Более",L7="Имя",P7="Ноябрь",B7="Ок",j7="Октябрь",F7="Ok",z7="Пауза",U7="Pushover",H7="Pushsafer",W7="Перезагрузить",G7="Переименовать",V7="Повторение",Y7="Перезапустить",K7="Результат",J7="Сб",X7="суббота",q7="Сохранить",Z7="Расписание",Q7="скрипт",eJ="Сентябрь",tJ="Симулировать",sJ="Stack",oJ="Начинать",iJ="Состояние",nJ="Вс",rJ="Воскресенье",aJ="Telegram",lJ="Чт",cJ="Четверг",uJ="Время",dJ="Срабатывает",hJ="Триггеры",pJ="Вт",gJ="вторник",mJ="URL",fJ="Значение",$J="Громкость",bJ="Ср",vJ="среда",yJ="Напишите",_J="Да",wJ="подтверждение",kJ="все",CJ="и",TJ="Астро",SJ="в",EJ="контроль",IJ="копия",xJ="CRON",DJ="Рассвет",AJ="Это особый режим, в котором состояния и объекты не будут меняться. Но в протоколе будет отображаться только информация о каждом планируемом изменении.",OJ="Отлаживать",RJ="Сумерки",MJ="легкий",NJ="каждые(ый)",LJ="Функция",PJ="ID",BJ="Название",jJ="Роль",FJ="Комната",zJ="Золотой час",UJ="Конец золотого часа",HJ="Код будет выполняться только каждый раз, когда условие истинно. Например. при срабатывании по значению датчика температуры и условию «если температура выше 20°C», действия «затем» будут выполняться каждый раз, когда датчик отправляет значение температуры, и оно превышает 20°C. На 21°С, на 22°С и так далее.",WJ="Код будет выполнен только в случае изменения результата условия. Например, при срабатывании по значению датчика температуры и условию «если температура больше 20°C», действия «затем» будут выполнены один раз, когда температура превысит 20°C. В следующий раз действия «затем» будут выполнены, когда температура опустится ниже 20°C, а затем снова поднимается выше 20°C.",GJ="час(ов)",VJ="содержит",YJ="интервал",KJ="магия",JJ="миллисекунды",XJ="минут(у)",qJ="мс",ZJ="Надир",QJ="Морской рассвет",eX="Морские сумерки",tX="Следующий восход",sX="Следующий закат",oX="Ночь",iX="Конец ночи",nX="нормальный",rX="сдвиг",aX="один",lX="или",cX="тихий",uX="поиск",dX="секунд",hX="Солнечный полдень",pX="Восход солнца",gX="Конец восхода",mX="Закат солнца",fX="Начало заката",$X="тогда",bX="Подтверждено",vX="От",yX="Последнее изменение",_X="Качественный",wX="Время",kX="Пользователь",CX="Значение",TX="два",SX="обновить",EX="Добавляет вывод отладки в журнал для многих системных команд.",IX="Подробный протокол",xX="если",DX="Мастер",AX="Повторить",OX={"%s not found":"%s не найден","()":"()","(at %s)":"(в %s)","(optional)":"(необязательный)","-":"-",".":".","AI code generator":"ИИ Генератор кода","Planning...":"Планирование...","Generating code...":"Генерация кода...","Show plan":"Показать план",Ack:BK,Actions:jK,"Actual time of day":"Фактическое время суток",Add:FK,"Add new script":"Добавить новый скрипт",All:zK,"All files will be accepted":"Все файлы будут приняты",Any:UK,"Any month":"В любой месяц",Apply:HK,April:WK,"Are you sure?":"Вы уверены?",Ask:GK,Astronomical:VK,"Astronomical events today":"Астрономические события сегодня",August:YK,"Blockly description":"Создание правил графическими блоками","Body:":"Тело:",Cancel:KK,"Cannot delete non empty item!":"Не удается удалить непустой элемент!","Change layout":"Изменить макет",'Change theme (actual "%s")':'Сменить тему (сейчас - "%s")',"Check blocks":"Проверить блоки","Check is not active, because javascript adapter is disabled":"Проверка неактивна, потому что адаптер Javascript отключен","Clear search input":"Очистить ввод","Click on this icon":"Нажмите на этот значок",Close:JK,"Close all but current":"Закрыть все кроме текущего","Collapse all":"Свернуть все","Compares current time with astronomical event":"Сравнивает текущее время с астрономическим событием","Compares current time with the user specific time":"Сравнивает текущее время с конкретным временем пользователя","Compares the state value with user defined value":"Сравнивает значение состояния с пользовательским значением",Condition:XK,Conditions:qK,"Configuration not saved.":"Конфигурация не сохранена.",Console:ZK,"Control or update some state":"Контролировать или обновлять какое-то состояние","Control or update some state with delay":"Контролировать или обновлять какое-либо состояние с задержкой","Convert blockly to javascript for ever.":"Преобразовать blockly в Javascript навсегда.",Copied:QK,"Copy script":"Скопировать скрипт","Copy to clipboard":"Скопировать в буфер обмена","Create new":"Создать новый","Create new folder":"Создать новую папку","Create new script":"Создать новый скрипт","Create or edit CRON or time wizard":"Создание или редактирование CRON или мастера времени","Dark Theme":"Тёмная тема","Dark style":"Темный стиль",Date:"Дата","Debug instance":"Экземпляр отладки","Debug options":"Варианты отладки",December:e7,Default:t7,"Define cron...":"Задать правило ...","Define schedule...":"Задать расписание...",Delay:s7,Delete:o7,"Delete %s":"Удалить %s...","Delete folder":"Удалить папку","Delete script":"Удалить скрипт",Description:i7,"Deselect all":"Снять выбор со всех","Discard changes for %s":"Отменить изменения для %s",Done:n7,"Double click to write value":"Двойной щелчок для записи значения","Download as file":"Скачать как файл","Drop some files here or click...":"Перетыщите сюда файлы или нажмите ...","Duplicate name":"Повторяющееся имя","Edit script or just double click":"Редактировать скрипт или просто дважды щелкнуть","Empty name is not allowed":"Пустое имя не допускается","End search mode":"Закончить поиск","Enter your question":"Введи свою просьбу",Error:"Ошибка","Error formatting code":"Ошибка форматирования кода","Error was found":"Ошибка была найдена","Every day":"Каждый день",Exec:r7,"Executes some shell command":"Выполняет некоторую команду оболочки","Existing scripts will be overwritten.":"Существующие скрипты будут перезаписаны.","Expand all":"Открыть все","Expert mode":"Экспертный режим",Explanation:a7,Export:l7,"Export all scripts":"Экспорт всех скриптов","Export blocks":"Экспортировать блоки","Export selected blocks":"Экспортировать выбранные блоки",Februar:c7,February:u7,Filter:d7,Folder:h7,Fr:p7,Friday:g7,Function:"Функция","Function editor":"Редактор функции","Function: executed":"Функция: выполнено","Go to next line":"Перейти к следующей строке","HTTP Call":"HTTP-вызов","Hide logs":"Скрыть журналы",ID:m7,ID1:f7,ID2:$7,Import:b7,"Import blocks":"Импортировать блоки","Import error":"Ошибка импорта","Import scripts":"Импорт скриптов","Insert object ID":"Вставить ID объекта",Instance:v7,"Instance is disabled":"Экземпляр отключен","Instance:":"Пример:",Instances:y7,Instructions:_7,"Invalid CRON":"Неправильный CRON","It will not be possible to revert this operation.":"Невозможно вернуть эту операцию.","JS description":"Создание правил путём написания Javascript",Januar:w7,January:k7,July:C7,June:T7,"Just check":"Просто проверить","Keep my changes":"Сохранить мои изменения","Language:":"Язык:","Learn More":"Узнать больше","Light style":"Светлый стиль",Limit:S7,"Local time":"Местное время","Locate file":"Показать файл в дереве","Log outputs":"Журнал","Log text":"Текст журнала","Log: %s":"Журнал: %s","Make a HTTP get request":"Сделайте HTTP-запрос на получение","Make a pause between actions":"Сделайте паузу между действиями",March:E7,"March ":"Март ",May:I7,Menu:x7,Message:D7,Mo:A7,Model:O7,Monday:R7,Month:M7,More:N7,Name:L7,"No API key found":"API-ключ не найден","No Chat GPT Key found":"Ключ GPT для чата не найден","No active host found":"Активный host не найден","Nothing found":"Ничего не найдено",November:P7,OK:B7,October:j7,Ok:F7,"On condition change":"При изменении реузльтата условий","On script save or adapter start":"При сохранении скрипта или запуске адаптера","On weekdays":"По дням недели","Open configuration":"Открыть настройки","Operate two states":"Операции над двумя состояниями","Operations with two states":"Операции с двумя состояниями","Paste your blocks here":"Вставьте свои блоки сюда",Pause:z7,"Pause execution":"Приостановить выполнение","Pause script":"Остановить скрипт","Phone:":"Телефон:","Please select object ID...":"Пожалуйста, выберите ID объекта ...","Press Ctrl+Enter to get the answer":"Нажмите Ctrl+Enter, чтобы получить ответ","Prettify the script":"Украсьте сценарий","Print some text in log":"Напечатать текст в журнале","Priority:":"Приоритет:",Pushover:U7,Pushsafer:H7,"Read only ID selected: %s":"Выбран идентификатор только для чтения: %s",Reload:W7,Rename:G7,"Reorder scripts in folders":"Сортировать скрипты в папках",Repeat:V7,Restart:Y7,Result:K7,"Resume execution":"Возобновить выполнение","Root folder":"Корневая папка","Rules description":"Создавайте правила с блоками ЕСЛИ, ТО, ИНАЧЕ","Run script":"Запустить скрипт",Sa:J7,Saturday:X7,Save:q7,"Save all":"Сохранить все","Say It":"Say It","Say some text via sayit adapter":"Произнесите текст через адаптер Sayit",Schedule:Z7,Script:Q7,"Script %s was modified on disk":'Скрипт "%s" был изменен на диске',"Script was modified externally":"Скрипт был изменён извне","Script is not running":"Сценарий не запущен","Search in scripts":"Поиск в скриптах","Search...":"Поиск...","Select all":"Выбрать все","Send email":"Отправить email","Sends an email":"Отправляет электронное письмо","Sends message via Pushsafer":"Отправляет сообщение через Pushsafer","Sends message via pushover":"Отправляет сообщение через пустышку","Sends message via telegram":"Отправляет сообщение в телеграмме","Sends message via whatsapp-cmb":"Отправляет сообщение через whatsapp-cmb",September:eJ,"Server time":"Время сервера","Set state action":"Установить состояние","Set with delay":"Установить с задержкой","Shell command":"Команда оболочки","Show astronomical events":"Показать астрономические события","Show javascript code":"Показать код Javascript","Show logs":"Показать журналы","Show only paused scripts":"Показывать только приостановленные сценарии","Show only running scripts":"Показывать только запущенные скрипты","Show only scripts with problems":"Показывать только скрипты с проблемами",Simulate:tJ,"Some files will be rejected":"Некоторые файлы будут отклонены","Sound:":"Звук:",Stack:sJ,Start:oJ,"Start script":"Старт скрипта",State:iJ,"State condition":"Сравнение состояния","Step into function":"Шаг в функционирование","Step out from function":"Выйти из функции","Stop on exception":"Остановить при исключении",Su:nJ,"Subject:":"Предмет:",Sunday:rJ,"TS description":"Создание правил путём написания Typescript",Telegram:aJ,"Text:":"Текст:",Th:lJ,'The script "%s" has been modified by another user or in another window. Do you want to reload the script or keep your local changes?':'Скрипт "%s" был изменён другим пользователем или в другом окне. Вы хотите перезагрузить скрипт или сохранить свои локальные изменения?',"The script will be stopped and must be activated manually after debugging. Continue?":"Cкрипт будет остановлен и должен быть активирован вручную после отладки. Продолжать?","This is advances option. You can write your own code here and it will be executed on trigger":"Это расширеный вариант. Вы можете написать здесь свой код и он будет выполняться по триггеру",Thursday:cJ,Time:uJ,"Time condition":"Условие времени","Title:":"Заголовок:","To:":"К:","Trigger with value":"Триггер со значением",Triggered:dJ,Triggers:hJ,"Triggers the on script saving or the javascript instance restart":"Запускает при сохранении скрипта или перезапуске экземпляра javascript","Triggers the rule on update or change of some state":"Запускает правило при обновлении или изменении какого-либо состояния","Triggers the rule periodically or on some specific time":"Срабатывает правило периодически или в определенное время",Tu:pJ,Tuesday:gJ,URL:mJ,"Unknown error":"Неизвестная ошибка","Unknown error!":"Неизвестная ошибка!","Use generated code":"Использовать сгенерированный код","User function":"Функция пользователя","User:":"Пользователь:",Value:fJ,"Vibration:":"Вибрация:",Volume:$J,We:bJ,Wednesday:vJ,"Whatsapp-cmb":"Whatsapp-cmb",Write:yJ,"Write your own code":"Напишите свой код",Yes:_J,"Yet exists!":"Имя уже существует!","You can use %s in the URL to use current trigger value or %id to use the triggered object ID":"Вы можете использовать %s в URL-адресе, чтобы использовать текущее значение триггера, %id, чтобы использовать идентификатор инициированного объекта, %name, чтобы показать имя идентификатора инициированного объекта, или %old, чтобы использовать старое значение триггера.","You can use %s in the command to use current trigger value or %id to use the triggered object ID":"Вы можете использовать %s в команде, чтобы использовать текущее значение триггера, %id, чтобы использовать идентификатор сработавшего объекта, %name, чтобы показать имя сработавшего идентификатора объекта, или %old, чтобы использовать старое значение триггера.","You can use %s in the text to display current trigger value or %id to display the triggered object ID":"Вы можете использовать %s в тексте для отображения текущего значения триггера, %id для использования идентификатора сработавшего объекта, %name для отображения имени сработавшего идентификатора объекта или %old для использования старого значения триггера.","You can use %s in the value to use the current trigger value or %id to display the triggered object ID":"Вы можете использовать %s в значении, чтобы использовать текущее значение триггера, %id, чтобы использовать идентификатор инициированного объекта, %name, чтобы показать имя идентификатора инициированного объекта, или %old, чтобы использовать старое значение триггера.","You have to enter OpenAI API key in the configuration of javascript adapter.":"Вы должны ввести ключ OpenAI API в конфигурации адаптера javascript.","You have to enter at least one API key in the configuration of javascript adapter.":"Необходимо ввести хотя бы один API-ключ (OpenAI, Anthropic или Gemini) в конфигурации адаптера javascript.","Please select a valid model":"Пожалуйста, выберите допустимую модель","[equal]":"[равно]","[greater or equal]":"[больше или равно]","[greater]":"[больше]","[hysteresis]":"[гистерезис]","[includes]":"[содержит]","[less or equal]":"[меньше или равно]","[less]":"[меньше]","[not equal]":"[не равно]",acknowledgment:wJ,all:kJ,and:CJ,"as JSON":"как JSON","as plain text":"как текст",astro:TJ,at:SJ,"clear running":"остановить уже бегущие",control:EJ,copy:IJ,cron:xJ,dawn:DJ,debug_help:AJ,debug_label:OJ,default:"дефолт",dusk:RJ,easy:MJ,else:"иначе","equal to":"равно",every:NJ,"every hour at 0 minutes":"каждый час через 0 минут",false:"false","file reading has failed: %s":"Ошибка чтения файла: %s","file reading was aborted":"Чтение файла было прервано",filter_func:LJ,filter_id:PJ,filter_name:BJ,filter_role:jJ,filter_room:FJ,"for edit or create script":"для редактирования или создайте новый скрипт","for professionals":"для профессионалов","for programmers":"для программистов",goldenHour:zJ,goldenHourEnd:UJ,"greater or equal":"больше или равно","greater or equal to":"больше или равно","greater than":"больше чем",help_just_check:HJ,help_on_change:WJ,"high priority":"высокий приоритет","high-priority":"высокий-приоритет","highest priority":"высший приоритет",hours:GJ,includes:VJ,interval:YJ,"just check":"просто проверить","less or equal":"меньше или равно","less or equal to":"меньше или равно","less than":"меньше, чем","lower priority":"более низкий приоритет","lowest priority":"самый низкий приоритет",magic:KJ,milliseconds:JJ,minutes:XJ,ms:qJ,nadir:ZJ,nauticalDawn:QJ,nauticalDusk:eX,nextSunrise:tX,nextSunset:sX,night:oX,nightEnd:iX,"no blocks found":"Блоков нет","no group":"Нет группы",normal:nX,"normal priority":"нормальный приоритет","not running":"не запущен","not equal to":"не равно","not properly connected":"Этот блок неправильно соединён или не соединён с другими блоками.",offset:rX,"on change":"по изменению","on condition change":"при изменении результата условия","on update":"при обновлении",one:aX,or:lX,quiet:cX,"reset search":"Cбросить поиск",search:uX,seconds:dX,solarNoon:hX,"store in":"сохранить в",sunrise:pX,sunriseEnd:gX,sunset:mX,sunsetStart:fX,then:$X,"toggle value":"инвертировать текщее значение",tooltip_ack:bX,tooltip_from:vX,tooltip_lc:yX,tooltip_quality:_X,tooltip_ts:wX,tooltip_user:kX,tooltip_value:CX,true:"true",two:TX,undefined:"неопределенный",update:SX,"use seconds":"использовать секунды","use trigger value":"использовать значение триггера",verbose_help:EX,verbose_label:IX,when:xX,with:"с","with date":"с датой","with offset":"со сдвигом",wizard:DX,"Loading models...":"Загрузка моделей...","Could not connect to API at %s":"Не удалось подключиться к API по адресу %s","Invalid API key":"Недействительный ключ API","Access denied by API":"Доступ запрещён API","API error: %s":"Ошибка API: %s",'Model "%s" not found':'Модель "%s" не найдена',"Request failed: %s":"Запрос не удался: %s",Retry:AX,"No running javascript instance found":"Не найден работающий экземпляр JavaScript","OID display mode":"Режим отображения OID"},RX="Визнано",MX="Дії",NX="додати",LX="все",PX="Будь-який",BX="Застосувати",jX="квітень",FX="Запитуйте",zX="Астрономічний",UX="серпень",HX="Скасувати",WX="Закрити",GX="Хвороба",VX="Умови",YX="Консоль",KX="Скопійовано",JX="Грудень",XX="За замовчуванням",qX="Затримка",ZX="Видалити",QX="опис",eq="Готово",tq="Виконавча оболонка",sq="Пояснення",oq="Експорт",iq="Лютий",nq="Лютий",rq="фільтр",aq="Папка",lq="О",cq="П'ятниця",uq="ID",dq="ID1",hq="ID2",pq="Імпорт",gq="Екземпляр",mq="Примірники",fq="Інструкції",$q="січень",bq="січня",vq="липень",yq="червень",_q="Ліміт",wq="березень",kq="Може",Cq="Меню",Tq="повідомлення",Sq="пн",Eq="Модель",Iq="понеділок",xq="місяць",Dq="Більше",Aq="Ім'я",Oq="Листопад",Rq="в порядку",Mq="жовтень",Nq="В порядку",Lq="Пауза",Pq="Pushover",Bq="Pushsafer",jq="Перезавантажити",Fq="Перейменувати",zq="Повторіть",Uq="Перезапустіть",Hq="Результат",Wq="Sa",Gq="Субота",Vq="зберегти",Yq="розклад",Kq="Сценарій",Jq="Вересень",Xq="Симулювати",qq="Стек",Zq="старт",Qq="Держава",eZ="Нд",tZ="неділя",sZ="Телеграма",oZ="чт",iZ="четвер",nZ="час",rZ="Спрацьовує",aZ="Тригери",lZ="вт",cZ="вівторок",uZ="URL",dZ="Значення",hZ="Обсяг",pZ="ми",gZ="Середа",mZ="Напишіть",fZ="Так",$Z="підтвердження",bZ="все",vZ="і",yZ="Астро",_Z="в",wZ="КОНТРОЛЬ",kZ="копія",CZ="CRON",TZ="Світанок",SZ="Це особливий режим, в якому стану та об'єкти не змінюватимуться. Але в протоколі відображатиметься лише інформація про кожну заплановану зміну.",EZ="Відлагоджувати",IZ="Сутінки",xZ="легко",DZ="кожен",AZ="функція",OZ="ID",RZ="Ім'я",MZ="Роль",NZ="Кімната",LZ="Золота година",PZ="Кінець золотої години",BZ="Код буде виконуватися лише щоразу, коли умова виконується. наприклад якщо спрацьовує значення датчика температури та умова «якщо температура перевищує 20°C», дії «тоді» виконуватимуться щоразу, коли датчик надсилає температуру, і вона перевищує 20°C. На 21°C, на 22°C і так далі.",jZ="Код буде виконано лише у разі зміни результату умови. наприклад якщо спрацьовує значення датчика температури та умова «якщо температура перевищує 20°C», дії «тоді» будуть виконані один раз, коли температура буде вище 20. Наступного разу дії «тоді» буде виконано, коли температура падає нижче 20, а потім знову піднімається вище 20.",FZ="години",zZ="включає в себе",UZ="інтервал",HZ="магія",WZ="мілісекунд",GZ="хвилин",VZ="РС",YZ="Надір",KZ="Морський світанок",JZ="Морські сутінки",XZ="Наступний схід сонця",qZ="Наступний захід сонця",ZZ="ніч",QZ="Кінець ночі",eQ="нормально",tQ="зсув",sQ="один",oQ="або",iQ="тихо",nQ="пошук",rQ="секунд",aQ="Сонячний полудень",lQ="схід сонця",cQ="Кінець сходу сонця",uQ="Захід сонця",dQ="Початок заходу сонця",hQ="потім",pQ="Визнати",gQ="Від",mQ="Востаннє змінено",fQ="якість",$Q="Мітка часу",bQ="Користувач",vQ="Значення",yQ="два",_Q="оновлення",wQ="Додає вихідні дані налагодження до журналу для багатьох системних команд",kQ="Докладні результати журналу",CQ="коли",TQ="майстер",SQ="Повторити",EQ={"%s not found":"%s не знайдено","()":"()","(at %s)":"(у %s)","(optional)":"(необов'язково)","-":"-",".":".","AI code generator":"Генератор коду ШІ","Planning...":"Планування...","Generating code...":"Генерування коду...","Show plan":"Показати план",Ack:RX,Actions:MX,"Actual time of day":"Фактичний час доби",Add:NX,"Add new script":"Додати новий сценарій",All:LX,"All files will be accepted":"Усі файли будуть прийняті",Any:PX,"Any month":"Будь-який місяць",Apply:BX,April:jX,"Are you sure?":"Ти впевнений?",Ask:FX,Astronomical:zX,"Astronomical events today":"Астрономічні події сьогодні",August:UX,"Blockly description":"Створення правил за графічними блоками","Body:":"Тіло:",Cancel:HX,"Cannot delete non empty item!":"Неможливо видалити непорожній елемент!","Change layout":"Змінити макет",'Change theme (actual "%s")':'Змінити тему (тепер - "%s")',"Check blocks":"Перевірте блоки","Check is not active, because javascript adapter is disabled":"Перевірка не активна, оскільки адаптер Javascript вимкнено","Clear search input":"Очистити пошуковий запит","Click on this icon":"Натисніть на цей значок",Close:WX,"Close all but current":"Закрити всі, крім поточних","Collapse all":"Закрити всі","Compares current time with astronomical event":"Порівнює поточний час з астрономічною подією","Compares current time with the user specific time":"Порівнює поточний час із конкретним часом користувача","Compares the state value with user defined value":"Порівнює значення стану з визначеним користувачем значенням",Condition:GX,Conditions:VX,"Configuration not saved.":"Конфігурація не збережена.",Console:YX,"Control or update some state":"Контролюйте або оновлюйте певний стан","Control or update some state with delay":"Контролюйте або оновлюйте деякий стан із затримкою","Convert blockly to javascript for ever.":"Назавжди конвертуйте Blockly у Javascript.",Copied:KX,"Copy script":"Копіювати сценарій","Copy to clipboard":"Копіювати в буфер обміну","Create new":"Створити новий","Create new folder":"Створити нову папку","Create new script":"Створіть новий сценарій","Create or edit CRON or time wizard":"Створення або редагування CRON або майстра часу","Dark Theme":"Темна тема","Dark style":"Темний стиль",Date:"Дата","Debug instance":"Екземпляр налагодження","Debug options":"Параметри налагодження",December:JX,Default:XX,"Define cron...":"Визначити cron...","Define schedule...":"Визначити розклад...",Delay:qX,Delete:ZX,"Delete %s":"Видалити %s...","Delete folder":"Видалити папку","Delete script":"Видалити сценарій",Description:QX,"Deselect all":"Зняти вибір із усіх","Discard changes for %s":"Скасувати зміни для %s",Done:eq,"Double click to write value":"Двічі клацніть, щоб записати значення","Download as file":"Завантажити файл","Drop some files here or click...":"Перетягніть кілька файлів сюди або натисніть...","Duplicate name":"Повторюване ім'я","Edit script or just double click":"Відредагуйте сценарій або просто двічі клацніть","Empty name is not allowed":"Порожнє ім'я не допускається","End search mode":"Завершити режим пошуку","Enter your question":"Введи своє прохання",Error:"Помилка","Error formatting code":"Помилка форматування коду","Error was found":"Виявлено помилку","Every day":"Кожен день",Exec:tq,"Executes some shell command":"Виконує певну команду оболонки","Existing scripts will be overwritten.":"Існуючі сценарії буде перезаписано.","Expand all":"Розгорнути все","Expert mode":"Експертний режим",Explanation:sq,Export:oq,"Export all scripts":"Експортувати всі сценарії","Export blocks":"Експорт блоків","Export selected blocks":"Експортувати вибрані блоки",Februar:iq,February:nq,Filter:rq,Folder:aq,Fr:lq,Friday:cq,Function:"функція","Function editor":"Редактор функцій","Function: executed":"Функція: виконано","Go to next line":"Перейти до наступного рядка","HTTP Call":"Виклик HTTP","Hide logs":"Приховати журнали",ID:uq,ID1:dq,ID2:hq,Import:pq,"Import blocks":"Імпорт блоків","Import error":"Помилка імпорту","Import scripts":"Імпорт скриптів","Insert object ID":"Вставте ID об'єкта",Instance:gq,"Instance is disabled":"Примірник вимкнено","Instance:":"екземпляр:",Instances:mq,Instructions:fq,"Invalid CRON":"Недійсний CRON","It will not be possible to revert this operation.":"Скасувати цю операцію буде неможливо.","JS description":"Створення правил шляхом написання Javascript",Januar:$q,January:bq,July:vq,June:yq,"Just check":"Просто перевірте","Keep my changes":"Зберегти мої зміни","Language:":"Мову:","Learn More":"Вивчайте більше","Light style":"Легкий стиль",Limit:_q,"Local time":"Місцевий час","Locate file":"Знайти файл","Log outputs":"Виходи журналу","Log text":"Текст журналу","Log: %s":"Журнал: %s","Make a HTTP get request":"Зробіть HTTP-запит на отримання","Make a pause between actions":"Між діями робіть паузу",March:wq,"March ":"березень",May:kq,Menu:Cq,Message:Tq,Mo:Sq,Model:Eq,Monday:Iq,Month:xq,More:Dq,Name:Aq,"No API key found":"API-ключ не знайдено","No Chat GPT Key found":"Ключ GPT для чату не знайдено","No active host found":"Активний хост не знайдено","Nothing found":"Нічого не знайдено",November:Oq,OK:Rq,October:Mq,Ok:Nq,"On condition change":"За умови зміни результату","On script save or adapter start":"Під час збереження сценарію або запуску адаптера","On weekdays":"В будні дні","Open configuration":"Відкрита конфігурація","Operate two states":"Керуйте двома станами","Operations with two states":"Операції з двома станами","Paste your blocks here":"Вставте сюди свої блоки",Pause:Lq,"Pause execution":"Призупинити виконання","Pause script":"Призупинити сценарій","Phone:":"телефон:","Please select object ID...":"Виберіть ідентифікатор об'єкта...","Press Ctrl+Enter to get the answer":"Натисніть Ctrl+Enter, щоб отримати відповідь","Prettify the script":"Прикрасьте сценарій","Print some text in log":"Надрукувати текст у журналі","Priority:":"Пріоритет:",Pushover:Pq,Pushsafer:Bq,"Read only ID selected: %s":"Вибрано ідентифікатор лише для читання: %s",Reload:jq,Rename:Fq,"Reorder scripts in folders":"Зміна порядку сценаріїв у папках",Repeat:zq,Restart:Uq,Result:Hq,"Resume execution":"Відновити виконання","Root folder":"Коренева папка","Rules description":"Створюйте правила з блоками IF, THEN, ELSE","Run script":"Запустіть сценарій",Sa:Wq,Saturday:Gq,Save:Vq,"Save all":"Зберегти все","Say It":"Скажи це","Say some text via sayit adapter":"Скажіть текст через адаптер sayit",Schedule:Yq,Script:Kq,"Script %s was modified on disk":"Сценарій %s змінено на диску","Script was modified externally":"Скрипт було змінено ззовні","Script is not running":"Сценарій не працює","Search in scripts":"Пошук у скриптах","Search...":"пошук...","Select all":"Вибрати все","Send email":"Відправити лист","Sends an email":"Надсилає електронний лист","Sends message via Pushsafer":"Надсилає повідомлення через Pushsafer","Sends message via pushover":"Надсилає повідомлення через pushover","Sends message via telegram":"Надсилає повідомлення через телеграм","Sends message via whatsapp-cmb":"Надсилає повідомлення через whatsapp-cmb",September:Jq,"Server time":"Час сервера","Set state action":"Встановити дію стану","Set with delay":"Встановити із затримкою","Shell command":"Команда оболонки","Show astronomical events":"Показати астрономічні події","Show javascript code":"Показати код Javascript","Show logs":"Показати журнали","Show only paused scripts":"Показувати лише призупинені сценарії","Show only running scripts":"Показувати лише запущені сценарії","Show only scripts with problems":"Показувати лише сценарії з проблемами",Simulate:Xq,"Some files will be rejected":"Деякі файли буде відхилено","Sound:":"звук:",Stack:qq,Start:Zq,"Start script":"Запустити сценарій",State:Qq,"State condition":"Стан стану","Step into function":"Крок у функції","Step out from function":"Вийти з функції","Stop on exception":"Зупинка на винятках",Su:eZ,"Subject:":"Тема:",Sunday:tZ,"TS description":"Створення правил шляхом написання Typescript",Telegram:sZ,"Text:":"Текст:",Th:oZ,'The script "%s" has been modified by another user or in another window. Do you want to reload the script or keep your local changes?':'Скрипт "%s" було змінено іншим користувачем або в іншому вікні. Бажаєте перезавантажити скрипт чи зберегти свої локальні зміни?',"The script will be stopped and must be activated manually after debugging. Continue?":"Сценарій буде зупинено, і його необхідно активувати вручну після налагодження. Продовжити?","This is advances option. You can write your own code here and it will be executed on trigger":"Це авансовий варіант. Ви можете написати тут свій власний код, і він буде виконано на тригері",Thursday:iZ,Time:nZ,"Time condition":"Умова часу","Title:":"Назва:","To:":"до:","Trigger with value":"Тригер зі значенням",Triggered:rZ,Triggers:aZ,"Triggers the on script saving or the javascript instance restart":"Ініціює збереження сценарію або перезапуск екземпляра JavaScript","Triggers the rule on update or change of some state":"Запускає правило при оновленні або зміні якогось стану","Triggers the rule periodically or on some specific time":"Спрацьовує правило періодично або в певний час",Tu:lZ,Tuesday:cZ,URL:uZ,"Unknown error":"Невідома помилка","Unknown error!":"Невідома помилка!","Use generated code":"Використовуйте згенерований код","User function":"Функція користувача","User:":"Користувач:",Value:dZ,"Vibration:":"Вібрація:",Volume:hZ,We:pZ,Wednesday:gZ,"Whatsapp-cmb":"Whatsapp-cmb",Write:mZ,"Write your own code":"Напишіть власний код",Yes:fZ,"Yet exists!":"Все ж існує!","You can use %s in the URL to use current trigger value or %id to use the triggered object ID":"Ви можете використовувати %s в URL-адресі, щоб використовувати поточне значення тригера, %id, щоб використовувати ідентифікатор активованого об’єкта, %name, щоб показати назву ідентифікатора активованого об’єкта, або %old, щоб використовувати старе значення тригера","You can use %s in the command to use current trigger value or %id to use the triggered object ID":"Ви можете використовувати %s у команді, щоб використовувати поточне значення тригера, %id, щоб використовувати ідентифікатор активованого об’єкта, %name, щоб показати назву ідентифікатора активованого об’єкта, або %old, щоб використовувати старе значення тригера","You can use %s in the text to display current trigger value or %id to display the triggered object ID":"Ви можете використовувати %s у тексті для відображення поточного значення тригера, %id для використання ідентифікатора активованого об’єкта, %name для відображення імені ідентифікатора активованого об’єкта або %old для використання старого значення тригера","You can use %s in the value to use the current trigger value or %id to display the triggered object ID":"Ви можете використовувати %s у значенні, щоб використовувати поточне значення тригера, %id, щоб використовувати ідентифікатор активованого об’єкта, %name, щоб показати назву ідентифікатора активованого об’єкта, або %old, щоб використовувати старе значення тригера","You have to enter OpenAI API key in the configuration of javascript adapter.":"Ви повинні ввести ключ OpenAI API у конфігурації адаптера JavaScript.","You have to enter at least one API key in the configuration of javascript adapter.":"Необхідно ввести хоча б один API-ключ (OpenAI, Anthropic або Gemini) у конфігурації адаптера JavaScript.","Please select a valid model":"Будь ласка, виберіть дійсну модель","[equal]":"[рівний]","[greater or equal]":"[більше або дорівнює]","[greater]":"[більший]","[hysteresis]":"[гістерезис]","[includes]":"[включає]","[less or equal]":"[менше або рівно]","[less]":"[менше]","[not equal]":"[не дорівнює]",acknowledgment:$Z,all:bZ,and:vZ,"as JSON":"як JSON","as plain text":"як текст",astro:yZ,at:_Z,"clear running":"чіткий біг",control:wZ,copy:kZ,cron:CZ,dawn:TZ,debug_help:SZ,debug_label:EZ,default:"за замовчуванням",dusk:IZ,easy:xZ,else:"інше","equal to":"дорівнює",every:DZ,"every hour at 0 minutes":"щогодини о 0 хвилин",false:"помилковий","file reading has failed: %s":"не вдалося прочитати файл: %s","file reading was aborted":"читання файлу було перервано",filter_func:AZ,filter_id:OZ,filter_name:RZ,filter_role:MZ,filter_room:NZ,"for edit or create script":"для редагування або створення нового сценарію","for professionals":"для професіоналів","for programmers":"для програмістів",goldenHour:LZ,goldenHourEnd:PZ,"greater or equal":"більший або рівний","greater or equal to":"більше або дорівнює","greater than":"більше, ніж, величніше ніж, крутіший за",help_just_check:BZ,help_on_change:jZ,"high priority":"високий пріоритет","high-priority":"високий пріоритет","highest priority":"найвищий пріоритет",hours:FZ,includes:zZ,interval:UZ,"just check":"просто перевірте","less or equal":"менше або дорівнює","less or equal to":"менше або дорівнює","less than":"менше ніж","lower priority":"нижчий пріоритет","lowest priority":"найнижчий пріоритет",magic:HZ,milliseconds:WZ,minutes:GZ,ms:VZ,nadir:YZ,nauticalDawn:KZ,nauticalDusk:JZ,nextSunrise:XZ,nextSunset:qZ,night:ZZ,nightEnd:QZ,"no blocks found":"Блоків не знайдено","no group":"НЕМАЄ ГРУПИ",normal:eQ,"normal priority":"нормальний пріоритет","not running":"не запущено","not equal to":"не дорівнює","not properly connected":"Цей блок неправильно з’єднаний з іншими блоками.",offset:tQ,"on change":"на зміну","on condition change":"про зміну умов","on update":"на оновлення",one:sQ,or:oQ,quiet:iQ,"reset search":"скинути пошук",search:nQ,seconds:rQ,solarNoon:aQ,"store in":"зберігати в",sunrise:lQ,sunriseEnd:cQ,sunset:uQ,sunsetStart:dQ,then:hQ,"toggle value":"значення перемикання",tooltip_ack:pQ,tooltip_from:gQ,tooltip_lc:mQ,tooltip_quality:fQ,tooltip_ts:$Q,tooltip_user:bQ,tooltip_value:vQ,true:"правда",two:yQ,undefined:"невизначений",update:_Q,"use seconds":"використовуйте секунди","use trigger value":"використовувати значення тригера",verbose_help:wQ,verbose_label:kQ,when:CQ,with:"з","with date":"з датою","with offset":"зі зміщенням",wizard:TQ,"Loading models...":"Завантаження моделей...","Could not connect to API at %s":"Не вдалося підключитися до API за адресою %s","Invalid API key":"Недійсний ключ API","Access denied by API":"Доступ заборонено API","API error: %s":"Помилка API: %s",'Model "%s" not found':'Модель "%s" не знайдено',"Request failed: %s":"Запит не вдався: %s",Retry:SQ,"No running javascript instance found":"Не знайдено запущеного екземпляра JavaScript","OID display mode":"Режим відображення OID"},IQ="确认",xQ="动作",DQ="添加",AQ="所有",OQ="任何",RQ="申请",MQ="四月",NQ="问",LQ="天文",PQ="八月",BQ="取消",jQ="关闭",FQ="健康)状况",zQ="情况",UQ="安慰",HQ="复制的",WQ="十二月",GQ="默认",VQ="延迟",YQ="删除",KQ="描述",JQ="完成",XQ="执行力",qQ="解释",ZQ="导出",QQ="二月",eee="二月",tee="筛选",see="文件夹",oee="r",iee="星期五",nee="ID",ree="ID1",aee="ID2",lee="导入",cee="实例",uee="实例",dee="指示",hee="亚努尔",pee="一月",gee="七月",mee="六月",fee="限制",$ee="三月",bee="五月",vee="菜单",yee="信息",_ee="莫",wee="模型",kee="星期一",Cee="月",Tee="更多的",See="名称",Eee="十一月",Iee="好的",xee="十月",Dee="确定",Aee="暂停",Oee="俯卧撑",Ree="推安全",Mee="重新加载",Nee="重命名",Lee="重复",Pee="重启",Bee="结果",jee="萨",Fee="星期六",zee="保存",Uee="日程",Hee="脚本",Wee="九月",Gee="模拟",Vee="堆",Yee="开始",Kee="状态",Jee="苏",Xee="星期日",qee="电报",Zee="4",Qee="星期四",ete="时间",tte="触发",ste="扳机",ote="涂",ite="星期二",nte="网址",rte="价值",ate="体积",lte="3",cte="星期三",ute="写",dte="是的",hte="致谢",pte="全部",gte="和",mte="天文",fte="在",$te="控制",bte="复制",vte="克朗",yte="黎明",_te="这是一种特殊模式,其中状态和对象不会改变。但只有有关每个计划更改的信息才会显示在协议中。",wte="调试",kte="黄昏",Cte="简单的",Tte="每一个",Ste="功能",Ete="ID",Ite="名字",xte="角色",Dte="房间",Ate="黄金时段",Ote="黄金时段结束",Rte="仅在条件为真时才执行代码。例如。如果触发温度传感器值并且条件为“如果温度大于20°C”,则每次传感器发送温度且温度超过20°C时,将执行“然后”动作。 21°C,22°C等。",Mte="仅当条件结果更改时,代码才会执行。例如。如果触发温度传感器值且条件为“如果温度大于20°C”,则温度超过20时将执行一次“则”动作,下一次,当温度超过20时将执行“则”动作低于20失败,然后再次超过20。",Nte="小时",Lte="包括",Pte="间隔",Bte="魔法",jte="毫秒",Fte="分钟",zte="毫秒",Ute="最低点",Hte="航海黎明",Wte="航海黄昏",Gte="下一个日出",Vte="下一个日落",Yte="夜晚",Kte="夜晚结束",Jte="普通的",Xte="抵消",qte="一",Zte="或",Qte="安静的",ese="搜索",tse="秒",sse="星期日正午",ose="日出",ise="日出结束",nse="日落",rse="日落开始",ase="然后",lse="确认",cse="从",use="上一次改变",dse="质量",hse="时间戳",pse="用户",gse="值",mse="二",fse="更新",$se="将调试输出添加到许多系统命令的日志中",bse="详细日志输出",vse="什么时候",yse="巫师",_se="重试",wse={"%s not found":"%s 未找到","()":"()","(at %s)":"(在 %s)","(optional)":"(选修的)","-":"-",".":".","AI code generator":"AI代码生成器","Planning...":"规划中...","Generating code...":"生成代码中...","Show plan":"显示计划",Ack:IQ,Actions:xQ,"Actual time of day":"一天中的实际时间",Add:DQ,"Add new script":"添加新脚本",All:AQ,"All files will be accepted":"所有文件都将被接受",Any:OQ,"Any month":"任何月份",Apply:RQ,April:MQ,"Are you sure?":"你确定吗?",Ask:NQ,Astronomical:LQ,"Astronomical events today":"今天的天文事件",August:PQ,"Blockly description":"按图形块创建规则","Body:":"身体:",Cancel:BQ,"Cannot delete non empty item!":"无法删除非空项目!","Change layout":"变更版面",'Change theme (actual "%s")':"更改主题(现在为“%s”)","Check blocks":"检查块","Check is not active, because javascript adapter is disabled":"检查未激活,因为禁用了Javascript适配器","Clear search input":"清除搜索输入","Click on this icon":"单击此图标",Close:jQ,"Close all but current":"关闭所有(当前除外)","Collapse all":"全部收缩","Compares current time with astronomical event":"将当前时间与天文事件进行比较","Compares current time with the user specific time":"将当前时间与用户特定时间进行比较","Compares the state value with user defined value":"比较状态值和用户定义的值",Condition:FQ,Conditions:zQ,"Configuration not saved.":"配置未保存。",Console:UQ,"Control or update some state":"控制或更新某些状态","Control or update some state with delay":"延迟控制或更新某些状态","Convert blockly to javascript for ever.":"立即将blockly转换为Javascript。",Copied:HQ,"Copy script":"复制脚本","Copy to clipboard":"复制到剪贴板","Create new":"创建新的","Create new folder":"创建新文件夹","Create new script":"创建新脚本","Create or edit CRON or time wizard":"创建或编辑周期任务或时间向导","Dark Theme":"深色调主题","Dark style":"深色调风格",Date:"日期","Debug instance":"调试实例","Debug options":"调试选项",December:WQ,Default:GQ,"Define cron...":"定义周期任务...","Define schedule...":"定义调度器......",Delay:VQ,Delete:YQ,"Delete %s":"删除%s...","Delete folder":"删除文件夹","Delete script":"删除脚本",Description:KQ,"Deselect all":"取消全选","Discard changes for %s":"放弃%s的更改",Done:JQ,"Double click to write value":"Double click to write value","Download as file":"档案","Drop some files here or click...":"将文件拖拽到这里或单击......","Duplicate name":"重名","Edit script or just double click":"双击编辑脚本","Empty name is not allowed":"不允许使用空名称","End search mode":"结束搜索模式","Enter your question":"输入您的要求",Error:"错误","Error formatting code":"代码格式错误","Error was found":"发现错误","Every day":"每天",Exec:XQ,"Executes some shell command":"执行一些shell命令","Existing scripts will be overwritten.":"现有脚本将被覆盖。","Expand all":"展开全部","Expert mode":"专家模式",Explanation:qQ,Export:ZQ,"Export all scripts":"导出所有脚本","Export blocks":"导出块","Export selected blocks":"导出选定的块",Februar:QQ,February:eee,Filter:tee,Folder:see,Fr:oee,Friday:iee,Function:"功能","Function editor":"功能编辑器","Function: executed":"功能:执行","Go to next line":"转到下一行","HTTP Call":"HTTP呼叫","Hide logs":"隐藏日志",ID:nee,ID1:ree,ID2:aee,Import:lee,"Import blocks":"导入块","Import error":"导入错误","Import scripts":"导入脚本","Insert object ID":"插入对象ID",Instance:cee,"Instance is disabled":"实例已禁用","Instance:":"实例:",Instances:uee,Instructions:dee,"Invalid CRON":"无效的周期任务","It will not be possible to revert this operation.":"无法恢复此操作。","JS description":"通过编写Javascript来创建规则",Januar:hee,January:pee,July:gee,June:mee,"Just check":"只是检查","Keep my changes":"保留我的更改","Language:":"语言:","Learn More":"了解更多","Light style":"浅色调风格",Limit:fee,"Local time":"当地时间","Locate file":"定位文件","Log outputs":"记录输出","Log text":"记录文字","Log: %s":"日志:%s","Make a HTTP get request":"发出HTTP获取请求","Make a pause between actions":"在动作之间暂停",March:$ee,"March ":"行进",May:bee,Menu:vee,Message:yee,Mo:_ee,Model:wee,Monday:kee,Month:Cee,More:Tee,Name:See,"No API key found":"未找到 API 密钥","No Chat GPT Key found":"找不到聊天 GPT 密钥","No active host found":"找不到活动主机","Nothing found":"没有发现",November:Eee,OK:Iee,October:xee,Ok:Dee,"On condition change":"条件变化时","On script save or adapter start":"在脚本保存或适配器启动时","On weekdays":"在工作日","Open configuration":"开放配置","Operate two states":"操作两种状态","Operations with two states":"具有两种状态的操作","Paste your blocks here":"在此处粘贴您的区块",Pause:Aee,"Pause execution":"暂停执行","Pause script":"暂停脚本","Phone:":"电话:","Please select object ID...":"请选择对象ID...","Press Ctrl+Enter to get the answer":"按 Ctrl+Enter 即可得到答案","Prettify the script":"美化脚本","Print some text in log":"在日志中打印一些文本","Priority:":"优先:",Pushover:Oee,Pushsafer:Ree,"Read only ID selected: %s":"选择的只读ID:%s",Reload:Mee,Rename:Nee,"Reorder scripts in folders":"重新排序文件夹中的脚本",Repeat:Lee,Restart:Pee,Result:Bee,"Resume execution":"恢复执行","Root folder":"根文件夹","Rules description":"使用IF,THEN,ELSE块创建规则","Run script":"运行脚本",Sa:jee,Saturday:Fee,Save:zee,"Save all":"保存全部","Say It":"Say It","Say some text via sayit adapter":"通过sayit适配器说一些文字",Schedule:Uee,Script:Hee,"Script %s was modified on disk":"脚本%s已在磁盘上修改","Script was modified externally":"脚本已被外部修改","Script is not running":"脚本没有运行","Search in scripts":"在脚本中搜索","Search...":"搜索...","Select all":"全选","Send email":"发送电子邮件","Sends an email":"发送邮件","Sends message via Pushsafer":"通过Pushsafer发送消息","Sends message via pushover":"通过推播发送消息","Sends message via telegram":"通过电报发送消息","Sends message via whatsapp-cmb":"通过whatsapp-cmb发送消息",September:Wee,"Server time":"服务器时间","Set state action":"设定状态动作","Set with delay":"延迟设置","Shell command":"Shell命令","Show astronomical events":"显示天文事件","Show javascript code":"显示Javascript代码","Show logs":"显示记录","Show only paused scripts":"仅显示暂停的脚本","Show only running scripts":"仅显示正在运行的脚本","Show only scripts with problems":"仅显示有问题的脚本",Simulate:Gee,"Some files will be rejected":"有些文件将被拒绝","Sound:":"声音:",Stack:Vee,Start:Yee,"Start script":"启动脚本",State:Kee,"State condition":"状态条件","Step into function":"进入功能","Step out from function":"退出函数","Stop on exception":"异常停止",Su:Jee,"Subject:":"学科:",Sunday:Xee,"TS description":"通过编写Typescript来创建规则",Telegram:qee,"Text:":"文本:",Th:Zee,'The script "%s" has been modified by another user or in another window. Do you want to reload the script or keep your local changes?':'脚本 "%s" 已被其他用户或在其他窗口中修改。您想重新加载脚本还是保留您的本地更改?',"The script will be stopped and must be activated manually after debugging. Continue?":"该脚本将停止,并且必须在调试后手动激活。继续?","This is advances option. You can write your own code here and it will be executed on trigger":"这是高级选项。您可以在此处编写自己的代码,它将在触发器上执行",Thursday:Qee,Time:ete,"Time condition":"时间条件","Title:":"标题:","To:":"到:","Trigger with value":"用值触发",Triggered:tte,Triggers:ste,"Triggers the on script saving or the javascript instance restart":"触发脚本保存或javascript实例重启","Triggers the rule on update or change of some state":"在某些状态的更新或更改时触发规则","Triggers the rule periodically or on some specific time":"定期或在特定时间触发规则",Tu:ote,Tuesday:ite,URL:nte,"Unknown error":"未知错误","Unknown error!":"未知错误!","Use generated code":"使用生成的代码","User function":"用户功能","User:":"用户:",Value:rte,"Vibration:":"振动:",Volume:ate,We:lte,Wednesday:cte,"Whatsapp-cmb":"Whatsapp的cmb",Write:ute,"Write your own code":"编写自己的代码",Yes:dte,"Yet exists!":"不存在!","You can use %s in the URL to use current trigger value or %id to use the triggered object ID":"您可以在 URL 中使用 %s 以使用当前触发值,%id 以使用触发对象 ID,%name 以显示触发对象 ID 名称或 %old 以使用旧触发值","You can use %s in the command to use current trigger value or %id to use the triggered object ID":"您可以在命令中使用 %s 以使用当前触发值,%id 使用触发对象 ID,%name 显示触发对象 ID 名称或 %old 使用旧触发值","You can use %s in the text to display current trigger value or %id to display the triggered object ID":"您可以在文本中使用 %s 显示当前触发值,%id 使用触发对象 ID,%name 显示触发对象 ID 名称或 %old 使用旧触发值","You can use %s in the value to use the current trigger value or %id to display the triggered object ID":"您可以在值中使用 %s 以使用当前触发器值,%id 使用触发对象 ID,%name 显示触发对象 ID 名称或 %old 使用旧触发器值","You have to enter OpenAI API key in the configuration of javascript adapter.":"您必须在 javascript 适配器的配置中输入 OpenAI API 密钥。","You have to enter at least one API key in the configuration of javascript adapter.":"您必须在 javascript 适配器的配置中输入至少一个 API 密钥(OpenAI、Anthropic 或 Gemini)。","Please select a valid model":"请选择一个有效的模型","[equal]":"[平等的]","[greater or equal]":"[大于等于]","[greater]":"[更大]","[hysteresis]":"[磁滞]","[includes]":"[包括]","[less or equal]":"[小于或等于]","[less]":"[较少的]","[not equal]":"[不相等]",acknowledgment:hte,all:pte,and:gte,"as JSON":"为 JSON","as plain text":"为纯文本",astro:mte,at:fte,"clear running":"畅通无阻",control:$te,copy:bte,cron:vte,dawn:yte,debug_help:_te,debug_label:wte,default:"默认",dusk:kte,easy:Cte,else:"别的","equal to":"等于",every:Tte,"every hour at 0 minutes":"每小时0分钟",false:"错误的","file reading has failed: %s":"文件读取失败:%s","file reading was aborted":"文件读取中止",filter_func:Ste,filter_id:Ete,filter_name:Ite,filter_role:xte,filter_room:Dte,"for edit or create script":"用于编辑或创建脚本","for professionals":"对于专业人士","for programmers":"对于程序员",goldenHour:Ate,goldenHourEnd:Ote,"greater or equal":"大于或等于","greater or equal to":"大于或等于","greater than":"比...更棒",help_just_check:Rte,help_on_change:Mte,"high priority":"高优先级","high-priority":"高优先级","highest priority":"最高优先级",hours:Nte,includes:Lte,interval:Pte,"just check":"只是检查","less or equal":"小于或等于","less or equal to":"小于或等于","less than":"少于","lower priority":"低优先级","lowest priority":"最低优先级",magic:Bte,milliseconds:jte,minutes:Fte,ms:zte,nadir:Ute,nauticalDawn:Hte,nauticalDusk:Wte,nextSunrise:Gte,nextSunset:Vte,night:Yte,nightEnd:Kte,"no blocks found":"找不到块","no group":"没有组",normal:Jte,"normal priority":"正常优先","not running":"未运行","not equal to":"不等于","not properly connected":"此块未正确连接到其他块。",offset:Xte,"on change":"在变化","on condition change":"在条件变化时","on update":"更新时",one:qte,or:Zte,quiet:Qte,"reset search":"重置搜索",search:ese,seconds:tse,solarNoon:sse,"store in":"存放在",sunrise:ose,sunriseEnd:ise,sunset:nse,sunsetStart:rse,then:ase,"toggle value":"切换值",tooltip_ack:lse,tooltip_from:cse,tooltip_lc:use,tooltip_quality:dse,tooltip_ts:hse,tooltip_user:pse,tooltip_value:gse,true:"真的",two:mse,undefined:"不明确的",update:fse,"use seconds":"精确到秒","use trigger value":"使用触发值",verbose_help:$se,verbose_label:bse,when:vse,with:"和","with date":"有日期","with offset":"带偏移",wizard:yse,"Loading models...":"加载模型...","Could not connect to API at %s":"无法连接到 %s 的 API","Invalid API key":"无效的 API 密钥","Access denied by API":"API 拒绝访问","API error: %s":"API 错误:%s",'Model "%s" not found':'未找到模型 "%s"',"Request failed: %s":"请求失败:%s",Retry:_se,"No running javascript instance found":"未找到正在运行的 JavaScript 实例","OID display mode":"OID显示模式"};function gc(a){throw new Error('Could not dynamically require "'+a+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var RC={exports:{}};(function(a,s){(function(i){a.exports=i()})(function(){return(function i(r,l,c){function d(f,b){if(!l[f]){if(!r[f]){var y=typeof gc=="function"&&gc;if(!b&&y)return y(f,!0);if(h)return h(f,!0);var w=new Error("Cannot find module '"+f+"'");throw w.code="MODULE_NOT_FOUND",w}var v=l[f]={exports:{}};r[f][0].call(v.exports,function(_){var $=r[f][1][_];return d($||_)},v,v.exports,i,r,l,c)}return l[f].exports}for(var h=typeof gc=="function"&&gc,p=0;p>2,v=(3&f)<<4|b>>4,_=1>6:64,$=2>4,b=(15&w)<<4|(v=h.indexOf(p.charAt($++)))>>2,y=(3&v)<<6|(_=h.indexOf(p.charAt($++))),E[T++]=f,v!==64&&(E[T++]=b),_!==64&&(E[T++]=y);return E}},{"./support":30,"./utils":32}],2:[function(i,r,l){var c=i("./external"),d=i("./stream/DataWorker"),h=i("./stream/Crc32Probe"),p=i("./stream/DataLengthProbe");function f(b,y,w,v,_){this.compressedSize=b,this.uncompressedSize=y,this.crc32=w,this.compression=v,this.compressedContent=_}f.prototype={getContentWorker:function(){var b=new d(c.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new p("data_length")),y=this;return b.on("end",function(){if(this.streamInfo.data_length!==y.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),b},getCompressedWorker:function(){return new d(c.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},f.createWorkerFrom=function(b,y,w){return b.pipe(new h).pipe(new p("uncompressedSize")).pipe(y.compressWorker(w)).pipe(new p("compressedSize")).withStreamInfo("compression",y)},r.exports=f},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(i,r,l){var c=i("./stream/GenericWorker");l.STORE={magic:"\0\0",compressWorker:function(){return new c("STORE compression")},uncompressWorker:function(){return new c("STORE decompression")}},l.DEFLATE=i("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(i,r,l){var c=i("./utils"),d=(function(){for(var h,p=[],f=0;f<256;f++){h=f;for(var b=0;b<8;b++)h=1&h?3988292384^h>>>1:h>>>1;p[f]=h}return p})();r.exports=function(h,p){return h!==void 0&&h.length?c.getTypeOf(h)!=="string"?(function(f,b,y,w){var v=d,_=w+y;f^=-1;for(var $=w;$<_;$++)f=f>>>8^v[255&(f^b[$])];return-1^f})(0|p,h,h.length,0):(function(f,b,y,w){var v=d,_=w+y;f^=-1;for(var $=w;$<_;$++)f=f>>>8^v[255&(f^b.charCodeAt($))];return-1^f})(0|p,h,h.length,0):0}},{"./utils":32}],5:[function(i,r,l){l.base64=!1,l.binary=!1,l.dir=!1,l.createFolders=!0,l.date=null,l.compression=null,l.compressionOptions=null,l.comment=null,l.unixPermissions=null,l.dosPermissions=null},{}],6:[function(i,r,l){var c=null;c=typeof Promise<"u"?Promise:i("lie"),r.exports={Promise:c}},{lie:37}],7:[function(i,r,l){var c=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",d=i("pako"),h=i("./utils"),p=i("./stream/GenericWorker"),f=c?"uint8array":"array";function b(y,w){p.call(this,"FlateWorker/"+y),this._pako=null,this._pakoAction=y,this._pakoOptions=w,this.meta={}}l.magic="\b\0",h.inherits(b,p),b.prototype.processChunk=function(y){this.meta=y.meta,this._pako===null&&this._createPako(),this._pako.push(h.transformTo(f,y.data),!1)},b.prototype.flush=function(){p.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},b.prototype.cleanUp=function(){p.prototype.cleanUp.call(this),this._pako=null},b.prototype._createPako=function(){this._pako=new d[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var y=this;this._pako.onData=function(w){y.push({data:w,meta:y.meta})}},l.compressWorker=function(y){return new b("Deflate",y)},l.uncompressWorker=function(){return new b("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(i,r,l){function c(v,_){var $,T="";for($=0;$<_;$++)T+=String.fromCharCode(255&v),v>>>=8;return T}function d(v,_,$,T,S,E){var D,R,L=v.file,H=v.compression,G=E!==f.utf8encode,z=h.transformTo("string",E(L.name)),Z=h.transformTo("string",f.utf8encode(L.name)),he=L.comment,Ce=h.transformTo("string",E(he)),M=h.transformTo("string",f.utf8encode(he)),Y=Z.length!==L.name.length,C=M.length!==he.length,Q="",ve="",ce="",ne=L.dir,me=L.date,re={crc32:0,compressedSize:0,uncompressedSize:0};_&&!$||(re.crc32=v.crc32,re.compressedSize=v.compressedSize,re.uncompressedSize=v.uncompressedSize);var B=0;_&&(B|=8),G||!Y&&!C||(B|=2048);var N=0,te=0;ne&&(N|=16),S==="UNIX"?(te=798,N|=(function(se,F){var Te=se;return se||(Te=F?16893:33204),(65535&Te)<<16})(L.unixPermissions,ne)):(te=20,N|=(function(se){return 63&(se||0)})(L.dosPermissions)),D=me.getUTCHours(),D<<=6,D|=me.getUTCMinutes(),D<<=5,D|=me.getUTCSeconds()/2,R=me.getUTCFullYear()-1980,R<<=4,R|=me.getUTCMonth()+1,R<<=5,R|=me.getUTCDate(),Y&&(ve=c(1,1)+c(b(z),4)+Z,Q+="up"+c(ve.length,2)+ve),C&&(ce=c(1,1)+c(b(Ce),4)+M,Q+="uc"+c(ce.length,2)+ce);var X="";return X+=` +\0`,X+=c(B,2),X+=H.magic,X+=c(D,2),X+=c(R,2),X+=c(re.crc32,4),X+=c(re.compressedSize,4),X+=c(re.uncompressedSize,4),X+=c(z.length,2),X+=c(Q.length,2),{fileRecord:y.LOCAL_FILE_HEADER+X+z+Q,dirRecord:y.CENTRAL_FILE_HEADER+c(te,2)+X+c(Ce.length,2)+"\0\0\0\0"+c(N,4)+c(T,4)+z+Q+Ce}}var h=i("../utils"),p=i("../stream/GenericWorker"),f=i("../utf8"),b=i("../crc32"),y=i("../signature");function w(v,_,$,T){p.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=_,this.zipPlatform=$,this.encodeFileName=T,this.streamFiles=v,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}h.inherits(w,p),w.prototype.push=function(v){var _=v.meta.percent||0,$=this.entriesCount,T=this._sources.length;this.accumulate?this.contentBuffer.push(v):(this.bytesWritten+=v.data.length,p.prototype.push.call(this,{data:v.data,meta:{currentFile:this.currentFile,percent:$?(_+100*($-T-1))/$:100}}))},w.prototype.openedSource=function(v){this.currentSourceOffset=this.bytesWritten,this.currentFile=v.file.name;var _=this.streamFiles&&!v.file.dir;if(_){var $=d(v,_,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:$.fileRecord,meta:{percent:0}})}else this.accumulate=!0},w.prototype.closedSource=function(v){this.accumulate=!1;var _=this.streamFiles&&!v.file.dir,$=d(v,_,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push($.dirRecord),_)this.push({data:(function(T){return y.DATA_DESCRIPTOR+c(T.crc32,4)+c(T.compressedSize,4)+c(T.uncompressedSize,4)})(v),meta:{percent:100}});else for(this.push({data:$.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},w.prototype.flush=function(){for(var v=this.bytesWritten,_=0;_=this.index;p--)f=(f<<8)+this.byteAt(p);return this.index+=h,f},readString:function(h){return c.transformTo("string",this.readData(h))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var h=this.readInt(4);return new Date(Date.UTC(1980+(h>>25&127),(h>>21&15)-1,h>>16&31,h>>11&31,h>>5&63,(31&h)<<1))}},r.exports=d},{"../utils":32}],19:[function(i,r,l){var c=i("./Uint8ArrayReader");function d(h){c.call(this,h)}i("../utils").inherits(d,c),d.prototype.readData=function(h){this.checkOffset(h);var p=this.data.slice(this.zero+this.index,this.zero+this.index+h);return this.index+=h,p},r.exports=d},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(i,r,l){var c=i("./DataReader");function d(h){c.call(this,h)}i("../utils").inherits(d,c),d.prototype.byteAt=function(h){return this.data.charCodeAt(this.zero+h)},d.prototype.lastIndexOfSignature=function(h){return this.data.lastIndexOf(h)-this.zero},d.prototype.readAndCheckSignature=function(h){return h===this.readData(4)},d.prototype.readData=function(h){this.checkOffset(h);var p=this.data.slice(this.zero+this.index,this.zero+this.index+h);return this.index+=h,p},r.exports=d},{"../utils":32,"./DataReader":18}],21:[function(i,r,l){var c=i("./ArrayReader");function d(h){c.call(this,h)}i("../utils").inherits(d,c),d.prototype.readData=function(h){if(this.checkOffset(h),h===0)return new Uint8Array(0);var p=this.data.subarray(this.zero+this.index,this.zero+this.index+h);return this.index+=h,p},r.exports=d},{"../utils":32,"./ArrayReader":17}],22:[function(i,r,l){var c=i("../utils"),d=i("../support"),h=i("./ArrayReader"),p=i("./StringReader"),f=i("./NodeBufferReader"),b=i("./Uint8ArrayReader");r.exports=function(y){var w=c.getTypeOf(y);return c.checkSupport(w),w!=="string"||d.uint8array?w==="nodebuffer"?new f(y):d.uint8array?new b(c.transformTo("uint8array",y)):new h(c.transformTo("array",y)):new p(y)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(i,r,l){l.LOCAL_FILE_HEADER="PK",l.CENTRAL_FILE_HEADER="PK",l.CENTRAL_DIRECTORY_END="PK",l.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK\x07",l.ZIP64_CENTRAL_DIRECTORY_END="PK",l.DATA_DESCRIPTOR="PK\x07\b"},{}],24:[function(i,r,l){var c=i("./GenericWorker"),d=i("../utils");function h(p){c.call(this,"ConvertWorker to "+p),this.destType=p}d.inherits(h,c),h.prototype.processChunk=function(p){this.push({data:d.transformTo(this.destType,p.data),meta:p.meta})},r.exports=h},{"../utils":32,"./GenericWorker":28}],25:[function(i,r,l){var c=i("./GenericWorker"),d=i("../crc32");function h(){c.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}i("../utils").inherits(h,c),h.prototype.processChunk=function(p){this.streamInfo.crc32=d(p.data,this.streamInfo.crc32||0),this.push(p)},r.exports=h},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(i,r,l){var c=i("../utils"),d=i("./GenericWorker");function h(p){d.call(this,"DataLengthProbe for "+p),this.propName=p,this.withStreamInfo(p,0)}c.inherits(h,d),h.prototype.processChunk=function(p){if(p){var f=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=f+p.data.length}d.prototype.processChunk.call(this,p)},r.exports=h},{"../utils":32,"./GenericWorker":28}],27:[function(i,r,l){var c=i("../utils"),d=i("./GenericWorker");function h(p){d.call(this,"DataWorker");var f=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,p.then(function(b){f.dataIsReady=!0,f.data=b,f.max=b&&b.length||0,f.type=c.getTypeOf(b),f.isPaused||f._tickAndRepeat()},function(b){f.error(b)})}c.inherits(h,d),h.prototype.cleanUp=function(){d.prototype.cleanUp.call(this),this.data=null},h.prototype.resume=function(){return!!d.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,c.delay(this._tickAndRepeat,[],this)),!0)},h.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(c.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},h.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var p=null,f=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":p=this.data.substring(this.index,f);break;case"uint8array":p=this.data.subarray(this.index,f);break;case"array":case"nodebuffer":p=this.data.slice(this.index,f)}return this.index=f,this.push({data:p,meta:{percent:this.max?this.index/this.max*100:0}})},r.exports=h},{"../utils":32,"./GenericWorker":28}],28:[function(i,r,l){function c(d){this.name=d||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}c.prototype={push:function(d){this.emit("data",d)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(d){this.emit("error",d)}return!0},error:function(d){return!this.isFinished&&(this.isPaused?this.generatedError=d:(this.isFinished=!0,this.emit("error",d),this.previous&&this.previous.error(d),this.cleanUp()),!0)},on:function(d,h){return this._listeners[d].push(h),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(d,h){if(this._listeners[d])for(var p=0;p "+d:d}},r.exports=c},{}],29:[function(i,r,l){var c=i("../utils"),d=i("./ConvertWorker"),h=i("./GenericWorker"),p=i("../base64"),f=i("../support"),b=i("../external"),y=null;if(f.nodestream)try{y=i("../nodejs/NodejsStreamOutputAdapter")}catch{}function w(_,$){return new b.Promise(function(T,S){var E=[],D=_._internalType,R=_._outputType,L=_._mimeType;_.on("data",function(H,G){E.push(H),$&&$(G)}).on("error",function(H){E=[],S(H)}).on("end",function(){try{var H=(function(G,z,Z){switch(G){case"blob":return c.newBlob(c.transformTo("arraybuffer",z),Z);case"base64":return p.encode(z);default:return c.transformTo(G,z)}})(R,(function(G,z){var Z,he=0,Ce=null,M=0;for(Z=0;Z"u")l.blob=!1;else{var c=new ArrayBuffer(0);try{l.blob=new Blob([c],{type:"application/zip"}).size===0}catch{try{var d=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);d.append(c),l.blob=d.getBlob("application/zip").size===0}catch{l.blob=!1}}}try{l.nodestream=!!i("readable-stream").Readable}catch{l.nodestream=!1}},{"readable-stream":16}],31:[function(i,r,l){for(var c=i("./utils"),d=i("./support"),h=i("./nodejsUtils"),p=i("./stream/GenericWorker"),f=new Array(256),b=0;b<256;b++)f[b]=252<=b?6:248<=b?5:240<=b?4:224<=b?3:192<=b?2:1;f[254]=f[254]=1;function y(){p.call(this,"utf-8 decode"),this.leftOver=null}function w(){p.call(this,"utf-8 encode")}l.utf8encode=function(v){return d.nodebuffer?h.newBufferFrom(v,"utf-8"):(function(_){var $,T,S,E,D,R=_.length,L=0;for(E=0;E>>6:(T<65536?$[D++]=224|T>>>12:($[D++]=240|T>>>18,$[D++]=128|T>>>12&63),$[D++]=128|T>>>6&63),$[D++]=128|63&T);return $})(v)},l.utf8decode=function(v){return d.nodebuffer?c.transformTo("nodebuffer",v).toString("utf-8"):(function(_){var $,T,S,E,D=_.length,R=new Array(2*D);for($=T=0;$>10&1023,R[T++]=56320|1023&S)}return R.length!==T&&(R.subarray?R=R.subarray(0,T):R.length=T),c.applyFromCharCode(R)})(v=c.transformTo(d.uint8array?"uint8array":"array",v))},c.inherits(y,p),y.prototype.processChunk=function(v){var _=c.transformTo(d.uint8array?"uint8array":"array",v.data);if(this.leftOver&&this.leftOver.length){if(d.uint8array){var $=_;(_=new Uint8Array($.length+this.leftOver.length)).set(this.leftOver,0),_.set($,this.leftOver.length)}else _=this.leftOver.concat(_);this.leftOver=null}var T=(function(E,D){var R;for((D=D||E.length)>E.length&&(D=E.length),R=D-1;0<=R&&(192&E[R])==128;)R--;return R<0||R===0?D:R+f[E[R]]>D?R:D})(_),S=_;T!==_.length&&(d.uint8array?(S=_.subarray(0,T),this.leftOver=_.subarray(T,_.length)):(S=_.slice(0,T),this.leftOver=_.slice(T,_.length))),this.push({data:l.utf8decode(S),meta:v.meta})},y.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:l.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},l.Utf8DecodeWorker=y,c.inherits(w,p),w.prototype.processChunk=function(v){this.push({data:l.utf8encode(v.data),meta:v.meta})},l.Utf8EncodeWorker=w},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(i,r,l){var c=i("./support"),d=i("./base64"),h=i("./nodejsUtils"),p=i("./external");function f($){return $}function b($,T){for(var S=0;S<$.length;++S)T[S]=255&$.charCodeAt(S);return T}i("setimmediate"),l.newBlob=function($,T){l.checkSupport("blob");try{return new Blob([$],{type:T})}catch{try{var S=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);return S.append($),S.getBlob(T)}catch{throw new Error("Bug : can't construct the Blob.")}}};var y={stringifyByChunk:function($,T,S){var E=[],D=0,R=$.length;if(R<=S)return String.fromCharCode.apply(null,$);for(;D>8;this.dir=!!(16&this.externalFileAttributes),v==0&&(this.dosPermissions=63&this.externalFileAttributes),v==3&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||this.fileNameStr.slice(-1)!=="/"||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var v=c(this.extraFields[1].value);this.uncompressedSize===d.MAX_VALUE_32BITS&&(this.uncompressedSize=v.readInt(8)),this.compressedSize===d.MAX_VALUE_32BITS&&(this.compressedSize=v.readInt(8)),this.localHeaderOffset===d.MAX_VALUE_32BITS&&(this.localHeaderOffset=v.readInt(8)),this.diskNumberStart===d.MAX_VALUE_32BITS&&(this.diskNumberStart=v.readInt(4))}},readExtraFields:function(v){var _,$,T,S=v.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});v.index+4>>6:(v<65536?w[T++]=224|v>>>12:(w[T++]=240|v>>>18,w[T++]=128|v>>>12&63),w[T++]=128|v>>>6&63),w[T++]=128|63&v);return w},l.buf2binstring=function(y){return b(y,y.length)},l.binstring2buf=function(y){for(var w=new c.Buf8(y.length),v=0,_=w.length;v<_;v++)w[v]=y.charCodeAt(v);return w},l.buf2string=function(y,w){var v,_,$,T,S=w||y.length,E=new Array(2*S);for(v=_=0;v>10&1023,E[_++]=56320|1023&$)}return b(E,_)},l.utf8border=function(y,w){var v;for((w=w||y.length)>y.length&&(w=y.length),v=w-1;0<=v&&(192&y[v])==128;)v--;return v<0||v===0?w:v+p[y[v]]>w?v:w}},{"./common":41}],43:[function(i,r,l){r.exports=function(c,d,h,p){for(var f=65535&c|0,b=c>>>16&65535|0,y=0;h!==0;){for(h-=y=2e3>>1:d>>>1;h[p]=d}return h})();r.exports=function(d,h,p,f){var b=c,y=f+p;d^=-1;for(var w=f;w>>8^b[255&(d^h[w])];return-1^d}},{}],46:[function(i,r,l){var c,d=i("../utils/common"),h=i("./trees"),p=i("./adler32"),f=i("./crc32"),b=i("./messages"),y=0,w=4,v=0,_=-2,$=-1,T=4,S=2,E=8,D=9,R=286,L=30,H=19,G=2*R+1,z=15,Z=3,he=258,Ce=he+Z+1,M=42,Y=113,C=1,Q=2,ve=3,ce=4;function ne(k,q){return k.msg=b[q],q}function me(k){return(k<<1)-(4k.avail_out&&(K=k.avail_out),K!==0&&(d.arraySet(k.output,q.pending_buf,q.pending_out,K,k.next_out),k.next_out+=K,q.pending_out+=K,k.total_out+=K,k.avail_out-=K,q.pending-=K,q.pending===0&&(q.pending_out=0))}function N(k,q){h._tr_flush_block(k,0<=k.block_start?k.block_start:-1,k.strstart-k.block_start,q),k.block_start=k.strstart,B(k.strm)}function te(k,q){k.pending_buf[k.pending++]=q}function X(k,q){k.pending_buf[k.pending++]=q>>>8&255,k.pending_buf[k.pending++]=255&q}function se(k,q){var K,O,A=k.max_chain_length,U=k.strstart,W=k.prev_length,ue=k.nice_match,V=k.strstart>k.w_size-Ce?k.strstart-(k.w_size-Ce):0,be=k.window,pe=k.w_mask,fe=k.prev,Le=k.strstart+he,He=be[U+W-1],Be=be[U+W];k.prev_length>=k.good_match&&(A>>=2),ue>k.lookahead&&(ue=k.lookahead);do if(be[(K=q)+W]===Be&&be[K+W-1]===He&&be[K]===be[U]&&be[++K]===be[U+1]){U+=2,K++;do;while(be[++U]===be[++K]&&be[++U]===be[++K]&&be[++U]===be[++K]&&be[++U]===be[++K]&&be[++U]===be[++K]&&be[++U]===be[++K]&&be[++U]===be[++K]&&be[++U]===be[++K]&&UV&&--A!=0);return W<=k.lookahead?W:k.lookahead}function F(k){var q,K,O,A,U,W,ue,V,be,pe,fe=k.w_size;do{if(A=k.window_size-k.lookahead-k.strstart,k.strstart>=fe+(fe-Ce)){for(d.arraySet(k.window,k.window,fe,fe,0),k.match_start-=fe,k.strstart-=fe,k.block_start-=fe,q=K=k.hash_size;O=k.head[--q],k.head[q]=fe<=O?O-fe:0,--K;);for(q=K=fe;O=k.prev[--q],k.prev[q]=fe<=O?O-fe:0,--K;);A+=fe}if(k.strm.avail_in===0)break;if(W=k.strm,ue=k.window,V=k.strstart+k.lookahead,be=A,pe=void 0,pe=W.avail_in,be=Z)for(U=k.strstart-k.insert,k.ins_h=k.window[U],k.ins_h=(k.ins_h<=Z&&(k.ins_h=(k.ins_h<=Z)if(O=h._tr_tally(k,k.strstart-k.match_start,k.match_length-Z),k.lookahead-=k.match_length,k.match_length<=k.max_lazy_match&&k.lookahead>=Z){for(k.match_length--;k.strstart++,k.ins_h=(k.ins_h<=Z&&(k.ins_h=(k.ins_h<=Z&&k.match_length<=k.prev_length){for(A=k.strstart+k.lookahead-Z,O=h._tr_tally(k,k.strstart-1-k.prev_match,k.prev_length-Z),k.lookahead-=k.prev_length-1,k.prev_length-=2;++k.strstart<=A&&(k.ins_h=(k.ins_h<k.pending_buf_size-5&&(K=k.pending_buf_size-5);;){if(k.lookahead<=1){if(F(k),k.lookahead===0&&q===y)return C;if(k.lookahead===0)break}k.strstart+=k.lookahead,k.lookahead=0;var O=k.block_start+K;if((k.strstart===0||k.strstart>=O)&&(k.lookahead=k.strstart-O,k.strstart=O,N(k,!1),k.strm.avail_out===0)||k.strstart-k.block_start>=k.w_size-Ce&&(N(k,!1),k.strm.avail_out===0))return C}return k.insert=0,q===w?(N(k,!0),k.strm.avail_out===0?ve:ce):(k.strstart>k.block_start&&(N(k,!1),k.strm.avail_out),C)}),new we(4,4,8,4,Te),new we(4,5,16,8,Te),new we(4,6,32,32,Te),new we(4,4,16,16,ae),new we(8,16,32,32,ae),new we(8,16,128,128,ae),new we(8,32,128,256,ae),new we(32,128,258,1024,ae),new we(32,258,258,4096,ae)],l.deflateInit=function(k,q){return We(k,q,E,15,8,0)},l.deflateInit2=We,l.deflateReset=Ae,l.deflateResetKeep=Me,l.deflateSetHeader=function(k,q){return k&&k.state?k.state.wrap!==2?_:(k.state.gzhead=q,v):_},l.deflate=function(k,q){var K,O,A,U;if(!k||!k.state||5>8&255),te(O,O.gzhead.time>>16&255),te(O,O.gzhead.time>>24&255),te(O,O.level===9?2:2<=O.strategy||O.level<2?4:0),te(O,255&O.gzhead.os),O.gzhead.extra&&O.gzhead.extra.length&&(te(O,255&O.gzhead.extra.length),te(O,O.gzhead.extra.length>>8&255)),O.gzhead.hcrc&&(k.adler=f(k.adler,O.pending_buf,O.pending,0)),O.gzindex=0,O.status=69):(te(O,0),te(O,0),te(O,0),te(O,0),te(O,0),te(O,O.level===9?2:2<=O.strategy||O.level<2?4:0),te(O,3),O.status=Y);else{var W=E+(O.w_bits-8<<4)<<8;W|=(2<=O.strategy||O.level<2?0:O.level<6?1:O.level===6?2:3)<<6,O.strstart!==0&&(W|=32),W+=31-W%31,O.status=Y,X(O,W),O.strstart!==0&&(X(O,k.adler>>>16),X(O,65535&k.adler)),k.adler=1}if(O.status===69)if(O.gzhead.extra){for(A=O.pending;O.gzindex<(65535&O.gzhead.extra.length)&&(O.pending!==O.pending_buf_size||(O.gzhead.hcrc&&O.pending>A&&(k.adler=f(k.adler,O.pending_buf,O.pending-A,A)),B(k),A=O.pending,O.pending!==O.pending_buf_size));)te(O,255&O.gzhead.extra[O.gzindex]),O.gzindex++;O.gzhead.hcrc&&O.pending>A&&(k.adler=f(k.adler,O.pending_buf,O.pending-A,A)),O.gzindex===O.gzhead.extra.length&&(O.gzindex=0,O.status=73)}else O.status=73;if(O.status===73)if(O.gzhead.name){A=O.pending;do{if(O.pending===O.pending_buf_size&&(O.gzhead.hcrc&&O.pending>A&&(k.adler=f(k.adler,O.pending_buf,O.pending-A,A)),B(k),A=O.pending,O.pending===O.pending_buf_size)){U=1;break}U=O.gzindexA&&(k.adler=f(k.adler,O.pending_buf,O.pending-A,A)),U===0&&(O.gzindex=0,O.status=91)}else O.status=91;if(O.status===91)if(O.gzhead.comment){A=O.pending;do{if(O.pending===O.pending_buf_size&&(O.gzhead.hcrc&&O.pending>A&&(k.adler=f(k.adler,O.pending_buf,O.pending-A,A)),B(k),A=O.pending,O.pending===O.pending_buf_size)){U=1;break}U=O.gzindexA&&(k.adler=f(k.adler,O.pending_buf,O.pending-A,A)),U===0&&(O.status=103)}else O.status=103;if(O.status===103&&(O.gzhead.hcrc?(O.pending+2>O.pending_buf_size&&B(k),O.pending+2<=O.pending_buf_size&&(te(O,255&k.adler),te(O,k.adler>>8&255),k.adler=0,O.status=Y)):O.status=Y),O.pending!==0){if(B(k),k.avail_out===0)return O.last_flush=-1,v}else if(k.avail_in===0&&me(q)<=me(K)&&q!==w)return ne(k,-5);if(O.status===666&&k.avail_in!==0)return ne(k,-5);if(k.avail_in!==0||O.lookahead!==0||q!==y&&O.status!==666){var ue=O.strategy===2?(function(V,be){for(var pe;;){if(V.lookahead===0&&(F(V),V.lookahead===0)){if(be===y)return C;break}if(V.match_length=0,pe=h._tr_tally(V,0,V.window[V.strstart]),V.lookahead--,V.strstart++,pe&&(N(V,!1),V.strm.avail_out===0))return C}return V.insert=0,be===w?(N(V,!0),V.strm.avail_out===0?ve:ce):V.last_lit&&(N(V,!1),V.strm.avail_out===0)?C:Q})(O,q):O.strategy===3?(function(V,be){for(var pe,fe,Le,He,Be=V.window;;){if(V.lookahead<=he){if(F(V),V.lookahead<=he&&be===y)return C;if(V.lookahead===0)break}if(V.match_length=0,V.lookahead>=Z&&0V.lookahead&&(V.match_length=V.lookahead)}if(V.match_length>=Z?(pe=h._tr_tally(V,1,V.match_length-Z),V.lookahead-=V.match_length,V.strstart+=V.match_length,V.match_length=0):(pe=h._tr_tally(V,0,V.window[V.strstart]),V.lookahead--,V.strstart++),pe&&(N(V,!1),V.strm.avail_out===0))return C}return V.insert=0,be===w?(N(V,!0),V.strm.avail_out===0?ve:ce):V.last_lit&&(N(V,!1),V.strm.avail_out===0)?C:Q})(O,q):c[O.level].func(O,q);if(ue!==ve&&ue!==ce||(O.status=666),ue===C||ue===ve)return k.avail_out===0&&(O.last_flush=-1),v;if(ue===Q&&(q===1?h._tr_align(O):q!==5&&(h._tr_stored_block(O,0,0,!1),q===3&&(re(O.head),O.lookahead===0&&(O.strstart=0,O.block_start=0,O.insert=0))),B(k),k.avail_out===0))return O.last_flush=-1,v}return q!==w?v:O.wrap<=0?1:(O.wrap===2?(te(O,255&k.adler),te(O,k.adler>>8&255),te(O,k.adler>>16&255),te(O,k.adler>>24&255),te(O,255&k.total_in),te(O,k.total_in>>8&255),te(O,k.total_in>>16&255),te(O,k.total_in>>24&255)):(X(O,k.adler>>>16),X(O,65535&k.adler)),B(k),0=K.w_size&&(U===0&&(re(K.head),K.strstart=0,K.block_start=0,K.insert=0),be=new d.Buf8(K.w_size),d.arraySet(be,q,pe-K.w_size,K.w_size,0),q=be,pe=K.w_size),W=k.avail_in,ue=k.next_in,V=k.input,k.avail_in=pe,k.next_in=0,k.input=q,F(K);K.lookahead>=Z;){for(O=K.strstart,A=K.lookahead-(Z-1);K.ins_h=(K.ins_h<>>=Z=z>>>24,D-=Z,(Z=z>>>16&255)===0)Q[b++]=65535&z;else{if(!(16&Z)){if((64&Z)==0){z=R[(65535&z)+(E&(1<>>=Z,D-=Z),D<15&&(E+=C[p++]<>>=Z=z>>>24,D-=Z,!(16&(Z=z>>>16&255))){if((64&Z)==0){z=L[(65535&z)+(E&(1<>>=Z,D-=Z,(Z=b-y)>3,E&=(1<<(D-=he<<3))-1,c.next_in=p,c.next_out=b,c.avail_in=p>>24&255)+(M>>>8&65280)+((65280&M)<<8)+((255&M)<<24)}function E(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new c.Buf16(320),this.work=new c.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function D(M){var Y;return M&&M.state?(Y=M.state,M.total_in=M.total_out=Y.total=0,M.msg="",Y.wrap&&(M.adler=1&Y.wrap),Y.mode=_,Y.last=0,Y.havedict=0,Y.dmax=32768,Y.head=null,Y.hold=0,Y.bits=0,Y.lencode=Y.lendyn=new c.Buf32($),Y.distcode=Y.distdyn=new c.Buf32(T),Y.sane=1,Y.back=-1,w):v}function R(M){var Y;return M&&M.state?((Y=M.state).wsize=0,Y.whave=0,Y.wnext=0,D(M)):v}function L(M,Y){var C,Q;return M&&M.state?(Q=M.state,Y<0?(C=0,Y=-Y):(C=1+(Y>>4),Y<48&&(Y&=15)),Y&&(Y<8||15=ce.wsize?(c.arraySet(ce.window,Y,C-ce.wsize,ce.wsize,0),ce.wnext=0,ce.whave=ce.wsize):(Q<(ve=ce.wsize-ce.wnext)&&(ve=Q),c.arraySet(ce.window,Y,C-Q,ve,ce.wnext),(Q-=ve)?(c.arraySet(ce.window,Y,C-Q,Q,0),ce.wnext=Q,ce.whave=ce.wsize):(ce.wnext+=ve,ce.wnext===ce.wsize&&(ce.wnext=0),ce.whave>>8&255,C.check=h(C.check,U,2,0),N=B=0,C.mode=2;break}if(C.flags=0,C.head&&(C.head.done=!1),!(1&C.wrap)||(((255&B)<<8)+(B>>8))%31){M.msg="incorrect header check",C.mode=30;break}if((15&B)!=8){M.msg="unknown compression method",C.mode=30;break}if(N-=4,k=8+(15&(B>>>=4)),C.wbits===0)C.wbits=k;else if(k>C.wbits){M.msg="invalid window size",C.mode=30;break}C.dmax=1<>8&1),512&C.flags&&(U[0]=255&B,U[1]=B>>>8&255,C.check=h(C.check,U,2,0)),N=B=0,C.mode=3;case 3:for(;N<32;){if(me===0)break e;me--,B+=Q[ce++]<>>8&255,U[2]=B>>>16&255,U[3]=B>>>24&255,C.check=h(C.check,U,4,0)),N=B=0,C.mode=4;case 4:for(;N<16;){if(me===0)break e;me--,B+=Q[ce++]<>8),512&C.flags&&(U[0]=255&B,U[1]=B>>>8&255,C.check=h(C.check,U,2,0)),N=B=0,C.mode=5;case 5:if(1024&C.flags){for(;N<16;){if(me===0)break e;me--,B+=Q[ce++]<>>8&255,C.check=h(C.check,U,2,0)),N=B=0}else C.head&&(C.head.extra=null);C.mode=6;case 6:if(1024&C.flags&&(me<(se=C.length)&&(se=me),se&&(C.head&&(k=C.head.extra_len-C.length,C.head.extra||(C.head.extra=new Array(C.head.extra_len)),c.arraySet(C.head.extra,Q,ce,se,k)),512&C.flags&&(C.check=h(C.check,Q,se,ce)),me-=se,ce+=se,C.length-=se),C.length))break e;C.length=0,C.mode=7;case 7:if(2048&C.flags){if(me===0)break e;for(se=0;k=Q[ce+se++],C.head&&k&&C.length<65536&&(C.head.name+=String.fromCharCode(k)),k&&se>9&1,C.head.done=!0),M.adler=C.check=0,C.mode=12;break;case 10:for(;N<32;){if(me===0)break e;me--,B+=Q[ce++]<>>=7&N,N-=7&N,C.mode=27;break}for(;N<3;){if(me===0)break e;me--,B+=Q[ce++]<>>=1)){case 0:C.mode=14;break;case 1:if(he(C),C.mode=20,Y!==6)break;B>>>=2,N-=2;break e;case 2:C.mode=17;break;case 3:M.msg="invalid block type",C.mode=30}B>>>=2,N-=2;break;case 14:for(B>>>=7&N,N-=7&N;N<32;){if(me===0)break e;me--,B+=Q[ce++]<>>16^65535)){M.msg="invalid stored block lengths",C.mode=30;break}if(C.length=65535&B,N=B=0,C.mode=15,Y===6)break e;case 15:C.mode=16;case 16:if(se=C.length){if(me>>=5,N-=5,C.ndist=1+(31&B),B>>>=5,N-=5,C.ncode=4+(15&B),B>>>=4,N-=4,286>>=3,N-=3}for(;C.have<19;)C.lens[W[C.have++]]=0;if(C.lencode=C.lendyn,C.lenbits=7,K={bits:C.lenbits},q=f(0,C.lens,0,19,C.lencode,0,C.work,K),C.lenbits=K.bits,q){M.msg="invalid code lengths set",C.mode=30;break}C.have=0,C.mode=19;case 19:for(;C.have>>16&255,Ie=65535&A,!((ae=A>>>24)<=N);){if(me===0)break e;me--,B+=Q[ce++]<>>=ae,N-=ae,C.lens[C.have++]=Ie;else{if(Ie===16){for(O=ae+2;N>>=ae,N-=ae,C.have===0){M.msg="invalid bit length repeat",C.mode=30;break}k=C.lens[C.have-1],se=3+(3&B),B>>>=2,N-=2}else if(Ie===17){for(O=ae+3;N>>=ae)),B>>>=3,N-=3}else{for(O=ae+7;N>>=ae)),B>>>=7,N-=7}if(C.have+se>C.nlen+C.ndist){M.msg="invalid bit length repeat",C.mode=30;break}for(;se--;)C.lens[C.have++]=k}}if(C.mode===30)break;if(C.lens[256]===0){M.msg="invalid code -- missing end-of-block",C.mode=30;break}if(C.lenbits=9,K={bits:C.lenbits},q=f(b,C.lens,0,C.nlen,C.lencode,0,C.work,K),C.lenbits=K.bits,q){M.msg="invalid literal/lengths set",C.mode=30;break}if(C.distbits=6,C.distcode=C.distdyn,K={bits:C.distbits},q=f(y,C.lens,C.nlen,C.ndist,C.distcode,0,C.work,K),C.distbits=K.bits,q){M.msg="invalid distances set",C.mode=30;break}if(C.mode=20,Y===6)break e;case 20:C.mode=21;case 21:if(6<=me&&258<=re){M.next_out=ne,M.avail_out=re,M.next_in=ce,M.avail_in=me,C.hold=B,C.bits=N,p(M,X),ne=M.next_out,ve=M.output,re=M.avail_out,ce=M.next_in,Q=M.input,me=M.avail_in,B=C.hold,N=C.bits,C.mode===12&&(C.back=-1);break}for(C.back=0;we=(A=C.lencode[B&(1<>>16&255,Ie=65535&A,!((ae=A>>>24)<=N);){if(me===0)break e;me--,B+=Q[ce++]<>Me)])>>>16&255,Ie=65535&A,!(Me+(ae=A>>>24)<=N);){if(me===0)break e;me--,B+=Q[ce++]<>>=Me,N-=Me,C.back+=Me}if(B>>>=ae,N-=ae,C.back+=ae,C.length=Ie,we===0){C.mode=26;break}if(32&we){C.back=-1,C.mode=12;break}if(64&we){M.msg="invalid literal/length code",C.mode=30;break}C.extra=15&we,C.mode=22;case 22:if(C.extra){for(O=C.extra;N>>=C.extra,N-=C.extra,C.back+=C.extra}C.was=C.length,C.mode=23;case 23:for(;we=(A=C.distcode[B&(1<>>16&255,Ie=65535&A,!((ae=A>>>24)<=N);){if(me===0)break e;me--,B+=Q[ce++]<>Me)])>>>16&255,Ie=65535&A,!(Me+(ae=A>>>24)<=N);){if(me===0)break e;me--,B+=Q[ce++]<>>=Me,N-=Me,C.back+=Me}if(B>>>=ae,N-=ae,C.back+=ae,64&we){M.msg="invalid distance code",C.mode=30;break}C.offset=Ie,C.extra=15&we,C.mode=24;case 24:if(C.extra){for(O=C.extra;N>>=C.extra,N-=C.extra,C.back+=C.extra}if(C.offset>C.dmax){M.msg="invalid distance too far back",C.mode=30;break}C.mode=25;case 25:if(re===0)break e;if(se=X-re,C.offset>se){if((se=C.offset-se)>C.whave&&C.sane){M.msg="invalid distance too far back",C.mode=30;break}F=se>C.wnext?(se-=C.wnext,C.wsize-se):C.wnext-se,se>C.length&&(se=C.length),Te=C.window}else Te=ve,F=ne-C.offset,se=C.length;for(reG?(Z=F[Te+T[Y]],N[te+T[Y]]):(Z=96,0),E=1<>ne)+(D-=E)]=z<<24|Z<<16|he|0,D!==0;);for(E=1<>=1;if(E!==0?(B&=E-1,B+=E):B=0,Y++,--X[M]==0){if(M===Q)break;M=y[w+T[Y]]}if(ve>>7)]}function te(A,U){A.pending_buf[A.pending++]=255&U,A.pending_buf[A.pending++]=U>>>8&255}function X(A,U,W){A.bi_valid>S-W?(A.bi_buf|=U<>S-A.bi_valid,A.bi_valid+=W-S):(A.bi_buf|=U<>>=1,W<<=1,0<--U;);return W>>>1}function Te(A,U,W){var ue,V,be=new Array(T+1),pe=0;for(ue=1;ue<=T;ue++)be[ue]=pe=pe+W[ue-1]<<1;for(V=0;V<=U;V++){var fe=A[2*V+1];fe!==0&&(A[2*V]=F(be[fe]++,fe))}}function ae(A){var U;for(U=0;U>1;1<=W;W--)Me(A,be,W);for(V=Le;W=A.heap[1],A.heap[1]=A.heap[A.heap_len--],Me(A,be,1),ue=A.heap[1],A.heap[--A.heap_max]=W,A.heap[--A.heap_max]=ue,be[2*V]=be[2*W]+be[2*ue],A.depth[V]=(A.depth[W]>=A.depth[ue]?A.depth[W]:A.depth[ue])+1,be[2*W+1]=be[2*ue+1]=V,A.heap[1]=V++,Me(A,be,1),2<=A.heap_len;);A.heap[--A.heap_max]=A.heap[1],(function(Be,jt){var ie,Oe,Ps,ze,Zo,Qe,At=jt.dyn_tree,Qo=jt.max_code,io=jt.stat_desc.static_tree,no=jt.stat_desc.has_stree,Un=jt.stat_desc.extra_bits,Io=jt.stat_desc.extra_base,Bs=jt.stat_desc.max_length,ro=0;for(ze=0;ze<=T;ze++)Be.bl_count[ze]=0;for(At[2*Be.heap[Be.heap_max]+1]=0,ie=Be.heap_max+1;ie<$;ie++)Bs<(ze=At[2*At[2*(Oe=Be.heap[ie])+1]+1]+1)&&(ze=Bs,ro++),At[2*Oe+1]=ze,Qo>=7;V>>=1)if(1&He&&fe.dyn_ltree[2*Le]!==0)return d;if(fe.dyn_ltree[18]!==0||fe.dyn_ltree[20]!==0||fe.dyn_ltree[26]!==0)return h;for(Le=32;Le>>3,(be=A.static_len+3+7>>>3)<=V&&(V=be)):V=be=W+5,W+4<=V&&U!==-1?O(A,U,W,ue):A.strategy===4||be===V?(X(A,2+(ue?1:0),3),Ae(A,Ce,M)):(X(A,4+(ue?1:0),3),(function(fe,Le,He,Be){var jt;for(X(fe,Le-257,5),X(fe,He-1,5),X(fe,Be-4,4),jt=0;jt>>8&255,A.pending_buf[A.d_buf+2*A.last_lit+1]=255&U,A.pending_buf[A.l_buf+A.last_lit]=255&W,A.last_lit++,U===0?A.dyn_ltree[2*W]++:(A.matches++,U--,A.dyn_ltree[2*(C[W]+y+1)]++,A.dyn_dtree[2*N(U)]++),A.last_lit===A.lit_bufsize-1},l._tr_align=function(A){X(A,2,3),se(A,D,Ce),(function(U){U.bi_valid===16?(te(U,U.bi_buf),U.bi_buf=0,U.bi_valid=0):8<=U.bi_valid&&(U.pending_buf[U.pending++]=255&U.bi_buf,U.bi_buf>>=8,U.bi_valid-=8)})(A)}},{"../utils/common":41}],53:[function(i,r,l){r.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(i,r,l){(function(c){(function(d,h){if(!d.setImmediate){var p,f,b,y,w=1,v={},_=!1,$=d.document,T=Object.getPrototypeOf&&Object.getPrototypeOf(d);T=T&&T.setTimeout?T:d,p={}.toString.call(d.process)==="[object process]"?function(R){process.nextTick(function(){E(R)})}:(function(){if(d.postMessage&&!d.importScripts){var R=!0,L=d.onmessage;return d.onmessage=function(){R=!1},d.postMessage("","*"),d.onmessage=L,R}})()?(y="setImmediate$"+Math.random()+"$",d.addEventListener?d.addEventListener("message",D,!1):d.attachEvent("onmessage",D),function(R){d.postMessage(y+R,"*")}):d.MessageChannel?((b=new MessageChannel).port1.onmessage=function(R){E(R.data)},function(R){b.port2.postMessage(R)}):$&&"onreadystatechange"in $.createElement("script")?(f=$.documentElement,function(R){var L=$.createElement("script");L.onreadystatechange=function(){E(R),L.onreadystatechange=null,f.removeChild(L),L=null},f.appendChild(L)}):function(R){setTimeout(E,0,R)},T.setImmediate=function(R){typeof R!="function"&&(R=new Function(""+R));for(var L=new Array(arguments.length-1),H=0;H"u"?c===void 0?this:c:self)}).call(this,typeof eo<"u"?eo:typeof self<"u"?self:typeof window<"u"?window:{})},{}]},{},[10])(10)})})(RC);var kse=RC.exports;const kw=qo(kse);function Cse(a){const[s,i]=_e.useState(""),[r,l]=_e.useState("");return Lt(()=>{a.socket.decrypt(a.systemConfig.native.javascriptPassword).then(c=>l(c))},[a.systemConfig,a.socket]),m.jsxs(Pt,{open:!0,onClose:()=>a.onEntered(null),fullWidth:!0,maxWidth:"sm",children:[m.jsx(qt,{children:x.I18n.t("Please enter a password for expert mode")}),m.jsx(Wt,{children:m.jsx(Eo,{autoFocus:!0,margin:"dense",variant:"standard",label:x.I18n.t("Password"),type:"password",fullWidth:!0,value:s,onKeyDown:c=>{c.key==="Enter"&&s&&(c.preventDefault(),c.stopPropagation(),r===s?a.onEntered(s):a.onEntered(""))},onChange:c=>i(c.target.value)})}),m.jsxs(Bt,{children:[m.jsx(Ue,{variant:"contained",disabled:!s,onClick:()=>{r===s?a.onEntered(s):a.onEntered("")},startIcon:m.jsx(Xo,{}),children:x.I18n.t("Ok")}),m.jsx(Ue,{color:"grey",variant:"contained",onClick:()=>a.onEntered(null),startIcon:m.jsx(so,{}),children:x.I18n.t("Cancel")})]})]})}const Gr={root:{flexGrow:1,display:"flex",width:"100%",height:"100%"},mainDiv:{width:"100%",height:"100%",overflow:"hidden"},content:a=>({width:"100%",height:"100%",backgroundColor:a.palette.background&&a.palette.background.default,position:"relative"}),menuOpenCloseButton:a=>({position:"absolute",left:0,borderRadius:"0 5px 5px 0",top:6,pt:1,cursor:"pointer",zIndex:1,height:25,width:20,background:a.palette.secondary.main,color:a.palette.primary.main,pl:"3px","&:hover":{color:"white"}}),showLogButton:a=>({position:"absolute",right:3,borderRadius:"5px 5px 0 0",bottom:0,pt:"3px",cursor:"pointer",zIndex:10,height:20,width:25,background:a.palette.secondary.main,color:a.palette.primary.main,pl:1,"&:hover":{color:"white"}})};class Tse extends x.GenericApp{hosts=[];importFile=null;importFileName=null;scripts={};confirmCallback=null;changedScripts={};javascriptPassword="";constructor(s){super(s,{Connection:x.AdminConnection,translations:{en:bN,de:pB,es:lF,fr:oH,it:Z5,nl:YV,pl:U6,pt:PK,ru:OX,uk:EQ,"zh-cn":wse},bottomButtons:!1,socket:{autoSubscribeLog:!0},sentryDSN:window.sentryDSN});const i=window.localStorage.getItem("JS.logSizes");let r=[80,20];if(i)try{r=JSON.parse(i)}catch{}const l=window.localStorage.getItem("JS.splitSizes");let c=[20,80];if(l)try{c=JSON.parse(l)}catch{}this.state={...this.state,splitSizes:c,logSizes:r},window.alert=d=>{console.error(d),this.showJsError(d.toString())}}onScriptsChanged=(s,i)=>{if(!s)return;let r=!1;const l={};s.startsWith("script.js.")&&(i?JSON.stringify(this.scripts[s])!==JSON.stringify(i)&&(this.scripts[s]=i,r=!0,l.scriptsHash=this.state.scriptsHash+1):this.scripts[s]&&(delete this.scripts[s],r=!0,l.scriptsHash=this.state.scriptsHash+1)),r&&this.setState(l)};onInstanceChanged=(s,i)=>{var c;if(!s)return;let r=!1;const l={};if(s.match(/^system\.adapter\.[-_\w\d]+\$/)){if(s.startsWith(`system.adapter.${this.adapterName}.`)){const d=parseInt(s.split(".").pop()||"0",10)||0;if((i==null?void 0:i.type)==="instance")this.state.instances.includes(d)||(l.instances=[...this.state.instances],l.instances.push(d),l.instances.sort(),r=!0,this.socket.subscribeState(`${i._id}.alive`,this.onInstanceAliveChange));else if(!i&&this.state.instances.includes(d)){this.socket.unsubscribeState(`${s}.alive`,this.onInstanceAliveChange),l.instances=[...this.state.instances];const h=l.instances.indexOf(d);l.instances.splice(h,1),r=!0}}(c=i==null?void 0:i.common)!=null&&c.blockly&&(this.confirmCallback=d=>d&&window.location.reload(),l.confirm=x.I18n.t("Some blocks were updated. Reload admin?"),r=!0)}r&&this.setState(l)};onHostChanged=(s,i)=>{if(s&&s.startsWith("system.host.")){if((i==null?void 0:i.type)==="host")this.hosts.includes(s)||(this.hosts.push(s),this.hosts.sort());else if(!i&&this.hosts.includes(s)){const r=this.hosts.indexOf(s);this.hosts.splice(r,1)}}};onConnectionReady(){window.systemLang=this.socket.systemLang,this.setState({ready:!1,scriptsHash:0,instances:[],updating:!1,resizing:!1,selected:null,logMessage:{},editing:[],menuOpened:window.localStorage.getItem("App.menuOpened")!=="false",menuSelectId:"",expertMode:window.localStorage.getItem("App.expertMode")==="true",logHorzLayout:window.localStorage.getItem("App.logHorzLayout")==="true",runningInstances:{},confirm:"",importFile:!1,message:"",searchText:"",hideLog:window.localStorage.getItem("App.hideLog")==="true",debugMode:!1,debugInstance:null,splitSizes:[20,80],password:""},async()=>{var d;const s={},i=await this.subscribeOnInstances();s.instances=i.instances,s.runningInstances=i.runningInstances,this.javascriptPassword=((d=this.socket.systemConfig)==null?void 0:d.native.javascriptPassword)||"",await this.readAdaptersWithBlockly();const r=await this.socket.getHosts();this.hosts=r.map(h=>h._id);const l=await this.readAllScripts();window.localStorage.getItem("App.expertMode")!=="true"&&window.localStorage.getItem("App.expertMode")!=="false"&&!this.javascriptPassword?Object.keys(l).find(h=>h.startsWith("script.js.global.")&&l[h].type==="script")&&(s.expertMode=!0):this.javascriptPassword&&(s.expertMode=!1),this.scripts=l;let c=this.state.scriptsHash;this.compareScripts(l)&&c++,s.scriptsHash=c,s.ready=!0,this.setState(s),await this.socket.subscribeObject("script.*",this.onScriptsChanged),await this.socket.subscribeObject("system.adapter.*",this.onInstanceChanged),await this.socket.subscribeObject("system.host.*",this.onHostChanged)})}async subscribeOnInstances(){const i=(await this.socket.getAdapterInstances(this.adapterName)).map(l=>parseInt(l._id.split(".").pop()||"0")).sort(),r={};i.forEach(l=>r[`system.adapter.${this.adapterName}.${l}`]=!1);for(let l=0;ls[r]=i[r]),s}async readAdaptersWithBlockly(){const s=await this.socket.getObjectViewSystem("adapter","system.adapter.","system.adapter.香");return new Promise(i=>Xe.loadCustomBlockly(s,()=>i()))}onInstanceAliveChange=(s,i)=>{if(s&&(s=s?s.substring(0,s.length-6):"",this.state.runningInstances[s]!==(i?i.val:!1))){const r=JSON.parse(JSON.stringify(this.state.runningInstances));r[s]=i?!!i.val:!1,this.setState({runningInstances:r})}};compareScripts(s){const i=Object.keys(this.scripts),r=Object.keys(s);if(i.length!==r.length)return this.scripts=s,!0;if(JSON.stringify(i)!==JSON.stringify(r))return this.scripts=s,!0;for(let l=0;l ${i}`),this.setState({updating:!0});try{if(((c=this.scripts[s])==null?void 0:c.type)==="script"){const d=JSON.parse(JSON.stringify(this.scripts[s].common));d.name=r||d.name,l!==void 0&&(d.engine=`system.adapter.javascript.${l}`);const h=i.split(".");h.pop();const p=h.join(".");this.scripts[p]&&this.scripts[p].type==="script"&&(h.pop(),i=`${h.join(".")}.${i.split(".").pop()}`),await this.updateScript(s,i,d)}else await this.renameGroup(s,i,r)}catch(d){d.toString().includes("canceled")||this.showJsError(d)}this.setState({updating:!1})}async renameGroup(s,i,r,l){if(l){if(l.length){let c=l.pop();if(c){const d=await this.socket.getObject(c);if(d){try{await this.socket.delObject(c)}catch{}c=i+c.substring(s.length),d._id=c,d.common=d.common||{},d.common.expert=!0,await this.socket.setObject(c,d),await this.renameGroup(s,i,r,l)}}}}else{l=[],l=Object.keys(this.scripts).filter(d=>d.startsWith(`${s}.`));let c=await this.socket.getObject(s);c=c||{common:{},type:"channel"},c.common.name=r||c.common.name||s.split(".").pop()||"",c._id=i;try{await this.socket.delObject(s)}catch{}try{await this.socket.setObject(i,c),await this.renameGroup(s,i,r,l)}catch(d){console.log(d);const h={_id:i,type:"channel",common:{name:r||s.split(".").pop()||"",expert:!0},native:{}};await this.socket.setObject(i,h),await this.renameGroup(s,i,r,l)}}}async onUpdateScript(s,i){var r;if(((r=this.scripts[s])==null?void 0:r.type)==="script")try{await this.updateScript(s,s,i)}catch(l){l.toString().includes("canceled")||this.showJsError(l)}}onSelect(s){this.scripts[s]&&this.scripts[s].common&&this.scripts[s].type==="script"&&this.setState({selected:s,menuSelectId:s},()=>setTimeout(()=>this.setState({menuSelectId:""}),300))}renderPasswordDialog(){return this.state.showPasswordDialog?m.jsx(Cse,{socket:this.socket,systemConfig:this.socket.systemConfig,onEntered:s=>{s===null?this.setState({showPasswordDialog:!1,expertMode:!1,password:""}):s?this.setState({expertMode:!0,showPasswordDialog:!1,password:s}):this.setState({showPasswordDialog:!1,expertMode:!1,message:x.I18n.t("Wrong password"),password:""})}},"passwordDialog"):null}onExpertModeChange(s){var i;if(this.state.expertMode!==s)if(s&&this.javascriptPassword)this.setState({showPasswordDialog:!0});else{let r=this.state.selected;r&&!s&&((i=this.scripts[r].native)!=null&&i.protected)&&(r=this.state.editing.find(l=>{var c;return this.scripts[l]&&!((c=this.scripts[l].native)!=null&&c.protected)})||null),window.localStorage.setItem("App.expertMode",s?"true":"false"),this.setState({expertMode:s,password:"",selected:r})}}showJsError(s){this.setState({errorText:s?s.toString():""})}showMessage(s){this.setState({message:s?s.toString():""})}onDelete(s){this.socket.delObject(s).catch(i=>this.showJsError(i))}onEdit(s){this.state.selected!==s&&this.setState({selected:s})}onAddNew(s,i,r,l,c,d){const h=new RegExp(`^${s}\\.`);if(Object.keys(this.scripts).find(p=>s===p||h.test(s)))return this.showJsError(x.I18n.t("Yet exists!"));r?this.socket.setObject(s,{_id:s,type:"channel",common:{name:i,expert:!0},native:{}}).then(()=>setTimeout(()=>this.setState({menuSelectId:s},()=>setTimeout(()=>this.setState({menuSelectId:""}),300)),1e3)).catch(p=>this.showJsError(p)):(c==="Blockly"&&!d&&(d=` +//${btoa(encodeURIComponent(''))}`),this.socket.setObject(s,{_id:s,type:"script",common:{name:i,expert:!0,engineType:c||"Javascript/js",enabled:!1,engine:`system.adapter.javascript.${l||0}`,source:d||"",debug:!1,verbose:!1},native:{}}).then(()=>setTimeout(()=>this.onSelect(s),1e3)).catch(p=>this.showJsError(p)))}async updateScript(s,i,r){let l=await this.socket.getObject(s);const c={common:{}};if(r.engine!==void 0&&(c.common.engine=r.engine),r.enabled!==void 0&&(c.common.enabled=r.enabled),r.source!==void 0&&(c.common.source=r.source),r.debug!==void 0&&(c.common.debug=r.debug),r.verbose!==void 0&&(c.common.verbose=r.verbose),c.from="system.adapter.admin.0",s===i&&(l!=null&&l.common)&&r.name===l.common.name){(!r.engineType||r.engineType!==l.common.engineType)&&r.engineType!==void 0&&(c.common.engineType=r.engineType||"Javascript/js"),c.type="script",await this.socket.extendObject(s,c);return}if(l!=null&&l.common){l.common.engineType=r.engineType||l.common.engineType||"Javascript/js",await this.socket.delObject(s),c.common.engine!==void 0&&(l.common.engine=c.common.engine),c.common.enabled!==void 0&&(l.common.enabled=c.common.enabled),c.common.source!==void 0&&(l.common.source=c.common.source),c.common.name!==void 0&&(l.common.name=c.common.name),c.common.debug!==void 0&&(l.common.debug=c.common.debug),c.common.verbose!==void 0&&(l.common.verbose=c.common.verbose),l._rev!==void 0&&delete l._rev,l.common.name=r.name,l.common.expert=!0,l.type="script",l._id=i,await this.socket.setObject(i,l);return}l=c,l.common.name=r.name,l.common.expert=!0,l.type="script",l._id=i,await this.socket.setObject(i,l)}onEnableDisable(s,i){var r;if(((r=this.scripts[s])==null?void 0:r.type)==="script"){const l=this.scripts[s].common;l.enabled=i,l.expert=!0,this.updateScript(s,s,l).catch(c=>c!=="canceled"&&this.showJsError(c))}}async getLiveHost(){for(let s=0;s{if(typeof d=="string"){const h=document.createElement("a");h.href=`../../files/${d}`,document.body.appendChild(h),h.click(),h.remove()}else if(d.error&&this.showJsError(d.error),d.data){const h=document.createElement("a");h.href=`data: application/zip;base64,${d.data}`,h.download=`${r}scripts.zip`,document.body.appendChild(h),h.click(),h.remove()}})}else{const c=new kw;for(const[d,h]of Object.entries(this.scripts))if(h.type==="script"){const p=h,f=p.common.engineType==="TypeScript/ts"?"ts":p.common.engineType==="Blockly"?"blockly":p.common.engineType==="Rules"?"rules":"js";let b=`/******* (ext=${f}/engine=${p.common.engine}/debug=${p.common.debug}/verbose=${p.common.verbose}/enabled=${p.common.enabled}) *******/ +`;b+=p.common.source||"";const y=`${d.substring(10).replace(/\./g,"/")}.${f}`;c.file(y,b)}c.generateAsync({type:"blob"}).then(d=>{const h=document.createElement("a");h.href=URL.createObjectURL(d),h.download=`${r}scripts_plain.zip`,document.body.appendChild(h),h.click(),h.remove(),URL.revokeObjectURL(h.href)})}}onImport(s,i){this.importFile=s||null,this.importFileName=i||null,s?(this.confirmCallback=this.onImportConfirmed.bind(this),this.setState({importFile:!1,confirm:x.I18n.t("Existing scripts will be overwritten.")})):this.setState({importFile:!1})}async onImportConfirmed(s){let i=this.importFile;const r=this.importFileName;if(this.importFile=null,this.importFileName=null,s&&i)if(r&&/_(plain|text)\.zip$/i.test(r)){i=i.split(",")[1];try{const c=await kw.loadAsync(i,{base64:!0}),d=[];c.forEach((h,p)=>{p.dir||d.push(p.async("string").then(async f=>{const b=f.split(` `),y=b[0]||"",w=b.slice(1).join(` -`),v=y.match(/\/\*{7}\s*\(ext=(\w+)\/engine=([^/]+)\/debug=(\w+)\/verbose=(\w+)\/enabled=(\w+)\)\s*\*{7}\//);let _="Javascript/js",$="system.adapter.javascript.0",S=!1,T=!1,E=!1;if(v){const G=v[1];$=v[2],S=v[3]==="true",T=v[4]==="true",E=v[5]==="true",G==="ts"?_="TypeScript/ts":G==="blockly"?_="Blockly":G==="rules"&&(_="Rules")}const D=h.replace(/\.\w+$/,"").replace(/\//g,"."),M=`script.js.${D}`,P=D.split(".").pop()||D,W=M.split(".");for(let G=3;G{d==="permissionError"?this.showJsError(x.I18n.t(d)):!d||d.error?this.showJsError(d?x.I18n.t(d.error||""):x.I18n.t("Unknown error")):this.showMessage(x.I18n.t("Done"))})}}toggleLogLayout(){window.localStorage.setItem("App.logHorzLayout",this.state.logHorzLayout?"false":"true"),this.setState({logHorzLayout:!this.state.logHorzLayout})}renderEditor(){var i;const s=Object.keys(this.scripts).reduce((r,l)=>r+(this.scripts[l].common.engineType==="Rules"?1:0),0);return m.jsx(Rn,{scriptsHash:this.state.scriptsHash,debugMode:this.state.debugMode,onDebugModeChange:r=>{r?this.setState({debugMode:!0}):this.setState({debugMode:!1,debugInstance:null})},visible:!this.state.resizing,socket:this.socket,adapterName:this.adapterName,onLocate:r=>this.setState({menuSelectId:r}),password:this.state.password,runningInstances:this.state.runningInstances,menuOpened:this.state.menuOpened,searchText:this.state.searchText,themeType:this.state.themeType,themeName:this.state.themeName,theme:this.state.theme,expertMode:this.state.expertMode,onChange:(r,l)=>this.onUpdateScript(r,l),isAnyRulesExists:s,debugInstance:this.state.debugInstance,onSelectedChange:(r,l)=>{const c={};let d=!1;r!==this.state.selected&&(d=!0,c.selected=r),JSON.stringify(l)!==JSON.stringify(this.state.editing)&&(d=!0,c.editing=[...l]),d&&this.setState(c)},onRestart:r=>this.socket.extendObject(r,{common:{enabled:!0}}),selected:this.state.selected&&((i=this.scripts[this.state.selected])==null?void 0:i.type)==="script"?this.state.selected:"",objects:this.scripts,resizing:this.state.resizing,onChangedChanged:r=>this.changedScripts=r},"editor")}showLogButton(){return m.jsx(wt,{title:x.I18n.t("Show logs"),sx:Gr.showLogButton,onClick:()=>{window.localStorage.setItem("App.hideLog","false"),this.setState({hideLog:!1,resizing:!0}),setTimeout(()=>this.setState({resizing:!1}),300)},children:m.jsx(SS,{})},"showLog")}renderErrorDialog(){return this.state.errorText?m.jsx(su,{onClose:()=>this.setState({errorText:""}),text:this.state.errorText},"dialogError"):null}renderMain(){let s;return this.state.debugMode||this.state.hideLog?s=m.jsxs(m.Fragment,{children:[!this.state.debugMode&&this.state.hideLog?this.showLogButton():void 0,this.renderEditor()]}):s=m.jsxs(d_,{direction:this.state.logHorzLayout?ft.Horizontal:ft.Vertical,initialSizes:this.state.logSizes,minWidths:[500,100],minHeights:[150,50],onResizeStarted:()=>this.setState({resizing:!0}),onResizeFinished:(i,r)=>{this.setState({logSizes:r,resizing:!1}),window.localStorage.setItem("JS.logSizes",JSON.stringify(r))},gutterClassName:this.state.themeType==="dark"?"Dark visGutter":"Light visGutter",children:[this.renderEditor(),m.jsx(wm,{verticalLayout:!this.state.logHorzLayout,onLayoutChange:()=>this.toggleLogLayout(),editing:this.state.editing,socket:this.socket,selected:this.state.selected,onHideLog:()=>{window.localStorage.setItem("App.hideLog","true"),this.setState({hideLog:!0,resizing:!0}),setTimeout(()=>this.setState({resizing:!1}),300)}},"log")]}),m.jsxs(wt,{sx:Gr.content,className:"iobVerticalSplitter",children:[m.jsx(wt,{sx:Gr.menuOpenCloseButton,onClick:()=>{window.localStorage.setItem("App.menuOpened",this.state.menuOpened?"false":"true"),this.setState({menuOpened:!this.state.menuOpened,resizing:!0}),setTimeout(()=>this.setState({resizing:!1}),300)},children:this.state.menuOpened?m.jsx(ES,{}):m.jsx(IS,{})},"closeMenu"),this.state.message?m.jsx(x.Message,{onClose:()=>this.setState({message:""}),text:this.state.message},"dialogMessage"):null,this.renderErrorDialog(),this.state.importFile?m.jsx(Hm,{onClose:(i,r)=>this.onImport(i,r)},"dialogImportFile"):null,this.state.confirm?m.jsx(x.Confirm,{onClose:i=>{this.state.confirm&&this.setState({confirm:""}),this.confirmCallback&&this.confirmCallback(i),this.confirmCallback=null},text:this.state.confirm},"dialogConfirm"):null,this.renderPasswordDialog(),s]},"main")}render(){if(!this.state.ready)return m.jsx(a_,{injectFirst:!0,children:m.jsx(l_,{theme:this.state.theme,children:m.jsx(x.Loader,{themeType:this.state.themeType})})});let s;return this.state.menuOpened?s=m.jsxs(d_,{direction:ft.Horizontal,initialSizes:this.state.splitSizes,minWidths:[270,400],onResizeFinished:(i,r)=>{this.setState({splitSizes:r}),window.localStorage.setItem("JS.splitSizes",JSON.stringify(r))},gutterClassName:this.state.themeType==="dark"?"Dark visGutter":"Light visGutter",children:[m.jsx("div",{style:Gr.mainDiv,children:m.jsx(So,{password:this.state.password,debugMode:this.state.debugMode,onDebugInstance:i=>this.setState({debugInstance:i,debugMode:!!i}),scripts:this.scripts,scriptsHash:this.state.scriptsHash,instances:this.state.instances,onRename:this.onRename.bind(this),socket:this.socket,selectId:this.state.menuSelectId,onEdit:this.onEdit.bind(this),expertMode:this.state.expertMode,themeName:this.state.themeName,onThemeChange:i=>{x.Utils.setThemeName(i);const r=x.Utils.getThemeType(i);this.setState({themeName:i,themeType:r},()=>this.toggleTheme(i))},runningInstances:this.state.runningInstances,onExpertModeChange:i=>this.onExpertModeChange(i),onDelete:this.onDelete.bind(this),onAddNew:this.onAddNew.bind(this),onEnableDisable:this.onEnableDisable.bind(this),onExport:this.onExport.bind(this),width:500,onImport:()=>this.setState({importFile:!0}),onSearch:i=>this.setState({searchText:i}),version:this.props.version,changedScripts:this.changedScripts},"sidemenu")},"menu"),this.renderMain()]}):s=this.renderMain(),m.jsx(a_,{injectFirst:!0,children:m.jsx(l_,{theme:this.state.theme,children:m.jsx("div",{style:Gr.root,children:m.jsx(bO,{socket:this.socket,children:s})})})})}}window.location.hostname==="localhost"||window.location.hostname==="[::1]"||window.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/);function _se(){"serviceWorker"in navigator&&navigator.serviceWorker.ready.then(a=>{a.unregister()})}const wse="9.1.1",OC={version:wse};var Jo;(function(a){a.mouse="mouse",a.touch="touch",a.keyboard="keyboard"})(Jo||(Jo={}));class kse{get delay(){var s;return(s=this.args.delay)!==null&&s!==void 0?s:0}get scrollAngleRanges(){return this.args.scrollAngleRanges}get getDropTargetElementsAtPoint(){return this.args.getDropTargetElementsAtPoint}get ignoreContextMenu(){var s;return(s=this.args.ignoreContextMenu)!==null&&s!==void 0?s:!1}get enableHoverOutsideTarget(){var s;return(s=this.args.enableHoverOutsideTarget)!==null&&s!==void 0?s:!1}get enableKeyboardEvents(){var s;return(s=this.args.enableKeyboardEvents)!==null&&s!==void 0?s:!1}get enableMouseEvents(){var s;return(s=this.args.enableMouseEvents)!==null&&s!==void 0?s:!1}get enableTouchEvents(){var s;return(s=this.args.enableTouchEvents)!==null&&s!==void 0?s:!0}get touchSlop(){return this.args.touchSlop||0}get delayTouchStart(){var s,i,r,l;return(l=(r=(s=this.args)===null||s===void 0?void 0:s.delayTouchStart)!==null&&r!==void 0?r:(i=this.args)===null||i===void 0?void 0:i.delay)!==null&&l!==void 0?l:0}get delayMouseStart(){var s,i,r,l;return(l=(r=(s=this.args)===null||s===void 0?void 0:s.delayMouseStart)!==null&&r!==void 0?r:(i=this.args)===null||i===void 0?void 0:i.delay)!==null&&l!==void 0?l:0}get window(){if(this.context&&this.context.window)return this.context.window;if(typeof window<"u")return window}get document(){var s;if(!((s=this.context)===null||s===void 0)&&s.document)return this.context.document;if(this.window)return this.window.document}get rootElement(){var s;return((s=this.args)===null||s===void 0?void 0:s.rootElement)||this.document}constructor(s,i){this.args=s,this.context=i}}function Cse(a,s,i,r){return Math.sqrt(Math.pow(Math.abs(i-a),2)+Math.pow(Math.abs(r-s),2))}function Tse(a,s,i,r,l){if(!l)return!1;const c=Math.atan2(r-s,i-a)*180/Math.PI+180;for(let d=0;d=h.start)&&(h.end==null||c<=h.end))return!0}return!1}const Sse={Left:1},Ese={Left:0};function Eg(a){return a.button===void 0||a.button===Ese.Left}function Ise(a){return a.buttons===void 0||(a.buttons&Sse.Left)===0}function NC(a){return!!a.targetTouches}const xse=1;function Dse(a){const s=a.nodeType===xse?a:a.parentElement;if(!s)return;const{top:i,left:r}=s.getBoundingClientRect();return{x:r,y:i}}function Ase(a,s){if(a.targetTouches.length===1)return Kc(a.targetTouches[0]);if(s&&a.touches.length===1&&a.touches[0].target===s.target)return Kc(a.touches[0])}function Kc(a,s){return NC(a)?Ase(a,s):{x:a.clientX,y:a.clientY}}const kw=(()=>{let a=!1;try{addEventListener("test",()=>{},Object.defineProperty({},"passive",{get(){return a=!0,!0}}))}catch{}return a})(),Vr={[Jo.mouse]:{start:"mousedown",move:"mousemove",end:"mouseup",contextmenu:"contextmenu"},[Jo.touch]:{start:"touchstart",move:"touchmove",end:"touchend"},[Jo.keyboard]:{keydown:"keydown"}};class Zr{profile(){var s;return{sourceNodes:this.sourceNodes.size,sourcePreviewNodes:this.sourcePreviewNodes.size,sourcePreviewNodeOptions:this.sourcePreviewNodeOptions.size,targetNodes:this.targetNodes.size,dragOverTargetIds:((s=this.dragOverTargetIds)===null||s===void 0?void 0:s.length)||0}}get document(){return this.options.document}setup(){const s=this.options.rootElement;s&&(Ve(!Zr.isSetUp,"Cannot have two Touch backends at the same time."),Zr.isSetUp=!0,this.addEventListener(s,"start",this.getTopMoveStartHandler()),this.addEventListener(s,"start",this.handleTopMoveStartCapture,!0),this.addEventListener(s,"move",this.handleTopMove),this.addEventListener(s,"move",this.handleTopMoveCapture,!0),this.addEventListener(s,"end",this.handleTopMoveEndCapture,!0),this.options.enableMouseEvents&&!this.options.ignoreContextMenu&&this.addEventListener(s,"contextmenu",this.handleTopMoveEndCapture),this.options.enableKeyboardEvents&&this.addEventListener(s,"keydown",this.handleCancelOnEscape,!0))}teardown(){const s=this.options.rootElement;s&&(Zr.isSetUp=!1,this._mouseClientOffset={},this.removeEventListener(s,"start",this.handleTopMoveStartCapture,!0),this.removeEventListener(s,"start",this.handleTopMoveStart),this.removeEventListener(s,"move",this.handleTopMoveCapture,!0),this.removeEventListener(s,"move",this.handleTopMove),this.removeEventListener(s,"end",this.handleTopMoveEndCapture,!0),this.options.enableMouseEvents&&!this.options.ignoreContextMenu&&this.removeEventListener(s,"contextmenu",this.handleTopMoveEndCapture),this.options.enableKeyboardEvents&&this.removeEventListener(s,"keydown",this.handleCancelOnEscape,!0),this.uninstallSourceNodeRemovalObserver())}addEventListener(s,i,r,l=!1){const c=kw?{capture:l,passive:!1}:l;this.listenerTypes.forEach(function(d){const h=Vr[d][i];h&&s.addEventListener(h,r,c)})}removeEventListener(s,i,r,l=!1){const c=kw?{capture:l,passive:!1}:l;this.listenerTypes.forEach(function(d){const h=Vr[d][i];h&&s.removeEventListener(h,r,c)})}connectDragSource(s,i){const r=this.handleMoveStart.bind(this,s);return this.sourceNodes.set(s,i),this.addEventListener(i,"start",r),()=>{this.sourceNodes.delete(s),this.removeEventListener(i,"start",r)}}connectDragPreview(s,i,r){return this.sourcePreviewNodeOptions.set(s,r),this.sourcePreviewNodes.set(s,i),()=>{this.sourcePreviewNodes.delete(s),this.sourcePreviewNodeOptions.delete(s)}}connectDropTarget(s,i){const r=this.options.rootElement;if(!this.document||!r)return()=>{};const l=c=>{if(!this.document||!r||!this.monitor.isDragging())return;let d;switch(c.type){case Vr.mouse.move:d={x:c.clientX,y:c.clientY};break;case Vr.touch.move:var h,p;d={x:((h=c.touches[0])===null||h===void 0?void 0:h.clientX)||0,y:((p=c.touches[0])===null||p===void 0?void 0:p.clientY)||0};break}const f=d!=null?this.document.elementFromPoint(d.x,d.y):void 0,b=f&&i.contains(f);if(f===i||b)return this.handleMove(c,s)};return this.addEventListener(this.document.body,"move",l),this.targetNodes.set(s,i),()=>{this.document&&(this.targetNodes.delete(s),this.removeEventListener(this.document.body,"move",l))}}getTopMoveStartHandler(){return!this.options.delayTouchStart&&!this.options.delayMouseStart?this.handleTopMoveStart:this.handleTopMoveStartDelay}installSourceNodeRemovalObserver(s){this.uninstallSourceNodeRemovalObserver(),this.draggedSourceNode=s,this.draggedSourceNodeRemovalObserver=new MutationObserver(()=>{s&&!s.parentElement&&(this.resurrectSourceNode(),this.uninstallSourceNodeRemovalObserver())}),!(!s||!s.parentElement)&&this.draggedSourceNodeRemovalObserver.observe(s.parentElement,{childList:!0})}resurrectSourceNode(){this.document&&this.draggedSourceNode&&(this.draggedSourceNode.style.display="none",this.draggedSourceNode.removeAttribute("data-reactid"),this.document.body.appendChild(this.draggedSourceNode))}uninstallSourceNodeRemovalObserver(){this.draggedSourceNodeRemovalObserver&&this.draggedSourceNodeRemovalObserver.disconnect(),this.draggedSourceNodeRemovalObserver=void 0,this.draggedSourceNode=void 0}constructor(s,i,r){this.getSourceClientOffset=l=>{const c=this.sourceNodes.get(l);return c&&Dse(c)},this.handleTopMoveStartCapture=l=>{Eg(l)&&(this.moveStartSourceIds=[])},this.handleMoveStart=l=>{Array.isArray(this.moveStartSourceIds)&&this.moveStartSourceIds.unshift(l)},this.handleTopMoveStart=l=>{if(!Eg(l))return;const c=Kc(l);c&&(NC(l)&&(this.lastTargetTouchFallback=l.targetTouches[0]),this._mouseClientOffset=c),this.waitingForDelay=!1},this.handleTopMoveStartDelay=l=>{if(!Eg(l))return;const c=l.type===Vr.touch.start?this.options.delayTouchStart:this.options.delayMouseStart;this.timeout=setTimeout(this.handleTopMoveStart.bind(this,l),c),this.waitingForDelay=!0},this.handleTopMoveCapture=()=>{this.dragOverTargetIds=[]},this.handleMove=(l,c)=>{this.dragOverTargetIds&&this.dragOverTargetIds.unshift(c)},this.handleTopMove=l=>{if(this.timeout&&clearTimeout(this.timeout),!this.document||this.waitingForDelay)return;const{moveStartSourceIds:c,dragOverTargetIds:d}=this,h=this.options.enableHoverOutsideTarget,p=Kc(l,this.lastTargetTouchFallback);if(!p)return;if(this._isScrolling||!this.monitor.isDragging()&&Tse(this._mouseClientOffset.x||0,this._mouseClientOffset.y||0,p.x,p.y,this.options.scrollAngleRanges)){this._isScrolling=!0;return}if(!this.monitor.isDragging()&&this._mouseClientOffset.hasOwnProperty("x")&&c&&Cse(this._mouseClientOffset.x||0,this._mouseClientOffset.y||0,p.x,p.y)>(this.options.touchSlop?this.options.touchSlop:0)&&(this.moveStartSourceIds=void 0,this.actions.beginDrag(c,{clientOffset:this._mouseClientOffset,getSourceClientOffset:this.getSourceClientOffset,publishSource:!1})),!this.monitor.isDragging())return;const f=this.sourceNodes.get(this.monitor.getSourceId());this.installSourceNodeRemovalObserver(f),this.actions.publishDragSource(),l.cancelable&&l.preventDefault();const b=(d||[]).map(_=>this.targetNodes.get(_)).filter(_=>!!_),y=this.options.getDropTargetElementsAtPoint?this.options.getDropTargetElementsAtPoint(p.x,p.y,b):this.document.elementsFromPoint(p.x,p.y),w=[];for(const _ in y){if(!y.hasOwnProperty(_))continue;let $=y[_];for($!=null&&w.push($);$;)$=$.parentElement,$&&w.indexOf($)===-1&&w.push($)}const v=w.filter(_=>b.indexOf(_)>-1).map(_=>this._getDropTargetId(_)).filter(_=>!!_).filter((_,$,S)=>S.indexOf(_)===$);if(h)for(const _ in this.targetNodes){const $=this.targetNodes.get(_);if(f&&$&&$.contains(f)&&v.indexOf(_)===-1){v.unshift(_);break}}v.reverse(),this.actions.hover(v,{clientOffset:p})},this._getDropTargetId=l=>{const c=this.targetNodes.keys();let d=c.next();for(;d.done===!1;){const h=d.value;if(l===this.targetNodes.get(h))return h;d=c.next()}},this.handleTopMoveEndCapture=l=>{if(this._isScrolling=!1,this.lastTargetTouchFallback=void 0,!!Ise(l)){if(!this.monitor.isDragging()||this.monitor.didDrop()){this.moveStartSourceIds=void 0;return}l.cancelable&&l.preventDefault(),this._mouseClientOffset={},this.uninstallSourceNodeRemovalObserver(),this.actions.drop(),this.actions.endDrag()}},this.handleCancelOnEscape=l=>{l.key==="Escape"&&this.monitor.isDragging()&&(this._mouseClientOffset={},this.uninstallSourceNodeRemovalObserver(),this.actions.endDrag())},this.options=new kse(r,i),this.actions=s.getActions(),this.monitor=s.getMonitor(),this.sourceNodes=new Map,this.sourcePreviewNodes=new Map,this.sourcePreviewNodeOptions=new Map,this.targetNodes=new Map,this.listenerTypes=[],this._mouseClientOffset={},this._isScrolling=!1,this.options.enableMouseEvents&&this.listenerTypes.push(Jo.mouse),this.options.enableTouchEvents&&this.listenerTypes.push(Jo.touch),this.options.enableKeyboardEvents&&this.listenerTypes.push(Jo.keyboard)}}const Rse=function(s,i={},r={}){return new Zr(s,i,r)};window.GenericBlock=at;window.adapterName="javascript";window.sentryDSN="https://504499a725eb4898930d3b9e9da95740@sentry.iobroker.net/56";console.log(`iobroker.${window.adapterName}@${OC.version}`);const Ose=window.innerWidth<600,Cw=document.getElementById("root");Cw&&jw(Cw).render(m.jsx(ek,{backend:Ose?Rse:hk,children:m.jsx(yse,{version:OC.version})}));_se();const gc=window.loadDynamicScript;gc&&gc(window.location.port==="3000"?`${window.location.protocol}//${window.location.hostname}:8081/lib/js/socket.io.js`:"./../../lib/js/socket.io.js",()=>gc("vs/loader.js",()=>gc("vs/configure.js",()=>typeof window.socketLoadedHandler=="function"&&window.socketLoadedHandler())));export{$O as C,sR as D,at as G,pk as I,fw as M,Ns as S,$I as a,LI as b,WI as c,Ei as d,Cne as e,Gm as f,su as g,cx as h,Tne as j,d_ as m,zn as u,ft as z}; +`),v=y.match(/\/\*{7}\s*\(ext=(\w+)\/engine=([^/]+)\/debug=(\w+)\/verbose=(\w+)\/enabled=(\w+)\)\s*\*{7}\//);let _="Javascript/js",$="system.adapter.javascript.0",T=!1,S=!1,E=!1;if(v){const G=v[1];$=v[2],T=v[3]==="true",S=v[4]==="true",E=v[5]==="true",G==="ts"?_="TypeScript/ts":G==="blockly"?_="Blockly":G==="rules"&&(_="Rules")}const D=h.replace(/\.\w+$/,"").replace(/\//g,"."),R=`script.js.${D}`,L=D.split(".").pop()||D,H=R.split(".");for(let G=3;G{d==="permissionError"?this.showJsError(x.I18n.t(d)):!d||d.error?this.showJsError(d?x.I18n.t(d.error||""):x.I18n.t("Unknown error")):this.showMessage(x.I18n.t("Done"))})}}toggleLogLayout(){window.localStorage.setItem("App.logHorzLayout",this.state.logHorzLayout?"false":"true"),this.setState({logHorzLayout:!this.state.logHorzLayout})}renderEditor(){var i;const s=Object.keys(this.scripts).reduce((r,l)=>r+(this.scripts[l].common.engineType==="Rules"?1:0),0);return m.jsx(On,{scriptsHash:this.state.scriptsHash,debugMode:this.state.debugMode,onDebugModeChange:r=>{r?this.setState({debugMode:!0}):this.setState({debugMode:!1,debugInstance:null})},visible:!this.state.resizing,socket:this.socket,adapterName:this.adapterName,onLocate:r=>this.setState({menuSelectId:r}),password:this.state.password,runningInstances:this.state.runningInstances,menuOpened:this.state.menuOpened,searchText:this.state.searchText,themeType:this.state.themeType,themeName:this.state.themeName,theme:this.state.theme,expertMode:this.state.expertMode,onChange:(r,l)=>this.onUpdateScript(r,l),isAnyRulesExists:s,debugInstance:this.state.debugInstance,onSelectedChange:(r,l)=>{const c={};let d=!1;r!==this.state.selected&&(d=!0,c.selected=r),JSON.stringify(l)!==JSON.stringify(this.state.editing)&&(d=!0,c.editing=[...l]),d&&this.setState(c)},onRestart:r=>this.socket.extendObject(r,{common:{enabled:!0}}),selected:this.state.selected&&((i=this.scripts[this.state.selected])==null?void 0:i.type)==="script"?this.state.selected:"",objects:this.scripts,resizing:this.state.resizing,onChangedChanged:r=>this.changedScripts=r},"editor")}showLogButton(){return m.jsx(wt,{title:x.I18n.t("Show logs"),sx:Gr.showLogButton,onClick:()=>{window.localStorage.setItem("App.hideLog","false"),this.setState({hideLog:!1,resizing:!0}),setTimeout(()=>this.setState({resizing:!1}),300)},children:m.jsx(ES,{})},"showLog")}renderErrorDialog(){return this.state.errorText?m.jsx(ou,{onClose:()=>this.setState({errorText:""}),text:this.state.errorText},"dialogError"):null}renderMain(){let s;return this.state.debugMode||this.state.hideLog?s=m.jsxs(m.Fragment,{children:[!this.state.debugMode&&this.state.hideLog?this.showLogButton():void 0,this.renderEditor()]}):s=m.jsxs(h_,{direction:this.state.logHorzLayout?ft.Horizontal:ft.Vertical,initialSizes:this.state.logSizes,minWidths:[500,100],minHeights:[150,50],onResizeStarted:()=>this.setState({resizing:!0}),onResizeFinished:(i,r)=>{this.setState({logSizes:r,resizing:!1}),window.localStorage.setItem("JS.logSizes",JSON.stringify(r))},gutterClassName:this.state.themeType==="dark"?"Dark visGutter":"Light visGutter",children:[this.renderEditor(),m.jsx(Cm,{verticalLayout:!this.state.logHorzLayout,onLayoutChange:()=>this.toggleLogLayout(),editing:this.state.editing,socket:this.socket,selected:this.state.selected,onHideLog:()=>{window.localStorage.setItem("App.hideLog","true"),this.setState({hideLog:!0,resizing:!0}),setTimeout(()=>this.setState({resizing:!1}),300)}},"log")]}),m.jsxs(wt,{sx:Gr.content,className:"iobVerticalSplitter",children:[m.jsx(wt,{sx:Gr.menuOpenCloseButton,onClick:()=>{window.localStorage.setItem("App.menuOpened",this.state.menuOpened?"false":"true"),this.setState({menuOpened:!this.state.menuOpened,resizing:!0}),setTimeout(()=>this.setState({resizing:!1}),300)},children:this.state.menuOpened?m.jsx(IS,{}):m.jsx(xS,{})},"closeMenu"),this.state.message?m.jsx(x.Message,{onClose:()=>this.setState({message:""}),text:this.state.message},"dialogMessage"):null,this.renderErrorDialog(),this.state.importFile?m.jsx(Gm,{onClose:(i,r)=>this.onImport(i,r)},"dialogImportFile"):null,this.state.confirm?m.jsx(x.Confirm,{onClose:i=>{this.state.confirm&&this.setState({confirm:""}),this.confirmCallback&&this.confirmCallback(i),this.confirmCallback=null},text:this.state.confirm},"dialogConfirm"):null,this.renderPasswordDialog(),s]},"main")}render(){if(!this.state.ready)return m.jsx(l_,{injectFirst:!0,children:m.jsx(c_,{theme:this.state.theme,children:m.jsx(x.Loader,{themeType:this.state.themeType})})});let s;return this.state.menuOpened?s=m.jsxs(h_,{direction:ft.Horizontal,initialSizes:this.state.splitSizes,minWidths:[270,400],onResizeFinished:(i,r)=>{this.setState({splitSizes:r}),window.localStorage.setItem("JS.splitSizes",JSON.stringify(r))},gutterClassName:this.state.themeType==="dark"?"Dark visGutter":"Light visGutter",children:[m.jsx("div",{style:Gr.mainDiv,children:m.jsx(So,{password:this.state.password,debugMode:this.state.debugMode,onDebugInstance:i=>this.setState({debugInstance:i,debugMode:!!i}),scripts:this.scripts,scriptsHash:this.state.scriptsHash,instances:this.state.instances,onRename:this.onRename.bind(this),socket:this.socket,selectId:this.state.menuSelectId,onEdit:this.onEdit.bind(this),expertMode:this.state.expertMode,themeName:this.state.themeName,onThemeChange:i=>{x.Utils.setThemeName(i);const r=x.Utils.getThemeType(i);this.setState({themeName:i,themeType:r},()=>this.toggleTheme(i))},runningInstances:this.state.runningInstances,onExpertModeChange:i=>this.onExpertModeChange(i),onDelete:this.onDelete.bind(this),onAddNew:this.onAddNew.bind(this),onEnableDisable:this.onEnableDisable.bind(this),onExport:this.onExport.bind(this),width:500,onImport:()=>this.setState({importFile:!0}),onSearch:i=>this.setState({searchText:i}),version:this.props.version,changedScripts:this.changedScripts},"sidemenu")},"menu"),this.renderMain()]}):s=this.renderMain(),m.jsx(l_,{injectFirst:!0,children:m.jsx(c_,{theme:this.state.theme,children:m.jsx("div",{style:Gr.root,children:m.jsx(kR,{socket:this.socket,children:s})})})})}}window.location.hostname==="localhost"||window.location.hostname==="[::1]"||window.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/);function Sse(){"serviceWorker"in navigator&&navigator.serviceWorker.ready.then(a=>{a.unregister()})}const Ese="9.1.1",MC={version:Ese};var Jo;(function(a){a.mouse="mouse",a.touch="touch",a.keyboard="keyboard"})(Jo||(Jo={}));class Ise{get delay(){var s;return(s=this.args.delay)!==null&&s!==void 0?s:0}get scrollAngleRanges(){return this.args.scrollAngleRanges}get getDropTargetElementsAtPoint(){return this.args.getDropTargetElementsAtPoint}get ignoreContextMenu(){var s;return(s=this.args.ignoreContextMenu)!==null&&s!==void 0?s:!1}get enableHoverOutsideTarget(){var s;return(s=this.args.enableHoverOutsideTarget)!==null&&s!==void 0?s:!1}get enableKeyboardEvents(){var s;return(s=this.args.enableKeyboardEvents)!==null&&s!==void 0?s:!1}get enableMouseEvents(){var s;return(s=this.args.enableMouseEvents)!==null&&s!==void 0?s:!1}get enableTouchEvents(){var s;return(s=this.args.enableTouchEvents)!==null&&s!==void 0?s:!0}get touchSlop(){return this.args.touchSlop||0}get delayTouchStart(){var s,i,r,l;return(l=(r=(s=this.args)===null||s===void 0?void 0:s.delayTouchStart)!==null&&r!==void 0?r:(i=this.args)===null||i===void 0?void 0:i.delay)!==null&&l!==void 0?l:0}get delayMouseStart(){var s,i,r,l;return(l=(r=(s=this.args)===null||s===void 0?void 0:s.delayMouseStart)!==null&&r!==void 0?r:(i=this.args)===null||i===void 0?void 0:i.delay)!==null&&l!==void 0?l:0}get window(){if(this.context&&this.context.window)return this.context.window;if(typeof window<"u")return window}get document(){var s;if(!((s=this.context)===null||s===void 0)&&s.document)return this.context.document;if(this.window)return this.window.document}get rootElement(){var s;return((s=this.args)===null||s===void 0?void 0:s.rootElement)||this.document}constructor(s,i){this.args=s,this.context=i}}function xse(a,s,i,r){return Math.sqrt(Math.pow(Math.abs(i-a),2)+Math.pow(Math.abs(r-s),2))}function Dse(a,s,i,r,l){if(!l)return!1;const c=Math.atan2(r-s,i-a)*180/Math.PI+180;for(let d=0;d=h.start)&&(h.end==null||c<=h.end))return!0}return!1}const Ase={Left:1},Ose={Left:0};function xg(a){return a.button===void 0||a.button===Ose.Left}function Rse(a){return a.buttons===void 0||(a.buttons&Ase.Left)===0}function NC(a){return!!a.targetTouches}const Mse=1;function Nse(a){const s=a.nodeType===Mse?a:a.parentElement;if(!s)return;const{top:i,left:r}=s.getBoundingClientRect();return{x:r,y:i}}function Lse(a,s){if(a.targetTouches.length===1)return Kc(a.targetTouches[0]);if(s&&a.touches.length===1&&a.touches[0].target===s.target)return Kc(a.touches[0])}function Kc(a,s){return NC(a)?Lse(a,s):{x:a.clientX,y:a.clientY}}const Cw=(()=>{let a=!1;try{addEventListener("test",()=>{},Object.defineProperty({},"passive",{get(){return a=!0,!0}}))}catch{}return a})(),Vr={[Jo.mouse]:{start:"mousedown",move:"mousemove",end:"mouseup",contextmenu:"contextmenu"},[Jo.touch]:{start:"touchstart",move:"touchmove",end:"touchend"},[Jo.keyboard]:{keydown:"keydown"}};class Qr{profile(){var s;return{sourceNodes:this.sourceNodes.size,sourcePreviewNodes:this.sourcePreviewNodes.size,sourcePreviewNodeOptions:this.sourcePreviewNodeOptions.size,targetNodes:this.targetNodes.size,dragOverTargetIds:((s=this.dragOverTargetIds)===null||s===void 0?void 0:s.length)||0}}get document(){return this.options.document}setup(){const s=this.options.rootElement;s&&(Ve(!Qr.isSetUp,"Cannot have two Touch backends at the same time."),Qr.isSetUp=!0,this.addEventListener(s,"start",this.getTopMoveStartHandler()),this.addEventListener(s,"start",this.handleTopMoveStartCapture,!0),this.addEventListener(s,"move",this.handleTopMove),this.addEventListener(s,"move",this.handleTopMoveCapture,!0),this.addEventListener(s,"end",this.handleTopMoveEndCapture,!0),this.options.enableMouseEvents&&!this.options.ignoreContextMenu&&this.addEventListener(s,"contextmenu",this.handleTopMoveEndCapture),this.options.enableKeyboardEvents&&this.addEventListener(s,"keydown",this.handleCancelOnEscape,!0))}teardown(){const s=this.options.rootElement;s&&(Qr.isSetUp=!1,this._mouseClientOffset={},this.removeEventListener(s,"start",this.handleTopMoveStartCapture,!0),this.removeEventListener(s,"start",this.handleTopMoveStart),this.removeEventListener(s,"move",this.handleTopMoveCapture,!0),this.removeEventListener(s,"move",this.handleTopMove),this.removeEventListener(s,"end",this.handleTopMoveEndCapture,!0),this.options.enableMouseEvents&&!this.options.ignoreContextMenu&&this.removeEventListener(s,"contextmenu",this.handleTopMoveEndCapture),this.options.enableKeyboardEvents&&this.removeEventListener(s,"keydown",this.handleCancelOnEscape,!0),this.uninstallSourceNodeRemovalObserver())}addEventListener(s,i,r,l=!1){const c=Cw?{capture:l,passive:!1}:l;this.listenerTypes.forEach(function(d){const h=Vr[d][i];h&&s.addEventListener(h,r,c)})}removeEventListener(s,i,r,l=!1){const c=Cw?{capture:l,passive:!1}:l;this.listenerTypes.forEach(function(d){const h=Vr[d][i];h&&s.removeEventListener(h,r,c)})}connectDragSource(s,i){const r=this.handleMoveStart.bind(this,s);return this.sourceNodes.set(s,i),this.addEventListener(i,"start",r),()=>{this.sourceNodes.delete(s),this.removeEventListener(i,"start",r)}}connectDragPreview(s,i,r){return this.sourcePreviewNodeOptions.set(s,r),this.sourcePreviewNodes.set(s,i),()=>{this.sourcePreviewNodes.delete(s),this.sourcePreviewNodeOptions.delete(s)}}connectDropTarget(s,i){const r=this.options.rootElement;if(!this.document||!r)return()=>{};const l=c=>{if(!this.document||!r||!this.monitor.isDragging())return;let d;switch(c.type){case Vr.mouse.move:d={x:c.clientX,y:c.clientY};break;case Vr.touch.move:var h,p;d={x:((h=c.touches[0])===null||h===void 0?void 0:h.clientX)||0,y:((p=c.touches[0])===null||p===void 0?void 0:p.clientY)||0};break}const f=d!=null?this.document.elementFromPoint(d.x,d.y):void 0,b=f&&i.contains(f);if(f===i||b)return this.handleMove(c,s)};return this.addEventListener(this.document.body,"move",l),this.targetNodes.set(s,i),()=>{this.document&&(this.targetNodes.delete(s),this.removeEventListener(this.document.body,"move",l))}}getTopMoveStartHandler(){return!this.options.delayTouchStart&&!this.options.delayMouseStart?this.handleTopMoveStart:this.handleTopMoveStartDelay}installSourceNodeRemovalObserver(s){this.uninstallSourceNodeRemovalObserver(),this.draggedSourceNode=s,this.draggedSourceNodeRemovalObserver=new MutationObserver(()=>{s&&!s.parentElement&&(this.resurrectSourceNode(),this.uninstallSourceNodeRemovalObserver())}),!(!s||!s.parentElement)&&this.draggedSourceNodeRemovalObserver.observe(s.parentElement,{childList:!0})}resurrectSourceNode(){this.document&&this.draggedSourceNode&&(this.draggedSourceNode.style.display="none",this.draggedSourceNode.removeAttribute("data-reactid"),this.document.body.appendChild(this.draggedSourceNode))}uninstallSourceNodeRemovalObserver(){this.draggedSourceNodeRemovalObserver&&this.draggedSourceNodeRemovalObserver.disconnect(),this.draggedSourceNodeRemovalObserver=void 0,this.draggedSourceNode=void 0}constructor(s,i,r){this.getSourceClientOffset=l=>{const c=this.sourceNodes.get(l);return c&&Nse(c)},this.handleTopMoveStartCapture=l=>{xg(l)&&(this.moveStartSourceIds=[])},this.handleMoveStart=l=>{Array.isArray(this.moveStartSourceIds)&&this.moveStartSourceIds.unshift(l)},this.handleTopMoveStart=l=>{if(!xg(l))return;const c=Kc(l);c&&(NC(l)&&(this.lastTargetTouchFallback=l.targetTouches[0]),this._mouseClientOffset=c),this.waitingForDelay=!1},this.handleTopMoveStartDelay=l=>{if(!xg(l))return;const c=l.type===Vr.touch.start?this.options.delayTouchStart:this.options.delayMouseStart;this.timeout=setTimeout(this.handleTopMoveStart.bind(this,l),c),this.waitingForDelay=!0},this.handleTopMoveCapture=()=>{this.dragOverTargetIds=[]},this.handleMove=(l,c)=>{this.dragOverTargetIds&&this.dragOverTargetIds.unshift(c)},this.handleTopMove=l=>{if(this.timeout&&clearTimeout(this.timeout),!this.document||this.waitingForDelay)return;const{moveStartSourceIds:c,dragOverTargetIds:d}=this,h=this.options.enableHoverOutsideTarget,p=Kc(l,this.lastTargetTouchFallback);if(!p)return;if(this._isScrolling||!this.monitor.isDragging()&&Dse(this._mouseClientOffset.x||0,this._mouseClientOffset.y||0,p.x,p.y,this.options.scrollAngleRanges)){this._isScrolling=!0;return}if(!this.monitor.isDragging()&&this._mouseClientOffset.hasOwnProperty("x")&&c&&xse(this._mouseClientOffset.x||0,this._mouseClientOffset.y||0,p.x,p.y)>(this.options.touchSlop?this.options.touchSlop:0)&&(this.moveStartSourceIds=void 0,this.actions.beginDrag(c,{clientOffset:this._mouseClientOffset,getSourceClientOffset:this.getSourceClientOffset,publishSource:!1})),!this.monitor.isDragging())return;const f=this.sourceNodes.get(this.monitor.getSourceId());this.installSourceNodeRemovalObserver(f),this.actions.publishDragSource(),l.cancelable&&l.preventDefault();const b=(d||[]).map(_=>this.targetNodes.get(_)).filter(_=>!!_),y=this.options.getDropTargetElementsAtPoint?this.options.getDropTargetElementsAtPoint(p.x,p.y,b):this.document.elementsFromPoint(p.x,p.y),w=[];for(const _ in y){if(!y.hasOwnProperty(_))continue;let $=y[_];for($!=null&&w.push($);$;)$=$.parentElement,$&&w.indexOf($)===-1&&w.push($)}const v=w.filter(_=>b.indexOf(_)>-1).map(_=>this._getDropTargetId(_)).filter(_=>!!_).filter((_,$,T)=>T.indexOf(_)===$);if(h)for(const _ in this.targetNodes){const $=this.targetNodes.get(_);if(f&&$&&$.contains(f)&&v.indexOf(_)===-1){v.unshift(_);break}}v.reverse(),this.actions.hover(v,{clientOffset:p})},this._getDropTargetId=l=>{const c=this.targetNodes.keys();let d=c.next();for(;d.done===!1;){const h=d.value;if(l===this.targetNodes.get(h))return h;d=c.next()}},this.handleTopMoveEndCapture=l=>{if(this._isScrolling=!1,this.lastTargetTouchFallback=void 0,!!Rse(l)){if(!this.monitor.isDragging()||this.monitor.didDrop()){this.moveStartSourceIds=void 0;return}l.cancelable&&l.preventDefault(),this._mouseClientOffset={},this.uninstallSourceNodeRemovalObserver(),this.actions.drop(),this.actions.endDrag()}},this.handleCancelOnEscape=l=>{l.key==="Escape"&&this.monitor.isDragging()&&(this._mouseClientOffset={},this.uninstallSourceNodeRemovalObserver(),this.actions.endDrag())},this.options=new Ise(r,i),this.actions=s.getActions(),this.monitor=s.getMonitor(),this.sourceNodes=new Map,this.sourcePreviewNodes=new Map,this.sourcePreviewNodeOptions=new Map,this.targetNodes=new Map,this.listenerTypes=[],this._mouseClientOffset={},this._isScrolling=!1,this.options.enableMouseEvents&&this.listenerTypes.push(Jo.mouse),this.options.enableTouchEvents&&this.listenerTypes.push(Jo.touch),this.options.enableKeyboardEvents&&this.listenerTypes.push(Jo.keyboard)}}const Pse=function(s,i={},r={}){return new Qr(s,i,r)};window.GenericBlock=at;window.adapterName="javascript";window.sentryDSN="https://504499a725eb4898930d3b9e9da95740@sentry.iobroker.net/56";console.log(`iobroker.${window.adapterName}@${MC.version}`);const Bse=window.innerWidth<600,Tw=document.getElementById("root");Tw&&Fw(Tw).render(m.jsx(tk,{backend:Bse?Pse:pk,children:m.jsx(Tse,{version:MC.version})}));Sse();const mc=window.loadDynamicScript;mc&&mc(window.location.port==="3000"?`${window.location.protocol}//${window.location.hostname}:8081/lib/js/socket.io.js`:"./../../lib/js/socket.io.js",()=>mc("vs/loader.js",()=>mc("vs/configure.js",()=>typeof window.socketLoadedHandler=="function"&&window.socketLoadedHandler())));export{wR as C,aO as D,at as G,gk as I,$w as M,Ms as S,bI as a,PI as b,GI as c,Ei as d,xne as e,Ym as f,ou as g,ux as h,Dne as j,h_ as m,zn as u,ft as z}; diff --git a/admin/assets/index-ns4mNOlq.js b/admin/assets/index-ns4mNOlq.js deleted file mode 100644 index d39ef0dfa..000000000 --- a/admin/assets/index-ns4mNOlq.js +++ /dev/null @@ -1,16 +0,0 @@ -import{j as M}from"./createSvgIcon-DPvF8xqu.js";import{a as ft}from"./iobroker_javascript__loadShare__react__loadShare__.mjs-CTZOFJS2.js";import{m as Rt,z as Bt,g as Ut}from"./index-bny2V8S2.js";import{z as Ze,o as Te,v as Nt,w as Mt,s as Lt,u as Vt,r as zt,_ as Ht,a as Gt,C as Pt,D as _t,F as Yt,G as wt,H as Qt}from"./iobroker_javascript__loadShare___mf_0_mui_mf_1_material__loadShare__.mjs-QWG5Arqe.js";import{M as Zt,k as Xt,l as ea,O as Tt,S as ta,J as aa,n as ra,t as na,v as sa,u as oa,T as ia,U as la,V as ca,W as ua}from"./index-C49cpVll.js";import{_ as we}from"./iobroker_javascript__loadShare___mf_0_iobroker_mf_1_adapter_mf_2_react_mf_2_v5__loadShare__.mjs-DkBjPSMw.js";import pa from"./ScriptEditorVanillaMonaco-DSYvOslZ.js";import{r as fa}from"./iobroker_javascript__loadShare__react__loadShare__.mjs_commonjs-proxy-CE9lvhW8.js";function da(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}import"./iobroker_javascript__loadShare__prop_mf_2_types__loadShare__.mjs-BCtSFofY.js";import"./virtual_mf-REMOTE_ENTRY_ID_iobroker_javascript__remoteEntry_js-s4ROfmWJ.js";import"./preload-helper-BDBacUwf.js";import"./iobroker_javascript__loadShare__react_mf_2_dom__loadShare__.mjs_commonjs-proxy-RQRRZMX5.js";import"./iobroker_javascript__loadShare__react_mf_2_dom__loadShare__.mjs-DeVAS-oa.js";import"./inheritsLoose-B0Ba5G9z.js";const ba={editorDiv:{height:"100%",width:"100%",overflow:"hidden",position:"relative"}};class ha extends ft.Component{constructor(v){super(v),this.state={lines:(this.props.script||"").split(/\r\n|\n/)}}render(){return M.jsx("div",{style:ba.editorDiv,children:M.jsx(pa,{triggerPrettier:1,name:this.props.scriptName,adapterName:this.props.adapterName,readOnly:!0,code:this.props.script||"",isDark:this.props.themeType==="dark",socket:this.props.socket,runningInstances:this.props.runningInstances,language:"javascript",breakpoints:this.props.breakpoints,location:this.props.paused?this.props.location:null,onToggleBreakpoint:v=>this.props.onToggleBreakpoint(v)},"scriptEditor2")},"scriptEditorDiv2")}}const Dt=34,Ke={logBox:{width:"100%",height:"100%",position:"relative",overflow:"hidden"},logBoxInner:Z=>({display:"inline-block",color:Z.palette.mode==="dark"?"white":"black",width:`calc(100% - ${Dt}px)`,height:"100%",overflow:"auto",position:"relative",verticalAlign:"top"}),info:Z=>({background:Z.palette.mode==="dark"?"darkgrey":"lightgrey",color:(Z.palette.mode==="dark","black")}),error:Z=>({background:"#FF0000",color:Z.palette.mode==="dark"?"black":"white"}),warn:Z=>({background:"#FF8000",color:Z.palette.mode==="dark"?"black":"white"}),debug:Z=>({background:"gray",opacity:.8,color:Z.palette.mode==="dark"?"black":"white"}),silly:Z=>({background:"gray",opacity:.6,color:Z.palette.mode==="dark"?"black":"white"}),table:{fontFamily:"monospace",width:"100%"},toolbox:{width:Dt,height:"100%",boxShadow:"2px 0px 4px -1px rgba(0, 0, 0, 0.2), 4px 0px 5px 0px rgba(0, 0, 0, 0.14), 1px 0px 10px 0px rgba(0, 0, 0, 0.12)",display:"inline-block",verticalAlign:"top",overflow:"hidden"},trTime:{width:90},trSeverity:{width:40,fontWeight:"bold"},iconButtons:{width:32,height:32,padding:4}};function ma(Z){let v,g=Z.getHours();return g<10&&(g=`0${g.toString()}`),v=`${g}:`,g=Z.getMinutes(),g<10&&(g=`0${g.toString()}`),v+=`${g}:`,g=Z.getSeconds(),g<10&&(g=`0${g.toString()}`),v+=`${g}.`,g=Z.getMilliseconds(),g<10?g=`00${g.toString()}`:g<100&&(g=`0${g.toString()}`),v+=g,v}class Ct extends ft.Component{messagesEnd;constructor(v){super(v),this.state={goBottom:!0},this.messagesEnd=ft.createRef()}static generateLine(v){return M.jsxs(Ze,{component:"tr",sx:Ke[v.severity],children:[M.jsx("td",{style:Ke.trTime,children:ma(new Date(v.ts))}),M.jsx("td",{style:Ke.trSeverity,children:v.severity}),M.jsx("td",{children:v.text})]},`tr_${v.ts}_${v.text.substring(v.text.length-10,v.text.length)}`)}renderLogList(v){return v!=null&&v.length?M.jsxs(Ze,{sx:Ke.logBoxInner,children:[M.jsx("table",{style:Ke.table,children:M.jsx("tbody",{children:v.map(g=>Ct.generateLine(g))})},"logTable"),M.jsx("div",{ref:this.messagesEnd,style:{float:"left",clear:"both"}},"logScrollPoint")]},"logList"):M.jsx(Ze,{sx:Ke.logBoxInner,style:{paddingLeft:10},children:we.I18n.t("Log outputs")},"logList")}onCopy(){we.Utils.copyToClipboard(this.props.console.join(` -`))}scrollToBottom(){var v,g;(g=(v=this.messagesEnd)==null?void 0:v.current)==null||g.scrollIntoView({behavior:"smooth"})}componentDidUpdate(){this.state.goBottom&&this.scrollToBottom()}render(){const v=this.props.console;return M.jsxs("div",{style:Ke.logBox,children:[M.jsxs("div",{style:Ke.toolbox,children:[M.jsx(Te,{style:Ke.iconButtons,onClick:()=>this.setState({goBottom:!this.state.goBottom}),color:this.state.goBottom?"secondary":void 0,size:"medium",children:M.jsx(Zt,{})}),v!=null&&v.length?M.jsx(Te,{style:Ke.iconButtons,onClick:()=>this.props.onClearAllLogs(),size:"medium",children:M.jsx(Xt,{})}):null,v!=null&&v.length?M.jsx(Te,{style:Ke.iconButtons,onClick:()=>this.onCopy(),size:"medium",children:M.jsx(ea,{})}):null]},"toolbox"),this.renderLogList(v)]})}}var It={exports:{}},va=It.exports;(function(Z,v){(function(g,a){Z.exports=a(fa)})(va,(function(g){return(function(a){var t={};function e(s){if(t[s])return t[s].exports;var c=t[s]={i:s,l:!1,exports:{}};return a[s].call(c.exports,c,c.exports,e),c.l=!0,c.exports}return e.m=a,e.c=t,e.d=function(s,c,d){e.o(s,c)||Object.defineProperty(s,c,{enumerable:!0,get:d})},e.r=function(s){typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(s,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(s,"__esModule",{value:!0})},e.t=function(s,c){if(1&c&&(s=e(s)),8&c||4&c&&typeof s=="object"&&s&&s.__esModule)return s;var d=Object.create(null);if(e.r(d),Object.defineProperty(d,"default",{enumerable:!0,value:s}),2&c&&typeof s!="string")for(var p in s)e.d(d,p,function(f){return s[f]}.bind(null,p));return d},e.n=function(s){var c=s&&s.__esModule?function(){return s.default}:function(){return s};return e.d(c,"a",c),c},e.o=function(s,c){return Object.prototype.hasOwnProperty.call(s,c)},e.p="",e(e.s=48)})([function(a,t){a.exports=g},function(a,t){var e=a.exports={version:"2.6.12"};typeof __e=="number"&&(__e=e)},function(a,t,e){var s=e(26)("wks"),c=e(17),d=e(3).Symbol,p=typeof d=="function";(a.exports=function(f){return s[f]||(s[f]=p&&d[f]||(p?d:c)("Symbol."+f))}).store=s},function(a,t){var e=a.exports=typeof window<"u"&&window.Math==Math?window:typeof self<"u"&&self.Math==Math?self:Function("return this")();typeof __g=="number"&&(__g=e)},function(a,t,e){a.exports=!e(8)((function(){return Object.defineProperty({},"a",{get:function(){return 7}}).a!=7}))},function(a,t){var e={}.hasOwnProperty;a.exports=function(s,c){return e.call(s,c)}},function(a,t,e){var s=e(7),c=e(16);a.exports=e(4)?function(d,p,f){return s.f(d,p,c(1,f))}:function(d,p,f){return d[p]=f,d}},function(a,t,e){var s=e(10),c=e(35),d=e(23),p=Object.defineProperty;t.f=e(4)?Object.defineProperty:function(f,h,S){if(s(f),h=d(h,!0),s(S),c)try{return p(f,h,S)}catch{}if("get"in S||"set"in S)throw TypeError("Accessors not supported!");return"value"in S&&(f[h]=S.value),f}},function(a,t){a.exports=function(e){try{return!!e()}catch{return!0}}},function(a,t,e){var s=e(40),c=e(22);a.exports=function(d){return s(c(d))}},function(a,t,e){var s=e(11);a.exports=function(c){if(!s(c))throw TypeError(c+" is not an object!");return c}},function(a,t){a.exports=function(e){return typeof e=="object"?e!==null:typeof e=="function"}},function(a,t){a.exports={}},function(a,t,e){var s=e(39),c=e(27);a.exports=Object.keys||function(d){return s(d,c)}},function(a,t){a.exports=!0},function(a,t,e){var s=e(3),c=e(1),d=e(53),p=e(6),f=e(5),h=function(S,b,w){var I,R,H,L=S&h.F,X=S&h.G,r=S&h.S,D=S&h.P,V=S&h.B,z=S&h.W,q=X?c:c[b]||(c[b]={}),k=q.prototype,A=X?s:r?s[b]:(s[b]||{}).prototype;for(I in X&&(w=b),w)(R=!L&&A&&A[I]!==void 0)&&f(q,I)||(H=R?A[I]:w[I],q[I]=X&&typeof A[I]!="function"?w[I]:V&&R?d(H,s):z&&A[I]==H?(function(T){var W=function(E,ee,J){if(this instanceof T){switch(arguments.length){case 0:return new T;case 1:return new T(E);case 2:return new T(E,ee)}return new T(E,ee,J)}return T.apply(this,arguments)};return W.prototype=T.prototype,W})(H):D&&typeof H=="function"?d(Function.call,H):H,D&&((q.virtual||(q.virtual={}))[I]=H,S&h.R&&k&&!k[I]&&p(k,I,H)))};h.F=1,h.G=2,h.S=4,h.P=8,h.B=16,h.W=32,h.U=64,h.R=128,a.exports=h},function(a,t){a.exports=function(e,s){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:s}}},function(a,t){var e=0,s=Math.random();a.exports=function(c){return"Symbol(".concat(c===void 0?"":c,")_",(++e+s).toString(36))}},function(a,t,e){var s=e(22);a.exports=function(c){return Object(s(c))}},function(a,t){t.f={}.propertyIsEnumerable},function(a,t,e){var s=e(52)(!0);e(34)(String,"String",(function(c){this._t=String(c),this._i=0}),(function(){var c,d=this._t,p=this._i;return p>=d.length?{value:void 0,done:!0}:(c=s(d,p),this._i+=c.length,{value:c,done:!1})}))},function(a,t){var e=Math.ceil,s=Math.floor;a.exports=function(c){return isNaN(c=+c)?0:(c>0?s:e)(c)}},function(a,t){a.exports=function(e){if(e==null)throw TypeError("Can't call method on "+e);return e}},function(a,t,e){var s=e(11);a.exports=function(c,d){if(!s(c))return c;var p,f;if(d&&typeof(p=c.toString)=="function"&&!s(f=p.call(c))||typeof(p=c.valueOf)=="function"&&!s(f=p.call(c))||!d&&typeof(p=c.toString)=="function"&&!s(f=p.call(c)))return f;throw TypeError("Can't convert object to primitive value")}},function(a,t){var e={}.toString;a.exports=function(s){return e.call(s).slice(8,-1)}},function(a,t,e){var s=e(26)("keys"),c=e(17);a.exports=function(d){return s[d]||(s[d]=c(d))}},function(a,t,e){var s=e(1),c=e(3),d=c["__core-js_shared__"]||(c["__core-js_shared__"]={});(a.exports=function(p,f){return d[p]||(d[p]=f!==void 0?f:{})})("versions",[]).push({version:s.version,mode:e(14)?"pure":"global",copyright:"© 2020 Denis Pushkarev (zloirock.ru)"})},function(a,t){a.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(a,t,e){var s=e(7).f,c=e(5),d=e(2)("toStringTag");a.exports=function(p,f,h){p&&!c(p=h?p:p.prototype,d)&&s(p,d,{configurable:!0,value:f})}},function(a,t,e){e(62);for(var s=e(3),c=e(6),d=e(12),p=e(2)("toStringTag"),f="CSSRuleList,CSSStyleDeclaration,CSSValueList,ClientRectList,DOMRectList,DOMStringList,DOMTokenList,DataTransferItemList,FileList,HTMLAllCollection,HTMLCollection,HTMLFormElement,HTMLSelectElement,MediaList,MimeTypeArray,NamedNodeMap,NodeList,PaintRequestList,Plugin,PluginArray,SVGLengthList,SVGNumberList,SVGPathSegList,SVGPointList,SVGStringList,SVGTransformList,SourceBufferList,StyleSheetList,TextTrackCueList,TextTrackList,TouchList".split(","),h=0;hdocument.F=Object<\/script>"),S.close(),h=S.F;w--;)delete h.prototype[d[w]];return h()};a.exports=Object.create||function(S,b){var w;return S!==null?(f.prototype=s(S),w=new f,f.prototype=null,w[p]=S):w=h(),b===void 0?w:c(w,b)}},function(a,t,e){var s=e(5),c=e(9),d=e(57)(!1),p=e(25)("IE_PROTO");a.exports=function(f,h){var S,b=c(f),w=0,I=[];for(S in b)S!=p&&s(b,S)&&I.push(S);for(;h.length>w;)s(b,S=h[w++])&&(~d(I,S)||I.push(S));return I}},function(a,t,e){var s=e(24);a.exports=Object("z").propertyIsEnumerable(0)?Object:function(c){return s(c)=="String"?c.split(""):Object(c)}},function(a,t,e){var s=e(39),c=e(27).concat("length","prototype");t.f=Object.getOwnPropertyNames||function(d){return s(d,c)}},function(a,t,e){var s=e(24),c=e(2)("toStringTag"),d=s((function(){return arguments})())=="Arguments";a.exports=function(p){var f,h,S;return p===void 0?"Undefined":p===null?"Null":typeof(h=(function(b,w){try{return b[w]}catch{}})(f=Object(p),c))=="string"?h:d?s(f):(S=s(f))=="Object"&&typeof f.callee=="function"?"Arguments":S}},function(a,t){var e;e=(function(){return this})();try{e=e||new Function("return this")()}catch{typeof window=="object"&&(e=window)}a.exports=e},function(a,t){var e=/-?\d+(\.\d+)?%?/g;a.exports=function(s){return s.match(e)}},function(a,t,e){Object.defineProperty(t,"__esModule",{value:!0}),t.getBase16Theme=t.createStyling=t.invertTheme=void 0;var s=R(e(49)),c=R(e(76)),d=R(e(81)),p=R(e(89)),f=R(e(93)),h=(function(k){if(k&&k.__esModule)return k;var A={};if(k!=null)for(var T in k)Object.prototype.hasOwnProperty.call(k,T)&&(A[T]=k[T]);return A.default=k,A})(e(94)),S=R(e(132)),b=R(e(133)),w=R(e(138)),I=e(139);function R(k){return k&&k.__esModule?k:{default:k}}var H=h.default,L=(0,p.default)(H),X=(0,w.default)(b.default,I.rgb2yuv,(function(k){var A,T=(0,d.default)(k,3),W=T[0],E=T[1],ee=T[2];return[(A=W,A<.25?1:A<.5?.9-A:1.1-A),E,ee]}),I.yuv2rgb,S.default),r=function(k){return function(A){return{className:[A.className,k.className].filter(Boolean).join(" "),style:(0,c.default)({},A.style||{},k.style||{})}}},D=function(k,A){var T=(0,p.default)(A);for(var W in k)T.indexOf(W)===-1&&T.push(W);return T.reduce((function(E,ee){return E[ee]=(function(J,C){if(J===void 0)return C;if(C===void 0)return J;var Y=J===void 0?"undefined":(0,s.default)(J),be=C===void 0?"undefined":(0,s.default)(C);switch(Y){case"string":switch(be){case"string":return[C,J].filter(Boolean).join(" ");case"object":return r({className:J,style:C});case"function":return function(ce){for(var U=arguments.length,le=Array(U>1?U-1:0),Q=1;Q1?U-1:0),Q=1;Q1?U-1:0),Q=1;Q1?U-1:0),Q=1;Q1?U-1:0),Q=1;Q2?T-2:0),E=2;E3?A-3:0),W=3;W1&&arguments[1]!==void 0?arguments[1]:{},ee=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},J=E.defaultBase16,C=J===void 0?H:J,Y=E.base16Themes,be=Y===void 0?null:Y,ce=q(ee,be);ce&&(ee=(0,c.default)({},ce,ee));var U=L.reduce((function(ve,Ne){return ve[Ne]=ee[Ne]||C[Ne],ve}),{}),le=(0,p.default)(ee).reduce((function(ve,Ne){return L.indexOf(Ne)===-1&&(ve[Ne]=ee[Ne]),ve}),{}),Q=k(U),he=D(le,Q);return(0,f.default)(V,2).apply(void 0,[he].concat(T))}),3),t.getBase16Theme=function(k,A){if(k&&k.extend&&(k=k.extend),typeof k=="string"){var T=k.split(":"),W=(0,d.default)(T,2),E=W[0],ee=W[1];k=(A||{})[E]||h[E],ee==="inverted"&&(k=z(k))}return k&&k.hasOwnProperty("base00")?k:void 0})},function(a,t,e){var s,c=typeof Reflect=="object"?Reflect:null,d=c&&typeof c.apply=="function"?c.apply:function(r,D,V){return Function.prototype.apply.call(r,D,V)};s=c&&typeof c.ownKeys=="function"?c.ownKeys:Object.getOwnPropertySymbols?function(r){return Object.getOwnPropertyNames(r).concat(Object.getOwnPropertySymbols(r))}:function(r){return Object.getOwnPropertyNames(r)};var p=Number.isNaN||function(r){return r!=r};function f(){f.init.call(this)}a.exports=f,a.exports.once=function(r,D){return new Promise((function(V,z){function q(){k!==void 0&&r.removeListener("error",k),V([].slice.call(arguments))}var k;D!=="error"&&(k=function(A){r.removeListener(D,q),z(A)},r.once("error",k)),r.once(D,q)}))},f.EventEmitter=f,f.prototype._events=void 0,f.prototype._eventsCount=0,f.prototype._maxListeners=void 0;var h=10;function S(r){if(typeof r!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof r)}function b(r){return r._maxListeners===void 0?f.defaultMaxListeners:r._maxListeners}function w(r,D,V,z){var q,k,A,T;if(S(V),(k=r._events)===void 0?(k=r._events=Object.create(null),r._eventsCount=0):(k.newListener!==void 0&&(r.emit("newListener",D,V.listener?V.listener:V),k=r._events),A=k[D]),A===void 0)A=k[D]=V,++r._eventsCount;else if(typeof A=="function"?A=k[D]=z?[V,A]:[A,V]:z?A.unshift(V):A.push(V),(q=b(r))>0&&A.length>q&&!A.warned){A.warned=!0;var W=new Error("Possible EventEmitter memory leak detected. "+A.length+" "+String(D)+" listeners added. Use emitter.setMaxListeners() to increase limit");W.name="MaxListenersExceededWarning",W.emitter=r,W.type=D,W.count=A.length,T=W,console&&console.warn&&console.warn(T)}return r}function I(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function R(r,D,V){var z={fired:!1,wrapFn:void 0,target:r,type:D,listener:V},q=I.bind(z);return q.listener=V,z.wrapFn=q,q}function H(r,D,V){var z=r._events;if(z===void 0)return[];var q=z[D];return q===void 0?[]:typeof q=="function"?V?[q.listener||q]:[q]:V?(function(k){for(var A=new Array(k.length),T=0;T0&&(k=D[0]),k instanceof Error)throw k;var A=new Error("Unhandled error."+(k?" ("+k.message+")":""));throw A.context=k,A}var T=q[r];if(T===void 0)return!1;if(typeof T=="function")d(T,this,D);else{var W=T.length,E=X(T,W);for(V=0;V=0;k--)if(V[k]===D||V[k].listener===D){A=V[k].listener,q=k;break}if(q<0)return this;q===0?V.shift():(function(T,W){for(;W+1=0;z--)this.removeListener(r,D[z]);return this},f.prototype.listeners=function(r){return H(this,r,!0)},f.prototype.rawListeners=function(r){return H(this,r,!1)},f.listenerCount=function(r,D){return typeof r.listenerCount=="function"?r.listenerCount(D):L.call(r,D)},f.prototype.listenerCount=L,f.prototype.eventNames=function(){return this._eventsCount>0?s(this._events):[]}},function(a,t,e){a.exports.Dispatcher=e(140)},function(a,t,e){a.exports=e(142)},function(a,t,e){t.__esModule=!0;var s=p(e(50)),c=p(e(65)),d=typeof c.default=="function"&&typeof s.default=="symbol"?function(f){return typeof f}:function(f){return f&&typeof c.default=="function"&&f.constructor===c.default&&f!==c.default.prototype?"symbol":typeof f};function p(f){return f&&f.__esModule?f:{default:f}}t.default=typeof c.default=="function"&&d(s.default)==="symbol"?function(f){return f===void 0?"undefined":d(f)}:function(f){return f&&typeof c.default=="function"&&f.constructor===c.default&&f!==c.default.prototype?"symbol":f===void 0?"undefined":d(f)}},function(a,t,e){a.exports={default:e(51),__esModule:!0}},function(a,t,e){e(20),e(29),a.exports=e(30).f("iterator")},function(a,t,e){var s=e(21),c=e(22);a.exports=function(d){return function(p,f){var h,S,b=String(c(p)),w=s(f),I=b.length;return w<0||w>=I?d?"":void 0:(h=b.charCodeAt(w))<55296||h>56319||w+1===I||(S=b.charCodeAt(w+1))<56320||S>57343?d?b.charAt(w):h:d?b.slice(w,w+2):S-56320+(h-55296<<10)+65536}}},function(a,t,e){var s=e(54);a.exports=function(c,d,p){if(s(c),d===void 0)return c;switch(p){case 1:return function(f){return c.call(d,f)};case 2:return function(f,h){return c.call(d,f,h)};case 3:return function(f,h,S){return c.call(d,f,h,S)}}return function(){return c.apply(d,arguments)}}},function(a,t){a.exports=function(e){if(typeof e!="function")throw TypeError(e+" is not a function!");return e}},function(a,t,e){var s=e(38),c=e(16),d=e(28),p={};e(6)(p,e(2)("iterator"),(function(){return this})),a.exports=function(f,h,S){f.prototype=s(p,{next:c(1,S)}),d(f,h+" Iterator")}},function(a,t,e){var s=e(7),c=e(10),d=e(13);a.exports=e(4)?Object.defineProperties:function(p,f){c(p);for(var h,S=d(f),b=S.length,w=0;b>w;)s.f(p,h=S[w++],f[h]);return p}},function(a,t,e){var s=e(9),c=e(58),d=e(59);a.exports=function(p){return function(f,h,S){var b,w=s(f),I=c(w.length),R=d(S,I);if(p&&h!=h){for(;I>R;)if((b=w[R++])!=b)return!0}else for(;I>R;R++)if((p||R in w)&&w[R]===h)return p||R||0;return!p&&-1}}},function(a,t,e){var s=e(21),c=Math.min;a.exports=function(d){return d>0?c(s(d),9007199254740991):0}},function(a,t,e){var s=e(21),c=Math.max,d=Math.min;a.exports=function(p,f){return(p=s(p))<0?c(p+f,0):d(p,f)}},function(a,t,e){var s=e(3).document;a.exports=s&&s.documentElement},function(a,t,e){var s=e(5),c=e(18),d=e(25)("IE_PROTO"),p=Object.prototype;a.exports=Object.getPrototypeOf||function(f){return f=c(f),s(f,d)?f[d]:typeof f.constructor=="function"&&f instanceof f.constructor?f.constructor.prototype:f instanceof Object?p:null}},function(a,t,e){var s=e(63),c=e(64),d=e(12),p=e(9);a.exports=e(34)(Array,"Array",(function(f,h){this._t=p(f),this._i=0,this._k=h}),(function(){var f=this._t,h=this._k,S=this._i++;return!f||S>=f.length?(this._t=void 0,c(1)):c(0,h=="keys"?S:h=="values"?f[S]:[S,f[S]])}),"values"),d.Arguments=d.Array,s("keys"),s("values"),s("entries")},function(a,t){a.exports=function(){}},function(a,t){a.exports=function(e,s){return{value:s,done:!!e}}},function(a,t,e){a.exports={default:e(66),__esModule:!0}},function(a,t,e){e(67),e(73),e(74),e(75),a.exports=e(1).Symbol},function(a,t,e){var s=e(3),c=e(5),d=e(4),p=e(15),f=e(37),h=e(68).KEY,S=e(8),b=e(26),w=e(28),I=e(17),R=e(2),H=e(30),L=e(31),X=e(69),r=e(70),D=e(10),V=e(11),z=e(18),q=e(9),k=e(23),A=e(16),T=e(38),W=e(71),E=e(72),ee=e(32),J=e(7),C=e(13),Y=E.f,be=J.f,ce=W.f,U=s.Symbol,le=s.JSON,Q=le&&le.stringify,he=R("_hidden"),ve=R("toPrimitive"),Ne={}.propertyIsEnumerable,Ee=b("symbol-registry"),Oe=b("symbols"),fe=b("op-symbols"),ge=Object.prototype,De=typeof U=="function"&&!!ee.f,Ue=s.QObject,Xe=!Ue||!Ue.prototype||!Ue.prototype.findChild,et=d&&S((function(){return T(be({},"a",{get:function(){return be(this,"a",{value:7}).a}})).a!=7}))?function(j,N,B){var K=Y(ge,N);K&&delete ge[N],be(j,N,B),K&&j!==ge&&be(ge,N,K)}:be,tt=function(j){var N=Oe[j]=T(U.prototype);return N._k=j,N},at=De&&typeof U.iterator=="symbol"?function(j){return typeof j=="symbol"}:function(j){return j instanceof U},He=function(j,N,B){return j===ge&&He(fe,N,B),D(j),N=k(N,!0),D(B),c(Oe,N)?(B.enumerable?(c(j,he)&&j[he][N]&&(j[he][N]=!1),B=T(B,{enumerable:A(0,!1)})):(c(j,he)||be(j,he,A(1,{})),j[he][N]=!0),et(j,N,B)):be(j,N,B)},st=function(j,N){D(j);for(var B,K=X(N=q(N)),re=0,te=K.length;te>re;)He(j,B=K[re++],N[B]);return j},ot=function(j){var N=Ne.call(this,j=k(j,!0));return!(this===ge&&c(Oe,j)&&!c(fe,j))&&(!(N||!c(this,j)||!c(Oe,j)||c(this,he)&&this[he][j])||N)},rt=function(j,N){if(j=q(j),N=k(N,!0),j!==ge||!c(Oe,N)||c(fe,N)){var B=Y(j,N);return!B||!c(Oe,N)||c(j,he)&&j[he][N]||(B.enumerable=!0),B}},it=function(j){for(var N,B=ce(q(j)),K=[],re=0;B.length>re;)c(Oe,N=B[re++])||N==he||N==h||K.push(N);return K},Ge=function(j){for(var N,B=j===ge,K=ce(B?fe:q(j)),re=[],te=0;K.length>te;)!c(Oe,N=K[te++])||B&&!c(ge,N)||re.push(Oe[N]);return re};De||(f((U=function(){if(this instanceof U)throw TypeError("Symbol is not a constructor!");var j=I(arguments.length>0?arguments[0]:void 0),N=function(B){this===ge&&N.call(fe,B),c(this,he)&&c(this[he],j)&&(this[he][j]=!1),et(this,j,A(1,B))};return d&&Xe&&et(ge,j,{configurable:!0,set:N}),tt(j)}).prototype,"toString",(function(){return this._k})),E.f=rt,J.f=He,e(41).f=W.f=it,e(19).f=ot,ee.f=Ge,d&&!e(14)&&f(ge,"propertyIsEnumerable",ot,!0),H.f=function(j){return tt(R(j))}),p(p.G+p.W+p.F*!De,{Symbol:U});for(var Ve="hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables".split(","),Ce=0;Ve.length>Ce;)R(Ve[Ce++]);for(var nt=C(R.store),F=0;nt.length>F;)L(nt[F++]);p(p.S+p.F*!De,"Symbol",{for:function(j){return c(Ee,j+="")?Ee[j]:Ee[j]=U(j)},keyFor:function(j){if(!at(j))throw TypeError(j+" is not a symbol!");for(var N in Ee)if(Ee[N]===j)return N},useSetter:function(){Xe=!0},useSimple:function(){Xe=!1}}),p(p.S+p.F*!De,"Object",{create:function(j,N){return N===void 0?T(j):st(T(j),N)},defineProperty:He,defineProperties:st,getOwnPropertyDescriptor:rt,getOwnPropertyNames:it,getOwnPropertySymbols:Ge});var x=S((function(){ee.f(1)}));p(p.S+p.F*x,"Object",{getOwnPropertySymbols:function(j){return ee.f(z(j))}}),le&&p(p.S+p.F*(!De||S((function(){var j=U();return Q([j])!="[null]"||Q({a:j})!="{}"||Q(Object(j))!="{}"}))),"JSON",{stringify:function(j){for(var N,B,K=[j],re=1;arguments.length>re;)K.push(arguments[re++]);if(B=N=K[1],(V(N)||j!==void 0)&&!at(j))return r(N)||(N=function(te,ue){if(typeof B=="function"&&(ue=B.call(this,te,ue)),!at(ue))return ue}),K[1]=N,Q.apply(le,K)}}),U.prototype[ve]||e(6)(U.prototype,ve,U.prototype.valueOf),w(U,"Symbol"),w(Math,"Math",!0),w(s.JSON,"JSON",!0)},function(a,t,e){var s=e(17)("meta"),c=e(11),d=e(5),p=e(7).f,f=0,h=Object.isExtensible||function(){return!0},S=!e(8)((function(){return h(Object.preventExtensions({}))})),b=function(I){p(I,s,{value:{i:"O"+ ++f,w:{}}})},w=a.exports={KEY:s,NEED:!1,fastKey:function(I,R){if(!c(I))return typeof I=="symbol"?I:(typeof I=="string"?"S":"P")+I;if(!d(I,s)){if(!h(I))return"F";if(!R)return"E";b(I)}return I[s].i},getWeak:function(I,R){if(!d(I,s)){if(!h(I))return!0;if(!R)return!1;b(I)}return I[s].w},onFreeze:function(I){return S&&w.NEED&&h(I)&&!d(I,s)&&b(I),I}}},function(a,t,e){var s=e(13),c=e(32),d=e(19);a.exports=function(p){var f=s(p),h=c.f;if(h)for(var S,b=h(p),w=d.f,I=0;b.length>I;)w.call(p,S=b[I++])&&f.push(S);return f}},function(a,t,e){var s=e(24);a.exports=Array.isArray||function(c){return s(c)=="Array"}},function(a,t,e){var s=e(9),c=e(41).f,d={}.toString,p=typeof window=="object"&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[];a.exports.f=function(f){return p&&d.call(f)=="[object Window]"?(function(h){try{return c(h)}catch{return p.slice()}})(f):c(s(f))}},function(a,t,e){var s=e(19),c=e(16),d=e(9),p=e(23),f=e(5),h=e(35),S=Object.getOwnPropertyDescriptor;t.f=e(4)?S:function(b,w){if(b=d(b),w=p(w,!0),h)try{return S(b,w)}catch{}if(f(b,w))return c(!s.f.call(b,w),b[w])}},function(a,t){},function(a,t,e){e(31)("asyncIterator")},function(a,t,e){e(31)("observable")},function(a,t,e){t.__esModule=!0;var s,c=e(77),d=(s=c)&&s.__esModule?s:{default:s};t.default=d.default||function(p){for(var f=1;fH;)for(var r,D=h(arguments[H++]),V=L?c(D).concat(L(D)):c(D),z=V.length,q=0;z>q;)r=V[q++],s&&!X.call(D,r)||(I[r]=D[r]);return I}:S},function(a,t,e){t.__esModule=!0;var s=d(e(82)),c=d(e(85));function d(p){return p&&p.__esModule?p:{default:p}}t.default=function(p,f){if(Array.isArray(p))return p;if((0,s.default)(Object(p)))return(function(h,S){var b=[],w=!0,I=!1,R=void 0;try{for(var H,L=(0,c.default)(h);!(w=(H=L.next()).done)&&(b.push(H.value),!S||b.length!==S);w=!0);}catch(X){I=!0,R=X}finally{try{!w&&L.return&&L.return()}finally{if(I)throw R}}return b})(p,f);throw new TypeError("Invalid attempt to destructure non-iterable instance")}},function(a,t,e){a.exports={default:e(83),__esModule:!0}},function(a,t,e){e(29),e(20),a.exports=e(84)},function(a,t,e){var s=e(42),c=e(2)("iterator"),d=e(12);a.exports=e(1).isIterable=function(p){var f=Object(p);return f[c]!==void 0||"@@iterator"in f||d.hasOwnProperty(s(f))}},function(a,t,e){a.exports={default:e(86),__esModule:!0}},function(a,t,e){e(29),e(20),a.exports=e(87)},function(a,t,e){var s=e(10),c=e(88);a.exports=e(1).getIterator=function(d){var p=c(d);if(typeof p!="function")throw TypeError(d+" is not iterable!");return s(p.call(d))}},function(a,t,e){var s=e(42),c=e(2)("iterator"),d=e(12);a.exports=e(1).getIteratorMethod=function(p){if(p!=null)return p[c]||p["@@iterator"]||d[s(p)]}},function(a,t,e){a.exports={default:e(90),__esModule:!0}},function(a,t,e){e(91),a.exports=e(1).Object.keys},function(a,t,e){var s=e(18),c=e(13);e(92)("keys",(function(){return function(d){return c(s(d))}}))},function(a,t,e){var s=e(15),c=e(1),d=e(8);a.exports=function(p,f){var h=(c.Object||{})[p]||Object[p],S={};S[p]=f(h),s(s.S+s.F*d((function(){h(1)})),"Object",S)}},function(a,t,e){(function(s){var c=[["ary",128],["bind",1],["bindKey",2],["curry",8],["curryRight",16],["flip",512],["partial",32],["partialRight",64],["rearg",256]],d=/^\s+|\s+$/g,p=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,f=/\{\n\/\* \[wrapped with (.+)\] \*/,h=/,? & /,S=/^[-+]0x[0-9a-f]+$/i,b=/^0b[01]+$/i,w=/^\[object .+?Constructor\]$/,I=/^0o[0-7]+$/i,R=/^(?:0|[1-9]\d*)$/,H=parseInt,L=typeof s=="object"&&s&&s.Object===Object&&s,X=typeof self=="object"&&self&&self.Object===Object&&self,r=L||X||Function("return this")();function D(F,x,j){switch(j.length){case 0:return F.call(x);case 1:return F.call(x,j[0]);case 2:return F.call(x,j[0],j[1]);case 3:return F.call(x,j[0],j[1],j[2])}return F.apply(x,j)}function V(F,x){return!!(F&&F.length)&&(function(j,N,B){if(N!=N)return(function(te,ue,ye,xe){for(var Ie=te.length,me=ye+-1;++me-1}function z(F){return F!=F}function q(F,x){for(var j=F.length,N=0;j--;)F[j]===x&&N++;return N}function k(F,x){for(var j=-1,N=F.length,B=0,K=[];++j2?T:void 0);function Ne(F){return Ve(F)?le(F):{}}function Ee(F){return!(!Ve(F)||(function(x){return!!C&&C in x})(F))&&((function(x){var j=Ve(x)?ce.call(x):"";return j=="[object Function]"||j=="[object GeneratorFunction]"})(F)||(function(x){var j=!1;if(x!=null&&typeof x.toString!="function")try{j=!!(x+"")}catch{}return j})(F)?U:w).test((function(x){if(x!=null){try{return Y.call(x)}catch{}try{return x+""}catch{}}return""})(F))}function Oe(F,x,j,N){for(var B=-1,K=F.length,re=j.length,te=-1,ue=x.length,ye=Q(K-re,0),xe=Array(ue+ye),Ie=!N;++te1&&se.reverse(),xe&&ue1?"& ":"")+x[N],x=x.join(j>2?", ":" "),F.replace(p,`{ -/* [wrapped with `+x+`] */ -`)}function st(F,x){return!!(x=x??9007199254740991)&&(typeof F=="number"||R.test(F))&&F>-1&&F%1==0&&F1&&d--,f=6*d<1?s+6*(c-s)*d:2*d<1?c:3*d<2?s+(c-s)*(2/3-d)*6:s,p[w]=255*f;return p}},function(a,t,e){(function(s){var c=typeof s=="object"&&s&&s.Object===Object&&s,d=typeof self=="object"&&self&&self.Object===Object&&self,p=c||d||Function("return this")();function f(k,A,T){switch(T.length){case 0:return k.call(A);case 1:return k.call(A,T[0]);case 2:return k.call(A,T[0],T[1]);case 3:return k.call(A,T[0],T[1],T[2])}return k.apply(A,T)}function h(k,A){for(var T=-1,W=A.length,E=k.length;++T-1&&E%1==0&&E<=9007199254740991})(W.length)&&!(function(E){var ee=(function(J){var C=typeof J;return!!J&&(C=="object"||C=="function")})(E)?w.call(E):"";return ee=="[object Function]"||ee=="[object GeneratorFunction]"})(W)})(T)})(A)&&b.call(A,"callee")&&(!R.call(A,"callee")||w.call(A)=="[object Arguments]")})(k)||!!(H&&k&&k[H])}var r=Array.isArray,D,V,z,q=(V=function(k){var A=(k=(function(E,ee,J,C,Y){var be=-1,ce=E.length;for(J||(J=X),Y||(Y=[]);++be2?d-2:0),f=2;f"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch{return!1}})();return function(){var n,o=w(l);if(u){var i=w(this).constructor;n=Reflect.construct(o,arguments,i)}else n=o.apply(this,arguments);return H(this,n)}}e.r(t);var X=e(0),r=e.n(X);function D(){var l=this.constructor.getDerivedStateFromProps(this.props,this.state);l!=null&&this.setState(l)}function V(l){this.setState(function(u){var n=this.constructor.getDerivedStateFromProps(l,u);return n??null}.bind(this))}function z(l,u){try{var n=this.props,o=this.state;this.props=l,this.state=u,this.__reactInternalSnapshotFlag=!0,this.__reactInternalSnapshot=this.getSnapshotBeforeUpdate(n,o)}finally{this.props=n,this.state=o}}function q(l){var u=l.prototype;if(!u||!u.isReactComponent)throw new Error("Can only polyfill class components");if(typeof l.getDerivedStateFromProps!="function"&&typeof u.getSnapshotBeforeUpdate!="function")return l;var n=null,o=null,i=null;if(typeof u.componentWillMount=="function"?n="componentWillMount":typeof u.UNSAFE_componentWillMount=="function"&&(n="UNSAFE_componentWillMount"),typeof u.componentWillReceiveProps=="function"?o="componentWillReceiveProps":typeof u.UNSAFE_componentWillReceiveProps=="function"&&(o="UNSAFE_componentWillReceiveProps"),typeof u.componentWillUpdate=="function"?i="componentWillUpdate":typeof u.UNSAFE_componentWillUpdate=="function"&&(i="UNSAFE_componentWillUpdate"),n!==null||o!==null||i!==null){var y=l.displayName||l.name,O=typeof l.getDerivedStateFromProps=="function"?"getDerivedStateFromProps()":"getSnapshotBeforeUpdate()";throw Error(`Unsafe legacy lifecycles will not be called for components using new component APIs. - -`+y+" uses "+O+" but also contains the following legacy lifecycles:"+(n!==null?` - `+n:"")+(o!==null?` - `+o:"")+(i!==null?` - `+i:"")+` - -The above lifecycles should be removed. Learn more about this warning here: -https://fb.me/react-async-component-lifecycle-hooks`)}if(typeof l.getDerivedStateFromProps=="function"&&(u.componentWillMount=D,u.componentWillReceiveProps=V),typeof u.getSnapshotBeforeUpdate=="function"){if(typeof u.componentDidUpdate!="function")throw new Error("Cannot polyfill getSnapshotBeforeUpdate() for components that do not define componentDidUpdate() on the prototype");u.componentWillUpdate=z;var _=u.componentDidUpdate;u.componentDidUpdate=function(m,P,$){var ne=this.__reactInternalSnapshotFlag?this.__reactInternalSnapshot:$;_.call(this,m,P,ne)}}return l}function k(l,u){if(l==null)return{};var n,o,i=(function(O,_){if(O==null)return{};var m,P,$={},ne=Object.keys(O);for(P=0;P=0||($[m]=O[m]);return $})(l,u);if(Object.getOwnPropertySymbols){var y=Object.getOwnPropertySymbols(l);for(o=0;o=0||Object.prototype.propertyIsEnumerable.call(l,n)&&(i[n]=l[n])}return i}function A(l){var u=(function(n){return{}.toString.call(n).match(/\s([a-zA-Z]+)/)[1].toLowerCase()})(l);return u==="number"&&(u=isNaN(l)?"nan":(0|l)!=l?"float":"integer"),u}D.__suppressDeprecationWarning=!0,V.__suppressDeprecationWarning=!0,z.__suppressDeprecationWarning=!0;var T={scheme:"rjv-default",author:"mac gainor",base00:"rgba(0, 0, 0, 0)",base01:"rgb(245, 245, 245)",base02:"rgb(235, 235, 235)",base03:"#93a1a1",base04:"rgba(0, 0, 0, 0.3)",base05:"#586e75",base06:"#073642",base07:"#002b36",base08:"#d33682",base09:"#cb4b16",base0A:"#dc322f",base0B:"#859900",base0C:"#6c71c4",base0D:"#586e75",base0E:"#2aa198",base0F:"#268bd2"},W={scheme:"rjv-grey",author:"mac gainor",base00:"rgba(1, 1, 1, 0)",base01:"rgba(1, 1, 1, 0.1)",base02:"rgba(0, 0, 0, 0.2)",base03:"rgba(1, 1, 1, 0.3)",base04:"rgba(0, 0, 0, 0.4)",base05:"rgba(1, 1, 1, 0.5)",base06:"rgba(1, 1, 1, 0.6)",base07:"rgba(1, 1, 1, 0.7)",base08:"rgba(1, 1, 1, 0.8)",base09:"rgba(1, 1, 1, 0.8)",base0A:"rgba(1, 1, 1, 0.8)",base0B:"rgba(1, 1, 1, 0.8)",base0C:"rgba(1, 1, 1, 0.8)",base0D:"rgba(1, 1, 1, 0.8)",base0E:"rgba(1, 1, 1, 0.8)",base0F:"rgba(1, 1, 1, 0.8)"},E={globalFontFamily:"monospace",globalCursor:"default",braceFontWeight:"bold",braceCursor:"pointer",ellipsisFontSize:"18px",ellipsisLineHeight:"10px",ellipsisCursor:"pointer",keyMargin:"0px 5px",keyLetterSpacing:"0.5px",keyFontStyle:"none",keyVerticalAlign:"top",keyOpacity:"0.85",keyOpacityHover:"1",keyValPaddingTop:"3px",keyValPaddingBottom:"3px",keyValPaddingRight:"5px",keyValBorderLeft:"1px solid",keyValBorderHover:"2px solid",pushedContentMarginLeft:"6px",variableValuePaddingRight:"6px",nullFontSize:"11px",nullFontWeight:"bold",nullPadding:"1px 2px",nullBorderRadius:"3px",nanFontSize:"11px",nanFontWeight:"bold",nanPadding:"1px 2px",nanBorderRadius:"3px",undefinedFontSize:"11px",undefinedPadding:"1px 2px",undefinedBorderRadius:"3px",dataTypeFontSize:"11px",dataTypeMarginRight:"4px",datatypeOpacity:"0.8",objectSizeBorderRadius:"3px",objectSizeFontStyle:"italic",objectSizeMargin:"0px 6px 0px 0px",clipboardCursor:"pointer",clipboardCheckMarginLeft:"-12px",metaDataPadding:"0px 0px 0px 10px",arrayGroupMetaPadding:"0px 0px 0px 4px",iconContainerWidth:"17px",tooltipPadding:"4px",editInputMinWidth:"130px",editInputBorderRadius:"2px",editInputPadding:"5px",editInputMarginRight:"4px",editInputFontFamily:"monospace",iconCursor:"pointer",iconFontSize:"15px",iconPaddingRight:"1px",dateValueMarginLeft:"2px",iconMarginRight:"3px",detectedRowPaddingTop:"3px",addKeyCoverBackground:"rgba(255, 255, 255, 0.3)",addKeyCoverPosition:"absolute",addKeyCoverPositionPx:"0px",addKeyModalWidth:"200px",addKeyModalMargin:"auto",addKeyModalPadding:"10px",addKeyModalRadius:"3px"},ee=e(45),J=function(l){var u=(function(n){return{backgroundColor:n.base00,ellipsisColor:n.base09,braceColor:n.base07,expandedIcon:n.base0D,collapsedIcon:n.base0E,keyColor:n.base07,arrayKeyColor:n.base0C,objectSize:n.base04,copyToClipboard:n.base0F,copyToClipboardCheck:n.base0D,objectBorder:n.base02,dataTypes:{boolean:n.base0E,date:n.base0D,float:n.base0B,function:n.base0D,integer:n.base0F,string:n.base09,nan:n.base08,null:n.base0A,undefined:n.base05,regexp:n.base0A,background:n.base02},editVariable:{editIcon:n.base0E,cancelIcon:n.base09,removeIcon:n.base09,addIcon:n.base0E,checkIcon:n.base0E,background:n.base01,color:n.base0A,border:n.base07},addKeyModal:{background:n.base05,border:n.base04,color:n.base0A,labelColor:n.base01},validationFailure:{background:n.base09,iconColor:n.base01,fontColor:n.base01}}})(l);return{"app-container":{fontFamily:E.globalFontFamily,cursor:E.globalCursor,backgroundColor:u.backgroundColor,position:"relative"},ellipsis:{display:"inline-block",color:u.ellipsisColor,fontSize:E.ellipsisFontSize,lineHeight:E.ellipsisLineHeight,cursor:E.ellipsisCursor},"brace-row":{display:"inline-block",cursor:"pointer"},brace:{display:"inline-block",cursor:E.braceCursor,fontWeight:E.braceFontWeight,color:u.braceColor},"expanded-icon":{color:u.expandedIcon},"collapsed-icon":{color:u.collapsedIcon},colon:{display:"inline-block",margin:E.keyMargin,color:u.keyColor,verticalAlign:"top"},objectKeyVal:function(n,o){return{style:d({paddingTop:E.keyValPaddingTop,paddingRight:E.keyValPaddingRight,paddingBottom:E.keyValPaddingBottom,borderLeft:E.keyValBorderLeft+" "+u.objectBorder,":hover":{paddingLeft:o.paddingLeft-1+"px",borderLeft:E.keyValBorderHover+" "+u.objectBorder}},o)}},"object-key-val-no-border":{padding:E.keyValPadding},"pushed-content":{marginLeft:E.pushedContentMarginLeft},variableValue:function(n,o){return{style:d({display:"inline-block",paddingRight:E.variableValuePaddingRight,position:"relative"},o)}},"object-name":{display:"inline-block",color:u.keyColor,letterSpacing:E.keyLetterSpacing,fontStyle:E.keyFontStyle,verticalAlign:E.keyVerticalAlign,opacity:E.keyOpacity,":hover":{opacity:E.keyOpacityHover}},"array-key":{display:"inline-block",color:u.arrayKeyColor,letterSpacing:E.keyLetterSpacing,fontStyle:E.keyFontStyle,verticalAlign:E.keyVerticalAlign,opacity:E.keyOpacity,":hover":{opacity:E.keyOpacityHover}},"object-size":{color:u.objectSize,borderRadius:E.objectSizeBorderRadius,fontStyle:E.objectSizeFontStyle,margin:E.objectSizeMargin,cursor:"default"},"data-type-label":{fontSize:E.dataTypeFontSize,marginRight:E.dataTypeMarginRight,opacity:E.datatypeOpacity},boolean:{display:"inline-block",color:u.dataTypes.boolean},date:{display:"inline-block",color:u.dataTypes.date},"date-value":{marginLeft:E.dateValueMarginLeft},float:{display:"inline-block",color:u.dataTypes.float},function:{display:"inline-block",color:u.dataTypes.function,cursor:"pointer",whiteSpace:"pre-line"},"function-value":{fontStyle:"italic"},integer:{display:"inline-block",color:u.dataTypes.integer},string:{display:"inline-block",color:u.dataTypes.string},nan:{display:"inline-block",color:u.dataTypes.nan,fontSize:E.nanFontSize,fontWeight:E.nanFontWeight,backgroundColor:u.dataTypes.background,padding:E.nanPadding,borderRadius:E.nanBorderRadius},null:{display:"inline-block",color:u.dataTypes.null,fontSize:E.nullFontSize,fontWeight:E.nullFontWeight,backgroundColor:u.dataTypes.background,padding:E.nullPadding,borderRadius:E.nullBorderRadius},undefined:{display:"inline-block",color:u.dataTypes.undefined,fontSize:E.undefinedFontSize,padding:E.undefinedPadding,borderRadius:E.undefinedBorderRadius,backgroundColor:u.dataTypes.background},regexp:{display:"inline-block",color:u.dataTypes.regexp},"copy-to-clipboard":{cursor:E.clipboardCursor},"copy-icon":{color:u.copyToClipboard,fontSize:E.iconFontSize,marginRight:E.iconMarginRight,verticalAlign:"top"},"copy-icon-copied":{color:u.copyToClipboardCheck,marginLeft:E.clipboardCheckMarginLeft},"array-group-meta-data":{display:"inline-block",padding:E.arrayGroupMetaPadding},"object-meta-data":{display:"inline-block",padding:E.metaDataPadding},"icon-container":{display:"inline-block",width:E.iconContainerWidth},tooltip:{padding:E.tooltipPadding},removeVarIcon:{verticalAlign:"top",display:"inline-block",color:u.editVariable.removeIcon,cursor:E.iconCursor,fontSize:E.iconFontSize,marginRight:E.iconMarginRight},addVarIcon:{verticalAlign:"top",display:"inline-block",color:u.editVariable.addIcon,cursor:E.iconCursor,fontSize:E.iconFontSize,marginRight:E.iconMarginRight},editVarIcon:{verticalAlign:"top",display:"inline-block",color:u.editVariable.editIcon,cursor:E.iconCursor,fontSize:E.iconFontSize,marginRight:E.iconMarginRight},"edit-icon-container":{display:"inline-block",verticalAlign:"top"},"check-icon":{display:"inline-block",cursor:E.iconCursor,color:u.editVariable.checkIcon,fontSize:E.iconFontSize,paddingRight:E.iconPaddingRight},"cancel-icon":{display:"inline-block",cursor:E.iconCursor,color:u.editVariable.cancelIcon,fontSize:E.iconFontSize,paddingRight:E.iconPaddingRight},"edit-input":{display:"inline-block",minWidth:E.editInputMinWidth,borderRadius:E.editInputBorderRadius,backgroundColor:u.editVariable.background,color:u.editVariable.color,padding:E.editInputPadding,marginRight:E.editInputMarginRight,fontFamily:E.editInputFontFamily},"detected-row":{paddingTop:E.detectedRowPaddingTop},"key-modal-request":{position:E.addKeyCoverPosition,top:E.addKeyCoverPositionPx,left:E.addKeyCoverPositionPx,right:E.addKeyCoverPositionPx,bottom:E.addKeyCoverPositionPx,backgroundColor:E.addKeyCoverBackground},"key-modal":{width:E.addKeyModalWidth,backgroundColor:u.addKeyModal.background,marginLeft:E.addKeyModalMargin,marginRight:E.addKeyModalMargin,padding:E.addKeyModalPadding,borderRadius:E.addKeyModalRadius,marginTop:"15px",position:"relative"},"key-modal-label":{color:u.addKeyModal.labelColor,marginLeft:"2px",marginBottom:"5px",fontSize:"11px"},"key-modal-input-container":{overflow:"hidden"},"key-modal-input":{width:"100%",padding:"3px 6px",fontFamily:"monospace",color:u.addKeyModal.color,border:"none",boxSizing:"border-box",borderRadius:"2px"},"key-modal-cancel":{backgroundColor:u.editVariable.removeIcon,position:"absolute",top:"0px",right:"0px",borderRadius:"0px 3px 0px 3px",cursor:"pointer"},"key-modal-cancel-icon":{color:u.addKeyModal.labelColor,fontSize:E.iconFontSize,transform:"rotate(45deg)"},"key-modal-submit":{color:u.editVariable.addIcon,fontSize:E.iconFontSize,position:"absolute",right:"2px",top:"3px",cursor:"pointer"},"function-ellipsis":{display:"inline-block",color:u.ellipsisColor,fontSize:E.ellipsisFontSize,lineHeight:E.ellipsisLineHeight,cursor:E.ellipsisCursor},"validation-failure":{float:"right",padding:"3px 6px",borderRadius:"2px",cursor:"pointer",color:u.validationFailure.fontColor,backgroundColor:u.validationFailure.background},"validation-failure-label":{marginRight:"6px"},"validation-failure-clear":{position:"relative",verticalAlign:"top",cursor:"pointer",color:u.validationFailure.iconColor,fontSize:E.iconFontSize,transform:"rotate(45deg)"}}};function C(l,u,n){return l||console.error("theme has not been set"),(function(o){var i=T;return o!==!1&&o!=="none"||(i=W),Object(ee.createStyling)(J,{defaultBase16:i})(o)})(l)(u,n)}var Y=(function(l){b(n,l);var u=L(n);function n(){return p(this,n),u.apply(this,arguments)}return h(n,[{key:"render",value:function(){var o=this.props,i=(o.rjvId,o.type_name),y=o.displayDataTypes,O=o.theme;return y?r.a.createElement("span",Object.assign({className:"data-type-label"},C(O,"data-type-label")),i):null}}]),n})(r.a.PureComponent),be=(function(l){b(n,l);var u=L(n);function n(){return p(this,n),u.apply(this,arguments)}return h(n,[{key:"render",value:function(){var o=this.props;return r.a.createElement("div",C(o.theme,"boolean"),r.a.createElement(Y,Object.assign({type_name:"bool"},o)),o.value?"true":"false")}}]),n})(r.a.PureComponent),ce=(function(l){b(n,l);var u=L(n);function n(){return p(this,n),u.apply(this,arguments)}return h(n,[{key:"render",value:function(){var o=this.props;return r.a.createElement("div",C(o.theme,"date"),r.a.createElement(Y,Object.assign({type_name:"date"},o)),r.a.createElement("span",Object.assign({className:"date-value"},C(o.theme,"date-value")),o.value.toLocaleTimeString("en-us",{weekday:"short",year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})))}}]),n})(r.a.PureComponent),U=(function(l){b(n,l);var u=L(n);function n(){return p(this,n),u.apply(this,arguments)}return h(n,[{key:"render",value:function(){var o=this.props;return r.a.createElement("div",C(o.theme,"float"),r.a.createElement(Y,Object.assign({type_name:"float"},o)),this.props.value)}}]),n})(r.a.PureComponent);function le(l,u){(u==null||u>l.length)&&(u=l.length);for(var n=0,o=new Array(u);n"u"||l[Symbol.iterator]==null){if(Array.isArray(l)||(n=Q(l))||u){n&&(l=n);var o=0,i=function(){};return{s:i,n:function(){return o>=l.length?{done:!0}:{done:!1,value:l[o++]}},e:function(m){throw m},f:i}}throw new TypeError(`Invalid attempt to iterate non-iterable instance. -In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var y,O=!0,_=!1;return{s:function(){n=l[Symbol.iterator]()},n:function(){var m=n.next();return O=m.done,m},e:function(m){_=!0,y=m},f:function(){try{O||n.return==null||n.return()}finally{if(_)throw y}}}}function ve(l){return(function(u){if(Array.isArray(u))return le(u)})(l)||(function(u){if(typeof Symbol<"u"&&Symbol.iterator in Object(u))return Array.from(u)})(l)||Q(l)||(function(){throw new TypeError(`Invalid attempt to spread non-iterable instance. -In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)})()}var Ne=e(46),Ee=new(e(47)).Dispatcher,Oe=new((function(l){b(n,l);var u=L(n);function n(){var o;p(this,n);for(var i=arguments.length,y=new Array(i),O=0;Oi&&(_.style.cursor="pointer",this.state.collapsed&&(O=r.a.createElement("span",null,O.substring(0,i),r.a.createElement("span",C(y,"ellipsis")," ...")))),r.a.createElement("div",C(y,"string"),r.a.createElement(Y,Object.assign({type_name:"string"},o)),r.a.createElement("span",Object.assign({className:"string-value"},_,{onClick:this.toggleCollapsed}),'"',O,'"'))}}]),n})(r.a.PureComponent),at=(function(l){b(n,l);var u=L(n);function n(){return p(this,n),u.apply(this,arguments)}return h(n,[{key:"render",value:function(){return r.a.createElement("div",C(this.props.theme,"undefined"),"undefined")}}]),n})(r.a.PureComponent);function He(){return(He=Object.assign||function(l){for(var u=1;u=0||(gt[Le]=G[Le]);return gt})(l,["cacheMeasurements","maxRows","minRows","onChange","onHeightChange"]),$,ne=P.value!==void 0,oe=Object(X.useRef)(null),pe=it(oe,u),ae=Object(X.useRef)(0),de=Object(X.useRef)(),je=function(){var G=oe.current,_e=n&&de.current?de.current:(function(Qe){var yt=window.getComputedStyle(Qe);if(yt===null)return null;var ct,Fe=(ct=yt,F.reduce((function(ht,pt){return ht[pt]=ct[pt],ht}),{})),ut=Fe.boxSizing;return ut===""?null:(x&&ut==="border-box"&&(Fe.width=parseFloat(Fe.width)+parseFloat(Fe.borderRightWidth)+parseFloat(Fe.borderLeftWidth)+parseFloat(Fe.paddingRight)+parseFloat(Fe.paddingLeft)+"px"),{sizingStyle:Fe,paddingSize:parseFloat(Fe.paddingBottom)+parseFloat(Fe.paddingTop),borderSize:parseFloat(Fe.borderBottomWidth)+parseFloat(Fe.borderTopWidth)})})(G);if(_e){de.current=_e;var Le=(function(Qe,yt,ct,Fe){ct===void 0&&(ct=1),Fe===void 0&&(Fe=1/0),Ce||((Ce=document.createElement("textarea")).setAttribute("tab-index","-1"),Ce.setAttribute("aria-hidden","true"),Ve(Ce)),Ce.parentNode===null&&document.body.appendChild(Ce);var ut=Qe.paddingSize,ht=Qe.borderSize,pt=Qe.sizingStyle,At=pt.boxSizing;Object.keys(pt).forEach((function(kt){var dt=kt;Ce.style[dt]=pt[dt]})),Ve(Ce),Ce.value=yt;var xt=(function(kt,dt){var Ft=kt.scrollHeight;return dt.sizingStyle.boxSizing==="border-box"?Ft+dt.borderSize:Ft-dt.paddingSize})(Ce,Qe);Ce.value="x";var jt=Ce.scrollHeight-ut,Et=jt*ct;At==="border-box"&&(Et=Et+ut+ht),xt=Math.max(Et,xt);var St=jt*Fe;return At==="border-box"&&(St=St+ut+ht),[xt=Math.min(St,xt),jt]})(_e,G.value||G.placeholder||"x",i,o),Ye=Le[0],gt=Le[1];ae.current!==Ye&&(ae.current=Ye,G.style.setProperty("height",Ye+"px","important"),m(Ye,{rowHeight:gt}))}};return Object(X.useLayoutEffect)(je),$=ot(je),Object(X.useLayoutEffect)((function(){var G=function(_e){$.current(_e)};return window.addEventListener("resize",G),function(){window.removeEventListener("resize",G)}}),[]),Object(X.createElement)("textarea",He({},P,{onChange:function(G){ne||je(),O(G)},ref:pe}))},N=Object(X.forwardRef)(j);function B(l){l=l.trim();try{if((l=JSON.stringify(JSON.parse(l)))[0]==="[")return K("array",JSON.parse(l));if(l[0]==="{")return K("object",JSON.parse(l));if(l.match(/\-?\d+\.\d+/)&&l.match(/\-?\d+\.\d+/)[0]===l)return K("float",parseFloat(l));if(l.match(/\-?\d+e-\d+/)&&l.match(/\-?\d+e-\d+/)[0]===l)return K("float",Number(l));if(l.match(/\-?\d+/)&&l.match(/\-?\d+/)[0]===l)return K("integer",parseInt(l));if(l.match(/\-?\d+e\+\d+/)&&l.match(/\-?\d+e\+\d+/)[0]===l)return K("integer",Number(l))}catch{}switch(l=l.toLowerCase()){case"undefined":return K("undefined",void 0);case"nan":return K("nan",NaN);case"null":return K("null",null);case"true":return K("boolean",!0);case"false":return K("boolean",!1);default:if(l=Date.parse(l))return K("date",new Date(l))}return K(!1,null)}function K(l,u){return{type:l,value:u}}var re=(function(l){b(n,l);var u=L(n);function n(){return p(this,n),u.apply(this,arguments)}return h(n,[{key:"render",value:function(){var o=this.props,i=o.style,y=k(o,["style"]);return r.a.createElement("span",y,r.a.createElement("svg",Object.assign({},se(i),{viewBox:"0 0 24 24",fill:"currentColor",preserveAspectRatio:"xMidYMid meet"}),r.a.createElement("path",{d:"M12,20C7.59,20 4,16.41 4,12C4,7.59 7.59,4 12,4C16.41,4 20,7.59 20,12C20,16.41 16.41,20 12,20M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2M7,13H17V11H7"})))}}]),n})(r.a.PureComponent),te=(function(l){b(n,l);var u=L(n);function n(){return p(this,n),u.apply(this,arguments)}return h(n,[{key:"render",value:function(){var o=this.props,i=o.style,y=k(o,["style"]);return r.a.createElement("span",y,r.a.createElement("svg",Object.assign({},se(i),{viewBox:"0 0 24 24",fill:"currentColor",preserveAspectRatio:"xMidYMid meet"}),r.a.createElement("path",{d:"M12,20C7.59,20 4,16.41 4,12C4,7.59 7.59,4 12,4C16.41,4 20,7.59 20,12C20,16.41 16.41,20 12,20M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2M13,7H11V11H7V13H11V17H13V13H17V11H13V7Z"})))}}]),n})(r.a.PureComponent),ue=(function(l){b(n,l);var u=L(n);function n(){return p(this,n),u.apply(this,arguments)}return h(n,[{key:"render",value:function(){var o=this.props,i=o.style,y=k(o,["style"]),O=se(i).style;return r.a.createElement("span",y,r.a.createElement("svg",{fill:O.color,width:O.height,height:O.width,style:O,viewBox:"0 0 1792 1792"},r.a.createElement("path",{d:"M1344 800v64q0 14-9 23t-23 9h-832q-14 0-23-9t-9-23v-64q0-14 9-23t23-9h832q14 0 23 9t9 23zm128 448v-832q0-66-47-113t-113-47h-832q-66 0-113 47t-47 113v832q0 66 47 113t113 47h832q66 0 113-47t47-113zm128-832v832q0 119-84.5 203.5t-203.5 84.5h-832q-119 0-203.5-84.5t-84.5-203.5v-832q0-119 84.5-203.5t203.5-84.5h832q119 0 203.5 84.5t84.5 203.5z"})))}}]),n})(r.a.PureComponent),ye=(function(l){b(n,l);var u=L(n);function n(){return p(this,n),u.apply(this,arguments)}return h(n,[{key:"render",value:function(){var o=this.props,i=o.style,y=k(o,["style"]),O=se(i).style;return r.a.createElement("span",y,r.a.createElement("svg",{fill:O.color,width:O.height,height:O.width,style:O,viewBox:"0 0 1792 1792"},r.a.createElement("path",{d:"M1344 800v64q0 14-9 23t-23 9h-352v352q0 14-9 23t-23 9h-64q-14 0-23-9t-9-23v-352h-352q-14 0-23-9t-9-23v-64q0-14 9-23t23-9h352v-352q0-14 9-23t23-9h64q14 0 23 9t9 23v352h352q14 0 23 9t9 23zm128 448v-832q0-66-47-113t-113-47h-832q-66 0-113 47t-47 113v832q0 66 47 113t113 47h832q66 0 113-47t47-113zm128-832v832q0 119-84.5 203.5t-203.5 84.5h-832q-119 0-203.5-84.5t-84.5-203.5v-832q0-119 84.5-203.5t203.5-84.5h832q119 0 203.5 84.5t84.5 203.5z"})))}}]),n})(r.a.PureComponent),xe=(function(l){b(n,l);var u=L(n);function n(){return p(this,n),u.apply(this,arguments)}return h(n,[{key:"render",value:function(){var o=this.props,i=o.style,y=k(o,["style"]);return r.a.createElement("span",y,r.a.createElement("svg",{style:d(d({},se(i).style),{},{paddingLeft:"2px",verticalAlign:"top"}),viewBox:"0 0 15 15",fill:"currentColor"},r.a.createElement("path",{d:"M0 14l6-6-6-6z"})))}}]),n})(r.a.PureComponent),Ie=(function(l){b(n,l);var u=L(n);function n(){return p(this,n),u.apply(this,arguments)}return h(n,[{key:"render",value:function(){var o=this.props,i=o.style,y=k(o,["style"]);return r.a.createElement("span",y,r.a.createElement("svg",{style:d(d({},se(i).style),{},{paddingLeft:"2px",verticalAlign:"top"}),viewBox:"0 0 15 15",fill:"currentColor"},r.a.createElement("path",{d:"M0 5l6 6 6-6z"})))}}]),n})(r.a.PureComponent),me=(function(l){b(n,l);var u=L(n);function n(){return p(this,n),u.apply(this,arguments)}return h(n,[{key:"render",value:function(){var o=this.props,i=o.style,y=k(o,["style"]);return r.a.createElement("span",y,r.a.createElement("svg",Object.assign({},se(i),{viewBox:"0 0 40 40",fill:"currentColor",preserveAspectRatio:"xMidYMid meet"}),r.a.createElement("g",null,r.a.createElement("path",{d:"m30 35h-25v-22.5h25v7.5h2.5v-12.5c0-1.4-1.1-2.5-2.5-2.5h-7.5c0-2.8-2.2-5-5-5s-5 2.2-5 5h-7.5c-1.4 0-2.5 1.1-2.5 2.5v27.5c0 1.4 1.1 2.5 2.5 2.5h25c1.4 0 2.5-1.1 2.5-2.5v-5h-2.5v5z m-20-27.5h2.5s2.5-1.1 2.5-2.5 1.1-2.5 2.5-2.5 2.5 1.1 2.5 2.5 1.3 2.5 2.5 2.5h2.5s2.5 1.1 2.5 2.5h-20c0-1.5 1.1-2.5 2.5-2.5z m-2.5 20h5v-2.5h-5v2.5z m17.5-5v-5l-10 7.5 10 7.5v-5h12.5v-5h-12.5z m-17.5 10h7.5v-2.5h-7.5v2.5z m12.5-17.5h-12.5v2.5h12.5v-2.5z m-7.5 5h-5v2.5h5v-2.5z"}))))}}]),n})(r.a.PureComponent),Pe=(function(l){b(n,l);var u=L(n);function n(){return p(this,n),u.apply(this,arguments)}return h(n,[{key:"render",value:function(){var o=this.props,i=o.style,y=k(o,["style"]);return r.a.createElement("span",y,r.a.createElement("svg",Object.assign({},se(i),{viewBox:"0 0 40 40",fill:"currentColor",preserveAspectRatio:"xMidYMid meet"}),r.a.createElement("g",null,r.a.createElement("path",{d:"m28.6 25q0-0.5-0.4-1l-4-4 4-4q0.4-0.5 0.4-1 0-0.6-0.4-1.1l-2-2q-0.4-0.4-1-0.4-0.6 0-1 0.4l-4.1 4.1-4-4.1q-0.4-0.4-1-0.4-0.6 0-1 0.4l-2 2q-0.5 0.5-0.5 1.1 0 0.5 0.5 1l4 4-4 4q-0.5 0.5-0.5 1 0 0.7 0.5 1.1l2 2q0.4 0.4 1 0.4 0.6 0 1-0.4l4-4.1 4.1 4.1q0.4 0.4 1 0.4 0.6 0 1-0.4l2-2q0.4-0.4 0.4-1z m8.7-5q0 4.7-2.3 8.6t-6.3 6.2-8.6 2.3-8.6-2.3-6.2-6.2-2.3-8.6 2.3-8.6 6.2-6.2 8.6-2.3 8.6 2.3 6.3 6.2 2.3 8.6z"}))))}}]),n})(r.a.PureComponent),Re=(function(l){b(n,l);var u=L(n);function n(){return p(this,n),u.apply(this,arguments)}return h(n,[{key:"render",value:function(){var o=this.props,i=o.style,y=k(o,["style"]);return r.a.createElement("span",y,r.a.createElement("svg",Object.assign({},se(i),{viewBox:"0 0 40 40",fill:"currentColor",preserveAspectRatio:"xMidYMid meet"}),r.a.createElement("g",null,r.a.createElement("path",{d:"m30.1 21.4v-2.8q0-0.6-0.4-1t-1-0.5h-5.7v-5.7q0-0.6-0.4-1t-1-0.4h-2.9q-0.6 0-1 0.4t-0.4 1v5.7h-5.7q-0.6 0-1 0.5t-0.5 1v2.8q0 0.6 0.5 1t1 0.5h5.7v5.7q0 0.5 0.4 1t1 0.4h2.9q0.6 0 1-0.4t0.4-1v-5.7h5.7q0.6 0 1-0.5t0.4-1z m7.2-1.4q0 4.7-2.3 8.6t-6.3 6.2-8.6 2.3-8.6-2.3-6.2-6.2-2.3-8.6 2.3-8.6 6.2-6.2 8.6-2.3 8.6 2.3 6.3 6.2 2.3 8.6z"}))))}}]),n})(r.a.PureComponent),$e=(function(l){b(n,l);var u=L(n);function n(){return p(this,n),u.apply(this,arguments)}return h(n,[{key:"render",value:function(){var o=this.props,i=o.style,y=k(o,["style"]);return r.a.createElement("span",y,r.a.createElement("svg",Object.assign({},se(i),{viewBox:"0 0 40 40",fill:"currentColor",preserveAspectRatio:"xMidYMid meet"}),r.a.createElement("g",null,r.a.createElement("path",{d:"m31.6 21.6h-10v10h-3.2v-10h-10v-3.2h10v-10h3.2v10h10v3.2z"}))))}}]),n})(r.a.PureComponent),ze=(function(l){b(n,l);var u=L(n);function n(){return p(this,n),u.apply(this,arguments)}return h(n,[{key:"render",value:function(){var o=this.props,i=o.style,y=k(o,["style"]);return r.a.createElement("span",y,r.a.createElement("svg",Object.assign({},se(i),{viewBox:"0 0 40 40",fill:"currentColor",preserveAspectRatio:"xMidYMid meet"}),r.a.createElement("g",null,r.a.createElement("path",{d:"m19.8 26.4l2.6-2.6-3.4-3.4-2.6 2.6v1.3h2.2v2.1h1.2z m9.8-16q-0.3-0.4-0.7 0l-7.8 7.8q-0.4 0.4 0 0.7t0.7 0l7.8-7.8q0.4-0.4 0-0.7z m1.8 13.2v4.3q0 2.6-1.9 4.5t-4.5 1.9h-18.6q-2.6 0-4.5-1.9t-1.9-4.5v-18.6q0-2.7 1.9-4.6t4.5-1.8h18.6q1.4 0 2.6 0.5 0.3 0.2 0.4 0.5 0.1 0.4-0.2 0.7l-1.1 1.1q-0.3 0.3-0.7 0.1-0.5-0.1-1-0.1h-18.6q-1.4 0-2.5 1.1t-1 2.5v18.6q0 1.4 1 2.5t2.5 1h18.6q1.5 0 2.5-1t1.1-2.5v-2.9q0-0.2 0.2-0.4l1.4-1.5q0.3-0.3 0.8-0.1t0.4 0.6z m-2.1-16.5l6.4 6.5-15 15h-6.4v-6.5z m9.9 3l-2.1 2-6.4-6.4 2.1-2q0.6-0.7 1.5-0.7t1.5 0.7l3.4 3.4q0.6 0.6 0.6 1.5t-0.6 1.5z"}))))}}]),n})(r.a.PureComponent),Se=(function(l){b(n,l);var u=L(n);function n(){return p(this,n),u.apply(this,arguments)}return h(n,[{key:"render",value:function(){var o=this.props,i=o.style,y=k(o,["style"]);return r.a.createElement("span",y,r.a.createElement("svg",Object.assign({},se(i),{viewBox:"0 0 40 40",fill:"currentColor",preserveAspectRatio:"xMidYMid meet"}),r.a.createElement("g",null,r.a.createElement("path",{d:"m31.7 16.4q0-0.6-0.4-1l-2.1-2.1q-0.4-0.4-1-0.4t-1 0.4l-9.1 9.1-5-5q-0.5-0.4-1-0.4t-1 0.4l-2.1 2q-0.4 0.4-0.4 1 0 0.6 0.4 1l8.1 8.1q0.4 0.4 1 0.4 0.6 0 1-0.4l12.2-12.1q0.4-0.4 0.4-1z m5.6 3.6q0 4.7-2.3 8.6t-6.3 6.2-8.6 2.3-8.6-2.3-6.2-6.2-2.3-8.6 2.3-8.6 6.2-6.2 8.6-2.3 8.6 2.3 6.3 6.2 2.3 8.6z"}))))}}]),n})(r.a.PureComponent);function se(l){return l||(l={}),{style:d(d({verticalAlign:"middle"},l),{},{color:l.color?l.color:"#000000",height:"1em",width:"1em"})}}var Ae=(function(l){b(n,l);var u=L(n);function n(o){var i;return p(this,n),(i=u.call(this,o)).copiedTimer=null,i.handleCopy=function(){var y=document.createElement("textarea"),O=i.props,_=O.clickCallback,m=O.src,P=O.namespace;y.innerHTML=JSON.stringify(i.clipboardValue(m),null," "),document.body.appendChild(y),y.select(),document.execCommand("copy"),document.body.removeChild(y),i.copiedTimer=setTimeout((function(){i.setState({copied:!1})}),5500),i.setState({copied:!0},(function(){typeof _=="function"&&_({src:m,namespace:P,name:P[P.length-1]})}))},i.getClippyIcon=function(){var y=i.props.theme;return i.state.copied?r.a.createElement("span",null,r.a.createElement(me,Object.assign({className:"copy-icon"},C(y,"copy-icon"))),r.a.createElement("span",C(y,"copy-icon-copied"),"✔")):r.a.createElement(me,Object.assign({className:"copy-icon"},C(y,"copy-icon")))},i.clipboardValue=function(y){switch(A(y)){case"function":case"regexp":return y.toString();default:return y}},i.state={copied:!1},i}return h(n,[{key:"componentWillUnmount",value:function(){this.copiedTimer&&(clearTimeout(this.copiedTimer),this.copiedTimer=null)}},{key:"render",value:function(){var o=this.props,i=(o.src,o.theme),y=o.hidden,O=o.rowHovered,_=C(i,"copy-to-clipboard").style,m="inline";return y&&(m="none"),r.a.createElement("span",{className:"copy-to-clipboard-container",title:"Copy to clipboard",style:{verticalAlign:"top",display:O?"inline-block":"none"}},r.a.createElement("span",{style:d(d({},_),{},{display:m}),onClick:this.handleCopy},this.getClippyIcon()))}}]),n})(r.a.PureComponent),Me=(function(l){b(n,l);var u=L(n);function n(o){var i;return p(this,n),(i=u.call(this,o)).getEditIcon=function(){var y=i.props,O=y.variable,_=y.theme;return r.a.createElement("div",{className:"click-to-edit",style:{verticalAlign:"top",display:i.state.hovered?"inline-block":"none"}},r.a.createElement(ze,Object.assign({className:"click-to-edit-icon"},C(_,"editVarIcon"),{onClick:function(){i.prepopInput(O)}})))},i.prepopInput=function(y){if(i.props.onEdit!==!1){var O=(function(m){var P;switch(A(m)){case"undefined":P="undefined";break;case"nan":P="NaN";break;case"string":P=m;break;case"date":case"function":case"regexp":P=m.toString();break;default:try{P=JSON.stringify(m,null," ")}catch{P=""}}return P})(y.value),_=B(O);i.setState({editMode:!0,editValue:O,parsedInput:{type:_.type,value:_.value}})}},i.getRemoveIcon=function(){var y=i.props,O=y.variable,_=y.namespace,m=y.theme,P=y.rjvId;return r.a.createElement("div",{className:"click-to-remove",style:{verticalAlign:"top",display:i.state.hovered?"inline-block":"none"}},r.a.createElement(Pe,Object.assign({className:"click-to-remove-icon"},C(m,"removeVarIcon"),{onClick:function(){Ee.dispatch({name:"VARIABLE_REMOVED",rjvId:P,data:{name:O.name,namespace:_,existing_value:O.value,variable_removed:!0}})}})))},i.getValue=function(y,O){var _=!O&&y.type,m=R(i).props;switch(_){case!1:return i.getEditInput();case"string":return r.a.createElement(tt,Object.assign({value:y.value},m));case"integer":return r.a.createElement(Xe,Object.assign({value:y.value},m));case"float":return r.a.createElement(U,Object.assign({value:y.value},m));case"boolean":return r.a.createElement(be,Object.assign({value:y.value},m));case"function":return r.a.createElement(ge,Object.assign({value:y.value},m));case"null":return r.a.createElement(Ue,m);case"nan":return r.a.createElement(De,m);case"undefined":return r.a.createElement(at,m);case"date":return r.a.createElement(ce,Object.assign({value:y.value},m));case"regexp":return r.a.createElement(et,Object.assign({value:y.value},m));default:return r.a.createElement("div",{className:"object-value"},JSON.stringify(y.value))}},i.getEditInput=function(){var y=i.props.theme,O=i.state.editValue;return r.a.createElement("div",null,r.a.createElement(N,Object.assign({type:"text",inputRef:function(_){return _&&_.focus()},value:O,className:"variable-editor",onChange:function(_){var m=_.target.value,P=B(m);i.setState({editValue:m,parsedInput:{type:P.type,value:P.value}})},onKeyDown:function(_){switch(_.key){case"Escape":i.setState({editMode:!1,editValue:""});break;case"Enter":(_.ctrlKey||_.metaKey)&&i.submitEdit(!0)}_.stopPropagation()},placeholder:"update this value",minRows:2},C(y,"edit-input"))),r.a.createElement("div",C(y,"edit-icon-container"),r.a.createElement(Pe,Object.assign({className:"edit-cancel"},C(y,"cancel-icon"),{onClick:function(){i.setState({editMode:!1,editValue:""})}})),r.a.createElement(Se,Object.assign({className:"edit-check string-value"},C(y,"check-icon"),{onClick:function(){i.submitEdit()}})),r.a.createElement("div",null,i.showDetected())))},i.submitEdit=function(y){var O=i.props,_=O.variable,m=O.namespace,P=O.rjvId,$=i.state,ne=$.editValue,oe=$.parsedInput,pe=ne;y&&oe.type&&(pe=oe.value),i.setState({editMode:!1}),Ee.dispatch({name:"VARIABLE_UPDATED",rjvId:P,data:{name:_.name,namespace:m,existing_value:_.value,new_value:pe,variable_removed:!1}})},i.showDetected=function(){var y=i.props,O=y.theme,_=(y.variable,y.namespace,y.rjvId,i.state.parsedInput),m=(_.type,_.value,i.getDetectedInput());if(m)return r.a.createElement("div",null,r.a.createElement("div",C(O,"detected-row"),m,r.a.createElement(Se,{className:"edit-check detected",style:d({verticalAlign:"top",paddingLeft:"3px"},C(O,"check-icon").style),onClick:function(){i.submitEdit(!0)}})))},i.getDetectedInput=function(){var y=i.state.parsedInput,O=y.type,_=y.value,m=R(i).props,P=m.theme;if(O!==!1)switch(O.toLowerCase()){case"object":return r.a.createElement("span",null,r.a.createElement("span",{style:d(d({},C(P,"brace").style),{},{cursor:"default"})},"{"),r.a.createElement("span",{style:d(d({},C(P,"ellipsis").style),{},{cursor:"default"})},"..."),r.a.createElement("span",{style:d(d({},C(P,"brace").style),{},{cursor:"default"})},"}"));case"array":return r.a.createElement("span",null,r.a.createElement("span",{style:d(d({},C(P,"brace").style),{},{cursor:"default"})},"["),r.a.createElement("span",{style:d(d({},C(P,"ellipsis").style),{},{cursor:"default"})},"..."),r.a.createElement("span",{style:d(d({},C(P,"brace").style),{},{cursor:"default"})},"]"));case"string":return r.a.createElement(tt,Object.assign({value:_},m));case"integer":return r.a.createElement(Xe,Object.assign({value:_},m));case"float":return r.a.createElement(U,Object.assign({value:_},m));case"boolean":return r.a.createElement(be,Object.assign({value:_},m));case"function":return r.a.createElement(ge,Object.assign({value:_},m));case"null":return r.a.createElement(Ue,m);case"nan":return r.a.createElement(De,m);case"undefined":return r.a.createElement(at,m);case"date":return r.a.createElement(ce,Object.assign({value:new Date(_)},m))}},i.state={editMode:!1,editValue:"",hovered:!1,renameKey:!1,parsedInput:{type:!1,value:null}},i}return h(n,[{key:"render",value:function(){var o=this,i=this.props,y=i.variable,O=i.singleIndent,_=i.type,m=i.theme,P=i.namespace,$=i.indentWidth,ne=i.enableClipboard,oe=i.onEdit,pe=i.onDelete,ae=i.onSelect,de=i.displayArrayKey,je=i.quotesOnKeys,G=this.state.editMode;return r.a.createElement("div",Object.assign({},C(m,"objectKeyVal",{paddingLeft:$*O}),{onMouseEnter:function(){return o.setState(d(d({},o.state),{},{hovered:!0}))},onMouseLeave:function(){return o.setState(d(d({},o.state),{},{hovered:!1}))},className:"variable-row",key:y.name}),_=="array"?de?r.a.createElement("span",Object.assign({},C(m,"array-key"),{key:y.name+"_"+P}),y.name,r.a.createElement("div",C(m,"colon"),":")):null:r.a.createElement("span",null,r.a.createElement("span",Object.assign({},C(m,"object-name"),{className:"object-key",key:y.name+"_"+P}),!!je&&r.a.createElement("span",{style:{verticalAlign:"top"}},'"'),r.a.createElement("span",{style:{display:"inline-block"}},y.name),!!je&&r.a.createElement("span",{style:{verticalAlign:"top"}},'"')),r.a.createElement("span",C(m,"colon"),":")),r.a.createElement("div",Object.assign({className:"variable-value",onClick:ae===!1&&oe===!1?null:function(_e){var Le=ve(P);(_e.ctrlKey||_e.metaKey)&&oe!==!1?o.prepopInput(y):ae!==!1&&(Le.shift(),ae(d(d({},y),{},{namespace:Le})))}},C(m,"variableValue",{cursor:ae===!1?"default":"pointer"})),this.getValue(y,G)),ne?r.a.createElement(Ae,{rowHovered:this.state.hovered,hidden:G,src:y.value,clickCallback:ne,theme:m,namespace:[].concat(ve(P),[y.name])}):null,oe!==!1&&G==0?this.getEditIcon():null,pe!==!1&&G==0?this.getRemoveIcon():null)}}]),n})(r.a.PureComponent),Je=(function(l){b(n,l);var u=L(n);function n(){var o;p(this,n);for(var i=arguments.length,y=new Array(i),O=0;O0?ne:null,namespace:$.splice(0,$.length-1),existing_value:oe,variable_removed:!1,key_name:null};A(oe)==="object"?Ee.dispatch({name:"ADD_VARIABLE_KEY_REQUEST",rjvId:pe,data:de}):Ee.dispatch({name:"VARIABLE_ADDED",rjvId:pe,data:d(d({},de),{},{new_value:[].concat(ve(oe),[null])})})}})))},o.getRemoveObject=function(_){var m=o.props,P=m.theme,$=(m.hover,m.namespace),ne=m.name,oe=m.src,pe=m.rjvId;if($.length!==1)return r.a.createElement("span",{className:"click-to-remove",style:{display:_?"inline-block":"none"}},r.a.createElement(Pe,Object.assign({className:"click-to-remove-icon"},C(P,"removeVarIcon"),{onClick:function(){Ee.dispatch({name:"VARIABLE_REMOVED",rjvId:pe,data:{name:ne,namespace:$.splice(0,$.length-1),existing_value:oe,variable_removed:!0}})}})))},o.render=function(){var _=o.props,m=_.theme,P=_.onDelete,$=_.onAdd,ne=_.enableClipboard,oe=_.src,pe=_.namespace,ae=_.rowHovered;return r.a.createElement("div",Object.assign({},C(m,"object-meta-data"),{className:"object-meta-data",onClick:function(de){de.stopPropagation()}}),o.getObjectSize(),ne?r.a.createElement(Ae,{rowHovered:ae,clickCallback:ne,src:oe,theme:m,namespace:pe}):null,$!==!1?o.getAddAttribute(ae):null,P!==!1?o.getRemoveObject(ae):null)},o}return n})(r.a.PureComponent);function qe(l){var u=l.parent_type,n=l.namespace,o=l.quotesOnKeys,i=l.theme,y=l.jsvRoot,O=l.name,_=l.displayArrayKey,m=l.name?l.name:"";return!y||O!==!1&&O!==null?u=="array"?_?r.a.createElement("span",Object.assign({},C(i,"array-key"),{key:n}),r.a.createElement("span",{className:"array-key"},m),r.a.createElement("span",C(i,"colon"),":")):r.a.createElement("span",null):r.a.createElement("span",Object.assign({},C(i,"object-name"),{key:n}),r.a.createElement("span",{className:"object-key"},o&&r.a.createElement("span",{style:{verticalAlign:"top"}},'"'),r.a.createElement("span",null,m),o&&r.a.createElement("span",{style:{verticalAlign:"top"}},'"')),r.a.createElement("span",C(i,"colon"),":")):r.a.createElement("span",null)}function Be(l){var u=l.theme;switch(l.iconStyle){case"triangle":return r.a.createElement(Ie,Object.assign({},C(u,"expanded-icon"),{className:"expanded-icon"}));case"square":return r.a.createElement(ue,Object.assign({},C(u,"expanded-icon"),{className:"expanded-icon"}));default:return r.a.createElement(re,Object.assign({},C(u,"expanded-icon"),{className:"expanded-icon"}))}}function We(l){var u=l.theme;switch(l.iconStyle){case"triangle":return r.a.createElement(xe,Object.assign({},C(u,"collapsed-icon"),{className:"collapsed-icon"}));case"square":return r.a.createElement(ye,Object.assign({},C(u,"collapsed-icon"),{className:"collapsed-icon"}));default:return r.a.createElement(te,Object.assign({},C(u,"collapsed-icon"),{className:"collapsed-icon"}))}}var lt=(function(l){b(n,l);var u=L(n);function n(o){var i;return p(this,n),(i=u.call(this,o)).toggleCollapsed=function(y){var O=[];for(var _ in i.state.expanded)O.push(i.state.expanded[_]);O[y]=!O[y],i.setState({expanded:O})},i.state={expanded:[]},i}return h(n,[{key:"getExpandedIcon",value:function(o){var i=this.props,y=i.theme,O=i.iconStyle;return this.state.expanded[o]?r.a.createElement(Be,{theme:y,iconStyle:O}):r.a.createElement(We,{theme:y,iconStyle:O})}},{key:"render",value:function(){var o=this,i=this.props,y=i.src,O=i.groupArraysAfterLength,_=(i.depth,i.name),m=i.theme,P=i.jsvRoot,$=i.namespace,ne=(i.parent_type,k(i,["src","groupArraysAfterLength","depth","name","theme","jsvRoot","namespace","parent_type"])),oe=0,pe=5*this.props.indentWidth;P||(oe=5*this.props.indentWidth);var ae=O,de=Math.ceil(y.length/ae);return r.a.createElement("div",Object.assign({className:"object-key-val"},C(m,P?"jsv-root":"objectKeyVal",{paddingLeft:oe})),r.a.createElement(qe,this.props),r.a.createElement("span",null,r.a.createElement(Je,Object.assign({size:y.length},this.props))),ve(Array(de)).map((function(je,G){return r.a.createElement("div",Object.assign({key:G,className:"object-key-val array-group"},C(m,"objectKeyVal",{marginLeft:6,paddingLeft:pe})),r.a.createElement("span",C(m,"brace-row"),r.a.createElement("div",Object.assign({className:"icon-container"},C(m,"icon-container"),{onClick:function(_e){o.toggleCollapsed(G)}}),o.getExpandedIcon(G)),o.state.expanded[G]?r.a.createElement(mt,Object.assign({key:_+G,depth:0,name:!1,collapsed:!1,groupArraysAfterLength:ae,index_offset:G*ae,src:y.slice(G*ae,G*ae+ae),namespace:$,type:"array",parent_type:"array_group",theme:m},ne)):r.a.createElement("span",Object.assign({},C(m,"brace"),{onClick:function(_e){o.toggleCollapsed(G)},className:"array-group-brace"}),"[",r.a.createElement("div",Object.assign({},C(m,"array-group-meta-data"),{className:"array-group-meta-data"}),r.a.createElement("span",Object.assign({className:"object-size"},C(m,"object-size")),G*ae," - ",G*ae+ae>y.length?y.length:G*ae+ae)),"]")))})))}}]),n})(r.a.PureComponent),bt=(function(l){b(n,l);var u=L(n);function n(o){var i;p(this,n),(i=u.call(this,o)).toggleCollapsed=function(){i.setState({expanded:!i.state.expanded},(function(){fe.set(i.props.rjvId,i.props.namespace,"expanded",i.state.expanded)}))},i.getObjectContent=function(O,_,m){return r.a.createElement("div",{className:"pushed-content object-container"},r.a.createElement("div",Object.assign({className:"object-content"},C(i.props.theme,"pushed-content")),i.renderObjectContents(_,m)))},i.getEllipsis=function(){return i.state.size===0?null:r.a.createElement("div",Object.assign({},C(i.props.theme,"ellipsis"),{className:"node-ellipsis",onClick:i.toggleCollapsed}),"...")},i.getObjectMetaData=function(O){var _=i.props,m=(_.rjvId,_.theme,i.state),P=m.size,$=m.hovered;return r.a.createElement(Je,Object.assign({rowHovered:$,size:P},i.props))},i.renderObjectContents=function(O,_){var m,P=i.props,$=P.depth,ne=P.parent_type,oe=P.index_offset,pe=P.groupArraysAfterLength,ae=P.namespace,de=i.state.object_type,je=[],G=Object.keys(O||{});return i.props.sortKeys&&de!=="array"&&(G=G.sort()),G.forEach((function(_e){if(m=new qt(_e,O[_e]),ne==="array_group"&&oe&&(m.name=parseInt(m.name)+oe),O.hasOwnProperty(_e))if(m.type==="object")je.push(r.a.createElement(mt,Object.assign({key:m.name,depth:$+1,name:m.name,src:m.value,namespace:ae.concat(m.name),parent_type:de},_)));else if(m.type==="array"){var Le=mt;pe&&m.value.length>pe&&(Le=lt),je.push(r.a.createElement(Le,Object.assign({key:m.name,depth:$+1,name:m.name,src:m.value,namespace:ae.concat(m.name),type:"array",parent_type:de},_)))}else je.push(r.a.createElement(Me,Object.assign({key:m.name+"_"+ae,variable:m,singleIndent:5,namespace:ae,type:i.props.type},_)))})),je};var y=n.getState(o);return i.state=d(d({},y),{},{prevProps:{}}),i}return h(n,[{key:"getBraceStart",value:function(o,i){var y=this,O=this.props,_=O.src,m=O.theme,P=O.iconStyle;if(O.parent_type==="array_group")return r.a.createElement("span",null,r.a.createElement("span",C(m,"brace"),o==="array"?"[":"{"),i?this.getObjectMetaData(_):null);var $=i?Be:We;return r.a.createElement("span",null,r.a.createElement("span",Object.assign({onClick:function(ne){y.toggleCollapsed()}},C(m,"brace-row")),r.a.createElement("div",Object.assign({className:"icon-container"},C(m,"icon-container")),r.a.createElement($,{theme:m,iconStyle:P})),r.a.createElement(qe,this.props),r.a.createElement("span",C(m,"brace"),o==="array"?"[":"{")),i?this.getObjectMetaData(_):null)}},{key:"render",value:function(){var o=this,i=this.props,y=i.depth,O=i.src,_=(i.namespace,i.name,i.type,i.parent_type),m=i.theme,P=i.jsvRoot,$=i.iconStyle,ne=k(i,["depth","src","namespace","name","type","parent_type","theme","jsvRoot","iconStyle"]),oe=this.state,pe=oe.object_type,ae=oe.expanded,de={};return P||_==="array_group"?_==="array_group"&&(de.borderLeft=0,de.display="inline"):de.paddingLeft=5*this.props.indentWidth,r.a.createElement("div",Object.assign({className:"object-key-val",onMouseEnter:function(){return o.setState(d(d({},o.state),{},{hovered:!0}))},onMouseLeave:function(){return o.setState(d(d({},o.state),{},{hovered:!1}))}},C(m,P?"jsv-root":"objectKeyVal",de)),this.getBraceStart(pe,ae),ae?this.getObjectContent(y,O,d({theme:m,iconStyle:$},ne)):this.getEllipsis(),r.a.createElement("span",{className:"brace-row"},r.a.createElement("span",{style:d(d({},C(m,"brace").style),{},{paddingLeft:ae?"3px":"0px"})},pe==="array"?"]":"}"),ae?null:this.getObjectMetaData(O)))}}],[{key:"getDerivedStateFromProps",value:function(o,i){var y=i.prevProps;return o.src!==y.src||o.collapsed!==y.collapsed||o.name!==y.name||o.namespace!==y.namespace||o.rjvId!==y.rjvId?d(d({},n.getState(o)),{},{prevProps:o}):null}}]),n})(r.a.PureComponent);bt.getState=function(l){var u=Object.keys(l.src).length,n=(l.collapsed===!1||l.collapsed!==!0&&l.collapsed>l.depth)&&(!l.shouldCollapse||l.shouldCollapse({name:l.name,src:l.src,type:A(l.src),namespace:l.namespace})===!1)&&u!==0;return{expanded:fe.get(l.rjvId,l.namespace,"expanded",n),object_type:l.type==="array"?"array":"object",parent_type:l.type==="array"?"array":"object",size:u,hovered:!1}};var qt=function l(u,n){p(this,l),this.name=u,this.value=n,this.type=A(n)};q(bt);var mt=bt,Wt=(function(l){b(n,l);var u=L(n);function n(){var o;p(this,n);for(var i=arguments.length,y=new Array(i),O=0;O_.groupArraysAfterLength&&(P=lt),r.a.createElement("div",{className:"pretty-json-container object-container"},r.a.createElement("div",{className:"object-content"},r.a.createElement(P,Object.assign({namespace:m,depth:0,jsvRoot:!0},_))))},o}return n})(r.a.PureComponent),Kt=(function(l){b(n,l);var u=L(n);function n(o){var i;return p(this,n),(i=u.call(this,o)).closeModal=function(){Ee.dispatch({rjvId:i.props.rjvId,name:"RESET"})},i.submit=function(){i.props.submit(i.state.input)},i.state={input:o.input?o.input:""},i}return h(n,[{key:"render",value:function(){var o=this,i=this.props,y=i.theme,O=i.rjvId,_=i.isValid,m=this.state.input,P=_(m);return r.a.createElement("div",Object.assign({className:"key-modal-request"},C(y,"key-modal-request"),{onClick:this.closeModal}),r.a.createElement("div",Object.assign({},C(y,"key-modal"),{onClick:function($){$.stopPropagation()}}),r.a.createElement("div",C(y,"key-modal-label"),"Key Name:"),r.a.createElement("div",{style:{position:"relative"}},r.a.createElement("input",Object.assign({},C(y,"key-modal-input"),{className:"key-modal-input",ref:function($){return $&&$.focus()},spellCheck:!1,value:m,placeholder:"...",onChange:function($){o.setState({input:$.target.value})},onKeyPress:function($){P&&$.key==="Enter"?o.submit():$.key==="Escape"&&o.closeModal()}})),P?r.a.createElement(Se,Object.assign({},C(y,"key-modal-submit"),{className:"key-modal-submit",onClick:function($){return o.submit()}})):null),r.a.createElement("span",C(y,"key-modal-cancel"),r.a.createElement($e,Object.assign({},C(y,"key-modal-cancel-icon"),{className:"key-modal-cancel",onClick:function(){Ee.dispatch({rjvId:O,name:"RESET"})}})))))}}]),n})(r.a.PureComponent),$t=(function(l){b(n,l);var u=L(n);function n(){var o;p(this,n);for(var i=arguments.length,y=new Array(i),O=0;O({color:Z.palette.mode==="dark"?"#CCC":"#333"}),frameTextSecondary:{fontStyle:"italic",fontSize:12,opacity:.6,pl:1},listRoot:{padding:0,fontSize:"small"},scopeType:{verticalAlign:"top",textTransform:"uppercase",width:50},scopeType_local:{color:"#53a944"},scopeType_closure:{color:"#365b80"},scopeType_user:{color:"#a48a15"},scopeName:{color:"#bc5b5b",width:"calc(100% - 82px)",whiteSpace:"nowrap",textOverflow:"ellipsis"},scopeButton:{width:32},scopeValueEditable:{cursor:"pointer"},selectedFrame:{backgroundColor:"#777",color:"white"},splitter:{width:"100%",height:"calc(100% - 36px)",overflow:"hidden",fontSize:12},toolbarScopes:Z=>({width:24,display:"inline-block",height:"100%",background:Z.palette.mode==="dark"?"#222":"#EEE",verticalAlign:"top"}),scopesAfterToolbar:{width:"calc(100% - 24px)",display:"inline-block",height:"100%",verticalAlign:"top"},scopeNameName:{fontWeight:"bold",display:"inline-block",verticalAlign:"top"},scopeNameEqual:Z=>({display:"inline-block",color:Z.palette.mode==="dark"?"#EEE":"#222",verticalAlign:"top"}),scopeNameValue:{verticalAlign:"top",display:"inline-block",color:"#3b709f",whiteSpace:"nowrap"},scopeButtonDel:{padding:0,float:"right"},valueNull:{color:"#a44a24"},valueUndefined:{color:"#a44a24"},valueString:{color:"#1e8816"},valueNumber:{color:"#163c88"},valueBoolean:{color:"#a44a24"},valueObject:{color:"#721b70"},valueNone:{color:"#8a8a8a"},valueFunc:{color:"#ac4343"},error:Z=>({color:Z.palette.mode==="dark"?"#FF8080":"#FF0000",fontStyle:"italic"})};function xa(Z){var g,a;const v={};return Z.className==="ReferenceError"?Z.description:((a=(g=Z.preview)==null?void 0:g.properties)==null||a.forEach(t=>{(t==null?void 0:t.type)==="object"?t.subtype==="null"?v[t.name]=null:v[t.name]=`{ ${t.value==="Object"?"...":t.value} }`:t.type==="boolean"?v[t.name||t.description]=t.value==="true":t.type==="number"?v[t.name||t.description]=parseFloat(t.value):t.type==="function"?v[t.name||t.description]="function(){}":t.type==="undefined"?v[t.name||t.description]=void 0:v[t.name||t.description]=t.value}),v)}class ja extends ft.Component{editRef;scopeValue=null;constructor(v){super(v);const g=window.localStorage.getItem("JS.framesSizes");let a=[30,70];if(g)try{a=JSON.parse(g)}catch{}this.state={editValue:null,callFrames:this.props.callFrames,framesSizes:a},this.editRef=ft.createRef()}onExpressionNameUpdate(){this.state.editValue&&this.props.onExpressionNameUpdate(this.state.editValue.index,this.scopeValue,()=>{this.setState({editValue:null}),this.scopeValue=null})}renderExpression(v,g){const a=this.state.editValue&&this.state.editValue.type==="expression"&&this.state.editValue.index===g?M.jsx(Nt,{inputRef:this.editRef,fullWidth:!0,margin:"dense",onBlur:()=>this.state.editValue&&this.setState({editValue:null}),defaultValue:v.name,onKeyUp:t=>{t.key==="Enter"?this.onExpressionNameUpdate():t.key==="Escape"&&this.setState({editValue:null})},onChange:t=>this.scopeValue=t.target.value,endAdornment:M.jsx(Mt,{position:"end",children:M.jsx(Te,{onClick:()=>this.onExpressionNameUpdate(),size:"medium",children:M.jsx(Tt,{})})})}):[M.jsx("div",{style:ie.scopeNameName,title:we.I18n.t("Double click to edit expression"),children:v.name},"name"),M.jsxs(Ze,{sx:ie.scopeNameEqual,children:[" ","="," "]},"="),M.jsx("div",{style:ie.scopeNameValue,children:this.formatValue(v.value)},"val")];return M.jsxs("tr",{children:[M.jsx("td",{style:{...ie.scopeType,...ie.scopeType_user},children:"user"}),M.jsx("td",{style:ie.scopeName,onDoubleClick:()=>{this.scopeValue=v.name||"",this.setState({editValue:{type:"expression",valueType:"string",index:g,name:v.name,value:v.name||""}})},children:a}),M.jsx(Te,{style:ie.scopeButtonDel,size:"small",disabled:!!this.state.editValue,onClick:()=>this.props.onExpressionDelete(g),children:M.jsx(ta,{})})]},`user_${g}${v.name}`)}renderExpressions(){return this.props.expressions.map((v,g)=>this.renderExpression(v,g))}renderOneFrameTitle(v,g){if(this.props.mainScriptId===this.props.currentScriptId&&v.location.scriptId!==this.props.mainScriptId)return null;const a=(v.url.split("/").pop()||"").replace(/^script\.js\./,"");return M.jsx(Lt,{onClick:()=>this.props.onChangeCurrentFrame(g),dense:!0,selected:this.props.currentFrame===g,style:ie.frameRoot,children:M.jsx(Vt,{sx:{...ie.frameTextRoot,"& .MuiListItemText-primary":ie.frameTextPrimary,"& .MuiListItemText-secondary":ie.frameTextSecondary},title:v.url,primary:v.functionName||"anonymous",secondary:`${a} (${v.location.lineNumber}:${v.location.columnNumber})`})},v.callFrameId)}formatValue(v,g){if(!v)return g?"none":M.jsx("span",{style:ie.valueNone,children:"none"});if(v.type==="undefined")return g?"undefined":M.jsx("span",{style:ie.valueUndefined,children:"undefined"});if(v.type==="null")return g?"null":M.jsx("span",{style:ie.valueNull,children:"null"});if(v.type==="function"){const a=v.description?v.description.length>100?`${v.description.substring(0,100)}...`:v.description:"function";return g?a:M.jsx("span",{style:ie.valueFunc,title:v.description,children:a})}if(v.type==="object"){const a=xa(v);return g?JSON.stringify(a):typeof a=="string"?M.jsx(Ze,{component:"span",sx:ie.error,children:a}):M.jsx(ya,{name:!1,enableClipboard:!1,style:{backgroundColor:"inherit",marginTop:3},src:a,collapsed:!0,theme:this.props.themeType==="dark"?"brewer":"rjv-default",displayDataTypes:!1})}if(v.value===void 0)return g?"undefined":M.jsx("span",{style:ie.valueUndefined,children:"undefined"});if(v.value===null)return g?"null":M.jsx("span",{style:ie.valueNull,children:"null"});if(v.type==="string"){if(g)return v.value;const a=`"${v.value?v.value.length>100?`${v.value.substring(0,100)}...`:v.value:""}"`;return M.jsx("span",{style:ie.valueString,title:a,children:a})}return v.type==="boolean"?g?v.value.toString():M.jsx("span",{style:ie.valueBoolean,children:v.value.toString()}):v.value.toString()}onWriteScopeValue(){var v,g;this.scopeValue==="true"?this.scopeValue=!0:this.scopeValue==="false"?this.scopeValue=!1:this.scopeValue==="null"?this.scopeValue=null:this.scopeValue==="undefined"?this.scopeValue=void 0:parseFloat(this.scopeValue).toString()===this.scopeValue&&(this.scopeValue=parseFloat(this.scopeValue)),this.props.onWriteScopeValue({variableName:((v=this.state.editValue)==null?void 0:v.name)||"",scopeNumber:0,newValue:{value:this.scopeValue,valueType:typeof this.scopeValue},callFrameId:(g=this.props.callFrames)==null?void 0:g[this.props.currentFrame].callFrameId}),this.setState({editValue:null}),this.scopeValue=null}componentDidUpdate(){var v;(v=this.editRef.current)==null||v.focus()}renderScope(v,g,a){var s,c,d,p;const t=!this.props.currentFrame&&g.value&&(g.value.type==="undefined"||g.value.type==="string"||g.value.type==="number"||g.value.type==="boolean"||((s=g.value)==null?void 0:s.value)===null||((c=g.value)==null?void 0:c.value)===void 0&&g.value.type!=="object"),e=((d=this.state.editValue)==null?void 0:d.type)===a&&((p=this.state.editValue)==null?void 0:p.name)===g.name?[M.jsx("div",{style:ie.scopeNameName,children:g.name},"name"),M.jsxs(Ze,{sx:ie.scopeNameEqual,children:[" ","="," "]},"="),M.jsx(Nt,{inputRef:this.editRef,margin:"dense",onBlur:()=>this.state.editValue&&this.setState({editValue:null}),defaultValue:this.formatValue(g.value,!0),onKeyUp:f=>{f.key==="Enter"?this.onWriteScopeValue():f.key==="Escape"&&this.setState({editValue:null})},onChange:f=>this.scopeValue=f.target.value,endAdornment:M.jsx(Mt,{position:"end",children:M.jsx(Te,{onClick:()=>this.onWriteScopeValue(),size:"medium",children:M.jsx(Tt,{})})})},"input")]:[M.jsx("div",{style:ie.scopeNameName,title:we.I18n.t("Double click to write value"),children:g.name},"name"),M.jsxs(Ze,{sx:ie.scopeNameEqual,children:[" ","="," "]},"="),M.jsxs("div",{style:ie.scopeNameValue,children:[this.formatValue(g.value)," (",g.value.type,")"]},"val")];return M.jsxs("tr",{children:[M.jsx("td",{style:{...ie.scopeType,...ie[`scopeType_${a}`]},children:a}),M.jsx("td",{style:{...ie.scopeName,...!this.props.currentFrame&&t?ie.scopeValueEditable:void 0},onDoubleClick:()=>{t&&(this.scopeValue=g.value.value,this.setState({editValue:{scopeId:v,type:a,index:0,valueType:g.value.type,name:g.name,value:g.value.value}}))},children:e})]},`${a}_${v}_${g.name}`)}renderScopes(v){var t,e,s,c,d,p;if(!v)return null;const g=this.renderExpressions();let a=(s=(e=(t=this.props.scopes)==null?void 0:t.local)==null?void 0:e.properties)==null?void 0:s.result.map(f=>this.props.scopes&&this.renderScope("",f,"local"));return a==null||a.forEach(f=>f&&g.push(f)),a=(p=(d=(c=this.props.scopes)==null?void 0:c.closure)==null?void 0:d.properties)==null?void 0:p.result.map(f=>this.props.scopes&&this.renderScope("",f,"closure")),a==null||a.forEach(f=>f&&g.push(f)),M.jsx("table",{style:{width:"100%",fontSize:"small"},children:M.jsx("tbody",{children:g})})}render(){var v,g;return M.jsxs(Rt,{direction:Bt.Horizontal,initialSizes:this.state.framesSizes,minWidths:[100,200],onResizeFinished:(a,t)=>{this.setState({framesSizes:t}),window.localStorage.setItem("JS.framesSizes",JSON.stringify(t))},gutterClassName:this.props.themeType==="dark"?"Dark visGutter":"Light visGutter",children:[M.jsx("div",{style:{width:"100%",height:"100%",overflow:"auto"},children:M.jsx(zt,{style:ie.listRoot,children:((v=this.props.callFrames)==null?void 0:v.map((a,t)=>this.renderOneFrameTitle(a,t)))||null})}),M.jsxs("div",{style:{width:"100%",height:"100%",overflow:"auto"},children:[M.jsx(Ze,{sx:ie.toolbarScopes,children:M.jsx(Te,{size:"small",onClick:()=>this.props.onExpressionAdd((a,t)=>{this.scopeValue=t.name||"",this.setState({editValue:{type:"expression",valueType:"string",index:a,name:t.name,value:t.name||""}})}),children:M.jsx(aa,{})})}),M.jsx("div",{style:ie.scopesAfterToolbar,children:((g=this.props.callFrames)==null?void 0:g.length)&&this.renderScopes(this.props.callFrames[this.props.currentFrame])})]})]})}}const ke={root:Z=>({width:"100%",height:`calc(100% - ${parseInt(Z.toolbar.height,10)+38+5}px)`,overflow:"hidden",position:"relative"}),toolbar:{minHeight:38,boxShadow:"0px 2px 4px -1px rgba(0, 0, 0, 0.2), 0px 4px 5px 0px rgba(0, 0, 0, 0.14), 0px 1px 10px 0px rgba(0, 0, 0, 0.12)"},buttonRun:{color:"green"},buttonPause:{color:"orange"},buttonRestart:{color:"darkgreen"},buttonNext:{color:"blue"},buttonStep:{color:"blue"},buttonOut:{color:"blue"},buttonException:{},tabFile:Z=>({textTransform:"inherit",color:Z.palette.mode==="dark"?"#DDD":"inherit"}),tabText:{maxWidth:130,textOverflow:"ellipsis",whiteSpace:"nowrap",overflow:"hidden",display:"inline-block",verticalAlign:"middle"},closeButton:{position:"absolute",top:8,right:0,zIndex:10,padding:8,cursor:"pointer"},tabsRoot:Z=>({minHeight:24,background:Z.palette.mode==="dark"?"#333":"#e6e6e6",color:Z.palette.mode==="dark"?"white":"inherit"}),tabRoot:{minHeight:24},bpListItem:{borderTop:"1px dashed #bfbfbf44"},monospace:{fontFamily:"Courier New, monospace",whiteSpace:"pre",fontSize:12},arrow:{color:"#fffa4f"}};class Ot extends ft.Component{console=null;scripts={};mainScriptId=null;constructor(v){super(v);const g=window.localStorage.getItem(`javascript.tools.bp.${this.props.src}`);let a;try{a=g?JSON.parse(g):[]}catch{a=[]}const t=window.localStorage.getItem(`javascript.tools.exps.${this.props.src}`);let e;try{e=(t?JSON.parse(t):[]).map(p=>({name:p,value:{type:"undefined",description:"",value:"undefined",name:"name"}}))}catch{e=[]}const s=window.localStorage.getItem("JS.toolSizes");let c=[80,20];if(s)try{c=JSON.parse(s)}catch{}this.state={starting:!0,selected:null,tabs:{},script:"",breakpoints:a,expressions:e,running:!1,error:"",started:!1,paused:!0,location:null,toolsTab:window.localStorage.getItem("javascript.tools.tab")||"console",stopOnException:window.localStorage.getItem("javascript.tools.stopOnException")==="true",console:[],finished:!1,currentFrame:0,scopes:{},queryBreakpoints:null,logErrors:0,logWarnings:0,logs:0,toolSizes:c,instance:void 0,context:null}}async componentDidMount(){var g,a;let v;if(this.props.debugInstance)v=this.props.debugInstance.instance;else{const t=await this.props.socket.getObject(this.props.src);v=((a=(g=t==null?void 0:t.common)==null?void 0:g.engine)==null?void 0:a.replace("system.adapter.",""))||""}this.setState({instance:v},()=>{this.state.instance?(this.props.socket.setState(`${this.state.instance}.debug.from`,{val:'{"cmd": "subscribed"}',ack:!0}),setTimeout(()=>this.props.socket.subscribeState(`${this.state.instance}.debug.from`,this.fromInstance),200)):this.setState({error:"Unknown instance"})})}componentWillUnmount(){this.state.instance&&(this.props.socket.unsubscribeState(`${this.state.instance}.debug.from`,this.fromInstance),this.props.socket.sendTo(this.state.instance,"debugStop"))}sendToInstance(v){this.props.socket.setState(`${this.state.instance}.debug.to`,{val:JSON.stringify(v),ack:!1})}reinitBreakpoints(v){if(this.state.breakpoints.length){const a=JSON.parse(JSON.stringify(this.state.breakpoints)).map(t=>t.location);this.setState({breakpoints:[]},()=>{this.sendToInstance({breakpoints:a,cmd:"sb"}),this.state.stopOnException&&this.sendToInstance({cmd:"stopOnException",state:!0}),v&&v()})}else this.state.stopOnException&&this.sendToInstance({cmd:"stopOnException",state:!0}),v&&v()}static getLocation(v){return v.callFrames?v.callFrames[0].location:null}readCurrentScope(){var g;const v=((g=this.state.context)==null?void 0:g.callFrames)&&this.state.context.callFrames[this.state.currentFrame];if(v){const a=v.scopeChain.filter(t=>t.type!=="global");a.length?this.sendToInstance({cmd:"scope",scopes:a}):(this.state.scopes.global||this.state.scopes.local||this.state.scopes.closure)&&this.setState({scopes:{}})}}readExpressions(v){var g;this.state.expressions.length&&((g=this.state.context)!=null&&g.callFrames)&&this.state.context.callFrames[this.state.currentFrame]&&(v!==void 0?this.sendToInstance({cmd:"expressions",expressions:[this.state.expressions[v]],callFrameId:this.state.context.callFrames[this.state.currentFrame].callFrameId}):this.sendToInstance({cmd:"expressions",expressions:this.state.expressions,callFrameId:this.state.context.callFrames[this.state.currentFrame].callFrameId}))}fromInstance=(v,g)=>{var a,t,e,s,c,d,p,f,h,S;if(g!=null&&g.val&&this.state.instance!==void 0)try{const b=JSON.parse(g.val);if(b.cmd==="subscribed")this.props.socket.sendTo(this.state.instance,"debug",this.props.debugInstance||{scriptName:this.props.src});else if(b.cmd==="readyToDebug"){this.mainScriptId=b.scriptId,this.scripts[b.scriptId]=b.script,b.script.startsWith(`(async () => {debugger; -`)?this.scripts[b.scriptId]=`(async () => { -${b.script.substring(24)}`:b.script.startsWith("debugger;")&&(this.scripts[b.scriptId]=b.script.substring(9));const w=JSON.parse(JSON.stringify(this.state.tabs));w[b.scriptId]=this.props.debugInstance?b.url:this.props.src.replace("script.js.","");const I=`${Date.now()}.${Math.random()*1e4}`;(t=(a=b.context)==null?void 0:a.callFrames)==null||t.forEach((R,H)=>R.id=I+H),this.setState({starting:!1,finished:!1,selected:this.mainScriptId,script:this.scripts[b.scriptId],tabs:w,currentFrame:0,started:!0,paused:!0,location:Ot.getLocation(b.context),context:b.context},()=>this.reinitBreakpoints(()=>{this.readCurrentScope(),this.readExpressions()}))}else if(b.cmd==="paused"){const w=`${Date.now()}.${Math.random()*1e4}`;(s=(e=b.context)==null?void 0:e.callFrames)==null||s.forEach((X,r)=>X.id=w+r);const I=Ot.getLocation(b.context),R=JSON.parse(JSON.stringify(this.state.tabs)),H=b.context.callFrames[0].url.split("iobroker.javascript");I&&(R[I.scriptId]=(H[1]||H[0]).replace("script.js.",""));const L={tabs:R,paused:!0,location:I,currentFrame:0,context:b.context};L.script=!(I!=null&&I.scriptId)||this.scripts[I.scriptId]===void 0?we.I18n.t("loading..."):this.scripts[I.scriptId],L.selected=I==null?void 0:I.scriptId,this.setState(L,()=>{this.readCurrentScope(),this.readExpressions(),I!=null&&I.scriptId&&(this.scripts[I.scriptId]||this.sendToInstance({cmd:"source",scriptId:I.scriptId}))})}else if(b.cmd==="script")this.scripts[b.scriptId]=b.text,this.state.selected===b.scriptId&&this.setState({script:this.scripts[b.scriptId]});else if(b.cmd==="resumed")this.setState({paused:!1});else if(b.cmd==="log")if(this.state.toolsTab==="console"){this.console=null;const w=[...this.state.console];w.push({text:b.text,severity:b.severity,ts:b.ts}),this.setState({console:w})}else b.severity==="error"?this.setState({logErrors:this.state.logErrors+1}):b.severity==="warn"?this.setState({logWarnings:this.state.logWarnings+1}):this.setState({logs:this.state.logs+1}),this.console=this.console||[...this.state.console],this.console.push({text:b.text,severity:b.severity,ts:b.ts});else if(b.cmd==="error")this.setState({error:b.error});else if(b.cmd==="finished"||b.cmd==="debugStopped")this.setState({finished:!0,starting:!1,started:!0});else if(b.cmd==="sb"){const w=JSON.parse(JSON.stringify(this.state.breakpoints));let I=!1;b.breakpoints.filter(R=>R).forEach(R=>{w.find(L=>L.location.scriptId===R.location.scriptId&&L.location.lineNumber===R.location.lineNumber)||(I=!0,w.push(R))}),I&&window.localStorage.setItem(`javascript.tools.bp.${this.props.src}`,JSON.stringify(w)),I&&this.setState({breakpoints:w})}else if(b.cmd==="cb"){const w=JSON.parse(JSON.stringify(this.state.breakpoints));let I=!1;b.breakpoints.filter(R=>R!=null).forEach(R=>{const H=w.find(L=>L.id===R);if(H){const L=w.indexOf(H);w.splice(L,1),I=!0}}),I&&window.localStorage.setItem(`javascript.tools.bp.${this.props.src}`,JSON.stringify(w)),I&&this.setState({breakpoints:w})}else if(b.cmd==="scope"){const w=b.scopes.find(R=>R.type==="local")||void 0,I=b.scopes.find(R=>R.type==="closure")||void 0;console.log(JSON.stringify(I)),this.setState({scopes:{local:w,closure:I}})}else if(b.cmd==="setValue"){const w=JSON.parse(JSON.stringify(this.state.scopes));let I;b.scopeNumber===0?I=(d=(c=w==null?void 0:w.local)==null?void 0:c.properties)==null?void 0:d.result.find(R=>R.name===b.variableName):I=(f=(p=w==null?void 0:w.closure)==null?void 0:p.properties)==null?void 0:f.result.find(R=>R.name===b.variableName),I&&(I.value.value=b.newValue.value,this.setState({scopes:w}))}else if(b.cmd==="expressions"){const w=JSON.parse(JSON.stringify(this.state.expressions));let I=!1;b.expressions.forEach(R=>{const H=w.find(L=>L.name===R.name);H&&(I=!0,H.value=R.result)}),I&&this.setState({expressions:w}),console.log(`expressions: ${JSON.stringify(b)}`)}else b.cmd==="getPossibleBreakpoints"?((h=b.breakpoints)==null?void 0:h.length)===1?this.sendToInstance({breakpoints:b.breakpoints,cmd:"sb"}):(S=b.breakpoints)!=null&&S.length?this.setState({queryBreakpoints:b.breakpoints}):window.alert("cannot set"):console.error(`Unknown command: ${JSON.stringify(b)}`)}catch{}};getTextAtLocation(v){let g=this.state.script.split(/\r\n|\n/)[v.lineNumber],a;return v.columnNumber!==void 0&&v.columnNumber>=10?(g=g.substring(v.columnNumber-10,v.columnNumber+20),a=`${"".padStart(10," ")}↑`):v.columnNumber!==void 0&&(g=g.substring(0,30-v.columnNumber),a=`${"".padStart(v.columnNumber," ")}↑`),[M.jsx("div",{style:ke.monospace,children:g},"line"),M.jsx("div",{style:{...ke.monospace,...ke.arrow},children:a},"arrow")]}renderQueryBreakpoints(){return this.state.queryBreakpoints?M.jsxs(Ht,{onClose:()=>this.setState({queryBreakpoints:null}),"aria-labelledby":"bp-dialog-title",open:!0,children:[M.jsx(Gt,{id:"bp-dialog-title",children:we.I18n.t("Select breakpoint")}),M.jsx(zt,{children:this.state.queryBreakpoints.map((v,g)=>M.jsx(Lt,{style:ke.bpListItem,dense:!0,onClick:()=>{this.sendToInstance({breakpoints:[v],cmd:"sb"}),this.setState({queryBreakpoints:null})},children:M.jsx(Vt,{primary:this.getTextAtLocation(v)})},g))})]}):null}renderError(){return this.state.error?M.jsx(Ut,{onClose:()=>this.setState({error:""}),text:this.state.error},"dialogError"):null}closeTab(v,g){g==null||g.stopPropagation();const a=JSON.parse(JSON.stringify(this.state.tabs));delete a[v];const t={tabs:a,script:this.mainScriptId?this.scripts[this.mainScriptId]:"...",selected:this.mainScriptId};this.state.location&&this.state.location.scriptId!==this.mainScriptId&&(t.location=null),this.setState(t)}renderTabs(){const v=!this.state.tabs||!this.state.started;return M.jsx(Pt,{component:"div",indicatorColor:"primary",style:{position:"relative",width:"calc(100% - 300px)",display:"inline-block"},value:this.state.selected,onChange:(g,a)=>{this.scripts[a]?this.setState({selected:a,script:this.scripts[a]}):this.setState({selected:a,script:"loading..."},()=>this.sendToInstance({cmd:"source",scriptId:a}))},scrollButtons:"auto",children:Object.keys(this.state.tabs||[]).map(g=>{let a=g;const t=this.state.tabs[g]||"";this.state.tabs[g]&&(a=this.state.tabs[g].split("/").pop()||"");const e=[M.jsx("div",{style:ke.tabText,children:a},"text"),g!==this.mainScriptId?M.jsx("span",{style:ke.closeButton,children:M.jsx(ra,{onClick:s=>this.closeTab(g,s),fontSize:"small"},"close")},"icon"):null];return M.jsx(_t,{disabled:v,sx:ke.tabFile,label:e,title:t,value:g},g)})})}onResume(){this.sendToInstance({cmd:"cont"})}onPause(){this.sendToInstance({cmd:"pause"})}onNext(){this.sendToInstance({cmd:"next"})}onStepIn(){this.sendToInstance({cmd:"step"})}onStepOut(){this.sendToInstance({cmd:"out"})}onRestart(){this.setState({started:!1,starting:!0},()=>this.state.instance!==void 0&&this.props.socket.sendTo(this.state.instance,"debug",this.props.debugInstance||{scriptName:this.props.src}))}onToggleException(){const v=!this.state.stopOnException;window.localStorage.setItem("javascript.tools.stopOnException",v?"true":"false"),this.setState({stopOnException:v},()=>this.sendToInstance({cmd:"stopOnException",state:v}))}renderToolbar(){const v=!this.state.started;return M.jsxs(Yt,{variant:"dense",style:ke.toolbar,children:[M.jsx(Te,{style:ke.buttonRestart,disabled:v,onClick:()=>this.onRestart(),title:we.I18n.t("Restart"),size:"medium",children:M.jsx(na,{})}),!this.state.finished&&this.state.paused?M.jsx(Te,{style:ke.buttonRun,disabled:v,onClick:()=>this.onResume(),title:we.I18n.t("Resume execution"),size:"medium",children:M.jsx(sa,{})}):!this.state.finished&&M.jsx(Te,{disabled:v,style:ke.buttonPause,onClick:()=>this.onPause(),title:we.I18n.t("Pause execution"),size:"medium",children:M.jsx(oa,{})}),!this.state.finished&&M.jsx(Te,{style:ke.buttonNext,disabled:v||!this.state.paused,onClick:()=>this.onNext(),title:we.I18n.t("Go to next line"),size:"medium",children:M.jsx(ia,{})}),!this.state.finished&&M.jsx(Te,{style:ke.buttonStep,disabled:v||!this.state.paused,onClick:()=>this.onStepIn(),title:we.I18n.t("Step into function"),size:"medium",children:M.jsx(la,{})}),!this.state.finished&&M.jsx(Te,{style:ke.buttonOut,disabled:v||!this.state.paused,onClick:()=>this.onStepOut(),title:we.I18n.t("Step out from function"),size:"medium",children:M.jsx(ca,{})}),!this.state.finished&&M.jsx(Te,{style:ke.buttonException,color:this.state.stopOnException?"primary":"default",disabled:v||!this.state.paused,onClick:()=>this.onToggleException(),title:we.I18n.t("Stop on exception"),size:"medium",children:M.jsx(ua,{})}),this.renderTabs()]},"toolbar1")}getPossibleBreakpoints(v){const g={...v,columnNumber:1e3};this.sendToInstance({cmd:"getPossibleBreakpoints",start:v,end:g})}toggleBreakpoint(v){const g=this.state.breakpoints.find(a=>a.location.scriptId===this.state.selected&&a.location.lineNumber===v);if(g){const a=JSON.parse(JSON.stringify(this.state.breakpoints));this.setState({breakpoints:a},()=>this.sendToInstance({breakpoints:[g.id],cmd:"cb"}))}else this.getPossibleBreakpoints({scriptId:this.state.selected,lineNumber:v,columnNumber:0})}renderCode(){if(this.state.script&&this.state.started){const v=this.state.breakpoints.filter(g=>g.location.scriptId===this.state.selected);return M.jsx(ha,{runningInstances:this.props.runningInstances,socket:this.props.socket,adapterName:this.props.adapterName,scriptName:this.state.selected?this.state.tabs[this.state.selected]:"",sourceId:this.state.selected,script:this.state.script,paused:this.state.paused,breakpoints:v,location:this.state.location,themeType:this.props.themeType,themeName:this.props.themeName,onToggleBreakpoint:g=>this.toggleBreakpoint(g)})}return null}renderFrames(){var v;return this.state.paused?M.jsx(ja,{currentScriptId:this.state.selected,scopes:this.state.scopes,expressions:this.state.expressions,themeType:this.props.themeType,callFrames:(v=this.state.context)==null?void 0:v.callFrames,currentFrame:this.state.currentFrame,onChangeCurrentFrame:g=>{this.setState({currentFrame:g,scopes:{}},()=>{this.readCurrentScope(),this.readExpressions()})},onWriteScopeValue:g=>{this.sendToInstance({cmd:"setValue",variableName:g.variableName,scopeNumber:g.scopeNumber,newValue:g.newValue,callFrameId:g.callFrameId})},onExpressionDelete:g=>{const a=JSON.parse(JSON.stringify(this.state.expressions));a.splice(g,1),this.setState({expressions:a}),window.localStorage.setItem(`javascript.tools.exps.${this.props.src}`,JSON.stringify(a.map(t=>t.name)))},onExpressionAdd:g=>{const a=JSON.parse(JSON.stringify(this.state.expressions));a.push({name:"",value:{value:""}}),this.setState({expressions:a},()=>g&&g(a.length-1,this.state.expressions[a.length-1]))},onExpressionNameUpdate:(g,a,t)=>{const e=JSON.parse(JSON.stringify(this.state.expressions));if(!a)e.splice(g,1);else{if(e.find(s=>s.name===a))return t&&t();e[g].name=a}this.setState({expressions:e},()=>{a&&this.readExpressions(g),t&&t()}),window.localStorage.setItem(`javascript.tools.exps.${this.props.src}`,JSON.stringify(e.map(s=>s.name)))}}):null}renderConsole(){return M.jsx(Ct,{console:this.state.console,onClearAllLogs:()=>this.setState({console:[],logErrors:0,logWarnings:0,logs:0})})}renderTools(){const v=!this.state.tabs||!this.state.started;let g;return this.state.logErrors?g=M.jsx(wt,{badgeContent:this.state.logErrors,color:"error",children:M.jsx("span",{children:we.I18n.t("Console")})}):this.state.logWarnings?g=M.jsx(wt,{badgeContent:this.state.logWarnings,color:"secondary",children:M.jsx("span",{children:we.I18n.t("Console")})}):this.state.logs?g=M.jsx(wt,{badgeContent:this.state.logs,color:"default",children:M.jsx("span",{children:we.I18n.t("Console")})}):g=we.I18n.t("Console"),M.jsxs("div",{style:{width:"100%",height:"100%",overflow:"hidden"},children:[M.jsxs(Pt,{sx:ke.tabsRoot,component:"div",indicatorColor:"primary",style:{position:"relative",width:"100%"},value:this.state.toolsTab,onChange:(a,t)=>{const e={toolsTab:t};this.console&&t==="console"&&(e.console=this.console,this.console=null,e.logs=0,e.logWarnings=0,e.logErrors=0),window.localStorage.setItem("javascript.tools.tab",t),this.setState(e)},scrollButtons:"auto",children:[M.jsx(_t,{style:ke.tabRoot,disabled:v,label:we.I18n.t("Stack"),value:"stack"}),M.jsx(_t,{style:ke.tabRoot,disabled:v,label:g,value:"console"})]}),M.jsxs("div",{style:{width:"100%",height:"calc(100% - 36px)",overflow:"hidden"},children:[this.state.toolsTab==="stack"&&!v?this.renderFrames():null,this.state.toolsTab==="console"&&!v?this.renderConsole():null]})]})}render(){return M.jsxs(Ze,{sx:ke.root,children:[this.state.starting?M.jsx(Qt,{}):null,this.renderToolbar(),M.jsxs(Rt,{direction:Bt.Vertical,initialSizes:this.state.toolSizes,minHeights:[100,100],onResizeFinished:(v,g)=>{this.setState({toolSizes:g}),window.localStorage.setItem("JS.toolSizes",JSON.stringify(g))},gutterClassName:this.props.themeType==="dark"?"Dark visGutter":"Light visGutter",children:[M.jsxs("div",{style:{width:"100%",height:"100%",overflow:"hidden"},children:[this.renderCode(),this.renderQueryBreakpoints()]}),M.jsx("div",{style:{width:"100%",height:"100%",overflow:"hidden"},children:this.renderTools()})]}),this.renderError()]},"debugger")}}export{Ot as default}; diff --git a/admin/google-blockly/own/blocks_words.js b/admin/google-blockly/own/blocks_words.js index 6a5d08055..0af65e7ba 100644 --- a/admin/google-blockly/own/blocks_words.js +++ b/admin/google-blockly/own/blocks_words.js @@ -17,6 +17,13 @@ Blockly.Words['loglevel_error'] = { en: 'error', Blockly.Words['with_results'] = { en: 'with results', de: 'mit Ergebnissen', ru: 'анализировать результаты', pt: 'com resultados', nl: 'met resultaten', fr: 'avec des résultats', it: 'con risultati', es: 'con resultados', pl: 'z wynikami', uk: 'з результатами', 'zh-cn': '处理返回值' }; +// --- OID DISPLAY MODES ---------------------------------------- +Blockly.Words['oid_display_name'] = { en: 'Show name', de: 'Name anzeigen', ru: 'Показать имя', pt: 'Mostrar nome', nl: 'Naam tonen', fr: 'Afficher le nom', it: 'Mostra nome', es: 'Mostrar nombre', pl: 'Pokaż nazwę', uk: 'Показати назву', 'zh-cn': '显示名称' }; +Blockly.Words['oid_display_path'] = { en: 'Show name path', de: 'Namenspfad anzeigen', ru: 'Показать путь имён', pt: 'Mostrar caminho do nome', nl: 'Naampad tonen', fr: 'Afficher le chemin du nom', it: 'Mostra percorso nome', es: 'Mostrar ruta de nombre', pl: 'Pokaż ścieżkę nazwy', uk: 'Показати шлях назви', 'zh-cn': '显示名称路径' }; +Blockly.Words['oid_display_id'] = { en: 'Show ID', de: 'ID anzeigen', ru: 'Показать ID', pt: 'Mostrar ID', nl: 'ID tonen', fr: 'Afficher l\'ID', it: 'Mostra ID', es: 'Mostrar ID', pl: 'Pokaż ID', uk: 'Показати ID', 'zh-cn': '显示ID' }; +Blockly.Words['oid_display_full_id'] = { en: 'Show full ID', de: 'Vollständige ID anzeigen', ru: 'Показать полный ID', pt: 'Mostrar ID completo', nl: 'Volledige ID tonen', fr: 'Afficher l\'ID complet', it: 'Mostra ID completo', es: 'Mostrar ID completo', pl: 'Pokaż pełne ID', uk: 'Показати повний ID', 'zh-cn': '显示完整ID' }; +Blockly.Words['oid_show_icon'] = { en: 'Show icon', de: 'Icon anzeigen', ru: 'Показать значок', pt: 'Mostrar ícone', nl: 'Pictogram tonen', fr: 'Afficher l\'icône', it: 'Mostra icona', es: 'Mostrar icono', pl: 'Pokaż ikonę', uk: 'Показати значок', 'zh-cn': '显示图标' }; + // --- OBJECT -------------------------------------------------- Blockly.Words['Object'] = { en: 'Object', de: 'Objekt', ru: 'Объект', pt: 'Objeto', nl: 'Doel', fr: 'Objet', it: 'Oggetto', es: 'Objeto', pl: 'Obiekt', uk: 'Об\'єкт', 'zh-cn': '对象' }; diff --git a/admin/google-blockly/own/field_oid.js b/admin/google-blockly/own/field_oid.js index 00765db8d..526c85a6e 100644 --- a/admin/google-blockly/own/field_oid.js +++ b/admin/google-blockly/own/field_oid.js @@ -19,6 +19,7 @@ class FieldOID extends Blockly.Field { this.CURSOR = 'pointer'; this.SERIALIZABLE = true; this.spellcheck_ = false; + this.maxDisplayLength = 200; } dispose() { @@ -26,6 +27,235 @@ class FieldOID extends Blockly.Field { super.dispose(); } + initView() { + super.initView(); + const id = this.getValue(); + if (id) { + this.updateIcon_(id); + } + } + + static _resolveObjectName(id) { + const objects = window.main.objects; + if (!objects || !objects[id] || !objects[id].common || !objects[id].common.name) { + return null; + } + let name = objects[id].common.name; + if (typeof name === 'object') { + name = name[systemLang] || name.en; + } + return name || null; + } + + static computeDisplayText(id, maxLen) { + const mode = FieldOID.displayMode; + const objects = window.main.objects; + let text; + + switch (mode) { + case 1: { // Path: all parent names joined with "." + const parts = id.split('.'); + const names = []; + for (let i = 0; i < parts.length; i++) { + const ancestorId = parts.slice(0, i + 1).join('.'); + const name = FieldOID._resolveObjectName(ancestorId); + names.push(name || parts[i]); + } + text = names.join('.'); + break; + } + case 2: // State ID: last segment only + text = id.split('.').pop() || id; + break; + case 3: // Full ID + text = id; + break; + default: { // Mode 0: Name (current behavior) + text = FieldOID._resolveObjectName(id) || id; + break; + } + } + + // Append type suffix for non-state objects + if (objects && objects[id]?.type && !['state', 'meta', 'script'].includes(objects[id].type)) { + text += ` (${objects[id].type})`; + } + + if (maxLen && text.length > maxLen) { + text = text.substring(0, maxLen - 2) + '\u2026'; + } + + // Replace whitespace with non-breaking spaces so the text doesn't collapse. + text = text.replace(/\s/g, Blockly.Field.NBSP); + + return text || Blockly.Field.NBSP; + } + + refreshDisplay() { + const id = this.getValue(); + if (id) { + this._idName = FieldOID.computeDisplayText(id, this.maxDisplayLength); + this.updateIcon_(id); + this.forceRerender(); + // For path mode, async-fetch parent objects to resolve names + if (FieldOID.displayMode === 1) { + this._resolvePathNamesAsync(id); + } + } + } + + _resolvePathNamesAsync(id) { + if (typeof window.main.getObject !== 'function') return; + const objects = window.main.objects; + const parts = id.split('.'); + let pending = 0; + let updated = false; + for (let i = 0; i < parts.length; i++) { + const ancestorId = parts.slice(0, i + 1).join('.'); + if (objects[ancestorId]) continue; // already cached + pending++; + window.main.getObject(ancestorId, (err, obj) => { + if (obj) { + objects[obj._id] = objects[obj._id] || obj; + updated = true; + } + pending--; + if (pending === 0 && updated) { + this._idName = FieldOID.computeDisplayText(id, this.maxDisplayLength); + this.forceRerender(); + } + }); + } + } + + _getIconOffset() { + return (FieldOID.showIcon && this._iconElement) ? 20 : 0; + } + + // Override Blockly's size + position to account for icon + updateSize_(margin) { + const constants = this.getConstants(); + const xPad = margin !== undefined ? margin : + (this.isFullBlockField() ? 0 : constants.FIELD_BORDER_RECT_X_PADDING); + const iconOffset = this._getIconOffset(); + + let textWidth = 0; + if (this.textElement_) { + textWidth = this.textElement_.getComputedTextLength(); + } + + let totalWidth = 2 * xPad + textWidth + iconOffset; + let totalHeight = constants.FIELD_TEXT_HEIGHT; + if (!this.isFullBlockField()) { + totalHeight = Math.max(totalHeight, constants.FIELD_BORDER_RECT_HEIGHT); + } + + this.size_.height = totalHeight; + this.size_.width = totalWidth; + + this.positionTextElement_(xPad + iconOffset, textWidth); + this.positionBorderRect_(); + } + + updateIcon_(id) { + if (!this.fieldGroup_) { + return; + } + if (!FieldOID.showIcon) { + if (this._iconElement) { + this._iconElement.remove(); + this._iconElement = null; + this._iconUrl = null; + } + return; + } + // First try synchronous resolve with cached objects + const iconUrl = FieldOID.resolveIcon(id); + if (iconUrl) { + this._applyIcon(iconUrl); + } + // Then async-fetch parent objects to find a closer (more specific) icon + this._resolveIconAsync(id); + } + + _applyIcon(iconUrl) { + if (!this.fieldGroup_) return; + if (this._iconUrl === iconUrl && this._iconElement) { + return; + } + this._iconUrl = iconUrl; + const iconSize = 16; + if (!this._iconElement) { + this._iconElement = document.createElementNS('http://www.w3.org/2000/svg', 'image'); + this._iconElement.setAttribute('width', String(iconSize)); + this._iconElement.setAttribute('height', String(iconSize)); + if (this.textElement_) { + this.fieldGroup_.insertBefore(this._iconElement, this.textElement_); + } else { + this.fieldGroup_.appendChild(this._iconElement); + } + } + this._iconElement.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', iconUrl); + this._positionIcon(); + } + + _positionIcon() { + if (!this._iconElement || !this.textElement_) return; + const iconSize = 16; + try { + // Position icon at the start of the field content area + const constants = this.getConstants(); + const xPad = this.borderRect_ ? constants.FIELD_BORDER_RECT_X_PADDING : 0; + this._iconElement.setAttribute('x', String(xPad + 2)); + + // Vertically center icon with text + const textBBox = this.textElement_.getBBox(); + if (textBBox.height > 0) { + const textMidY = textBBox.y + textBBox.height / 2; + this._iconElement.setAttribute('y', String(textMidY - iconSize / 2)); + } + } catch (e) { + // getBBox can fail if element is not in DOM yet + } + } + + _resolveIconAsync(id) { + if (!FieldOID.showIcon || typeof window.main.getObject !== 'function') { + return; + } + const objects = window.main.objects; + const parts = id.split('.'); + const adapterName = parts[0]; + // Fetch ancestors from state level up to adapter instance level + // Start from the state itself, go up - first icon found wins + let remaining = parts.length; + const tryNext = (idx) => { + if (idx < 1) return; + const ancestorId = parts.slice(0, idx).join('.'); + // Already in cache? + if (objects[ancestorId]) { + if (objects[ancestorId].common && objects[ancestorId].common.icon) { + this._applyIcon(FieldOID._buildIconUrl(objects[ancestorId].common.icon, adapterName)); + return; // Found closest icon, stop + } + tryNext(idx - 1); // No icon here, try parent + return; + } + // Fetch this ancestor + window.main.getObject(ancestorId, (err, obj) => { + if (obj) { + objects[obj._id] = objects[obj._id] || obj; + if (obj.common && obj.common.icon) { + this._applyIcon(FieldOID._buildIconUrl(obj.common.icon, adapterName)); + return; // Found closest icon, stop + } + } + tryNext(idx - 1); // Try parent + }); + }; + tryNext(remaining); + } + setValue(id) { if (id === null) { return; // No change if null. @@ -38,50 +268,26 @@ class FieldOID extends Blockly.Field { window.main.getObject(id, (err, obj) => { if (obj) { objects[obj._id] = objects[obj._id] || obj; - let text = objects[obj._id].common && objects[obj._id].common.name && objects[obj._id].common.name; + const text = FieldOID.computeDisplayText(id, this.maxDisplayLength); if (text) { - if (typeof text === 'object') { - text = text[systemLang] || text.en; - } - if (text.length > this.maxDisplayLength) { - // Truncate displayed string and add an ellipsis ('...'). - text = text.substring(0, this.maxDisplayLength - 2) + '\u2026'; - } - if (objects && objects[id] && objects[id]?.type && !['state', 'meta', 'script'].includes(objects[id].type)) { - text += ` (${objects[id].type})`; - } - // Replace whitespace with non-breaking spaces so the text doesn't collapse. - text = text.replace(/\s/g, Blockly.Field.NBSP); - - if (text) { - this._idName = text; - this.forceRerender(); - } + this._idName = text; + this.forceRerender(); + } + // Resolve parent names for path mode + if (FieldOID.displayMode === 1) { + this._resolvePathNamesAsync(id); } } }); } else { - let text = objects && objects[id] && objects[id].common && objects[id].common.name ? objects[id].common.name : id; - if (typeof text === 'object') { - text = text[systemLang] || text.en; + this._idName = FieldOID.computeDisplayText(id, this.maxDisplayLength); + // Resolve parent names for path mode + if (FieldOID.displayMode === 1) { + this._resolvePathNamesAsync(id); } - if (text.length > this.maxDisplayLength) { - // Truncate the displayed string and add an ellipsis ('...'). - text = text.substring(0, this.maxDisplayLength - 2) + '\u2026'; - } - if (objects && objects[id] && objects[id]?.type && !['state', 'meta', 'script'].includes(objects[id].type)) { - text += ` (${objects[id].type})`; - } - // Replace whitespace with non-breaking spaces so the text doesn't collapse. - text = text.replace(/\s/g, Blockly.Field.NBSP); - - if (!text) { - // Prevent the field from disappearing if empty. - text = Blockly.Field.NBSP; - } - this._idName = text; } + this.updateIcon_(id); super.setValue(id); super.setTooltip(id); } @@ -98,7 +304,6 @@ class FieldOID extends Blockly.Field { } // Replace whitespace with non-breaking spaces so the text doesn't collapse. text = text.replace(/\s/g, Blockly.Field.NBSP); - if (this.sourceBlock_.RTL) { // The SVG is LTR, force text to be RTL. text += '\u200F'; @@ -214,6 +419,75 @@ class FieldOID extends Blockly.Field { } } +FieldOID.DISPLAY_MODE_KEYS = ['oid_display_name', 'oid_display_path', 'oid_display_id', 'oid_display_full_id']; +FieldOID.displayMode = parseInt(localStorage.getItem('Blockly.FieldOID.displayMode') || '0', 10) || 0; +FieldOID.showIcon = localStorage.getItem('Blockly.FieldOID.showIcon') === 'true'; + +FieldOID._buildIconUrl = function (icon, adapterName) { + if (!icon) return null; + // base64 data URIs and absolute URLs are used as-is + if (icon.startsWith('data:') || icon.startsWith('http://') || icon.startsWith('https://') || icon.startsWith('/')) { + return icon; + } + return '/adapter/' + adapterName + '/' + icon; +}; + +FieldOID.resolveIcon = function (id) { + const objects = window.main.objects; + if (!objects) return null; + const parts = id.split('.'); + const adapterName = parts[0]; + // Walk up the object hierarchy looking for common.icon + for (let i = parts.length; i >= 1; i--) { + const ancestorId = parts.slice(0, i).join('.'); + const obj = objects[ancestorId]; + if (obj && obj.common && obj.common.icon) { + return FieldOID._buildIconUrl(obj.common.icon, adapterName); + } + } + // Fallback: check system.adapter.{adapterName}.{instance} (e.g. system.adapter.zigbee2mqtt.0) + if (parts.length >= 2) { + const instanceId = 'system.adapter.' + parts[0] + '.' + parts[1]; + const sysInstance = objects[instanceId]; + if (sysInstance && sysInstance.common && sysInstance.common.icon) { + return FieldOID._buildIconUrl(sysInstance.common.icon, adapterName); + } + } + return null; +}; + +FieldOID.setDisplayMode = function (mode, workspace) { + FieldOID.displayMode = mode; + localStorage.setItem('Blockly.FieldOID.displayMode', String(mode)); + + const blocks = workspace.getAllBlocks(false); + for (const block of blocks) { + for (const input of block.inputList) { + for (const field of input.fieldRow) { + if (field instanceof FieldOID) { + field.refreshDisplay(); + } + } + } + } +}; + +FieldOID.setShowIcon = function (show, workspace) { + FieldOID.showIcon = show; + localStorage.setItem('Blockly.FieldOID.showIcon', String(show)); + + const blocks = workspace.getAllBlocks(false); + for (const block of blocks) { + for (const input of block.inputList) { + for (const field of input.fieldRow) { + if (field instanceof FieldOID) { + field.refreshDisplay(); + } + } + } + } +}; + Blockly.FieldOID = FieldOID; //Blockly.Field.register('field_oid', FieldOID); diff --git a/admin/tab.html b/admin/tab.html index 7da256982..a05c9de12 100644 --- a/admin/tab.html +++ b/admin/tab.html @@ -115,7 +115,7 @@ type="text/javascript" src="google-blockly/own/blocks_object.js" > - + diff --git a/build/lib/debugger.js b/build/lib/debugger.js index cacd629f0..ae6ee63e0 100644 --- a/build/lib/debugger.js +++ b/build/lib/debugger.js @@ -23,7 +23,7 @@ exports.default = createRepl; * IN THE SOFTWARE. */ const node_path_1 = require("node:path"); -const repl_1 = require("repl"); +const node_repl_1 = require("node:repl"); const node_util_1 = require("node:util"); const node_vm_1 = require("node:vm"); const node_url_1 = require("node:url"); @@ -1118,7 +1118,7 @@ function createRepl(inspector) { useGlobal: false, ignoreUndefined: true, }; - repl = (0, repl_1.start)(replOptions); + repl = (0, node_repl_1.start)(replOptions); initializeContext(repl.context); repl.on('reset', initializeContext); repl.defineCommand('interrupt', () => { diff --git a/build/lib/debugger.js.map b/build/lib/debugger.js.map index 5a8897bd3..4a3dcb5e9 100644 --- a/build/lib/debugger.js.map +++ b/build/lib/debugger.js.map @@ -1 +1 @@ -{"version":3,"file":"debugger.js","sourceRoot":"","sources":["../../src/lib/debugger.ts"],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zB,KAAK,CAAC,6BAA6B,GAAG,CAAC,OAAO,EAAE,CAAC,CAAC;QACtD,CAAC,CAAC,CAAC;QAEH,OAAO,IAAI,CAAC;IAChB,CAAC,CAAC;AACN,CAAC","sourcesContent":["/*\n * Copyright Node.js contributors. All rights reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\nimport { join, resolve } from 'node:path';\nimport { type ReplOptions, type REPLServer, start } from 'repl';\nimport {\n debuglog as debuglogUtil,\n inspect as inspectUtil,\n type InspectOptions,\n type InspectOptionsStylized,\n type Style,\n} from 'node:util';\nimport { type Context, runInContext } from 'node:vm';\nimport { fileURLToPath } from 'node:url';\nimport { builtinModules as PUBLIC_BUILTINS } from 'node:module';\nimport type { Debugger, Runtime } from 'node:inspector';\n\nimport type { NodeInspector } from './inspect';\n\nconst debuglog = debuglogUtil('inspect');\n\ninterface PropertyPreview {\n /**\n * Property name.\n */\n name: string;\n /**\n * Object type. Accessor means that the property itself is an accessor property.\n */\n type: string;\n /**\n * User-friendly property value string.\n */\n value?: string | undefined;\n /**\n * Object subtype hint. Specified for object type values only.\n */\n subtype?: string | undefined;\n}\n/*const SHORTCUTS = {\n cont: 'c',\n next: 'n',\n step: 's',\n out: 'o',\n backtrace: 'bt',\n setBreakpoint: 'sb',\n clearBreakpoint: 'cb',\n run: 'r',\n};\n\nconst HELP = `\nrun, restart, r Run the application or reconnect\nkill Kill a running application or disconnect\n\ncont, c Resume execution\nnext, n Continue to next line in current file\nstep, s Step into, potentially entering a function\nout, o Step out, leaving the current function\nbacktrace, bt Print the current backtrace\nlist Print the source around the current line where execution\n is currently paused\n\nsetBreakpoint, sb Set a breakpoint\nclearBreakpoint, cb Clear a breakpoint\nbreakpoints List all known breakpoints\nbreakOnException Pause execution whenever an exception is thrown\nbreakOnUncaught Pause execution whenever an exception isn't caught\nbreakOnNone Don't pause on exceptions (this is the default)\n\nwatch(expr) Start watching the given expression\nunwatch(expr) Stop watching an expression\nwatchers Print all watched expressions and their current values\n\nexec(expr) Evaluate the expression and print the value\nrepl Enter a debug repl that works like exec\n\nscripts List application scripts that are currently loaded\nscripts(true) List all scripts (including node-internals)\n\nprofile Start CPU profiling session.\nprofileEnd Stop current CPU profiling session.\nprofiles Array of completed CPU profiling sessions.\nprofiles[n].save(filepath = 'node.cpuprofile')\n Save CPU profiling session to disk as JSON.\n\ntakeHeapSnapshot(filepath = 'node.heapsnapshot')\n Take a heap snapshot and save to disk as JSON.\n`.trim();*/\n\nconst FUNCTION_NAME_PATTERN = /^(?:function\\*? )?([^(\\s]+)\\(/;\nfunction extractFunctionName(description: string | undefined): string {\n const fnNameMatch = description?.match(FUNCTION_NAME_PATTERN);\n return fnNameMatch ? `: ${fnNameMatch[1]}` : '';\n}\n\n// process.binding is a method available on the process object, which allows you to load internal modules written in C++\n// @ts-expect-error binding is internal function\nconst NATIVES = PUBLIC_BUILTINS ? process.binding('natives') : {};\n\nfunction isNativeUrl(url: string): boolean {\n url = url.replace(/\\.js$/, '');\n if (PUBLIC_BUILTINS) {\n if (url.startsWith('internal/') || PUBLIC_BUILTINS.includes(url)) {\n return true;\n }\n }\n\n return url in NATIVES || url === 'bootstrap_node';\n}\n\nfunction getRelativePath(filenameOrURL: string): string {\n const dir = join(resolve(), 'x').slice(0, -1);\n\n const filename = filenameOrURL.startsWith('file://') ? fileURLToPath(filenameOrURL) : filenameOrURL;\n\n // Change a path to relative, if possible\n if (filename.indexOf(dir) === 0) {\n return filename.slice(dir.length);\n }\n return filename;\n}\n\nfunction toCallback(promise: Promise, callback: (...args: any[]) => void): void {\n function forward(...args: any[]): void {\n process.nextTick(() => callback(...args));\n }\n\n promise.then(forward.bind(null, null), forward);\n}\n\n// Adds spaces and prefix to number\n// maxN is a maximum number we should have space for\nfunction leftPad(n: number, prefix: string, maxN: number): string {\n const s = n.toString();\n const nchars = Math.max(2, String(maxN).length) + 1;\n const nspaces = nchars - s.length - 1;\n\n return prefix + ' '.repeat(nspaces) + s;\n}\n\nfunction markSourceColumn(sourceText: string, position: number, useColors?: boolean): string {\n if (!sourceText) {\n return '';\n }\n\n const head = sourceText.slice(0, position);\n let tail = sourceText.slice(position);\n\n // Colorize char if stdout supports colours\n if (useColors) {\n tail = tail.replace(/(.+?)([^\\w]|$)/, '\\u001b[32m$1\\u001b[39m$2');\n }\n\n // Return source line with coloured char at `position`\n return [head, tail].join('');\n}\n\nfunction extractErrorMessage(stack: string | undefined): string {\n if (!stack) {\n return '';\n }\n const m = stack.match(/^\\w+: ([^\\n]+)/);\n return m ? m[1] : stack;\n}\n\nfunction convertResultToError(result: Runtime.RemoteObject): Error {\n const { className, description } = result;\n const err = new Error(extractErrorMessage(description));\n err.stack = description;\n Object.defineProperty(err, 'name', { value: className });\n return err;\n}\n\nclass RemoteObject implements Runtime.RemoteObject {\n type: string;\n subtype?: string | undefined;\n className?: string | undefined;\n\n value: any;\n unserializableValue?: Runtime.UnserializableValue | undefined;\n description: string | undefined;\n objectId?: Runtime.RemoteObjectId | undefined;\n preview?: Runtime.ObjectPreview | undefined;\n customPreview?: Runtime.CustomPreview | undefined;\n\n constructor(attributes: Runtime.RemoteObject | undefined) {\n this.type = 'undefined';\n Object.assign(this, attributes);\n if (this.type === 'number') {\n this.value = this.unserializableValue ? +this.unserializableValue : +this.value;\n }\n }\n\n [inspectUtil.custom](_depth: number, opts: InspectOptionsStylized): string {\n function formatProperty(prop: PropertyPreview): any {\n switch (prop.type) {\n case 'string':\n case 'undefined':\n return inspectUtil(prop.value, opts);\n\n case 'number':\n case 'boolean':\n return opts.stylize(prop.value as string, prop.type);\n\n case 'object':\n case 'symbol':\n if (prop.subtype === 'date') {\n return inspectUtil(new Date(prop.value as string), opts);\n }\n if (prop.subtype === 'array') {\n return opts.stylize(prop.value as string, 'special');\n }\n return opts.stylize(prop.value as string, (prop.subtype as Style) || 'special');\n\n default:\n return prop.value;\n }\n }\n\n switch (this.type) {\n case 'boolean':\n case 'number':\n case 'string':\n case 'undefined':\n return inspectUtil(this.value, opts);\n\n case 'symbol':\n return opts.stylize(this.description as string, 'special');\n\n case 'function': {\n const fnName = extractFunctionName(this.description);\n const formatted = `[${this.className}${fnName}]`;\n return opts.stylize(formatted, 'special');\n }\n\n case 'object':\n switch (this.subtype) {\n case 'date':\n return inspectUtil(new Date(this.description as string), opts);\n\n case 'null':\n return inspectUtil(null, opts);\n\n case 'regexp':\n return opts.stylize(this.description as string, 'regexp');\n\n default:\n break;\n }\n if (this.preview) {\n const props: any[] = this.preview.properties.map((prop, idx) => {\n const value = formatProperty(prop);\n if (prop.name === `${idx}`) {\n return value;\n }\n return `${prop.name}: ${value}`;\n });\n if (this.preview.overflow) {\n props.push('...');\n }\n const singleLine = props.join(', ');\n const propString = singleLine.length > 60 ? props.join(',\\n ') : singleLine;\n\n return this.subtype === 'array' ? `[ ${propString} ]` : `{ ${propString} }`;\n }\n return this.description || '';\n\n default:\n return this.description || '';\n }\n }\n\n static fromEvalResult({ result, wasThrown }: { result: RemoteObject; wasThrown?: boolean }): RemoteObject | Error {\n if (wasThrown) {\n return convertResultToError(result);\n }\n return new RemoteObject(result);\n }\n}\n\nclass ScopeSnapshot implements Debugger.Scope {\n /**\n * Scope type.\n */\n type: string;\n /**\n * Object representing the scope. For global and with scopes it represents the actual object; for the rest of the scopes, it is artificial transient object enumerating scope variables as its properties.\n */\n object: Runtime.RemoteObject;\n\n name?: string | undefined;\n /**\n * Location in the source code where scope starts\n */\n startLocation?: Debugger.Location | undefined;\n /**\n * Location in the source code where scope ends\n */\n endLocation?: Debugger.Location | undefined;\n\n properties: Map;\n\n completionGroup: string[];\n\n constructor(scope: Debugger.Scope, properties: Runtime.PropertyDescriptor[]) {\n this.type = scope.type;\n this.object = scope.object;\n\n Object.assign(this, scope);\n\n this.properties = new Map(\n properties.map(prop => {\n const value = new RemoteObject(prop.value);\n return [prop.name, value];\n }),\n );\n\n this.completionGroup = properties.map(prop => prop.name);\n }\n\n [inspectUtil.custom](_depth: number, opts: InspectOptions): string {\n const type = `${this.type[0].toUpperCase()}${this.type.slice(1)}`;\n const name = this.name ? `<${this.name}>` : '';\n const prefix = `${type}${name} `;\n return inspectUtil(this.properties, opts).replace(/^Map /, prefix);\n }\n}\n/*\nfunction copyOwnProperties(target: any, source: any): void {\n Object.getOwnPropertyNames(source).forEach(prop => {\n const descriptor = Object.getOwnPropertyDescriptor(source, prop);\n if (descriptor) {\n Object.defineProperty(target, prop, descriptor);\n }\n });\n}\n\nfunction aliasProperties(target, mapping) {\n Object.keys(mapping).forEach((key) => {\n const descriptor = Object.getOwnPropertyDescriptor(target, key);\n Object.defineProperty(target, mapping[key], descriptor);\n });\n}\n*/\nexport default function createRepl(inspector: NodeInspector): () => REPLServer {\n const { Debugger, /*HeapProfiler, Profiler,*/ Runtime } = inspector;\n\n let repl: REPLServer;\n\n // Things we want to keep around\n // const history = { control: [], debug: [] };\n // const watchedExpressions = [];\n // const knownBreakpoints = [];\n // let pauseOnExceptionState = 'none';\n let lastCommand: string;\n\n // Things we need to reset when the app restarts\n let knownScripts: Record = {};\n let currentBacktrace: CallFrame[] | undefined;\n let selectedFrame: CallFrame | undefined;\n let exitDebugRepl: undefined | (() => void);\n\n function resetOnStart(): void {\n knownScripts = {};\n currentBacktrace = undefined;\n selectedFrame = undefined;\n\n if (exitDebugRepl) {\n exitDebugRepl();\n }\n exitDebugRepl = undefined;\n }\n\n resetOnStart();\n\n const INSPECT_OPTIONS: InspectOptions = { colors: inspector.stdout.isTTY };\n function inspect(value: any): string {\n return inspectUtil(value, INSPECT_OPTIONS);\n }\n\n function print(value: any, oneline = false): void {\n const text = typeof value === 'string' ? value : inspect(value);\n return inspector.print(text, oneline);\n }\n\n function getCurrentLocation(): Debugger.Location {\n if (!selectedFrame) {\n throw new Error('Requires execution to be paused');\n }\n return selectedFrame.location;\n }\n\n function isCurrentScript(script: Debugger.ScriptParsedEventDataType & { isNative: boolean }): boolean {\n return !!selectedFrame && getCurrentLocation().scriptId === script.scriptId;\n }\n\n function formatScripts(displayNatives = false): string {\n function isVisible(script: Debugger.ScriptParsedEventDataType & { isNative: boolean }): boolean {\n if (displayNatives) {\n return true;\n }\n return !script.isNative || isCurrentScript(script);\n }\n\n return Object.keys(knownScripts)\n .map(scriptId => knownScripts[scriptId])\n .filter(isVisible)\n .map(script => {\n const isCurrent = isCurrentScript(script);\n const { isNative, url } = script;\n const name = `${getRelativePath(url)}${isNative ? ' ' : ''}`;\n return `${isCurrent ? '*' : ' '} ${script.scriptId}: ${name}`;\n })\n .join('\\n');\n }\n function listScripts(displayNatives = false): void {\n print(formatScripts(displayNatives));\n }\n // @ts-expect-error no idea what this is\n listScripts[inspectUtil.custom] = function listWithoutInternal(): string {\n return formatScripts();\n };\n /*\n const profiles = [];\n class Profile {\n constructor(data) {\n this.data = data;\n }\n\n static createAndRegister({ profile }) {\n const p = new Profile(profile);\n profiles.push(p);\n return p;\n }\n\n [util.inspect.custom](depth, { stylize }) {\n const { startTime, endTime } = this.data;\n return stylize(`[Profile ${endTime - startTime}μs]`, 'special');\n }\n\n save(filename = 'node.cpuprofile') {\n const absoluteFile = Path.resolve(filename);\n const json = JSON.stringify(this.data);\n FS.writeFileSync(absoluteFile, json);\n print('Saved profile to ' + absoluteFile);\n }\n }\n*/\n class SourceSnippet {\n scriptSource: string;\n /**\n * Script identifier as reported in the Debugger.scriptParsed.\n */\n scriptId: Runtime.ScriptId;\n /**\n * Line number in the script (0-based).\n */\n lineNumber: number;\n /**\n * Column number in the script (0-based).\n */\n columnNumber: number;\n delta: number;\n constructor(location: Debugger.Location, delta: number, scriptSource: string) {\n this.lineNumber = location.lineNumber;\n this.columnNumber = location.columnNumber || 0;\n this.scriptId = location.scriptId;\n this.scriptSource = scriptSource;\n this.delta = delta;\n Object.assign(this, location);\n }\n\n [inspectUtil.custom](_depth: number, options: InspectOptions): string {\n const { /* scriptId, */ lineNumber, columnNumber, delta, scriptSource } = this;\n const start = Math.max(1, lineNumber - delta + 1);\n const end = lineNumber + delta + 1;\n\n const lines = scriptSource.split('\\n');\n return lines\n .slice(start - 1, end)\n .map((lineText, offset) => {\n const i = start + offset;\n const isCurrent = i === lineNumber + 1;\n\n const markedLine = isCurrent ? markSourceColumn(lineText, columnNumber, options.colors) : lineText;\n\n /*\n let isBreakpoint = false;\n knownBreakpoints.forEach(({ location }) => {\n if (!location) return;\n if (scriptId === location.scriptId &&\n i === (location.lineNumber + 1)) {\n isBreakpoint = true;\n }\n });\n */\n\n let prefixChar = ' ';\n if (isCurrent) {\n prefixChar = '>';\n } /*else if (isBreakpoint) {\n prefixChar = '*';\n }*/\n return `${leftPad(i, prefixChar, end)} ${markedLine}`;\n })\n .join('\\n');\n }\n }\n\n function getSourceSnippet(location: Debugger.Location, delta: number = 5): SourceSnippet {\n const { scriptId } = location;\n return Debugger.getScriptSource({ scriptId }).then(\n ({ scriptSource }: Debugger.GetScriptSourceReturnType) => new SourceSnippet(location, delta, scriptSource),\n );\n }\n\n class CallFrame implements Debugger.CallFrame {\n /**\n * Call frame identifier. This identifier is only valid while the virtual machine is paused.\n */\n callFrameId: Debugger.CallFrameId;\n /**\n * Name of the JavaScript function called on this call frame.\n */\n functionName: string;\n /**\n * Location in the source code.\n */\n functionLocation?: Debugger.Location | undefined;\n /**\n * Location in the source code.\n */\n location: Debugger.Location;\n /**\n * JavaScript script name or url.\n */\n url: string;\n /**\n * Scope chain for this call frame.\n */\n scopeChain: Debugger.Scope[];\n /**\n * this object for this call frame.\n */\n this: Runtime.RemoteObject;\n /**\n * The value being returned if the function is at return point.\n */\n returnValue?: Runtime.RemoteObject | undefined;\n\n constructor(callFrame: Debugger.CallFrame) {\n this.functionName = callFrame.functionName;\n this.url = callFrame.url;\n this.scopeChain = callFrame.scopeChain;\n this.this = callFrame.this;\n this.returnValue = callFrame.returnValue;\n this.location = callFrame.location;\n this.callFrameId = callFrame.callFrameId;\n\n Object.assign(this, callFrame);\n }\n\n loadScopes(): Promise {\n return Promise.all(\n this.scopeChain\n .filter(scope => scope.type !== 'global')\n .map(scope => {\n const { objectId } = scope.object;\n return Runtime.getProperties({\n objectId,\n generatePreview: true,\n } as Runtime.GetPropertiesParameterType).then(({ result }: Runtime.GetPropertiesReturnType) => {\n return new ScopeSnapshot(scope, result);\n });\n }),\n );\n }\n\n list(delta: number = 5): SourceSnippet {\n return getSourceSnippet(this.location, delta);\n }\n }\n\n class Backtrace extends Array {\n [inspectUtil.custom](): string {\n return this.map((callFrame, idx) => {\n const {\n location: { scriptId, lineNumber, columnNumber },\n functionName,\n } = callFrame;\n const name = functionName || '(anonymous)';\n\n const script = knownScripts[scriptId];\n const relativeUrl = (script && getRelativePath(script.url)) || '';\n const frameLocation = `${relativeUrl}:${lineNumber + 1}:${columnNumber}`;\n\n return `#${idx} ${name} ${frameLocation}`;\n }).join('\\n');\n }\n\n static from(callFrames: CallFrame[]): CallFrame[] {\n return super.from(\n Array.from(callFrames).map(callFrame => {\n if (callFrame instanceof CallFrame) {\n return callFrame;\n }\n return new CallFrame(callFrame);\n }),\n );\n }\n }\n\n function prepareControlCode(input: string): string {\n if (input === '\\n') {\n return lastCommand;\n }\n // exec process.title => exec(\"process.title\");\n const match = input.match(/^\\s*exec\\s+([^\\n]*)/);\n if (match) {\n lastCommand = `exec(${JSON.stringify(match[1])})`;\n } else {\n lastCommand = input;\n }\n return lastCommand;\n }\n\n // function evalInCurrentContext(code) {\n // // Repl asked for scope variables\n // if (code === '.scope') {\n // if (!selectedFrame) {\n // return Promise.reject(new Error('Requires execution to be paused'));\n // }\n // return selectedFrame.loadScopes().then((scopes) => {\n // return scopes.map((scope) => scope.completionGroup);\n // });\n // }\n //\n // if (selectedFrame) {\n // return Debugger.evaluateOnCallFrame({\n // callFrameId: selectedFrame.callFrameId,\n // expression: code,\n // objectGroup: 'node-inspect',\n // generatePreview: true,\n // }).then(RemoteObject.fromEvalResult);\n // }\n // return Runtime.evaluate({\n // expression: code,\n // objectGroup: 'node-inspect',\n // generatePreview: true,\n // }).then(RemoteObject.fromEvalResult);\n // }\n\n function controlEval(\n input: string,\n context: Context,\n filename: string,\n callback: (error: Error | null, result?: any) => void,\n ): void {\n debuglog('eval:', input);\n function returnToCallback(error: Error | null, result?: any): void {\n debuglog('end-eval:', input, error);\n callback(error, result);\n }\n\n try {\n const code = prepareControlCode(input);\n const result = runInContext(code, context, filename);\n\n if (result && typeof result.then === 'function') {\n toCallback(result, returnToCallback);\n return;\n }\n returnToCallback(null, result);\n } catch (e: any) {\n returnToCallback(e as Error);\n }\n }\n\n // function debugEval(input, context, filename, callback) {\n // debuglog('eval:', input);\n // function returnToCallback(error, result) {\n // debuglog('end-eval:', input, error);\n // callback(error, result);\n // }\n //\n // try {\n // const result = evalInCurrentContext(input);\n //\n // if (result && typeof result.then === 'function') {\n // toCallback(result, returnToCallback);\n // return;\n // }\n // returnToCallback(null, result);\n // } catch (e) {\n // returnToCallback(e);\n // }\n // }\n\n /*function formatWatchers(verbose = false) {\n if (!watchedExpressions.length) {\n return Promise.resolve('');\n }\n\n const inspectValue = (expr) =>\n evalInCurrentContext(expr)\n // .then(formatValue)\n .catch((error) => `<${error.message}>`);\n const lastIndex = watchedExpressions.length - 1;\n\n return Promise.all(watchedExpressions.map(inspectValue))\n .then((values) => {\n const lines = watchedExpressions\n .map((expr, idx) => {\n const prefix = `${leftPad(idx, ' ', lastIndex)}: ${expr} =`;\n const value = inspect(values[idx], { colors: true });\n if (value.indexOf('\\n') === -1) {\n return `${prefix} ${value}`;\n }\n return `${prefix}\\n ${value.split('\\n').join('\\n ')}`;\n });\n return lines.join('\\n');\n })\n .then((valueList) => {\n return verbose ? `Watchers:\\n${valueList}\\n` : valueList;\n });\n }*/\n\n //function watchers(verbose = false) {\n // return formatWatchers(verbose).then(print);\n //}\n\n // List source code\n // function list(delta = 5) {\n // return selectedFrame.list(delta)\n // .then(null, (error) => {\n // print('You can\\'t list source code right now');\n // throw error;\n // });\n // }\n\n //function handleBreakpointResolved({ breakpointId, location }) {\n // const script = knownScripts[location.scriptId];\n // const scriptUrl = script && script.url;\n // if (scriptUrl) {\n // Object.assign(location, { scriptUrl });\n // }\n // const isExisting = knownBreakpoints.some((bp) => {\n // if (bp.breakpointId === breakpointId) {\n // Object.assign(bp, { location });\n // return true;\n // }\n // return false;\n // });\n // if (!isExisting) {\n // knownBreakpoints.push({ breakpointId, location });\n // }\n //}\n\n // function listBreakpoints() {\n // if (!knownBreakpoints.length) {\n // print('No breakpoints yet');\n // return;\n // }\n //\n // function formatLocation(location) {\n // if (!location) return '';\n // const script = knownScripts[location.scriptId];\n // const scriptUrl = script ? script.url : location.scriptUrl;\n // return `${getRelativePath(scriptUrl)}:${location.lineNumber + 1}`;\n // }\n // const breaklist = knownBreakpoints\n // .map((bp, idx) => `#${idx} ${formatLocation(bp.location)}`)\n // .join('\\n');\n // print(breaklist);\n // }\n\n // function setBreakpoint(script, line, condition, silent) {\n // function registerBreakpoint({ breakpointId, actualLocation }) {\n // handleBreakpointResolved({ breakpointId, location: actualLocation });\n // if (actualLocation && actualLocation.scriptId) {\n // if (!silent) return getSourceSnippet(actualLocation, 5);\n // } else {\n // print(`Warning: script '${script}' was not loaded yet.`);\n // }\n // return undefined;\n // }\n //\n // // setBreakpoint(): set breakpoint at current location\n // if (script === undefined) {\n // return Debugger\n // .setBreakpoint({ location: getCurrentLocation(), condition })\n // .then(registerBreakpoint);\n // }\n //\n // // setBreakpoint(line): set breakpoint in current script at specific line\n // if (line === undefined && typeof script === 'number') {\n // const location = {\n // scriptId: getCurrentLocation().scriptId,\n // lineNumber: script - 1,\n // };\n // return Debugger.setBreakpoint({ location, condition })\n // .then(registerBreakpoint);\n // }\n //\n // if (typeof script !== 'string') {\n // throw new TypeError(`setBreakpoint() expects a string, got ${script}`);\n // }\n //\n // // setBreakpoint('fn()'): Break when a function is called\n // if (script.endsWith('()')) {\n // const debugExpr = `debug(${script.slice(0, -2)})`;\n // const debugCall = selectedFrame\n // ? Debugger.evaluateOnCallFrame({\n // callFrameId: selectedFrame.callFrameId,\n // expression: debugExpr,\n // includeCommandLineAPI: true,\n // })\n // : Runtime.evaluate({\n // expression: debugExpr,\n // includeCommandLineAPI: true,\n // });\n // return debugCall.then(({ result, wasThrown }) => {\n // if (wasThrown) return convertResultToError(result);\n // return undefined; // This breakpoint can't be removed the same way\n // });\n // }\n //\n // // setBreakpoint('scriptname')\n // let scriptId = null;\n // let ambiguous = false;\n // if (knownScripts[script]) {\n // scriptId = script;\n // } else {\n // for (const id of Object.keys(knownScripts)) {\n // const scriptUrl = knownScripts[id].url;\n // if (scriptUrl && scriptUrl.indexOf(script) !== -1) {\n // if (scriptId !== null) {\n // ambiguous = true;\n // }\n // scriptId = id;\n // }\n // }\n // }\n //\n // if (ambiguous) {\n // print('Script name is ambiguous');\n // return undefined;\n // }\n // if (line <= 0) {\n // print('Line should be a positive value');\n // return undefined;\n // }\n //\n // if (scriptId !== null) {\n // const location = { scriptId, lineNumber: line - 1 };\n // return Debugger.setBreakpoint({ location, condition })\n // .then(registerBreakpoint);\n // }\n //\n // const escapedPath = script.replace(/([/\\\\.?*()^${}|[\\]])/g, '\\\\$1');\n // const urlRegex = `^(.*[\\\\/\\\\\\\\])?${escapedPath}$`;\n //\n // return Debugger\n // .setBreakpointByUrl({ urlRegex, lineNumber: line - 1, condition })\n // .then((bp) => {\n // // TODO: handle bp.locations in case the regex matches existing files\n // if (!bp.location) { // Fake it for now.\n // Object.assign(bp, {\n // actualLocation: {\n // scriptUrl: `.*/${script}$`,\n // lineNumber: line - 1,\n // },\n // });\n // }\n // return registerBreakpoint(bp);\n // });\n // }\n //\n // function clearBreakpoint(url, line) {\n // const breakpoint = knownBreakpoints.find(({ location }) => {\n // if (!location) return false;\n // const script = knownScripts[location.scriptId];\n // if (!script) return false;\n // return (\n // script.url.indexOf(url) !== -1 && (location.lineNumber + 1) === line\n // );\n // });\n // if (!breakpoint) {\n // print(`Could not find breakpoint at ${url}:${line}`);\n // return Promise.resolve();\n // }\n // return Debugger.removeBreakpoint({ breakpointId: breakpoint.breakpointId })\n // .then(() => {\n // const idx = knownBreakpoints.indexOf(breakpoint);\n // knownBreakpoints.splice(idx, 1);\n // });\n // }\n //\n // function restoreBreakpoints() {\n // const lastBreakpoints = knownBreakpoints.slice();\n // knownBreakpoints.length = 0;\n // const newBreakpoints = lastBreakpoints\n // .filter(({ location }) => !!location.scriptUrl)\n // .map(({ location }) =>\n // setBreakpoint(location.scriptUrl, location.lineNumber + 1));\n // if (!newBreakpoints.length) return Promise.resolve();\n // return Promise.all(newBreakpoints).then((results) => {\n // print(`${results.length} breakpoints restored.`);\n // });\n // }\n\n // function setPauseOnExceptions(state) {\n // return Debugger.setPauseOnExceptions({ state })\n // .then(() => {\n // pauseOnExceptionState = state;\n // });\n // }\n\n Debugger.on('paused', (data: Debugger.PausedEventDataType): void => {\n const callFrames: CallFrame[] = data.callFrames as CallFrame[];\n const reason: string = data.reason;\n\n if (process.env.NODE_INSPECT_RESUME_ON_START === '1' && reason === 'Break on start') {\n debuglog('Paused on start, but NODE_INSPECT_RESUME_ON_START environment variable is set to 1, resuming');\n inspector.client.callMethod('Debugger.resume');\n return;\n }\n\n // Save execution context's data\n currentBacktrace = Backtrace.from(callFrames);\n selectedFrame = currentBacktrace[0];\n // const { scriptId, lineNumber } = selectedFrame.location;\n\n // const breakType = reason === 'other' ? 'break' : reason;\n // const script = knownScripts[scriptId];\n // const scriptUrl = script ? getRelativePath(script.url) : '[unknown]';\n\n // const header = `${breakType} in ${scriptUrl}:${lineNumber + 1}`;\n\n void inspector.suspendReplWhile(() => {\n const context = selectedFrame?.list(3);\n inspect(context);\n });\n });\n\n function handleResumed(): void {\n currentBacktrace = undefined;\n selectedFrame = undefined;\n }\n\n Debugger.on('resumed', handleResumed);\n\n //Debugger.on('breakpointResolved', handleBreakpointResolved);\n\n Debugger.on('scriptParsed', (script: Debugger.ScriptParsedEventDataType) => {\n const { scriptId, url } = script;\n if (url) {\n knownScripts[scriptId] = Object.assign(\n {\n isNative: isNativeUrl(url),\n },\n script,\n );\n }\n });\n\n /*Profiler.on('consoleProfileFinished', ({ profile }) => {\n Profile.createAndRegister({ profile });\n print([\n 'Captured new CPU profile.',\n `Access it with profiles[${profiles.length - 1}]`\n ].join('\\n'));\n });*/\n\n function initializeContext(context: Context): void {\n Object.defineProperty(context, 'Debugger', {\n value: inspector.Debugger,\n enumerable: true,\n configurable: true,\n // @ts-expect-error fix later\n writeable: false,\n });\n Object.defineProperty(context, 'HeapProfiler', {\n value: inspector.HeapProfiler,\n enumerable: true,\n configurable: true,\n // @ts-expect-error fix later\n writeable: false,\n });\n Object.defineProperty(context, 'Profiler', {\n value: inspector.Profiler,\n enumerable: true,\n configurable: true,\n // @ts-expect-error fix later\n writeable: false,\n });\n Object.defineProperty(context, 'Runtime', {\n value: inspector.Runtime,\n enumerable: true,\n configurable: true,\n // @ts-expect-error fix later\n writeable: false,\n });\n\n /*copyOwnProperties(context, {\n get help() {\n print(HELP);\n },\n\n get run() {\n return inspector.run();\n },\n\n get kill() {\n return inspector.killChild();\n },\n\n get restart() {\n return inspector.run();\n },\n\n get cont() {\n handleResumed();\n return Debugger.resume();\n },\n\n get next() {\n handleResumed();\n return Debugger.stepOver();\n },\n\n get step() {\n handleResumed();\n return Debugger.stepInto();\n },\n\n get out() {\n handleResumed();\n return Debugger.stepOut();\n },\n\n get pause() {\n return Debugger.pause();\n },\n\n get backtrace() {\n return currentBacktrace;\n },\n\n get breakpoints() {\n return listBreakpoints();\n },\n\n exec(expr) {\n return evalInCurrentContext(expr);\n },\n\n get profile() {\n return Profiler.start();\n },\n\n get profileEnd() {\n return Profiler.stop()\n .then(Profile.createAndRegister);\n },\n\n get profiles() {\n return profiles;\n },\n\n takeHeapSnapshot(filename = 'node.heapsnapshot') {\n return new Promise((resolve, reject) => {\n const absoluteFile = Path.resolve(filename);\n const writer = FS.createWriteStream(absoluteFile);\n let sizeWritten = 0;\n function onProgress({ done, total, finished }) {\n if (finished) {\n print('Heap snaphost prepared.');\n } else {\n print(`Heap snapshot: ${done}/${total}`, true);\n }\n }\n function onChunk({ chunk }) {\n sizeWritten += chunk.length;\n writer.write(chunk);\n print(`Writing snapshot: ${sizeWritten}`, true);\n }\n function onResolve() {\n writer.end(() => {\n teardown();\n print(`Wrote snapshot: ${absoluteFile}`);\n resolve();\n });\n }\n function onReject(error) {\n teardown();\n reject(error);\n }\n function teardown() {\n HeapProfiler.removeListener(\n 'reportHeapSnapshotProgress', onProgress);\n HeapProfiler.removeListener('addHeapSnapshotChunk', onChunk);\n }\n\n HeapProfiler.on('reportHeapSnapshotProgress', onProgress);\n HeapProfiler.on('addHeapSnapshotChunk', onChunk);\n\n print('Heap snapshot: 0/0', true);\n HeapProfiler.takeHeapSnapshot({ reportProgress: true })\n .then(onResolve, onReject);\n });\n },\n\n get watchers() {\n return watchers();\n },\n\n watch(expr) {\n watchedExpressions.push(expr);\n },\n\n unwatch(expr) {\n const index = watchedExpressions.indexOf(expr);\n\n // Unwatch by expression\n // or\n // Unwatch by watcher number\n watchedExpressions.splice(index !== -1 ? index : +expr, 1);\n },\n\n get repl() {\n // Don't display any default messages\n const listeners = repl.listeners('SIGINT').slice(0);\n repl.removeAllListeners('SIGINT');\n\n const oldContext = repl.context;\n\n exitDebugRepl = () => {\n // Restore all listeners\n process.nextTick(() => {\n listeners.forEach((listener) => {\n repl.on('SIGINT', listener);\n });\n });\n\n // Exit debug repl\n repl.eval = controlEval;\n\n // Swap history\n history.debug = repl.history;\n repl.history = history.control;\n\n repl.context = oldContext;\n repl.setPrompt('debug> ');\n repl.displayPrompt();\n\n repl.removeListener('SIGINT', exitDebugRepl);\n repl.removeListener('exit', exitDebugRepl);\n\n exitDebugRepl = null;\n };\n\n // Exit debug repl on SIGINT\n repl.on('SIGINT', exitDebugRepl);\n\n // Exit debug repl on repl exit\n repl.on('exit', exitDebugRepl);\n\n // Set new\n repl.eval = debugEval;\n repl.context = {};\n\n // Swap history\n history.control = repl.history;\n repl.history = history.debug;\n\n repl.setPrompt('> ');\n\n print('Press Ctrl + C to leave debug repl');\n repl.displayPrompt();\n },\n\n get version() {\n return Runtime.evaluate({\n expression: 'process.versions.v8',\n contextId: 1,\n returnByValue: true,\n }).then(({ result }) => {\n print(result.value);\n });\n },\n\n scripts: listScripts,\n\n //setBreakpoint,\n //clearBreakpoint,\n setPauseOnExceptions,\n get breakOnException() {\n return setPauseOnExceptions('all');\n },\n get breakOnUncaught() {\n return setPauseOnExceptions('uncaught');\n },\n get breakOnNone() {\n return setPauseOnExceptions('none');\n },\n\n list,\n });*/\n //aliasProperties(context, SHORTCUTS);\n }\n\n function initAfterStart(): Promise {\n const setupTasks = [\n Runtime.enable(),\n //Profiler.enable(),\n //Profiler.setSamplingInterval({ interval: 100 }),\n Debugger.enable(),\n Debugger.setPauseOnExceptions({ state: 'none' }),\n Debugger.setAsyncCallStackDepth({ maxDepth: 1 }),\n Debugger.setBlackboxPatterns({ patterns: [] }),\n // Debugger.setPauseOnExceptions({ state: 'all' }),\n //restoreBreakpoints(),\n Runtime.runIfWaitingForDebugger(),\n ];\n return Promise.all(setupTasks);\n }\n\n return function startRepl(): REPLServer {\n inspector.client.on('close', () => resetOnStart());\n inspector.client.on('ready', () => {\n initAfterStart().catch(err => {\n print(`Error starting inspector: ${err.message}`);\n });\n });\n\n const replOptions: ReplOptions = {\n prompt: 'debug> ',\n input: inspector.stdin,\n output: inspector.stdout,\n eval: controlEval,\n useGlobal: false,\n ignoreUndefined: true,\n };\n\n repl = start(replOptions);\n initializeContext(repl.context);\n repl.on('reset', initializeContext);\n\n repl.defineCommand('interrupt', () => {\n // We want this for testing purposes where sending CTRL-C can be tricky.\n repl.emit('SIGINT');\n });\n\n // Init once for the initial connection\n initAfterStart().catch(err => {\n print(`Error starting inspector: ${err.message}`);\n });\n\n return repl;\n };\n}\n"]} \ No newline at end of file +{"version":3,"file":"debugger.js","sourceRoot":"","sources":["../../src/lib/debugger.ts"],"names":[],"mappings":";;AA0WA,6BAq5BC;AA/vCD;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,yCAA0C;AAC1C,yCAAqE;AACrE,yCAMmB;AACnB,qCAAqD;AACrD,uCAAyC;AACzC,6CAAgE;AAKhE,MAAM,QAAQ,GAAG,IAAA,oBAAY,EAAC,SAAS,CAAC,CAAC;AAoBzC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;WAgDW;AAEX,MAAM,qBAAqB,GAAG,+BAA+B,CAAC;AAC9D,SAAS,mBAAmB,CAAC,WAA+B;IACxD,MAAM,WAAW,GAAG,WAAW,EAAE,KAAK,CAAC,qBAAqB,CAAC,CAAC;IAC9D,OAAO,WAAW,CAAC,CAAC,CAAC,KAAK,WAAW,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;AACpD,CAAC;AAED,wHAAwH;AACxH,gDAAgD;AAChD,MAAM,OAAO,GAAG,4BAAe,CAAC,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;AAElE,SAAS,WAAW,CAAC,GAAW;IAC5B,GAAG,GAAG,GAAG,CAAC,OAAO,CAAC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xB,IAAI,EAAE,WAAW;YACjB,SAAS,EAAE,KAAK;YAChB,eAAe,EAAE,IAAI;SACxB,CAAC;QAEF,IAAI,GAAG,IAAA,iBAAK,EAAC,WAAW,CAAC,CAAC;QAC1B,iBAAiB,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QAChC,IAAI,CAAC,EAAE,CAAC,OAAO,EAAE,iBAAiB,CAAC,CAAC;QAEpC,IAAI,CAAC,aAAa,CAAC,WAAW,EAAE,GAAG,EAAE;YACjC,wEAAwE;YACxE,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QACxB,CAAC,CAAC,CAAC;QAEH,uCAAuC;QACvC,cAAc,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE;YACzB,KAAK,CAAC,6BAA6B,GAAG,CAAC,OAAO,EAAE,CAAC,CAAC;QACtD,CAAC,CAAC,CAAC;QAEH,OAAO,IAAI,CAAC;IAChB,CAAC,CAAC;AACN,CAAC","sourcesContent":["/*\n * Copyright Node.js contributors. All rights reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\nimport { join, resolve } from 'node:path';\nimport { type ReplOptions, type REPLServer, start } from 'node:repl';\nimport {\n debuglog as debuglogUtil,\n inspect as inspectUtil,\n type InspectOptions,\n type InspectOptionsStylized,\n type Style,\n} from 'node:util';\nimport { type Context, runInContext } from 'node:vm';\nimport { fileURLToPath } from 'node:url';\nimport { builtinModules as PUBLIC_BUILTINS } from 'node:module';\nimport type { Debugger, Runtime } from 'node:inspector';\n\nimport type { NodeInspector } from './inspect';\n\nconst debuglog = debuglogUtil('inspect');\n\ninterface PropertyPreview {\n /**\n * Property name.\n */\n name: string;\n /**\n * Object type. Accessor means that the property itself is an accessor property.\n */\n type: string;\n /**\n * User-friendly property value string.\n */\n value?: string | undefined;\n /**\n * Object subtype hint. Specified for object type values only.\n */\n subtype?: string | undefined;\n}\n/*const SHORTCUTS = {\n cont: 'c',\n next: 'n',\n step: 's',\n out: 'o',\n backtrace: 'bt',\n setBreakpoint: 'sb',\n clearBreakpoint: 'cb',\n run: 'r',\n};\n\nconst HELP = `\nrun, restart, r Run the application or reconnect\nkill Kill a running application or disconnect\n\ncont, c Resume execution\nnext, n Continue to next line in current file\nstep, s Step into, potentially entering a function\nout, o Step out, leaving the current function\nbacktrace, bt Print the current backtrace\nlist Print the source around the current line where execution\n is currently paused\n\nsetBreakpoint, sb Set a breakpoint\nclearBreakpoint, cb Clear a breakpoint\nbreakpoints List all known breakpoints\nbreakOnException Pause execution whenever an exception is thrown\nbreakOnUncaught Pause execution whenever an exception isn't caught\nbreakOnNone Don't pause on exceptions (this is the default)\n\nwatch(expr) Start watching the given expression\nunwatch(expr) Stop watching an expression\nwatchers Print all watched expressions and their current values\n\nexec(expr) Evaluate the expression and print the value\nrepl Enter a debug repl that works like exec\n\nscripts List application scripts that are currently loaded\nscripts(true) List all scripts (including node-internals)\n\nprofile Start CPU profiling session.\nprofileEnd Stop current CPU profiling session.\nprofiles Array of completed CPU profiling sessions.\nprofiles[n].save(filepath = 'node.cpuprofile')\n Save CPU profiling session to disk as JSON.\n\ntakeHeapSnapshot(filepath = 'node.heapsnapshot')\n Take a heap snapshot and save to disk as JSON.\n`.trim();*/\n\nconst FUNCTION_NAME_PATTERN = /^(?:function\\*? )?([^(\\s]+)\\(/;\nfunction extractFunctionName(description: string | undefined): string {\n const fnNameMatch = description?.match(FUNCTION_NAME_PATTERN);\n return fnNameMatch ? `: ${fnNameMatch[1]}` : '';\n}\n\n// process.binding is a method available on the process object, which allows you to load internal modules written in C++\n// @ts-expect-error binding is internal function\nconst NATIVES = PUBLIC_BUILTINS ? process.binding('natives') : {};\n\nfunction isNativeUrl(url: string): boolean {\n url = url.replace(/\\.js$/, '');\n if (PUBLIC_BUILTINS) {\n if (url.startsWith('internal/') || PUBLIC_BUILTINS.includes(url)) {\n return true;\n }\n }\n\n return url in NATIVES || url === 'bootstrap_node';\n}\n\nfunction getRelativePath(filenameOrURL: string): string {\n const dir = join(resolve(), 'x').slice(0, -1);\n\n const filename = filenameOrURL.startsWith('file://') ? fileURLToPath(filenameOrURL) : filenameOrURL;\n\n // Change a path to relative, if possible\n if (filename.indexOf(dir) === 0) {\n return filename.slice(dir.length);\n }\n return filename;\n}\n\nfunction toCallback(promise: Promise, callback: (...args: any[]) => void): void {\n function forward(...args: any[]): void {\n process.nextTick(() => callback(...args));\n }\n\n promise.then(forward.bind(null, null), forward);\n}\n\n// Adds spaces and prefix to number\n// maxN is a maximum number we should have space for\nfunction leftPad(n: number, prefix: string, maxN: number): string {\n const s = n.toString();\n const nchars = Math.max(2, String(maxN).length) + 1;\n const nspaces = nchars - s.length - 1;\n\n return prefix + ' '.repeat(nspaces) + s;\n}\n\nfunction markSourceColumn(sourceText: string, position: number, useColors?: boolean): string {\n if (!sourceText) {\n return '';\n }\n\n const head = sourceText.slice(0, position);\n let tail = sourceText.slice(position);\n\n // Colorize char if stdout supports colours\n if (useColors) {\n tail = tail.replace(/(.+?)([^\\w]|$)/, '\\u001b[32m$1\\u001b[39m$2');\n }\n\n // Return source line with coloured char at `position`\n return [head, tail].join('');\n}\n\nfunction extractErrorMessage(stack: string | undefined): string {\n if (!stack) {\n return '';\n }\n const m = stack.match(/^\\w+: ([^\\n]+)/);\n return m ? m[1] : stack;\n}\n\nfunction convertResultToError(result: Runtime.RemoteObject): Error {\n const { className, description } = result;\n const err = new Error(extractErrorMessage(description));\n err.stack = description;\n Object.defineProperty(err, 'name', { value: className });\n return err;\n}\n\nclass RemoteObject implements Runtime.RemoteObject {\n type: string;\n subtype?: string | undefined;\n className?: string | undefined;\n\n value: any;\n unserializableValue?: Runtime.UnserializableValue | undefined;\n description: string | undefined;\n objectId?: Runtime.RemoteObjectId | undefined;\n preview?: Runtime.ObjectPreview | undefined;\n customPreview?: Runtime.CustomPreview | undefined;\n\n constructor(attributes: Runtime.RemoteObject | undefined) {\n this.type = 'undefined';\n Object.assign(this, attributes);\n if (this.type === 'number') {\n this.value = this.unserializableValue ? +this.unserializableValue : +this.value;\n }\n }\n\n [inspectUtil.custom](_depth: number, opts: InspectOptionsStylized): string {\n function formatProperty(prop: PropertyPreview): any {\n switch (prop.type) {\n case 'string':\n case 'undefined':\n return inspectUtil(prop.value, opts);\n\n case 'number':\n case 'boolean':\n return opts.stylize(prop.value as string, prop.type);\n\n case 'object':\n case 'symbol':\n if (prop.subtype === 'date') {\n return inspectUtil(new Date(prop.value as string), opts);\n }\n if (prop.subtype === 'array') {\n return opts.stylize(prop.value as string, 'special');\n }\n return opts.stylize(prop.value as string, (prop.subtype as Style) || 'special');\n\n default:\n return prop.value;\n }\n }\n\n switch (this.type) {\n case 'boolean':\n case 'number':\n case 'string':\n case 'undefined':\n return inspectUtil(this.value, opts);\n\n case 'symbol':\n return opts.stylize(this.description as string, 'special');\n\n case 'function': {\n const fnName = extractFunctionName(this.description);\n const formatted = `[${this.className}${fnName}]`;\n return opts.stylize(formatted, 'special');\n }\n\n case 'object':\n switch (this.subtype) {\n case 'date':\n return inspectUtil(new Date(this.description as string), opts);\n\n case 'null':\n return inspectUtil(null, opts);\n\n case 'regexp':\n return opts.stylize(this.description as string, 'regexp');\n\n default:\n break;\n }\n if (this.preview) {\n const props: any[] = this.preview.properties.map((prop, idx) => {\n const value = formatProperty(prop);\n if (prop.name === `${idx}`) {\n return value;\n }\n return `${prop.name}: ${value}`;\n });\n if (this.preview.overflow) {\n props.push('...');\n }\n const singleLine = props.join(', ');\n const propString = singleLine.length > 60 ? props.join(',\\n ') : singleLine;\n\n return this.subtype === 'array' ? `[ ${propString} ]` : `{ ${propString} }`;\n }\n return this.description || '';\n\n default:\n return this.description || '';\n }\n }\n\n static fromEvalResult({ result, wasThrown }: { result: RemoteObject; wasThrown?: boolean }): RemoteObject | Error {\n if (wasThrown) {\n return convertResultToError(result);\n }\n return new RemoteObject(result);\n }\n}\n\nclass ScopeSnapshot implements Debugger.Scope {\n /**\n * Scope type.\n */\n type: string;\n /**\n * Object representing the scope. For global and with scopes it represents the actual object; for the rest of the scopes, it is artificial transient object enumerating scope variables as its properties.\n */\n object: Runtime.RemoteObject;\n\n name?: string | undefined;\n /**\n * Location in the source code where scope starts\n */\n startLocation?: Debugger.Location | undefined;\n /**\n * Location in the source code where scope ends\n */\n endLocation?: Debugger.Location | undefined;\n\n properties: Map;\n\n completionGroup: string[];\n\n constructor(scope: Debugger.Scope, properties: Runtime.PropertyDescriptor[]) {\n this.type = scope.type;\n this.object = scope.object;\n\n Object.assign(this, scope);\n\n this.properties = new Map(\n properties.map(prop => {\n const value = new RemoteObject(prop.value);\n return [prop.name, value];\n }),\n );\n\n this.completionGroup = properties.map(prop => prop.name);\n }\n\n [inspectUtil.custom](_depth: number, opts: InspectOptions): string {\n const type = `${this.type[0].toUpperCase()}${this.type.slice(1)}`;\n const name = this.name ? `<${this.name}>` : '';\n const prefix = `${type}${name} `;\n return inspectUtil(this.properties, opts).replace(/^Map /, prefix);\n }\n}\n/*\nfunction copyOwnProperties(target: any, source: any): void {\n Object.getOwnPropertyNames(source).forEach(prop => {\n const descriptor = Object.getOwnPropertyDescriptor(source, prop);\n if (descriptor) {\n Object.defineProperty(target, prop, descriptor);\n }\n });\n}\n\nfunction aliasProperties(target, mapping) {\n Object.keys(mapping).forEach((key) => {\n const descriptor = Object.getOwnPropertyDescriptor(target, key);\n Object.defineProperty(target, mapping[key], descriptor);\n });\n}\n*/\nexport default function createRepl(inspector: NodeInspector): () => REPLServer {\n const { Debugger, /*HeapProfiler, Profiler,*/ Runtime } = inspector;\n\n let repl: REPLServer;\n\n // Things we want to keep around\n // const history = { control: [], debug: [] };\n // const watchedExpressions = [];\n // const knownBreakpoints = [];\n // let pauseOnExceptionState = 'none';\n let lastCommand: string;\n\n // Things we need to reset when the app restarts\n let knownScripts: Record = {};\n let currentBacktrace: CallFrame[] | undefined;\n let selectedFrame: CallFrame | undefined;\n let exitDebugRepl: undefined | (() => void);\n\n function resetOnStart(): void {\n knownScripts = {};\n currentBacktrace = undefined;\n selectedFrame = undefined;\n\n if (exitDebugRepl) {\n exitDebugRepl();\n }\n exitDebugRepl = undefined;\n }\n\n resetOnStart();\n\n const INSPECT_OPTIONS: InspectOptions = { colors: inspector.stdout.isTTY };\n function inspect(value: any): string {\n return inspectUtil(value, INSPECT_OPTIONS);\n }\n\n function print(value: any, oneline = false): void {\n const text = typeof value === 'string' ? value : inspect(value);\n return inspector.print(text, oneline);\n }\n\n function getCurrentLocation(): Debugger.Location {\n if (!selectedFrame) {\n throw new Error('Requires execution to be paused');\n }\n return selectedFrame.location;\n }\n\n function isCurrentScript(script: Debugger.ScriptParsedEventDataType & { isNative: boolean }): boolean {\n return !!selectedFrame && getCurrentLocation().scriptId === script.scriptId;\n }\n\n function formatScripts(displayNatives = false): string {\n function isVisible(script: Debugger.ScriptParsedEventDataType & { isNative: boolean }): boolean {\n if (displayNatives) {\n return true;\n }\n return !script.isNative || isCurrentScript(script);\n }\n\n return Object.keys(knownScripts)\n .map(scriptId => knownScripts[scriptId])\n .filter(isVisible)\n .map(script => {\n const isCurrent = isCurrentScript(script);\n const { isNative, url } = script;\n const name = `${getRelativePath(url)}${isNative ? ' ' : ''}`;\n return `${isCurrent ? '*' : ' '} ${script.scriptId}: ${name}`;\n })\n .join('\\n');\n }\n function listScripts(displayNatives = false): void {\n print(formatScripts(displayNatives));\n }\n // @ts-expect-error no idea what this is\n listScripts[inspectUtil.custom] = function listWithoutInternal(): string {\n return formatScripts();\n };\n /*\n const profiles = [];\n class Profile {\n constructor(data) {\n this.data = data;\n }\n\n static createAndRegister({ profile }) {\n const p = new Profile(profile);\n profiles.push(p);\n return p;\n }\n\n [util.inspect.custom](depth, { stylize }) {\n const { startTime, endTime } = this.data;\n return stylize(`[Profile ${endTime - startTime}μs]`, 'special');\n }\n\n save(filename = 'node.cpuprofile') {\n const absoluteFile = Path.resolve(filename);\n const json = JSON.stringify(this.data);\n FS.writeFileSync(absoluteFile, json);\n print('Saved profile to ' + absoluteFile);\n }\n }\n*/\n class SourceSnippet {\n scriptSource: string;\n /**\n * Script identifier as reported in the Debugger.scriptParsed.\n */\n scriptId: Runtime.ScriptId;\n /**\n * Line number in the script (0-based).\n */\n lineNumber: number;\n /**\n * Column number in the script (0-based).\n */\n columnNumber: number;\n delta: number;\n constructor(location: Debugger.Location, delta: number, scriptSource: string) {\n this.lineNumber = location.lineNumber;\n this.columnNumber = location.columnNumber || 0;\n this.scriptId = location.scriptId;\n this.scriptSource = scriptSource;\n this.delta = delta;\n Object.assign(this, location);\n }\n\n [inspectUtil.custom](_depth: number, options: InspectOptions): string {\n const { /* scriptId, */ lineNumber, columnNumber, delta, scriptSource } = this;\n const start = Math.max(1, lineNumber - delta + 1);\n const end = lineNumber + delta + 1;\n\n const lines = scriptSource.split('\\n');\n return lines\n .slice(start - 1, end)\n .map((lineText, offset) => {\n const i = start + offset;\n const isCurrent = i === lineNumber + 1;\n\n const markedLine = isCurrent ? markSourceColumn(lineText, columnNumber, options.colors) : lineText;\n\n /*\n let isBreakpoint = false;\n knownBreakpoints.forEach(({ location }) => {\n if (!location) return;\n if (scriptId === location.scriptId &&\n i === (location.lineNumber + 1)) {\n isBreakpoint = true;\n }\n });\n */\n\n let prefixChar = ' ';\n if (isCurrent) {\n prefixChar = '>';\n } /*else if (isBreakpoint) {\n prefixChar = '*';\n }*/\n return `${leftPad(i, prefixChar, end)} ${markedLine}`;\n })\n .join('\\n');\n }\n }\n\n function getSourceSnippet(location: Debugger.Location, delta: number = 5): SourceSnippet {\n const { scriptId } = location;\n return Debugger.getScriptSource({ scriptId }).then(\n ({ scriptSource }: Debugger.GetScriptSourceReturnType) => new SourceSnippet(location, delta, scriptSource),\n );\n }\n\n class CallFrame implements Debugger.CallFrame {\n /**\n * Call frame identifier. This identifier is only valid while the virtual machine is paused.\n */\n callFrameId: Debugger.CallFrameId;\n /**\n * Name of the JavaScript function called on this call frame.\n */\n functionName: string;\n /**\n * Location in the source code.\n */\n functionLocation?: Debugger.Location | undefined;\n /**\n * Location in the source code.\n */\n location: Debugger.Location;\n /**\n * JavaScript script name or url.\n */\n url: string;\n /**\n * Scope chain for this call frame.\n */\n scopeChain: Debugger.Scope[];\n /**\n * this object for this call frame.\n */\n this: Runtime.RemoteObject;\n /**\n * The value being returned if the function is at return point.\n */\n returnValue?: Runtime.RemoteObject | undefined;\n\n constructor(callFrame: Debugger.CallFrame) {\n this.functionName = callFrame.functionName;\n this.url = callFrame.url;\n this.scopeChain = callFrame.scopeChain;\n this.this = callFrame.this;\n this.returnValue = callFrame.returnValue;\n this.location = callFrame.location;\n this.callFrameId = callFrame.callFrameId;\n\n Object.assign(this, callFrame);\n }\n\n loadScopes(): Promise {\n return Promise.all(\n this.scopeChain\n .filter(scope => scope.type !== 'global')\n .map(scope => {\n const { objectId } = scope.object;\n return Runtime.getProperties({\n objectId,\n generatePreview: true,\n } as Runtime.GetPropertiesParameterType).then(({ result }: Runtime.GetPropertiesReturnType) => {\n return new ScopeSnapshot(scope, result);\n });\n }),\n );\n }\n\n list(delta: number = 5): SourceSnippet {\n return getSourceSnippet(this.location, delta);\n }\n }\n\n class Backtrace extends Array {\n [inspectUtil.custom](): string {\n return this.map((callFrame, idx) => {\n const {\n location: { scriptId, lineNumber, columnNumber },\n functionName,\n } = callFrame;\n const name = functionName || '(anonymous)';\n\n const script = knownScripts[scriptId];\n const relativeUrl = (script && getRelativePath(script.url)) || '';\n const frameLocation = `${relativeUrl}:${lineNumber + 1}:${columnNumber}`;\n\n return `#${idx} ${name} ${frameLocation}`;\n }).join('\\n');\n }\n\n static from(callFrames: CallFrame[]): CallFrame[] {\n return super.from(\n Array.from(callFrames).map(callFrame => {\n if (callFrame instanceof CallFrame) {\n return callFrame;\n }\n return new CallFrame(callFrame);\n }),\n );\n }\n }\n\n function prepareControlCode(input: string): string {\n if (input === '\\n') {\n return lastCommand;\n }\n // exec process.title => exec(\"process.title\");\n const match = input.match(/^\\s*exec\\s+([^\\n]*)/);\n if (match) {\n lastCommand = `exec(${JSON.stringify(match[1])})`;\n } else {\n lastCommand = input;\n }\n return lastCommand;\n }\n\n // function evalInCurrentContext(code) {\n // // Repl asked for scope variables\n // if (code === '.scope') {\n // if (!selectedFrame) {\n // return Promise.reject(new Error('Requires execution to be paused'));\n // }\n // return selectedFrame.loadScopes().then((scopes) => {\n // return scopes.map((scope) => scope.completionGroup);\n // });\n // }\n //\n // if (selectedFrame) {\n // return Debugger.evaluateOnCallFrame({\n // callFrameId: selectedFrame.callFrameId,\n // expression: code,\n // objectGroup: 'node-inspect',\n // generatePreview: true,\n // }).then(RemoteObject.fromEvalResult);\n // }\n // return Runtime.evaluate({\n // expression: code,\n // objectGroup: 'node-inspect',\n // generatePreview: true,\n // }).then(RemoteObject.fromEvalResult);\n // }\n\n function controlEval(\n input: string,\n context: Context,\n filename: string,\n callback: (error: Error | null, result?: any) => void,\n ): void {\n debuglog('eval:', input);\n function returnToCallback(error: Error | null, result?: any): void {\n debuglog('end-eval:', input, error);\n callback(error, result);\n }\n\n try {\n const code = prepareControlCode(input);\n const result = runInContext(code, context, filename);\n\n if (result && typeof result.then === 'function') {\n toCallback(result, returnToCallback);\n return;\n }\n returnToCallback(null, result);\n } catch (e: any) {\n returnToCallback(e as Error);\n }\n }\n\n // function debugEval(input, context, filename, callback) {\n // debuglog('eval:', input);\n // function returnToCallback(error, result) {\n // debuglog('end-eval:', input, error);\n // callback(error, result);\n // }\n //\n // try {\n // const result = evalInCurrentContext(input);\n //\n // if (result && typeof result.then === 'function') {\n // toCallback(result, returnToCallback);\n // return;\n // }\n // returnToCallback(null, result);\n // } catch (e) {\n // returnToCallback(e);\n // }\n // }\n\n /*function formatWatchers(verbose = false) {\n if (!watchedExpressions.length) {\n return Promise.resolve('');\n }\n\n const inspectValue = (expr) =>\n evalInCurrentContext(expr)\n // .then(formatValue)\n .catch((error) => `<${error.message}>`);\n const lastIndex = watchedExpressions.length - 1;\n\n return Promise.all(watchedExpressions.map(inspectValue))\n .then((values) => {\n const lines = watchedExpressions\n .map((expr, idx) => {\n const prefix = `${leftPad(idx, ' ', lastIndex)}: ${expr} =`;\n const value = inspect(values[idx], { colors: true });\n if (value.indexOf('\\n') === -1) {\n return `${prefix} ${value}`;\n }\n return `${prefix}\\n ${value.split('\\n').join('\\n ')}`;\n });\n return lines.join('\\n');\n })\n .then((valueList) => {\n return verbose ? `Watchers:\\n${valueList}\\n` : valueList;\n });\n }*/\n\n //function watchers(verbose = false) {\n // return formatWatchers(verbose).then(print);\n //}\n\n // List source code\n // function list(delta = 5) {\n // return selectedFrame.list(delta)\n // .then(null, (error) => {\n // print('You can\\'t list source code right now');\n // throw error;\n // });\n // }\n\n //function handleBreakpointResolved({ breakpointId, location }) {\n // const script = knownScripts[location.scriptId];\n // const scriptUrl = script && script.url;\n // if (scriptUrl) {\n // Object.assign(location, { scriptUrl });\n // }\n // const isExisting = knownBreakpoints.some((bp) => {\n // if (bp.breakpointId === breakpointId) {\n // Object.assign(bp, { location });\n // return true;\n // }\n // return false;\n // });\n // if (!isExisting) {\n // knownBreakpoints.push({ breakpointId, location });\n // }\n //}\n\n // function listBreakpoints() {\n // if (!knownBreakpoints.length) {\n // print('No breakpoints yet');\n // return;\n // }\n //\n // function formatLocation(location) {\n // if (!location) return '';\n // const script = knownScripts[location.scriptId];\n // const scriptUrl = script ? script.url : location.scriptUrl;\n // return `${getRelativePath(scriptUrl)}:${location.lineNumber + 1}`;\n // }\n // const breaklist = knownBreakpoints\n // .map((bp, idx) => `#${idx} ${formatLocation(bp.location)}`)\n // .join('\\n');\n // print(breaklist);\n // }\n\n // function setBreakpoint(script, line, condition, silent) {\n // function registerBreakpoint({ breakpointId, actualLocation }) {\n // handleBreakpointResolved({ breakpointId, location: actualLocation });\n // if (actualLocation && actualLocation.scriptId) {\n // if (!silent) return getSourceSnippet(actualLocation, 5);\n // } else {\n // print(`Warning: script '${script}' was not loaded yet.`);\n // }\n // return undefined;\n // }\n //\n // // setBreakpoint(): set breakpoint at current location\n // if (script === undefined) {\n // return Debugger\n // .setBreakpoint({ location: getCurrentLocation(), condition })\n // .then(registerBreakpoint);\n // }\n //\n // // setBreakpoint(line): set breakpoint in current script at specific line\n // if (line === undefined && typeof script === 'number') {\n // const location = {\n // scriptId: getCurrentLocation().scriptId,\n // lineNumber: script - 1,\n // };\n // return Debugger.setBreakpoint({ location, condition })\n // .then(registerBreakpoint);\n // }\n //\n // if (typeof script !== 'string') {\n // throw new TypeError(`setBreakpoint() expects a string, got ${script}`);\n // }\n //\n // // setBreakpoint('fn()'): Break when a function is called\n // if (script.endsWith('()')) {\n // const debugExpr = `debug(${script.slice(0, -2)})`;\n // const debugCall = selectedFrame\n // ? Debugger.evaluateOnCallFrame({\n // callFrameId: selectedFrame.callFrameId,\n // expression: debugExpr,\n // includeCommandLineAPI: true,\n // })\n // : Runtime.evaluate({\n // expression: debugExpr,\n // includeCommandLineAPI: true,\n // });\n // return debugCall.then(({ result, wasThrown }) => {\n // if (wasThrown) return convertResultToError(result);\n // return undefined; // This breakpoint can't be removed the same way\n // });\n // }\n //\n // // setBreakpoint('scriptname')\n // let scriptId = null;\n // let ambiguous = false;\n // if (knownScripts[script]) {\n // scriptId = script;\n // } else {\n // for (const id of Object.keys(knownScripts)) {\n // const scriptUrl = knownScripts[id].url;\n // if (scriptUrl && scriptUrl.indexOf(script) !== -1) {\n // if (scriptId !== null) {\n // ambiguous = true;\n // }\n // scriptId = id;\n // }\n // }\n // }\n //\n // if (ambiguous) {\n // print('Script name is ambiguous');\n // return undefined;\n // }\n // if (line <= 0) {\n // print('Line should be a positive value');\n // return undefined;\n // }\n //\n // if (scriptId !== null) {\n // const location = { scriptId, lineNumber: line - 1 };\n // return Debugger.setBreakpoint({ location, condition })\n // .then(registerBreakpoint);\n // }\n //\n // const escapedPath = script.replace(/([/\\\\.?*()^${}|[\\]])/g, '\\\\$1');\n // const urlRegex = `^(.*[\\\\/\\\\\\\\])?${escapedPath}$`;\n //\n // return Debugger\n // .setBreakpointByUrl({ urlRegex, lineNumber: line - 1, condition })\n // .then((bp) => {\n // // TODO: handle bp.locations in case the regex matches existing files\n // if (!bp.location) { // Fake it for now.\n // Object.assign(bp, {\n // actualLocation: {\n // scriptUrl: `.*/${script}$`,\n // lineNumber: line - 1,\n // },\n // });\n // }\n // return registerBreakpoint(bp);\n // });\n // }\n //\n // function clearBreakpoint(url, line) {\n // const breakpoint = knownBreakpoints.find(({ location }) => {\n // if (!location) return false;\n // const script = knownScripts[location.scriptId];\n // if (!script) return false;\n // return (\n // script.url.indexOf(url) !== -1 && (location.lineNumber + 1) === line\n // );\n // });\n // if (!breakpoint) {\n // print(`Could not find breakpoint at ${url}:${line}`);\n // return Promise.resolve();\n // }\n // return Debugger.removeBreakpoint({ breakpointId: breakpoint.breakpointId })\n // .then(() => {\n // const idx = knownBreakpoints.indexOf(breakpoint);\n // knownBreakpoints.splice(idx, 1);\n // });\n // }\n //\n // function restoreBreakpoints() {\n // const lastBreakpoints = knownBreakpoints.slice();\n // knownBreakpoints.length = 0;\n // const newBreakpoints = lastBreakpoints\n // .filter(({ location }) => !!location.scriptUrl)\n // .map(({ location }) =>\n // setBreakpoint(location.scriptUrl, location.lineNumber + 1));\n // if (!newBreakpoints.length) return Promise.resolve();\n // return Promise.all(newBreakpoints).then((results) => {\n // print(`${results.length} breakpoints restored.`);\n // });\n // }\n\n // function setPauseOnExceptions(state) {\n // return Debugger.setPauseOnExceptions({ state })\n // .then(() => {\n // pauseOnExceptionState = state;\n // });\n // }\n\n Debugger.on('paused', (data: Debugger.PausedEventDataType): void => {\n const callFrames: CallFrame[] = data.callFrames as CallFrame[];\n const reason: string = data.reason;\n\n if (process.env.NODE_INSPECT_RESUME_ON_START === '1' && reason === 'Break on start') {\n debuglog('Paused on start, but NODE_INSPECT_RESUME_ON_START environment variable is set to 1, resuming');\n inspector.client.callMethod('Debugger.resume');\n return;\n }\n\n // Save execution context's data\n currentBacktrace = Backtrace.from(callFrames);\n selectedFrame = currentBacktrace[0];\n // const { scriptId, lineNumber } = selectedFrame.location;\n\n // const breakType = reason === 'other' ? 'break' : reason;\n // const script = knownScripts[scriptId];\n // const scriptUrl = script ? getRelativePath(script.url) : '[unknown]';\n\n // const header = `${breakType} in ${scriptUrl}:${lineNumber + 1}`;\n\n void inspector.suspendReplWhile(() => {\n const context = selectedFrame?.list(3);\n inspect(context);\n });\n });\n\n function handleResumed(): void {\n currentBacktrace = undefined;\n selectedFrame = undefined;\n }\n\n Debugger.on('resumed', handleResumed);\n\n //Debugger.on('breakpointResolved', handleBreakpointResolved);\n\n Debugger.on('scriptParsed', (script: Debugger.ScriptParsedEventDataType) => {\n const { scriptId, url } = script;\n if (url) {\n knownScripts[scriptId] = Object.assign(\n {\n isNative: isNativeUrl(url),\n },\n script,\n );\n }\n });\n\n /*Profiler.on('consoleProfileFinished', ({ profile }) => {\n Profile.createAndRegister({ profile });\n print([\n 'Captured new CPU profile.',\n `Access it with profiles[${profiles.length - 1}]`\n ].join('\\n'));\n });*/\n\n function initializeContext(context: Context): void {\n Object.defineProperty(context, 'Debugger', {\n value: inspector.Debugger,\n enumerable: true,\n configurable: true,\n // @ts-expect-error fix later\n writeable: false,\n });\n Object.defineProperty(context, 'HeapProfiler', {\n value: inspector.HeapProfiler,\n enumerable: true,\n configurable: true,\n // @ts-expect-error fix later\n writeable: false,\n });\n Object.defineProperty(context, 'Profiler', {\n value: inspector.Profiler,\n enumerable: true,\n configurable: true,\n // @ts-expect-error fix later\n writeable: false,\n });\n Object.defineProperty(context, 'Runtime', {\n value: inspector.Runtime,\n enumerable: true,\n configurable: true,\n // @ts-expect-error fix later\n writeable: false,\n });\n\n /*copyOwnProperties(context, {\n get help() {\n print(HELP);\n },\n\n get run() {\n return inspector.run();\n },\n\n get kill() {\n return inspector.killChild();\n },\n\n get restart() {\n return inspector.run();\n },\n\n get cont() {\n handleResumed();\n return Debugger.resume();\n },\n\n get next() {\n handleResumed();\n return Debugger.stepOver();\n },\n\n get step() {\n handleResumed();\n return Debugger.stepInto();\n },\n\n get out() {\n handleResumed();\n return Debugger.stepOut();\n },\n\n get pause() {\n return Debugger.pause();\n },\n\n get backtrace() {\n return currentBacktrace;\n },\n\n get breakpoints() {\n return listBreakpoints();\n },\n\n exec(expr) {\n return evalInCurrentContext(expr);\n },\n\n get profile() {\n return Profiler.start();\n },\n\n get profileEnd() {\n return Profiler.stop()\n .then(Profile.createAndRegister);\n },\n\n get profiles() {\n return profiles;\n },\n\n takeHeapSnapshot(filename = 'node.heapsnapshot') {\n return new Promise((resolve, reject) => {\n const absoluteFile = Path.resolve(filename);\n const writer = FS.createWriteStream(absoluteFile);\n let sizeWritten = 0;\n function onProgress({ done, total, finished }) {\n if (finished) {\n print('Heap snaphost prepared.');\n } else {\n print(`Heap snapshot: ${done}/${total}`, true);\n }\n }\n function onChunk({ chunk }) {\n sizeWritten += chunk.length;\n writer.write(chunk);\n print(`Writing snapshot: ${sizeWritten}`, true);\n }\n function onResolve() {\n writer.end(() => {\n teardown();\n print(`Wrote snapshot: ${absoluteFile}`);\n resolve();\n });\n }\n function onReject(error) {\n teardown();\n reject(error);\n }\n function teardown() {\n HeapProfiler.removeListener(\n 'reportHeapSnapshotProgress', onProgress);\n HeapProfiler.removeListener('addHeapSnapshotChunk', onChunk);\n }\n\n HeapProfiler.on('reportHeapSnapshotProgress', onProgress);\n HeapProfiler.on('addHeapSnapshotChunk', onChunk);\n\n print('Heap snapshot: 0/0', true);\n HeapProfiler.takeHeapSnapshot({ reportProgress: true })\n .then(onResolve, onReject);\n });\n },\n\n get watchers() {\n return watchers();\n },\n\n watch(expr) {\n watchedExpressions.push(expr);\n },\n\n unwatch(expr) {\n const index = watchedExpressions.indexOf(expr);\n\n // Unwatch by expression\n // or\n // Unwatch by watcher number\n watchedExpressions.splice(index !== -1 ? index : +expr, 1);\n },\n\n get repl() {\n // Don't display any default messages\n const listeners = repl.listeners('SIGINT').slice(0);\n repl.removeAllListeners('SIGINT');\n\n const oldContext = repl.context;\n\n exitDebugRepl = () => {\n // Restore all listeners\n process.nextTick(() => {\n listeners.forEach((listener) => {\n repl.on('SIGINT', listener);\n });\n });\n\n // Exit debug repl\n repl.eval = controlEval;\n\n // Swap history\n history.debug = repl.history;\n repl.history = history.control;\n\n repl.context = oldContext;\n repl.setPrompt('debug> ');\n repl.displayPrompt();\n\n repl.removeListener('SIGINT', exitDebugRepl);\n repl.removeListener('exit', exitDebugRepl);\n\n exitDebugRepl = null;\n };\n\n // Exit debug repl on SIGINT\n repl.on('SIGINT', exitDebugRepl);\n\n // Exit debug repl on repl exit\n repl.on('exit', exitDebugRepl);\n\n // Set new\n repl.eval = debugEval;\n repl.context = {};\n\n // Swap history\n history.control = repl.history;\n repl.history = history.debug;\n\n repl.setPrompt('> ');\n\n print('Press Ctrl + C to leave debug repl');\n repl.displayPrompt();\n },\n\n get version() {\n return Runtime.evaluate({\n expression: 'process.versions.v8',\n contextId: 1,\n returnByValue: true,\n }).then(({ result }) => {\n print(result.value);\n });\n },\n\n scripts: listScripts,\n\n //setBreakpoint,\n //clearBreakpoint,\n setPauseOnExceptions,\n get breakOnException() {\n return setPauseOnExceptions('all');\n },\n get breakOnUncaught() {\n return setPauseOnExceptions('uncaught');\n },\n get breakOnNone() {\n return setPauseOnExceptions('none');\n },\n\n list,\n });*/\n //aliasProperties(context, SHORTCUTS);\n }\n\n function initAfterStart(): Promise {\n const setupTasks = [\n Runtime.enable(),\n //Profiler.enable(),\n //Profiler.setSamplingInterval({ interval: 100 }),\n Debugger.enable(),\n Debugger.setPauseOnExceptions({ state: 'none' }),\n Debugger.setAsyncCallStackDepth({ maxDepth: 1 }),\n Debugger.setBlackboxPatterns({ patterns: [] }),\n // Debugger.setPauseOnExceptions({ state: 'all' }),\n //restoreBreakpoints(),\n Runtime.runIfWaitingForDebugger(),\n ];\n return Promise.all(setupTasks);\n }\n\n return function startRepl(): REPLServer {\n inspector.client.on('close', () => resetOnStart());\n inspector.client.on('ready', () => {\n initAfterStart().catch(err => {\n print(`Error starting inspector: ${err.message}`);\n });\n });\n\n const replOptions: ReplOptions = {\n prompt: 'debug> ',\n input: inspector.stdin,\n output: inspector.stdout,\n eval: controlEval,\n useGlobal: false,\n ignoreUndefined: true,\n };\n\n repl = start(replOptions);\n initializeContext(repl.context);\n repl.on('reset', initializeContext);\n\n repl.defineCommand('interrupt', () => {\n // We want this for testing purposes where sending CTRL-C can be tricky.\n repl.emit('SIGINT');\n });\n\n // Init once for the initial connection\n initAfterStart().catch(err => {\n print(`Error starting inspector: ${err.message}`);\n });\n\n return repl;\n };\n}\n"]} \ No newline at end of file diff --git a/build/lib/inspect.js.map b/build/lib/inspect.js.map index 6e2c3a6b1..52abd2f66 100644 --- a/build/lib/inspect.js.map +++ b/build/lib/inspect.js.map @@ -1 +1 @@ -{"version":3,"file":"inspect.js","sourceRoot":"","sources":["../../src/lib/inspect.ts"],"names":[],"mappings":";;;;;;AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,2DAAgF;AAChF,6CAA2C;AAC3C,uCAAmC;AACnC,yCAA2F;AAC3F,yCAA4C;AAC5C,qCAAqC;AAGrC,sCAAsC;AACtC,8FAAqE;AAGrE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;QACvB,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACzB,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC;YACZ,OAAO,CAAC,KAAK,CAAC,gBAAgB,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QAC/D,CAAC;QACD,IAAI,IAAI,CAAC,EAAE,EAAE,CAAC;YACV,OAAO,CAAC,KAAK,CAAC,QAAQ,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;QACrD,CAAC;IACL,CAAC;IAED,IAAI,OAAO,CAAC,IAAI,EAAE,CAAC;QACf,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC;IACvC,CAAC;AACL,CAAC","sourcesContent":["/*\n * Copyright Node.js contributors. All rights reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\nimport { spawn, type ChildProcessWithoutNullStreams } from 'node:child_process';\nimport { EventEmitter } from 'node:events';\nimport { connect } from 'node:net';\nimport { debuglog as utilDebugLog, inspect, type InspectOptionsStylized } from 'node:util';\nimport { normalize, join } from 'node:path';\nimport { existsSync } from 'node:fs';\nimport type { WriteStream, ReadStream } from 'node:tty';\n\n// @ts-expect-error no types available\nimport InspectClient from 'node-inspect/lib/internal/inspect_client';\nimport type { Debugger, Runtime } from 'node:inspector';\nimport type { REPLServer } from 'repl';\nimport createRepl from './debugger';\n// const runAsStandalone = typeof __dirname !== 'undefined';\n\ninterface DebugValue {\n type: 'function' | 'string' | 'boolean' | 'number' | 'object' | 'undefined' | 'null' | 'bigint' | 'symbol';\n description: string;\n value: any;\n}\ninterface DebugVariable {\n name: string;\n value: DebugValue;\n configurable?: boolean;\n enumerable?: boolean;\n isOwn?: boolean;\n writable?: boolean;\n}\nconst breakOnStart = process.argv.includes('--breakOnStart');\n\nconst debuglog = utilDebugLog('inspect');\nlet inspector: NodeInspector;\nlet scriptToDebug = ''; // script.js.yy\nlet instanceToDebug = ''; // adapter.X\nlet alreadyPausedOnFirstLine = false;\n\nclass StartupError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'StartupError';\n }\n}\n\nfunction portIsFree(host: string, port: number, timeout: number = 9999): Promise {\n if (port === 0) {\n // Binding to a random port.\n return Promise.resolve();\n }\n\n const retryDelay = 150;\n let didTimeOut = false;\n\n return new Promise((resolve, reject) => {\n setTimeout(() => {\n didTimeOut = true;\n reject(new StartupError(`Timeout (${timeout}) waiting for ${host}:${port} to be free`));\n }, timeout);\n\n function pingPort(): void {\n if (didTimeOut) {\n return;\n }\n\n const socket = connect(port, host);\n let didRetry = false;\n function retry(): void {\n if (!didRetry && !didTimeOut) {\n didRetry = true;\n setTimeout(pingPort, retryDelay);\n }\n }\n\n socket.on('error', (error: Error) => {\n if ((error as any).code === 'ECONNREFUSED') {\n resolve();\n } else {\n retry();\n }\n });\n socket.on('connect', () => {\n socket.destroy();\n retry();\n });\n }\n pingPort();\n });\n}\n\nfunction runScript(\n script: string,\n scriptArgs: string[] | undefined,\n inspectHost: string,\n inspectPort: number,\n childPrint: (text: string, isError?: boolean) => void,\n): Promise<[ChildProcessWithoutNullStreams, number, string]> {\n script = normalize(script);\n return portIsFree(inspectHost, inspectPort).then(() => {\n return new Promise(resolve => {\n const args = [breakOnStart ? `--inspect-brk=${inspectPort}` : `--inspect=${inspectPort}`].concat(\n [script],\n scriptArgs || [],\n );\n const child = spawn(process.execPath, args);\n child.stdout.setEncoding('utf8');\n child.stderr.setEncoding('utf8');\n child.stdout.on('data', childPrint);\n child.stderr.on('data', text => childPrint(text, true));\n\n let output = '';\n function waitForListenHint(text: string): void {\n output += text;\n const res = /Debugger listening on ws:\\/\\/\\[?(.+?)]?:(\\d+)\\//.exec(output);\n if (res) {\n const host = res[1];\n const port = Number.parseInt(res[2]);\n child.stderr.removeListener('data', waitForListenHint);\n resolve([child, port, host]);\n }\n }\n\n child.stderr.on('data', waitForListenHint);\n });\n });\n}\n\nfunction createAgentProxy(domain: string, client: InspectClient): ProxyConstructor {\n const agent: any = new EventEmitter();\n\n agent.then = (...args: any[]) => {\n // TODO: potentially fetch the protocol and pretty-print it here.\n const descriptor = {\n [inspect.custom](_depth: number, { stylize }: InspectOptionsStylized): string {\n return stylize(`[Agent ${domain}]`, 'special');\n },\n };\n return Promise.resolve(descriptor).then(...args);\n };\n\n return new Proxy(agent, {\n get(target, name: string) {\n if (name in target) {\n return target[name];\n }\n return function callVirtualMethod(params: any) {\n return client.callMethod(`${domain}.${name}`, params);\n };\n },\n });\n}\n\ntype CommandToHostType =\n | 'log'\n | 'paused'\n | 'resumed'\n | 'setValue'\n | 'scope'\n | 'cb'\n | 'sb'\n | 'script'\n | 'ready'\n | 'readyToDebug'\n | 'error'\n | 'finished'\n | 'expressions'\n | 'stopOnException'\n | 'getPossibleBreakpoints';\n\ntype DebuggerContext = {\n url: string;\n scriptId: Runtime.ScriptId;\n reason: string;\n executionContextId: number;\n type: string;\n id: number;\n args: { value: any }[];\n};\n\ntype CommandToHost = {\n cmd: CommandToHostType;\n text?: string;\n expr?: { name: string };\n bp?: Debugger.Location;\n context?: DebuggerContext | null | string;\n error?: Error | string;\n errorContext?: Error;\n id?: Debugger.BreakpointId; // breakpoint ID\n breakpoints?: Debugger.Location[];\n scriptId?: Runtime.ScriptId;\n scopes?: Debugger.Scope[];\n variableName?: string;\n scopeNumber?: number;\n newValue?: string;\n callFrameId?: string;\n expressions?: { name: string; result: any }[];\n script?: string;\n url?: string;\n severity?: 'warn' | 'error';\n ts?: number;\n};\n\ninterface NodeInspectorOptions {\n script?: string | null;\n scriptArgs?: string[];\n isRemote?: boolean;\n host: string;\n port: number;\n}\n\nexport class NodeInspector {\n options: NodeInspectorOptions;\n stdin: ReadStream;\n stdout: WriteStream;\n scripts: Record | null>;\n delayedContext: DebuggerContext | null;\n paused: boolean;\n child: ChildProcessWithoutNullStreams | null;\n _runScript: () => Promise<[ChildProcessWithoutNullStreams | null, number, string]>;\n\n client: InspectClient;\n\n Debugger: InspectClient;\n HeapProfiler: InspectClient;\n Profiler: InspectClient;\n Runtime: InspectClient;\n\n handleDebugEvent: (fullName: string, params: DebuggerContext) => void;\n mainScriptId: Runtime.ScriptId | undefined;\n mainFile: string | undefined;\n repl: REPLServer | undefined;\n\n constructor(options: NodeInspectorOptions, stdin: ReadStream, stdout: WriteStream) {\n this.options = options;\n this.stdin = stdin;\n this.stdout = stdout;\n this.scripts = {};\n this.delayedContext = null;\n\n this.paused = true;\n this.child = null;\n\n if (options.script) {\n this._runScript = runScript.bind(\n null,\n options.script,\n options.scriptArgs,\n options.host,\n options.port,\n this.childPrint.bind(this),\n );\n } else {\n this._runScript = () => Promise.resolve([null, options.port, options.host]);\n }\n\n this.client = new InspectClient();\n\n this.Debugger = createAgentProxy('Debugger', this.client);\n this.HeapProfiler = createAgentProxy('HeapProfiler', this.client);\n this.Profiler = createAgentProxy('Profiler', this.client);\n this.Runtime = createAgentProxy('Runtime', this.client);\n\n this.handleDebugEvent = (\n fullName: string,\n params: {\n url: string;\n scriptId: Runtime.ScriptId;\n reason: string;\n executionContextId: number;\n type: string;\n id: number;\n args: { value: any }[];\n },\n ): void => {\n const [domain, name] = fullName.split('.');\n\n if (domain === 'Debugger' && name === 'scriptParsed') {\n // console.log(`Parsed: ${params.url}`);\n if (\n (scriptToDebug && params.url.includes(scriptToDebug)) ||\n (instanceToDebug && params.url.includes(instanceToDebug))\n ) {\n console.log(`My scriptID: ${params.scriptId}`);\n this.mainScriptId = params.scriptId;\n this.mainFile = params.url.replace('file:///', '');\n // load text of a script\n this.scripts[this.mainScriptId] = this.Debugger.getScriptSource({\n scriptId: this.mainScriptId,\n } as Debugger.GetScriptSourceParameterType).then((script: Debugger.GetScriptSourceReturnType) => ({\n script: script.scriptSource,\n scriptId: this.mainScriptId,\n }));\n\n // sometimes the pause event comes before scriptParsed\n if (this.delayedContext) {\n console.log('Send to debugger: readyToDebug');\n void this.scripts[this.mainScriptId]?.then(data => {\n // console.log('Send to debugger: readyToDebug ' + JSON.stringify(data));\n sendToHost({\n cmd: 'readyToDebug',\n scriptId: this.mainScriptId,\n script: data.script,\n context: this.delayedContext,\n url: this.mainFile,\n });\n this.delayedContext = null;\n });\n }\n }\n return;\n } else if (domain === 'Debugger' && name === 'resumed') {\n this.Debugger.emit(name, params);\n sendToHost({ cmd: 'resumed', context: params });\n return;\n } else if (domain === 'Debugger' && name === 'paused') {\n console.log(`PAUSED!! ${alreadyPausedOnFirstLine}`);\n if (!alreadyPausedOnFirstLine && params.reason === 'exception') {\n // ignore all exceptions by start\n this.Debugger.resume();\n return;\n }\n //console.warn(fullName + ': => \\n' + JSON.stringify(params, null, 2));\n this.Debugger.emit(name, params);\n\n if (!alreadyPausedOnFirstLine) {\n alreadyPausedOnFirstLine = true;\n // sometimes the pause event comes before scriptParsed\n if (this.mainScriptId && this.scripts[this.mainScriptId]) {\n void this.scripts[this.mainScriptId]?.then(data =>\n sendToHost({\n cmd: 'readyToDebug',\n scriptId: data.scriptId,\n script: data.script,\n context: params,\n url: this.mainFile,\n }),\n );\n } else {\n // store context to send it later when script ID will be known\n this.delayedContext = params;\n console.log('PAUSED, but no scriptId');\n }\n } else {\n // this.scripts[params.loca]\n // .then(data =>\n sendToHost({ cmd: 'paused', context: params });\n }\n return;\n }\n\n if (domain === 'Runtime') {\n //console.warn(fullName + ': => \\n' + JSON.stringify(params, null, 2));\n }\n if (domain === 'Runtime' && name === 'consoleAPICalled') {\n const text = params.args[0].value;\n if (instanceToDebug) {\n sendToHost({\n cmd: 'log',\n severity: params.type === 'warning' ? 'warn' : 'error',\n text,\n ts: Date.now(),\n });\n } else if (text.includes(`$$${scriptToDebug}$$`)) {\n console.log(`${fullName} [${params.executionContextId}]: => ${text}`);\n const [severity, _text] = text.split(`$$${scriptToDebug}$$`);\n sendToHost({\n cmd: 'log',\n severity: severity as 'warn' | 'error',\n text: _text,\n ts: params.args[1] && params.args[1].value ? (params.args[1].value as number) : Date.now(),\n });\n } else if (params.type === 'warning' || params.type === 'error') {\n sendToHost({\n cmd: 'log',\n severity: params.type === 'warning' ? 'warn' : 'error',\n text,\n ts: Date.now(),\n });\n }\n return;\n } else if (domain === 'Runtime' && (params.id === 2 || params.executionContextId === 2)) {\n if (name === 'executionContextCreated') {\n console.warn(`${fullName}: =>\\n${JSON.stringify(params, null, 2)}`);\n } else if (name === 'executionContextDestroyed') {\n console.warn(`${fullName}: =>\\n${JSON.stringify(params, null, 2)}`);\n sendToHost({ cmd: 'finished', context: params });\n }\n return;\n } else if (\n domain === 'Runtime' &&\n name === 'executionContextDestroyed' &&\n params.executionContextId === 1\n ) {\n sendToHost({ cmd: 'finished', context: params });\n console.log('Exited!');\n setTimeout(() => process.exit(125), 200);\n } else if (domain === 'Debugger' && name === 'scriptFailedToParse') {\n // ignore\n return;\n }\n\n console.warn(`${fullName}: =>\\n${JSON.stringify(params, null, 2)}`);\n\n /*if (domain in this) {\n this[domain].emit(name, params);\n }*/\n };\n this.client.on('debugEvent', this.handleDebugEvent);\n const startRepl: () => REPLServer = createRepl(this);\n\n // Handle all possible exits\n process.on('exit', () => this.killChild());\n process.once('SIGTERM', process.exit.bind(process, 0));\n process.once('SIGHUP', process.exit.bind(process, 0));\n\n this.run()\n .then(() => startRepl())\n .then(repl => {\n this.repl = repl;\n this.repl.on('exit', () => process.exit(0));\n this.paused = false;\n })\n .then(null, error =>\n process.nextTick(() => {\n throw error;\n }),\n );\n }\n\n suspendReplWhile(fn: () => any): Promise {\n if (this.repl) {\n this.repl.pause();\n }\n this.stdin.pause();\n this.paused = true;\n\n return new Promise(resolve => resolve(fn()))\n .then(() => {\n this.paused = false;\n if (this.repl) {\n this.repl.resume();\n this.repl.displayPrompt();\n }\n this.stdin.resume();\n })\n .then(null, error =>\n process.nextTick(() => {\n throw error;\n }),\n );\n }\n\n killChild(): void {\n this.client.reset();\n if (this.child) {\n this.child.kill();\n this.child = null;\n }\n }\n\n run(): Promise {\n this.killChild();\n\n return this._runScript().then(([child, port, host]) => {\n this.child = child;\n\n let connectionAttempts = 0;\n const attemptConnect = (): void => {\n ++connectionAttempts;\n debuglog('connection attempt #%d', connectionAttempts);\n this.stdout.write('.');\n return this.client.connect(port, host).then(\n () => {\n debuglog('connection established');\n this.stdout.write(' ok');\n },\n (error: unknown): Promise => {\n debuglog('connect failed', error);\n // If it's failed to connect 10 times, then print a failed message\n if (connectionAttempts >= 10) {\n this.stdout.write(' failed to connect, please retry\\n');\n process.exit(1);\n }\n\n return new Promise(resolve => setTimeout(resolve, 500)).then(attemptConnect);\n },\n );\n };\n\n this.print(`connecting to ${host}:${port} ..`, true);\n return attemptConnect();\n });\n }\n\n clearLine(): void {\n if (this.stdout.isTTY) {\n this.stdout.cursorTo(0);\n this.stdout.clearLine(1);\n } else {\n this.stdout.write('\\b');\n }\n }\n\n print(text: string, oneLine: boolean = false): void {\n this.clearLine();\n this.stdout.write(oneLine ? text : `${text}\\n`);\n }\n\n childPrint(text: string, isError?: boolean): void {\n isError &&\n this.print(\n text\n .toString()\n .split(/\\r\\n|\\r|\\n/g)\n .filter((chunk: string) => !!chunk)\n .map((chunk: string) => `< ${chunk}`)\n .join('\\n'),\n );\n if (!this.paused) {\n this.repl?.displayPrompt(true);\n }\n if (/Waiting for the debugger to disconnect\\.\\.\\.\\n$/.test(text)) {\n this.killChild();\n sendToHost({ cmd: 'finished', text });\n }\n }\n}\n\nfunction parseArgv([target, ...args]: string[]): NodeInspectorOptions {\n let host = '127.0.0.1';\n let port = 9229;\n let isRemote = false;\n let script: string | null = target;\n let scriptArgs = args;\n\n const hostMatch = target.match(/^([^:]+):(\\d+)$/);\n const portMatch = target.match(/^--port=(\\d+)$/);\n\n if (hostMatch) {\n // Connecting to remote debugger\n // `node-inspect localhost:9229`\n host = hostMatch[1];\n port = parseInt(hostMatch[2], 10);\n isRemote = true;\n script = null;\n } else if (portMatch) {\n // start debugee on custom port\n // `node inspect --port=9230 script.js`\n port = parseInt(portMatch[1], 10);\n script = args[0];\n scriptArgs = args.slice(1);\n } else if (args.length === 1 && /^\\d+$/.test(args[0]) && target === '-p') {\n // Start debugger against a given pid\n const pid = parseInt(args[0], 10);\n try {\n // Windows does not support UNIX signals. To enable debugging, you can use an undocumented API function\n // https://github.com/node-inspector/node-inspector?tab=readme-ov-file#windows\n // @ts-expect-error undocumented function\n process._debugProcess(pid);\n } catch (e: unknown) {\n if (e && (e as any).code === 'ESRCH') {\n console.error(`Target process: ${pid} doesn't exist.`);\n process.exit(1);\n }\n throw e;\n }\n script = null;\n isRemote = true;\n }\n\n return {\n host,\n port,\n isRemote,\n script,\n scriptArgs,\n };\n}\n\nfunction startInspect(\n argv: string[] = process.argv.slice(2),\n stdin: ReadStream = process.stdin,\n stdout: WriteStream = process.stdout,\n): void {\n /*\n if (argv.length < 1) {\n const invokedAs = runAsStandalone ? 'node-inspect' : `${process.argv0} ${process.argv[1]}`;\n\n console.error(`Usage: ${invokedAs} script.js`);\n console.error(` ${invokedAs} :`);\n console.error(` ${invokedAs} -p `);\n process.exit(1);\n }\n */\n\n const options = parseArgv(argv);\n inspector = new NodeInspector(options, stdin, stdout);\n\n stdin.resume();\n\n function handleUnexpectedError(e: Error): void {\n if (!(e instanceof StartupError)) {\n console.error('There was an internal error in node-inspect. Please report this bug.');\n console.error(e.message);\n console.error(e.stack);\n } else {\n console.error(e.message);\n }\n inspector.child?.kill();\n process.exit(1);\n }\n\n process.on('uncaughtException', handleUnexpectedError);\n}\n\nfunction extractErrorMessage(stack: string | undefined): string {\n if (!stack) {\n return '';\n }\n const m = stack.match(/^\\w+: ([^\\n]+)/);\n return m ? m[1] : stack;\n}\n\nfunction convertResultToError(result: Runtime.RemoteObject): Error {\n const { className, description } = result;\n const err = new Error(extractErrorMessage(description));\n err.stack = description;\n Object.defineProperty(err, 'name', { value: className });\n return err;\n}\n\nprocess.on('message', (message: DebugCommand | string): void => {\n if (typeof message === 'string') {\n try {\n message = JSON.parse(message) as DebugCommand;\n } catch {\n return console.error(`Cannot parse: ${JSON.stringify(message)}`);\n }\n }\n processCommand(message);\n});\n\nsendToHost({ cmd: 'ready' });\n\n// possible commands\n// start - {cmd: 'start', scriptName: 'script.js.myName'} - start the debugging\n// end - {cmd: 'end'} - end the debugging and stop process\n// source - {cmd: 'source', scriptId} - read text of script by id\n// watch - {cmd: 'watch', expressions: ['i']} - add to watch the variable\n// unwatch - {cmd: 'unwatch', expressions: ['i']} - add to watch the variable\n\n// sb - {cmd: 'sb', breakpoints: [{scriptId: 50, lineNumber: 4, columnNumber: 0}]} - set breakpoint\n// cb - {cmd: 'cb', breakpoints: [{scriptId: 50, lineNumber: 4, columnNumber: 0}]} - clear breakpoint\n\n// pause - {cmd: 'pause'} - pause execution\n// cont - {cmd: 'cont'} - resume execution\n// next - {cmd: 'next'} - Continue to next line in current file\n// step - {cmd: 'step'} - Step into, potentially entering a function\n// out - {cmd: 'step'} - Step out, leaving the current function\n\ntype DebugCommandType =\n | 'start'\n | 'end'\n | 'source'\n | 'watch'\n | 'unwatch'\n | 'sb'\n | 'cb'\n | 'pause'\n | 'cont'\n | 'next'\n | 'step'\n | 'out'\n | 'scope'\n | 'setValue'\n | 'expressions'\n | 'stopOnException'\n | 'getPossibleBreakpoints'\n | 'error';\n\ntype DebugCommand = {\n cmd: DebugCommandType;\n scriptName?: string;\n scriptId?: Runtime.ScriptId;\n instance?: number;\n adapterInstance?: string;\n breakpoints?: Debugger.Location[] | Debugger.BreakpointId[];\n expressions?: { name: string }[];\n scopes?: Debugger.Scope[];\n\n variableName?: string;\n scopeNumber?: number;\n newValue?: string;\n callFrameId?: string;\n state?: boolean;\n\n start?: number;\n end?: number;\n};\n\nfunction processCommand(data: DebugCommand): void {\n console.log(`[DEBUGGER]: processCommand: ${JSON.stringify(data)}`);\n\n if (data.cmd === 'start') {\n scriptToDebug = data.scriptName as string;\n // we can request the script by name or iobroker instance to debug\n if (scriptToDebug) {\n startInspect([\n `${__dirname}/../main.js`,\n (data.instance || 0).toString(),\n '--debug',\n '--debugScript',\n scriptToDebug,\n ]);\n } else {\n instanceToDebug = data.adapterInstance as string;\n const [adapter, instance] = instanceToDebug.split('.');\n let file: string | undefined;\n try {\n file = require.resolve(`iobroker.${adapter}`);\n } catch (e: unknown) {\n // try to locate in the same dir\n const dir = normalize(join(__dirname, '..', `iobroker.${adapter}`));\n if (existsSync(dir)) {\n const pack = require(join(dir, 'package.json'));\n if (existsSync(join(dir, pack.main || `${adapter}.js`))) {\n file = join(dir, pack.main || `${adapter}.js`);\n }\n }\n\n if (!file) {\n sendToHost({ cmd: 'error', error: `Cannot locate iobroker.${adapter}`, errorContext: e as Error });\n setTimeout(() => {\n sendToHost({ cmd: 'finished', context: `Cannot locate iobroker.${adapter}` });\n setTimeout(() => process.exit(124), 500);\n }, 200);\n return;\n }\n }\n file = file.replace(/\\\\/g, '/');\n instanceToDebug = file;\n console.log(`Start ${file} ${instance} --debug`);\n startInspect([file, instance, '--debug']);\n }\n } else if (data.cmd === 'end') {\n process.exit();\n } else if (data.cmd === 'source') {\n inspector.Debugger.getScriptSource({ scriptId: data.scriptId } as Debugger.GetScriptSourceParameterType).then(\n (script: Debugger.GetScriptSourceReturnType) =>\n sendToHost({ cmd: 'script', scriptId: data.scriptId, text: script.scriptSource }),\n );\n } else if (data.cmd === 'cont') {\n inspector.Debugger.resume().catch((e: unknown) => sendToHost({ cmd: 'error', error: e as Error }));\n } else if (data.cmd === 'next') {\n inspector.Debugger.stepOver().catch((e: unknown) => sendToHost({ cmd: 'error', error: e as Error }));\n } else if (data.cmd === 'pause') {\n inspector.Debugger.pause().catch((e: unknown) => sendToHost({ cmd: 'error', error: e as Error }));\n } else if (data.cmd === 'step') {\n inspector.Debugger.stepInto().catch((e: unknown) => sendToHost({ cmd: 'error', error: e as Error }));\n } else if (data.cmd === 'out') {\n inspector.Debugger.stepOut().catch((e: unknown) => sendToHost({ cmd: 'error', error: e as Error }));\n } else if (data.cmd === 'sb') {\n console.log(JSON.stringify(data));\n\n void Promise.all(\n (data.breakpoints as Debugger.Location[])?.map((bp: Debugger.Location) =>\n inspector.Debugger.setBreakpoint({\n location: {\n scriptId: bp.scriptId,\n lineNumber: bp.lineNumber,\n columnNumber: bp.columnNumber,\n },\n } as Debugger.SetBreakpointParameterType)\n .then((result: Debugger.SetBreakpointReturnType) => ({\n id: result.breakpointId,\n location: result.actualLocation,\n }))\n .catch((e: unknown) =>\n sendToHost({\n cmd: 'error',\n error: `Cannot set breakpoint: ${e as Error}`,\n errorContext: e as Error,\n bp,\n }),\n ),\n ) || [],\n ).then(breakpoints => sendToHost({ cmd: 'sb', breakpoints }));\n } else if (data.cmd === 'cb') {\n void Promise.all(\n (data.breakpoints as Debugger.BreakpointId[])?.map(breakpointId =>\n inspector.Debugger.removeBreakpoint({ breakpointId } as Debugger.RemoveBreakpointParameterType)\n .then(() => breakpointId)\n .catch((e: unknown) => {\n console.error(`[DEBUGGER]: Cannot clear breakpoint: ${e as Error}`);\n sendToHost({\n cmd: 'error',\n error: `Cannot clear breakpoint: ${e as Error}`,\n errorContext: e as Error,\n id: breakpointId,\n });\n }),\n ) || [],\n ).then(breakpoints => {\n console.error(`[DEBUGGER]: sent breakpoints ${JSON.stringify(breakpoints)}`);\n sendToHost({ cmd: 'cb', breakpoints });\n });\n } else if (data.cmd === 'watch') {\n void Promise.all(\n data.expressions?.map(expr =>\n inspector.Debugger.watch(expr).catch((e: unknown) =>\n sendToHost({\n cmd: 'error',\n error: `Cannot watch expr: ${e as Error}`,\n errorContext: e as Error,\n expr,\n }),\n ),\n ) || [],\n ).then(() => console.log('Watch done'));\n } else if (data.cmd === 'unwatch') {\n void Promise.all(\n data.expressions?.map(expr =>\n inspector.Debugger.unwatch(expr).catch((e: unknown) =>\n sendToHost({\n cmd: 'error',\n error: `Cannot unwatch expr: ${e as Error}`,\n errorContext: e as Error,\n expr,\n }),\n ),\n ) || [],\n ).then(() => console.log('Watch done'));\n } else if (data.cmd === 'scope') {\n void Promise.all(\n data.scopes\n ?.filter(scope => scope?.object?.objectId)\n .map(scope =>\n inspector.Runtime.getProperties({\n objectId: scope.object.objectId,\n generatePreview: true,\n } as Runtime.GetPropertiesParameterType)\n .then((result: { result: DebugVariable[] }) => {\n return { type: scope.type, properties: result };\n })\n .catch((e: unknown) =>\n sendToHost({\n cmd: 'error',\n error: `Cannot get scopes expr: ${e as Error}`,\n errorContext: e as Error,\n }),\n ),\n ) || [],\n ).then(scopes => sendToHost({ cmd: 'scope', scopes }));\n } else if (data.cmd === 'setValue') {\n inspector.Debugger.setVariableValue({\n variableName: data.variableName,\n scopeNumber: data.scopeNumber,\n newValue: data.newValue,\n callFrameId: data.callFrameId,\n } as Debugger.SetVariableValueParameterType)\n .catch((e: unknown) => {\n console.error(`Cannot setValue \"${data.variableName}\": ${e as Error}`);\n sendToHost({\n cmd: 'setValue',\n variableName: `Cannot setValue: ${e as Error}`,\n errorContext: e as Error,\n });\n })\n .then(() => {\n console.log(`setValue \"${data.variableName}\" successful`);\n sendToHost({\n cmd: 'setValue',\n variableName: data.variableName,\n scopeNumber: data.scopeNumber,\n newValue: data.newValue,\n callFrameId: data.callFrameId,\n });\n });\n } else if (data.cmd === 'expressions') {\n void Promise.all(\n data.expressions?.map(item =>\n inspector.Debugger.evaluateOnCallFrame({\n callFrameId: data.callFrameId,\n expression: item.name,\n objectGroup: 'node-inspect',\n returnByValue: true,\n generatePreview: true,\n } as Debugger.EvaluateOnCallFrameParameterType)\n // @ts-expect-error fix later\n .then(({ result, wasThrown }: Debugger.EvaluateOnCallFrameReturnType) => {\n if (wasThrown) {\n return { name: item.name, result: convertResultToError(result) };\n }\n return { name: item.name, result };\n })\n .catch((e: unknown) =>\n sendToHost({\n cmd: 'expressions',\n variableName: `Cannot setValue: ${e as Error}`,\n errorContext: e as Error,\n }),\n ),\n ) || [],\n ).then(expressions => {\n sendToHost({ cmd: 'expressions', expressions });\n });\n } else if (data.cmd === 'stopOnException') {\n inspector.Debugger.setPauseOnExceptions({\n state: data.state ? 'all' : 'none',\n } as Debugger.SetPauseOnExceptionsParameterType).catch((e: unknown) =>\n sendToHost({\n cmd: 'stopOnException',\n variableName: `Cannot stopOnException: ${e as Error}`,\n errorContext: e as Error,\n }),\n );\n } else if (data.cmd === 'getPossibleBreakpoints') {\n inspector.Debugger.getPossibleBreakpoints({ start: data.start, end: data.end })\n .then((breakpoints: Debugger.GetPossibleBreakpointsReturnType) =>\n sendToHost({ cmd: 'getPossibleBreakpoints', breakpoints: breakpoints.locations }),\n )\n .catch((e: unknown) =>\n sendToHost({\n cmd: 'getPossibleBreakpoints',\n variableName: `Cannot getPossibleBreakpoints: ${e as Error}`,\n errorContext: e as Error,\n }),\n );\n } else {\n console.error(`Unknown command: ${JSON.stringify(data)}`);\n }\n}\n\nfunction sendToHost(data: CommandToHost): void {\n if (data.cmd === 'error') {\n console.error(data.text);\n if (data.expr) {\n console.error(`[EXPRESSION] ${JSON.stringify(data.expr)}`);\n }\n if (data.bp) {\n console.error(`[BP] ${JSON.stringify(data.bp)}`);\n }\n }\n\n if (process.send) {\n process.send(JSON.stringify(data));\n }\n}\n"]} \ No newline at end of file +{"version":3,"file":"inspect.js","sourceRoot":"","sources":["../../src/lib/inspect.ts"],"names":[],"mappings":";;;;;;AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,2DAAgF;AAChF,6CAA2C;AAC3C,uCAAmC;AACnC,yCAA2F;AAC3F,yCAA4C;AAC5C,qCAAqC;AAGrC,sCAAsC;AACtC,8FAAqE;AAGrE,0DAAoC;AAgBpC,MAAM,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,gBAAgB,CAAC,CAAC;AAE7D,MAAM,QAAQ,GAAG,IAAA,oBAAY,EAAC,SAAS,CAAC,CAAC;AACzC,IAAI,SAAwB,CAAC;AAC7B,IAAI,aAAa,GAAG,EAAE,CAAC,CAAC,eAAe;AACvC,IAAI,eAAe,GAAG,EAAE,CAAC,CAAC,YAAY;AACtC,IAAI,wBAAwB,GAAG,KAAK,CAAC;AAErC,MAAM,YAAa,SAAQ,KAAK;IAC5B,YAAY,OAAe;QACvB,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,cAAc,CAAC;IAC/B,CAAC;CACJ;AAED,SAAS,UAAU,CAAC,IAAY,EAAE,IAAY,EAAE,UAAkB,IAAI;IAClE,IAAI,IAAI,KAAK,CAAC,EAAE,CAAC;QACb,4BAA4B;QAC5B,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC;IAC7B,CAAC;IAED,MAAM,UAAU,GAAG,GAAG,CAAC;IACvB,IAAI,UAAU,GAAG,KAAK,CAAC;IAEvB,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACnC,UAAU,CAAC,GAAG,EAAE;YACZ,UAAU,GAAG,IAAI,CAAC;YAClB,MAAM,CAAC,IAAI,YAAY,CAAC,YAAY,OAAO,iBAAiB,IAAI,IAAI,IAAI,aAAa,CAAC,CAAC,CAAC;QAC5F,CAAC,EAAE,OAA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E;YAC5D,YAAY,EAAE,CAAU;SAC3B,CAAC,CACL,CAAC;IACV,CAAC;SAAM,CAAC;QACJ,OAAO,CAAC,KAAK,CAAC,oBAAoB,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IAC9D,CAAC;AACL,CAAC;AAED,SAAS,UAAU,CAAC,IAAmB;IACnC,IAAI,IAAI,CAAC,GAAG,KAAK,OAAO,EAAE,CAAC;QACvB,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACzB,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC;YACZ,OAAO,CAAC,KAAK,CAAC,gBAAgB,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QAC/D,CAAC;QACD,IAAI,IAAI,CAAC,EAAE,EAAE,CAAC;YACV,OAAO,CAAC,KAAK,CAAC,QAAQ,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;QACrD,CAAC;IACL,CAAC;IAED,IAAI,OAAO,CAAC,IAAI,EAAE,CAAC;QACf,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC;IACvC,CAAC;AACL,CAAC","sourcesContent":["/*\n * Copyright Node.js contributors. All rights reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\nimport { spawn, type ChildProcessWithoutNullStreams } from 'node:child_process';\nimport { EventEmitter } from 'node:events';\nimport { connect } from 'node:net';\nimport { debuglog as utilDebugLog, inspect, type InspectOptionsStylized } from 'node:util';\nimport { normalize, join } from 'node:path';\nimport { existsSync } from 'node:fs';\nimport type { WriteStream, ReadStream } from 'node:tty';\n\n// @ts-expect-error no types available\nimport InspectClient from 'node-inspect/lib/internal/inspect_client';\nimport type { Debugger, Runtime } from 'node:inspector';\nimport type { REPLServer } from 'node:repl';\nimport createRepl from './debugger';\n// const runAsStandalone = typeof __dirname !== 'undefined';\n\ninterface DebugValue {\n type: 'function' | 'string' | 'boolean' | 'number' | 'object' | 'undefined' | 'null' | 'bigint' | 'symbol';\n description: string;\n value: any;\n}\ninterface DebugVariable {\n name: string;\n value: DebugValue;\n configurable?: boolean;\n enumerable?: boolean;\n isOwn?: boolean;\n writable?: boolean;\n}\nconst breakOnStart = process.argv.includes('--breakOnStart');\n\nconst debuglog = utilDebugLog('inspect');\nlet inspector: NodeInspector;\nlet scriptToDebug = ''; // script.js.yy\nlet instanceToDebug = ''; // adapter.X\nlet alreadyPausedOnFirstLine = false;\n\nclass StartupError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'StartupError';\n }\n}\n\nfunction portIsFree(host: string, port: number, timeout: number = 9999): Promise {\n if (port === 0) {\n // Binding to a random port.\n return Promise.resolve();\n }\n\n const retryDelay = 150;\n let didTimeOut = false;\n\n return new Promise((resolve, reject) => {\n setTimeout(() => {\n didTimeOut = true;\n reject(new StartupError(`Timeout (${timeout}) waiting for ${host}:${port} to be free`));\n }, timeout);\n\n function pingPort(): void {\n if (didTimeOut) {\n return;\n }\n\n const socket = connect(port, host);\n let didRetry = false;\n function retry(): void {\n if (!didRetry && !didTimeOut) {\n didRetry = true;\n setTimeout(pingPort, retryDelay);\n }\n }\n\n socket.on('error', (error: Error) => {\n if ((error as any).code === 'ECONNREFUSED') {\n resolve();\n } else {\n retry();\n }\n });\n socket.on('connect', () => {\n socket.destroy();\n retry();\n });\n }\n pingPort();\n });\n}\n\nfunction runScript(\n script: string,\n scriptArgs: string[] | undefined,\n inspectHost: string,\n inspectPort: number,\n childPrint: (text: string, isError?: boolean) => void,\n): Promise<[ChildProcessWithoutNullStreams, number, string]> {\n script = normalize(script);\n return portIsFree(inspectHost, inspectPort).then(() => {\n return new Promise(resolve => {\n const args = [breakOnStart ? `--inspect-brk=${inspectPort}` : `--inspect=${inspectPort}`].concat(\n [script],\n scriptArgs || [],\n );\n const child = spawn(process.execPath, args);\n child.stdout.setEncoding('utf8');\n child.stderr.setEncoding('utf8');\n child.stdout.on('data', childPrint);\n child.stderr.on('data', text => childPrint(text, true));\n\n let output = '';\n function waitForListenHint(text: string): void {\n output += text;\n const res = /Debugger listening on ws:\\/\\/\\[?(.+?)]?:(\\d+)\\//.exec(output);\n if (res) {\n const host = res[1];\n const port = Number.parseInt(res[2]);\n child.stderr.removeListener('data', waitForListenHint);\n resolve([child, port, host]);\n }\n }\n\n child.stderr.on('data', waitForListenHint);\n });\n });\n}\n\nfunction createAgentProxy(domain: string, client: InspectClient): ProxyConstructor {\n const agent: any = new EventEmitter();\n\n agent.then = (...args: any[]) => {\n // TODO: potentially fetch the protocol and pretty-print it here.\n const descriptor = {\n [inspect.custom](_depth: number, { stylize }: InspectOptionsStylized): string {\n return stylize(`[Agent ${domain}]`, 'special');\n },\n };\n return Promise.resolve(descriptor).then(...args);\n };\n\n return new Proxy(agent, {\n get(target, name: string) {\n if (name in target) {\n return target[name];\n }\n return function callVirtualMethod(params: any) {\n return client.callMethod(`${domain}.${name}`, params);\n };\n },\n });\n}\n\ntype CommandToHostType =\n | 'log'\n | 'paused'\n | 'resumed'\n | 'setValue'\n | 'scope'\n | 'cb'\n | 'sb'\n | 'script'\n | 'ready'\n | 'readyToDebug'\n | 'error'\n | 'finished'\n | 'expressions'\n | 'stopOnException'\n | 'getPossibleBreakpoints';\n\ntype DebuggerContext = {\n url: string;\n scriptId: Runtime.ScriptId;\n reason: string;\n executionContextId: number;\n type: string;\n id: number;\n args: { value: any }[];\n};\n\ntype CommandToHost = {\n cmd: CommandToHostType;\n text?: string;\n expr?: { name: string };\n bp?: Debugger.Location;\n context?: DebuggerContext | null | string;\n error?: Error | string;\n errorContext?: Error;\n id?: Debugger.BreakpointId; // breakpoint ID\n breakpoints?: Debugger.Location[];\n scriptId?: Runtime.ScriptId;\n scopes?: Debugger.Scope[];\n variableName?: string;\n scopeNumber?: number;\n newValue?: string;\n callFrameId?: string;\n expressions?: { name: string; result: any }[];\n script?: string;\n url?: string;\n severity?: 'warn' | 'error';\n ts?: number;\n};\n\ninterface NodeInspectorOptions {\n script?: string | null;\n scriptArgs?: string[];\n isRemote?: boolean;\n host: string;\n port: number;\n}\n\nexport class NodeInspector {\n options: NodeInspectorOptions;\n stdin: ReadStream;\n stdout: WriteStream;\n scripts: Record | null>;\n delayedContext: DebuggerContext | null;\n paused: boolean;\n child: ChildProcessWithoutNullStreams | null;\n _runScript: () => Promise<[ChildProcessWithoutNullStreams | null, number, string]>;\n\n client: InspectClient;\n\n Debugger: InspectClient;\n HeapProfiler: InspectClient;\n Profiler: InspectClient;\n Runtime: InspectClient;\n\n handleDebugEvent: (fullName: string, params: DebuggerContext) => void;\n mainScriptId: Runtime.ScriptId | undefined;\n mainFile: string | undefined;\n repl: REPLServer | undefined;\n\n constructor(options: NodeInspectorOptions, stdin: ReadStream, stdout: WriteStream) {\n this.options = options;\n this.stdin = stdin;\n this.stdout = stdout;\n this.scripts = {};\n this.delayedContext = null;\n\n this.paused = true;\n this.child = null;\n\n if (options.script) {\n this._runScript = runScript.bind(\n null,\n options.script,\n options.scriptArgs,\n options.host,\n options.port,\n this.childPrint.bind(this),\n );\n } else {\n this._runScript = () => Promise.resolve([null, options.port, options.host]);\n }\n\n this.client = new InspectClient();\n\n this.Debugger = createAgentProxy('Debugger', this.client);\n this.HeapProfiler = createAgentProxy('HeapProfiler', this.client);\n this.Profiler = createAgentProxy('Profiler', this.client);\n this.Runtime = createAgentProxy('Runtime', this.client);\n\n this.handleDebugEvent = (\n fullName: string,\n params: {\n url: string;\n scriptId: Runtime.ScriptId;\n reason: string;\n executionContextId: number;\n type: string;\n id: number;\n args: { value: any }[];\n },\n ): void => {\n const [domain, name] = fullName.split('.');\n\n if (domain === 'Debugger' && name === 'scriptParsed') {\n // console.log(`Parsed: ${params.url}`);\n if (\n (scriptToDebug && params.url.includes(scriptToDebug)) ||\n (instanceToDebug && params.url.includes(instanceToDebug))\n ) {\n console.log(`My scriptID: ${params.scriptId}`);\n this.mainScriptId = params.scriptId;\n this.mainFile = params.url.replace('file:///', '');\n // load text of a script\n this.scripts[this.mainScriptId] = this.Debugger.getScriptSource({\n scriptId: this.mainScriptId,\n } as Debugger.GetScriptSourceParameterType).then((script: Debugger.GetScriptSourceReturnType) => ({\n script: script.scriptSource,\n scriptId: this.mainScriptId,\n }));\n\n // sometimes the pause event comes before scriptParsed\n if (this.delayedContext) {\n console.log('Send to debugger: readyToDebug');\n void this.scripts[this.mainScriptId]?.then(data => {\n // console.log('Send to debugger: readyToDebug ' + JSON.stringify(data));\n sendToHost({\n cmd: 'readyToDebug',\n scriptId: this.mainScriptId,\n script: data.script,\n context: this.delayedContext,\n url: this.mainFile,\n });\n this.delayedContext = null;\n });\n }\n }\n return;\n } else if (domain === 'Debugger' && name === 'resumed') {\n this.Debugger.emit(name, params);\n sendToHost({ cmd: 'resumed', context: params });\n return;\n } else if (domain === 'Debugger' && name === 'paused') {\n console.log(`PAUSED!! ${alreadyPausedOnFirstLine}`);\n if (!alreadyPausedOnFirstLine && params.reason === 'exception') {\n // ignore all exceptions by start\n this.Debugger.resume();\n return;\n }\n //console.warn(fullName + ': => \\n' + JSON.stringify(params, null, 2));\n this.Debugger.emit(name, params);\n\n if (!alreadyPausedOnFirstLine) {\n alreadyPausedOnFirstLine = true;\n // sometimes the pause event comes before scriptParsed\n if (this.mainScriptId && this.scripts[this.mainScriptId]) {\n void this.scripts[this.mainScriptId]?.then(data =>\n sendToHost({\n cmd: 'readyToDebug',\n scriptId: data.scriptId,\n script: data.script,\n context: params,\n url: this.mainFile,\n }),\n );\n } else {\n // store context to send it later when script ID will be known\n this.delayedContext = params;\n console.log('PAUSED, but no scriptId');\n }\n } else {\n // this.scripts[params.loca]\n // .then(data =>\n sendToHost({ cmd: 'paused', context: params });\n }\n return;\n }\n\n if (domain === 'Runtime') {\n //console.warn(fullName + ': => \\n' + JSON.stringify(params, null, 2));\n }\n if (domain === 'Runtime' && name === 'consoleAPICalled') {\n const text = params.args[0].value;\n if (instanceToDebug) {\n sendToHost({\n cmd: 'log',\n severity: params.type === 'warning' ? 'warn' : 'error',\n text,\n ts: Date.now(),\n });\n } else if (text.includes(`$$${scriptToDebug}$$`)) {\n console.log(`${fullName} [${params.executionContextId}]: => ${text}`);\n const [severity, _text] = text.split(`$$${scriptToDebug}$$`);\n sendToHost({\n cmd: 'log',\n severity: severity as 'warn' | 'error',\n text: _text,\n ts: params.args[1] && params.args[1].value ? (params.args[1].value as number) : Date.now(),\n });\n } else if (params.type === 'warning' || params.type === 'error') {\n sendToHost({\n cmd: 'log',\n severity: params.type === 'warning' ? 'warn' : 'error',\n text,\n ts: Date.now(),\n });\n }\n return;\n } else if (domain === 'Runtime' && (params.id === 2 || params.executionContextId === 2)) {\n if (name === 'executionContextCreated') {\n console.warn(`${fullName}: =>\\n${JSON.stringify(params, null, 2)}`);\n } else if (name === 'executionContextDestroyed') {\n console.warn(`${fullName}: =>\\n${JSON.stringify(params, null, 2)}`);\n sendToHost({ cmd: 'finished', context: params });\n }\n return;\n } else if (\n domain === 'Runtime' &&\n name === 'executionContextDestroyed' &&\n params.executionContextId === 1\n ) {\n sendToHost({ cmd: 'finished', context: params });\n console.log('Exited!');\n setTimeout(() => process.exit(125), 200);\n } else if (domain === 'Debugger' && name === 'scriptFailedToParse') {\n // ignore\n return;\n }\n\n console.warn(`${fullName}: =>\\n${JSON.stringify(params, null, 2)}`);\n\n /*if (domain in this) {\n this[domain].emit(name, params);\n }*/\n };\n this.client.on('debugEvent', this.handleDebugEvent);\n const startRepl: () => REPLServer = createRepl(this);\n\n // Handle all possible exits\n process.on('exit', () => this.killChild());\n process.once('SIGTERM', process.exit.bind(process, 0));\n process.once('SIGHUP', process.exit.bind(process, 0));\n\n this.run()\n .then(() => startRepl())\n .then(repl => {\n this.repl = repl;\n this.repl.on('exit', () => process.exit(0));\n this.paused = false;\n })\n .then(null, error =>\n process.nextTick(() => {\n throw error;\n }),\n );\n }\n\n suspendReplWhile(fn: () => any): Promise {\n if (this.repl) {\n this.repl.pause();\n }\n this.stdin.pause();\n this.paused = true;\n\n return new Promise(resolve => resolve(fn()))\n .then(() => {\n this.paused = false;\n if (this.repl) {\n this.repl.resume();\n this.repl.displayPrompt();\n }\n this.stdin.resume();\n })\n .then(null, error =>\n process.nextTick(() => {\n throw error;\n }),\n );\n }\n\n killChild(): void {\n this.client.reset();\n if (this.child) {\n this.child.kill();\n this.child = null;\n }\n }\n\n run(): Promise {\n this.killChild();\n\n return this._runScript().then(([child, port, host]) => {\n this.child = child;\n\n let connectionAttempts = 0;\n const attemptConnect = (): void => {\n ++connectionAttempts;\n debuglog('connection attempt #%d', connectionAttempts);\n this.stdout.write('.');\n return this.client.connect(port, host).then(\n () => {\n debuglog('connection established');\n this.stdout.write(' ok');\n },\n (error: unknown): Promise => {\n debuglog('connect failed', error);\n // If it's failed to connect 10 times, then print a failed message\n if (connectionAttempts >= 10) {\n this.stdout.write(' failed to connect, please retry\\n');\n process.exit(1);\n }\n\n return new Promise(resolve => setTimeout(resolve, 500)).then(attemptConnect);\n },\n );\n };\n\n this.print(`connecting to ${host}:${port} ..`, true);\n return attemptConnect();\n });\n }\n\n clearLine(): void {\n if (this.stdout.isTTY) {\n this.stdout.cursorTo(0);\n this.stdout.clearLine(1);\n } else {\n this.stdout.write('\\b');\n }\n }\n\n print(text: string, oneLine: boolean = false): void {\n this.clearLine();\n this.stdout.write(oneLine ? text : `${text}\\n`);\n }\n\n childPrint(text: string, isError?: boolean): void {\n isError &&\n this.print(\n text\n .toString()\n .split(/\\r\\n|\\r|\\n/g)\n .filter((chunk: string) => !!chunk)\n .map((chunk: string) => `< ${chunk}`)\n .join('\\n'),\n );\n if (!this.paused) {\n this.repl?.displayPrompt(true);\n }\n if (/Waiting for the debugger to disconnect\\.\\.\\.\\n$/.test(text)) {\n this.killChild();\n sendToHost({ cmd: 'finished', text });\n }\n }\n}\n\nfunction parseArgv([target, ...args]: string[]): NodeInspectorOptions {\n let host = '127.0.0.1';\n let port = 9229;\n let isRemote = false;\n let script: string | null = target;\n let scriptArgs = args;\n\n const hostMatch = target.match(/^([^:]+):(\\d+)$/);\n const portMatch = target.match(/^--port=(\\d+)$/);\n\n if (hostMatch) {\n // Connecting to remote debugger\n // `node-inspect localhost:9229`\n host = hostMatch[1];\n port = parseInt(hostMatch[2], 10);\n isRemote = true;\n script = null;\n } else if (portMatch) {\n // start debugee on custom port\n // `node inspect --port=9230 script.js`\n port = parseInt(portMatch[1], 10);\n script = args[0];\n scriptArgs = args.slice(1);\n } else if (args.length === 1 && /^\\d+$/.test(args[0]) && target === '-p') {\n // Start debugger against a given pid\n const pid = parseInt(args[0], 10);\n try {\n // Windows does not support UNIX signals. To enable debugging, you can use an undocumented API function\n // https://github.com/node-inspector/node-inspector?tab=readme-ov-file#windows\n // @ts-expect-error undocumented function\n process._debugProcess(pid);\n } catch (e: unknown) {\n if (e && (e as any).code === 'ESRCH') {\n console.error(`Target process: ${pid} doesn't exist.`);\n process.exit(1);\n }\n throw e;\n }\n script = null;\n isRemote = true;\n }\n\n return {\n host,\n port,\n isRemote,\n script,\n scriptArgs,\n };\n}\n\nfunction startInspect(\n argv: string[] = process.argv.slice(2),\n stdin: ReadStream = process.stdin,\n stdout: WriteStream = process.stdout,\n): void {\n /*\n if (argv.length < 1) {\n const invokedAs = runAsStandalone ? 'node-inspect' : `${process.argv0} ${process.argv[1]}`;\n\n console.error(`Usage: ${invokedAs} script.js`);\n console.error(` ${invokedAs} :`);\n console.error(` ${invokedAs} -p `);\n process.exit(1);\n }\n */\n\n const options = parseArgv(argv);\n inspector = new NodeInspector(options, stdin, stdout);\n\n stdin.resume();\n\n function handleUnexpectedError(e: Error): void {\n if (!(e instanceof StartupError)) {\n console.error('There was an internal error in node-inspect. Please report this bug.');\n console.error(e.message);\n console.error(e.stack);\n } else {\n console.error(e.message);\n }\n inspector.child?.kill();\n process.exit(1);\n }\n\n process.on('uncaughtException', handleUnexpectedError);\n}\n\nfunction extractErrorMessage(stack: string | undefined): string {\n if (!stack) {\n return '';\n }\n const m = stack.match(/^\\w+: ([^\\n]+)/);\n return m ? m[1] : stack;\n}\n\nfunction convertResultToError(result: Runtime.RemoteObject): Error {\n const { className, description } = result;\n const err = new Error(extractErrorMessage(description));\n err.stack = description;\n Object.defineProperty(err, 'name', { value: className });\n return err;\n}\n\nprocess.on('message', (message: DebugCommand | string): void => {\n if (typeof message === 'string') {\n try {\n message = JSON.parse(message) as DebugCommand;\n } catch {\n return console.error(`Cannot parse: ${JSON.stringify(message)}`);\n }\n }\n processCommand(message);\n});\n\nsendToHost({ cmd: 'ready' });\n\n// possible commands\n// start - {cmd: 'start', scriptName: 'script.js.myName'} - start the debugging\n// end - {cmd: 'end'} - end the debugging and stop process\n// source - {cmd: 'source', scriptId} - read text of script by id\n// watch - {cmd: 'watch', expressions: ['i']} - add to watch the variable\n// unwatch - {cmd: 'unwatch', expressions: ['i']} - add to watch the variable\n\n// sb - {cmd: 'sb', breakpoints: [{scriptId: 50, lineNumber: 4, columnNumber: 0}]} - set breakpoint\n// cb - {cmd: 'cb', breakpoints: [{scriptId: 50, lineNumber: 4, columnNumber: 0}]} - clear breakpoint\n\n// pause - {cmd: 'pause'} - pause execution\n// cont - {cmd: 'cont'} - resume execution\n// next - {cmd: 'next'} - Continue to next line in current file\n// step - {cmd: 'step'} - Step into, potentially entering a function\n// out - {cmd: 'step'} - Step out, leaving the current function\n\ntype DebugCommandType =\n | 'start'\n | 'end'\n | 'source'\n | 'watch'\n | 'unwatch'\n | 'sb'\n | 'cb'\n | 'pause'\n | 'cont'\n | 'next'\n | 'step'\n | 'out'\n | 'scope'\n | 'setValue'\n | 'expressions'\n | 'stopOnException'\n | 'getPossibleBreakpoints'\n | 'error';\n\ntype DebugCommand = {\n cmd: DebugCommandType;\n scriptName?: string;\n scriptId?: Runtime.ScriptId;\n instance?: number;\n adapterInstance?: string;\n breakpoints?: Debugger.Location[] | Debugger.BreakpointId[];\n expressions?: { name: string }[];\n scopes?: Debugger.Scope[];\n\n variableName?: string;\n scopeNumber?: number;\n newValue?: string;\n callFrameId?: string;\n state?: boolean;\n\n start?: number;\n end?: number;\n};\n\nfunction processCommand(data: DebugCommand): void {\n console.log(`[DEBUGGER]: processCommand: ${JSON.stringify(data)}`);\n\n if (data.cmd === 'start') {\n scriptToDebug = data.scriptName as string;\n // we can request the script by name or iobroker instance to debug\n if (scriptToDebug) {\n startInspect([\n `${__dirname}/../main.js`,\n (data.instance || 0).toString(),\n '--debug',\n '--debugScript',\n scriptToDebug,\n ]);\n } else {\n instanceToDebug = data.adapterInstance as string;\n const [adapter, instance] = instanceToDebug.split('.');\n let file: string | undefined;\n try {\n file = require.resolve(`iobroker.${adapter}`);\n } catch (e: unknown) {\n // try to locate in the same dir\n const dir = normalize(join(__dirname, '..', `iobroker.${adapter}`));\n if (existsSync(dir)) {\n const pack = require(join(dir, 'package.json'));\n if (existsSync(join(dir, pack.main || `${adapter}.js`))) {\n file = join(dir, pack.main || `${adapter}.js`);\n }\n }\n\n if (!file) {\n sendToHost({ cmd: 'error', error: `Cannot locate iobroker.${adapter}`, errorContext: e as Error });\n setTimeout(() => {\n sendToHost({ cmd: 'finished', context: `Cannot locate iobroker.${adapter}` });\n setTimeout(() => process.exit(124), 500);\n }, 200);\n return;\n }\n }\n file = file.replace(/\\\\/g, '/');\n instanceToDebug = file;\n console.log(`Start ${file} ${instance} --debug`);\n startInspect([file, instance, '--debug']);\n }\n } else if (data.cmd === 'end') {\n process.exit();\n } else if (data.cmd === 'source') {\n inspector.Debugger.getScriptSource({ scriptId: data.scriptId } as Debugger.GetScriptSourceParameterType).then(\n (script: Debugger.GetScriptSourceReturnType) =>\n sendToHost({ cmd: 'script', scriptId: data.scriptId, text: script.scriptSource }),\n );\n } else if (data.cmd === 'cont') {\n inspector.Debugger.resume().catch((e: unknown) => sendToHost({ cmd: 'error', error: e as Error }));\n } else if (data.cmd === 'next') {\n inspector.Debugger.stepOver().catch((e: unknown) => sendToHost({ cmd: 'error', error: e as Error }));\n } else if (data.cmd === 'pause') {\n inspector.Debugger.pause().catch((e: unknown) => sendToHost({ cmd: 'error', error: e as Error }));\n } else if (data.cmd === 'step') {\n inspector.Debugger.stepInto().catch((e: unknown) => sendToHost({ cmd: 'error', error: e as Error }));\n } else if (data.cmd === 'out') {\n inspector.Debugger.stepOut().catch((e: unknown) => sendToHost({ cmd: 'error', error: e as Error }));\n } else if (data.cmd === 'sb') {\n console.log(JSON.stringify(data));\n\n void Promise.all(\n (data.breakpoints as Debugger.Location[])?.map((bp: Debugger.Location) =>\n inspector.Debugger.setBreakpoint({\n location: {\n scriptId: bp.scriptId,\n lineNumber: bp.lineNumber,\n columnNumber: bp.columnNumber,\n },\n } as Debugger.SetBreakpointParameterType)\n .then((result: Debugger.SetBreakpointReturnType) => ({\n id: result.breakpointId,\n location: result.actualLocation,\n }))\n .catch((e: unknown) =>\n sendToHost({\n cmd: 'error',\n error: `Cannot set breakpoint: ${e as Error}`,\n errorContext: e as Error,\n bp,\n }),\n ),\n ) || [],\n ).then(breakpoints => sendToHost({ cmd: 'sb', breakpoints }));\n } else if (data.cmd === 'cb') {\n void Promise.all(\n (data.breakpoints as Debugger.BreakpointId[])?.map(breakpointId =>\n inspector.Debugger.removeBreakpoint({ breakpointId } as Debugger.RemoveBreakpointParameterType)\n .then(() => breakpointId)\n .catch((e: unknown) => {\n console.error(`[DEBUGGER]: Cannot clear breakpoint: ${e as Error}`);\n sendToHost({\n cmd: 'error',\n error: `Cannot clear breakpoint: ${e as Error}`,\n errorContext: e as Error,\n id: breakpointId,\n });\n }),\n ) || [],\n ).then(breakpoints => {\n console.error(`[DEBUGGER]: sent breakpoints ${JSON.stringify(breakpoints)}`);\n sendToHost({ cmd: 'cb', breakpoints });\n });\n } else if (data.cmd === 'watch') {\n void Promise.all(\n data.expressions?.map(expr =>\n inspector.Debugger.watch(expr).catch((e: unknown) =>\n sendToHost({\n cmd: 'error',\n error: `Cannot watch expr: ${e as Error}`,\n errorContext: e as Error,\n expr,\n }),\n ),\n ) || [],\n ).then(() => console.log('Watch done'));\n } else if (data.cmd === 'unwatch') {\n void Promise.all(\n data.expressions?.map(expr =>\n inspector.Debugger.unwatch(expr).catch((e: unknown) =>\n sendToHost({\n cmd: 'error',\n error: `Cannot unwatch expr: ${e as Error}`,\n errorContext: e as Error,\n expr,\n }),\n ),\n ) || [],\n ).then(() => console.log('Watch done'));\n } else if (data.cmd === 'scope') {\n void Promise.all(\n data.scopes\n ?.filter(scope => scope?.object?.objectId)\n .map(scope =>\n inspector.Runtime.getProperties({\n objectId: scope.object.objectId,\n generatePreview: true,\n } as Runtime.GetPropertiesParameterType)\n .then((result: { result: DebugVariable[] }) => {\n return { type: scope.type, properties: result };\n })\n .catch((e: unknown) =>\n sendToHost({\n cmd: 'error',\n error: `Cannot get scopes expr: ${e as Error}`,\n errorContext: e as Error,\n }),\n ),\n ) || [],\n ).then(scopes => sendToHost({ cmd: 'scope', scopes }));\n } else if (data.cmd === 'setValue') {\n inspector.Debugger.setVariableValue({\n variableName: data.variableName,\n scopeNumber: data.scopeNumber,\n newValue: data.newValue,\n callFrameId: data.callFrameId,\n } as Debugger.SetVariableValueParameterType)\n .catch((e: unknown) => {\n console.error(`Cannot setValue \"${data.variableName}\": ${e as Error}`);\n sendToHost({\n cmd: 'setValue',\n variableName: `Cannot setValue: ${e as Error}`,\n errorContext: e as Error,\n });\n })\n .then(() => {\n console.log(`setValue \"${data.variableName}\" successful`);\n sendToHost({\n cmd: 'setValue',\n variableName: data.variableName,\n scopeNumber: data.scopeNumber,\n newValue: data.newValue,\n callFrameId: data.callFrameId,\n });\n });\n } else if (data.cmd === 'expressions') {\n void Promise.all(\n data.expressions?.map(item =>\n inspector.Debugger.evaluateOnCallFrame({\n callFrameId: data.callFrameId,\n expression: item.name,\n objectGroup: 'node-inspect',\n returnByValue: true,\n generatePreview: true,\n } as Debugger.EvaluateOnCallFrameParameterType)\n // @ts-expect-error fix later\n .then(({ result, wasThrown }: Debugger.EvaluateOnCallFrameReturnType) => {\n if (wasThrown) {\n return { name: item.name, result: convertResultToError(result) };\n }\n return { name: item.name, result };\n })\n .catch((e: unknown) =>\n sendToHost({\n cmd: 'expressions',\n variableName: `Cannot setValue: ${e as Error}`,\n errorContext: e as Error,\n }),\n ),\n ) || [],\n ).then(expressions => {\n sendToHost({ cmd: 'expressions', expressions });\n });\n } else if (data.cmd === 'stopOnException') {\n inspector.Debugger.setPauseOnExceptions({\n state: data.state ? 'all' : 'none',\n } as Debugger.SetPauseOnExceptionsParameterType).catch((e: unknown) =>\n sendToHost({\n cmd: 'stopOnException',\n variableName: `Cannot stopOnException: ${e as Error}`,\n errorContext: e as Error,\n }),\n );\n } else if (data.cmd === 'getPossibleBreakpoints') {\n inspector.Debugger.getPossibleBreakpoints({ start: data.start, end: data.end })\n .then((breakpoints: Debugger.GetPossibleBreakpointsReturnType) =>\n sendToHost({ cmd: 'getPossibleBreakpoints', breakpoints: breakpoints.locations }),\n )\n .catch((e: unknown) =>\n sendToHost({\n cmd: 'getPossibleBreakpoints',\n variableName: `Cannot getPossibleBreakpoints: ${e as Error}`,\n errorContext: e as Error,\n }),\n );\n } else {\n console.error(`Unknown command: ${JSON.stringify(data)}`);\n }\n}\n\nfunction sendToHost(data: CommandToHost): void {\n if (data.cmd === 'error') {\n console.error(data.text);\n if (data.expr) {\n console.error(`[EXPRESSION] ${JSON.stringify(data.expr)}`);\n }\n if (data.bp) {\n console.error(`[BP] ${JSON.stringify(data.bp)}`);\n }\n }\n\n if (process.send) {\n process.send(JSON.stringify(data));\n }\n}\n"]} \ No newline at end of file diff --git a/build/lib/nodeModulesManagement.js b/build/lib/nodeModulesManagement.js index 13800692d..5041a0d28 100644 --- a/build/lib/nodeModulesManagement.js +++ b/build/lib/nodeModulesManagement.js @@ -1,7 +1,7 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.requestModuleNameByUrl = requestModuleNameByUrl; -const child_process_1 = require("child_process"); +const node_child_process_1 = require("node:child_process"); /** * Request a module name by given url using `npm view` * @@ -9,7 +9,7 @@ const child_process_1 = require("child_process"); */ async function requestModuleNameByUrl(url) { return new Promise((resolve, reject) => { - (0, child_process_1.execFile)('npm', ['view', url, 'name'], { windowsHide: true, encoding: 'utf8', shell: false }, (error, stdout) => { + (0, node_child_process_1.execFile)('npm', ['view', url, 'name'], { windowsHide: true, encoding: 'utf8', shell: false }, (error, stdout) => { if (error) { reject(error); } diff --git a/build/lib/nodeModulesManagement.js.map b/build/lib/nodeModulesManagement.js.map index dd47f84b3..d71921b71 100644 --- a/build/lib/nodeModulesManagement.js.map +++ b/build/lib/nodeModulesManagement.js.map @@ -1 +1 @@ -{"version":3,"file":"nodeModulesManagement.js","sourceRoot":"","sources":["../../src/lib/nodeModulesManagement.ts"],"names":[],"mappings":";;AAOA,wDAwBC;AA/BD,iDAAiE;AAEjE;;;;GAIG;AACI,KAAK,UAAU,sBAAsB,CAAC,GAAW;IACpD,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACnC,IAAA,wBAAQ,EACJ,KAAK,EACL,CAAC,MAAM,EAAE,GAAG,EAAE,MAAM,CAAC,EACrB,EAAE,WAAW,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,EACrD,CAAC,KAA+B,EAAE,MAAc,EAAE,EAAE;YAChD,IAAI,KAAK,EAAE,CAAC;gBACR,MAAM,CAAC,KAAc,CAAC,CAAC;YAC3B,CAAC;iBAAM,CAAC;gBACJ,IAAI,OAAO,MAAM,KAAK,QAAQ,EAAE,CAAC;oBAC7B,MAAM,CACF,IAAI,KAAK,CACL,4CAA4C,GAAG,0BAA0B,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE,GAAG,CACnH,CACJ,CAAC;oBACF,OAAO;gBACX,CAAC;gBAED,OAAO,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC;YAC3B,CAAC;QACL,CAAC,CACJ,CAAC;IACN,CAAC,CAAC,CAAC;AACP,CAAC","sourcesContent":["import { execFile, type ExecFileException } from 'child_process';\n\n/**\n * Request a module name by given url using `npm view`\n *\n * @param url the url to the package which should be installed via npm\n */\nexport async function requestModuleNameByUrl(url: string): Promise {\n return new Promise((resolve, reject) => {\n execFile(\n 'npm',\n ['view', url, 'name'],\n { windowsHide: true, encoding: 'utf8', shell: false },\n (error: ExecFileException | null, stdout: string) => {\n if (error) {\n reject(error as Error);\n } else {\n if (typeof stdout !== 'string') {\n reject(\n new Error(\n `Could not determine module name for url \"${url}\". Unexpected stdout: \"${stdout ? JSON.stringify(stdout) : ''}\"`,\n ),\n );\n return;\n }\n\n resolve(stdout.trim());\n }\n },\n );\n });\n}\n"]} \ No newline at end of file +{"version":3,"file":"nodeModulesManagement.js","sourceRoot":"","sources":["../../src/lib/nodeModulesManagement.ts"],"names":[],"mappings":";;AAOA,wDAwBC;AA/BD,2DAAsE;AAEtE;;;;GAIG;AACI,KAAK,UAAU,sBAAsB,CAAC,GAAW;IACpD,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACnC,IAAA,6BAAQ,EACJ,KAAK,EACL,CAAC,MAAM,EAAE,GAAG,EAAE,MAAM,CAAC,EACrB,EAAE,WAAW,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,EACrD,CAAC,KAA+B,EAAE,MAAc,EAAE,EAAE;YAChD,IAAI,KAAK,EAAE,CAAC;gBACR,MAAM,CAAC,KAAc,CAAC,CAAC;YAC3B,CAAC;iBAAM,CAAC;gBACJ,IAAI,OAAO,MAAM,KAAK,QAAQ,EAAE,CAAC;oBAC7B,MAAM,CACF,IAAI,KAAK,CACL,4CAA4C,GAAG,0BAA0B,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE,GAAG,CACnH,CACJ,CAAC;oBACF,OAAO;gBACX,CAAC;gBAED,OAAO,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC;YAC3B,CAAC;QACL,CAAC,CACJ,CAAC;IACN,CAAC,CAAC,CAAC;AACP,CAAC","sourcesContent":["import { execFile, type ExecFileException } from 'node:child_process';\n\n/**\n * Request a module name by given url using `npm view`\n *\n * @param url the url to the package which should be installed via npm\n */\nexport async function requestModuleNameByUrl(url: string): Promise {\n return new Promise((resolve, reject) => {\n execFile(\n 'npm',\n ['view', url, 'name'],\n { windowsHide: true, encoding: 'utf8', shell: false },\n (error: ExecFileException | null, stdout: string) => {\n if (error) {\n reject(error as Error);\n } else {\n if (typeof stdout !== 'string') {\n reject(\n new Error(\n `Could not determine module name for url \"${url}\". Unexpected stdout: \"${stdout ? JSON.stringify(stdout) : ''}\"`,\n ),\n );\n return;\n }\n\n resolve(stdout.trim());\n }\n },\n );\n });\n}\n"]} \ No newline at end of file diff --git a/build/lib/protectFs.js.map b/build/lib/protectFs.js.map index a6a74d929..4d74f4b24 100644 --- a/build/lib/protectFs.js.map +++ b/build/lib/protectFs.js.map @@ -1 +1 @@ -{"version":3,"file":"protectFs.js","sourceRoot":"","sources":["../../src/lib/protectFs.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,gDAAkC;AAClC,yCAA0D;AAE1D,MAAqB,SAAS;IACT,GAAG,CAAkB;IACrB,eAAe,CAAS;IACzB,QAAQ,CA+DtB;IACc,SAAS,CAAyB;IAClD,MAAM,CAAC,GAAG,GAA2B,IAAI,CAAC;IAC1C,MAAM,CAAC,qBAAqB,GAAW,EAAE,CAAC;IAE1C,YAAY,GAAoB,EAAE,eAAuB;QACrD,IAAI,CAAC,eAAe,GAAG,eAAe,CAAC;QACvC,SAAS,CAAC,qBAAqB,GAAG,eAAe,CAAC;QAElD,IAAI,CAAC,GAAG,GAAG,GAAG,IAAI;YACd,KAAK,EAAE,CAAC,OAAe,EAAQ,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC;YACtD,KAAK,EAAE,CAAC,OAAe,EAAQ,EAAE,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC;YACxD,IAAI,EAAE,CAAC,OAAe,EAAQ,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC;YACtD,IAAI,EAAE,CAAC,OAAe,EAAQ,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC;YACtD,KAAK,EAAE,CAAC,OAAe,EAAQ,EAAE,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC;YACxD,KAAK,EAAE,MAAM;SAChB,CAAC;QAEF,SAAS,CAAC,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC;QAEzB,IAAI,CAAC,QAAQ,GAAG;YACZ,MAAM,EAAE,KAAK,EAAE,IAAc,EAAE,IAAa,EAAiB,EAAE;gBAC3D,SAAS,CAAC,cAAc,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;gBACrC,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,QAAkB,EAAE,QAA6C;QACzE,SAAS,CAAC,cAAc,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC;QACzC,OAAO,MAAM,CAAC,WAAW,CAAC,IAAI,CAAC,IAAI,EAAE,QAAQ,EAAE,QAA+B,CAAC,CAAC;IACpF,CAAC;;AAjzBL,4BAkzBC","sourcesContent":["import type {\n BufferEncodingOption,\n CopyOptions,\n Dirent,\n MakeDirectoryOptions,\n Mode,\n ObjectEncodingOptions,\n OpenMode,\n PathLike,\n RmDirOptions,\n RmOptions,\n StatOptions,\n Stats,\n TimeLike,\n CopySyncOptions,\n NoParamCallback,\n PathOrFileDescriptor,\n WriteFileOptions,\n EncodingOption,\n FSWatcher,\n ReadStream,\n StatsListener,\n StatWatcher,\n WatchListener,\n WriteStream,\n BigIntStatsListener,\n WatchOptions,\n} from 'node:fs';\nimport type { Abortable } from 'node:events';\nimport type { FileHandle, FlagAndOpenMode } from 'node:fs/promises';\nimport type { URL } from 'node:url';\nimport type { Stream } from 'node:stream';\n\nimport * as nodeFS from 'node:fs';\nimport { sep, normalize, join, resolve } from 'node:path';\n\nexport default class ProtectFs {\n private readonly log: ioBroker.Logger;\n private readonly ioBrokerDataDir: string;\n public readonly promises: {\n access: (path: PathLike, mode?: number) => Promise;\n cp: (source: string | URL, destination: string | URL, opts?: CopyOptions) => Promise;\n readFile: (\n path: PathLike | FileHandle,\n options:\n | ({\n encoding: BufferEncoding;\n flag?: OpenMode | undefined;\n } & Abortable)\n | BufferEncoding,\n ) => Promise;\n readlink: (path: PathLike, options: BufferEncodingOption) => Promise;\n symlink: (target: PathLike, path: PathLike, type?: string | null) => Promise;\n writeFile: (\n file: PathLike | FileHandle,\n data:\n | string\n | NodeJS.ArrayBufferView\n | Iterable\n | AsyncIterable\n | Stream,\n options?:\n | (ObjectEncodingOptions & {\n mode?: Mode | undefined;\n flag?: OpenMode | undefined;\n flush?: boolean | undefined;\n } & Abortable)\n | BufferEncoding\n | null,\n ) => Promise;\n unlink: (path: PathLike) => Promise;\n appendFile: (\n path: PathLike | FileHandle,\n data: string | Uint8Array,\n options?:\n | (ObjectEncodingOptions & FlagAndOpenMode & { flush?: boolean | undefined })\n | BufferEncoding\n | null,\n ) => Promise;\n chmod: (path: PathLike, mode: Mode) => Promise;\n copyFile: (src: PathLike, dest: PathLike, mode?: number) => Promise;\n rename: (oldPath: PathLike, newPath: PathLike) => Promise;\n open: (path: PathLike, flags?: string | number, mode?: Mode) => Promise;\n truncate: (path: PathLike, len?: number) => Promise;\n stat: (path: PathLike, opts?: StatOptions) => Promise;\n utimes: (path: PathLike, atime: TimeLike, mtime: TimeLike) => Promise;\n readdir: (\n path: PathLike,\n options?: ObjectEncodingOptions & {\n withFileTypes: true;\n recursive?: boolean | undefined;\n },\n ) => Promise;\n lchmod: (path: PathLike, mode: Mode) => Promise;\n lchown: (path: PathLike, uid: number, gid: number) => Promise;\n link: (existingPath: PathLike, newPath: PathLike) => Promise;\n lstat: (path: PathLike, opts?: StatOptions) => Promise;\n lutimes: (path: PathLike, atime: TimeLike, mtime: TimeLike) => Promise;\n mkdir: (path: PathLike, options?: Mode | MakeDirectoryOptions | null) => Promise;\n mkdtemp: (prefix: string, options?: ObjectEncodingOptions | BufferEncoding | null) => Promise;\n rm: (path: PathLike, options?: RmOptions) => Promise;\n rmdir: (path: PathLike, options?: RmDirOptions) => Promise;\n };\n public readonly constants: Record;\n static log: ioBroker.Logger | null = null;\n static staticIoBrokerDataDir: string = '';\n\n constructor(log: ioBroker.Logger, ioBrokerDataDir: string) {\n this.ioBrokerDataDir = ioBrokerDataDir;\n ProtectFs.staticIoBrokerDataDir = ioBrokerDataDir;\n\n this.log = log || {\n silly: (message: string): void => console.log(message),\n debug: (message: string): void => console.debug(message),\n info: (message: string): void => console.info(message),\n warn: (message: string): void => console.warn(message),\n error: (message: string): void => console.error(message),\n level: 'info',\n };\n\n ProtectFs.log = this.log;\n\n this.promises = {\n access: async (path: PathLike, mode?: number): Promise => {\n ProtectFs.checkProtected(path, true);\n return nodeFS.promises.access(path, mode);\n },\n cp: async (source: string | URL, destination: string | URL, opts?: CopyOptions): Promise => {\n ProtectFs.checkProtected(source, false);\n ProtectFs.checkProtected(destination, false);\n return nodeFS.promises.cp(source, destination, opts);\n },\n readFile: async (\n path: PathLike | FileHandle,\n options:\n | ({\n encoding: BufferEncoding;\n flag?: OpenMode | undefined;\n } & Abortable)\n | BufferEncoding,\n ): Promise => {\n ProtectFs.checkProtected(path, true);\n return nodeFS.promises.readFile(path, options); // async function readFile(path, options) {\n },\n readlink: async (path: PathLike, options: BufferEncodingOption): Promise => {\n ProtectFs.checkProtected(path, true);\n return nodeFS.promises.readlink(path, options); // async function readlink(path, options) {\n },\n symlink: async (target: PathLike, path: PathLike, type?: string | null): Promise => {\n ProtectFs.checkProtected(target, true);\n ProtectFs.checkProtected(path, false);\n return nodeFS.promises.symlink(target, path, type); // async function symlink(target, path, type_) {\n },\n writeFile: async (\n file: PathLike | FileHandle,\n data:\n | string\n | NodeJS.ArrayBufferView\n | Iterable\n | AsyncIterable\n | Stream,\n options?:\n | (ObjectEncodingOptions & {\n mode?: Mode | undefined;\n flag?: OpenMode | undefined;\n /**\n * If all data is successfully written to the file, and `flush`\n * is `true`, `filehandle.sync()` is used to flush the data.\n *\n * @default false\n */\n flush?: boolean | undefined;\n } & Abortable)\n | BufferEncoding\n | null,\n ): Promise => {\n ProtectFs.checkProtected(file, true);\n return nodeFS.promises.writeFile.call(this, file, data, options); // async function writeFile(path, data, options) {\n },\n unlink: async (path: PathLike): Promise => {\n ProtectFs.checkProtected(path, false);\n return nodeFS.promises.unlink.call(this, path); // async function unlink(path) {\n },\n appendFile: async (\n path: PathLike | FileHandle,\n data: string | Uint8Array,\n options?:\n | (ObjectEncodingOptions & FlagAndOpenMode & { flush?: boolean | undefined })\n | BufferEncoding\n | null,\n ): Promise => {\n ProtectFs.checkProtected(path, false);\n return nodeFS.promises.appendFile.call(this, path, data, options); // async function appendFile(path, data, options) {\n },\n chmod: async (path: PathLike, mode: Mode): Promise => {\n ProtectFs.checkProtected(path, false);\n return nodeFS.promises.chmod.call(this, path, mode); // async function chmod(path, mode) {\n },\n copyFile: async (src: PathLike, dest: PathLike, mode?: number): Promise => {\n ProtectFs.checkProtected(src, false);\n ProtectFs.checkProtected(dest, false);\n return nodeFS.promises.copyFile.call(this, src, dest, mode); // async function copyFile(src, dest, mode) {\n },\n rename: async (oldPath: PathLike, newPath: PathLike): Promise => {\n ProtectFs.checkProtected(oldPath, false);\n ProtectFs.checkProtected(newPath, false);\n return nodeFS.promises.rename.call(this, oldPath, newPath); // async function rename(oldPath, newPath) {\n },\n open: async (path: PathLike, flags?: string | number, mode?: Mode): Promise => {\n ProtectFs.checkProtected(path, true);\n return nodeFS.promises.open.call(this, path, flags, mode); // async function open(path, flags, mode) {\n },\n truncate: async (path: PathLike, len?: number): Promise => {\n ProtectFs.checkProtected(path, false);\n return nodeFS.promises.truncate.call(this, path, len); // async function truncate(path, len = 0) {\n },\n stat: async (path: PathLike, opts?: StatOptions): Promise => {\n ProtectFs.checkProtected(path, true);\n const result = await nodeFS.promises.stat.call(this, path, opts); // async function stat(path, options = { bigint: false }) {\n return result as Stats;\n },\n utimes: async (path: PathLike, atime: TimeLike, mtime: TimeLike): Promise => {\n ProtectFs.checkProtected(path, false);\n return nodeFS.promises.utimes.call(this, path, atime, mtime); // async function utimes(path, atime, mtime) {\n },\n readdir: async (\n path: PathLike,\n options?: ObjectEncodingOptions & {\n withFileTypes: true;\n recursive?: boolean | undefined;\n },\n ): Promise => {\n ProtectFs.checkProtected(path, true);\n // @ts-expect-error fix later\n return nodeFS.promises.readdir.call(this, path, options || { encoding: null, withFileTypes: true }); // async function readdir(path, options) {\n },\n lchmod: async (path: PathLike, mode: Mode): Promise => {\n ProtectFs.checkProtected(path, false);\n return nodeFS.promises.lchmod.call(this, path, mode); // async function lchmod(path, mode) {\n },\n lchown: async (path: PathLike, uid: number, gid: number): Promise => {\n ProtectFs.checkProtected(path, false);\n return nodeFS.promises.lchown.call(this, path, uid, gid); // async function lchown(path, uid, gid) {\n },\n link: async (existingPath: PathLike, newPath: PathLike): Promise => {\n ProtectFs.checkProtected(existingPath, false);\n ProtectFs.checkProtected(newPath, false);\n return nodeFS.promises.link.call(this, existingPath, newPath); // async function link(existingPath, newPath) {\n },\n lstat: async (path: PathLike, opts?: StatOptions): Promise => {\n ProtectFs.checkProtected(path, true);\n const res = await nodeFS.promises.lstat.call(this, path, opts); // async function lstat(path, options = { bigint: false }) {\n return res as Stats;\n },\n lutimes: async (path: PathLike, atime: TimeLike, mtime: TimeLike): Promise => {\n ProtectFs.checkProtected(path, false);\n return nodeFS.promises.lutimes.call(this, path, atime, mtime); // async function lutimes(path, atime, mtime) {\n },\n mkdir: async (\n path: PathLike,\n options?: Mode | MakeDirectoryOptions | null,\n ): Promise => {\n ProtectFs.checkProtected(path, false);\n return nodeFS.promises.mkdir.call(this, path, options); // async function mkdir(path, options) {\n },\n mkdtemp: async (\n prefix: string,\n options?: ObjectEncodingOptions | BufferEncoding | null,\n ): Promise => {\n ProtectFs.checkProtected(prefix, false);\n const tmp = await nodeFS.promises.mkdtemp.call(this, prefix, options); // async function mkdtemp(prefix, options) {\n return tmp.toString();\n },\n rm: async (path: PathLike, options?: RmOptions): Promise => {\n ProtectFs.checkProtected(path, false);\n return nodeFS.promises.rm.call(this, path, options); // async function rm(path, options) {\n },\n rmdir: async (path: PathLike): Promise => {\n ProtectFs.checkProtected(path, false);\n return nodeFS.promises.rmdir.call(this, path); // async function rmdir(path, options) {\n },\n };\n\n // Add missing constants\n this.constants = nodeFS.constants;\n\n // Add missing functions\n for (const m in nodeFS) {\n if (\n typeof (nodeFS as unknown as Record)[m] === 'function' &&\n Object.hasOwn(nodeFS, m) &&\n !Object.hasOwn(Object.getPrototypeOf(this), 'appendFile')\n ) {\n // console.debug(`Missing function in ProtectFS: ${m} - adding from node:fs`);\n // @ts-expect-error Elsewise we must implement EVERY function in fs\n this[m] = nodeFS[m];\n }\n }\n\n for (const m in nodeFS.promises) {\n if (\n typeof (nodeFS.promises as unknown as Record)[m] === 'function' &&\n Object.hasOwn(nodeFS.promises, m) &&\n !Object.hasOwn(this.promises, m)\n ) {\n // console.debug(`Missing function in ProtectFS: ${m} - adding from node:fs/promises`);\n // @ts-expect-error Elsewise we must implement EVERY function in fs\n this.promises[m] = nodeFS.promises[m];\n }\n }\n }\n\n static checkProtected(file: PathLike | FileHandle, readOnly: boolean): void {\n if ((file as FileHandle).fd) {\n // FileHandle objects bypass path checks — they were already validated at open() time.\n // This is safe because the sandbox only exposes the wrapped fs where open() is protected.\n return;\n }\n let filePath: string;\n try {\n // Use resolve() instead of normalize() to get an absolute path and eliminate .. traversals.\n // Then try realpath to resolve symlinks — fall back to resolved path if file doesn't exist yet.\n const resolved = resolve((file as PathLike).toString());\n try {\n filePath = nodeFS.realpathSync(resolved);\n } catch {\n filePath = resolved;\n }\n } catch {\n filePath = normalize((file as PathLike).toString());\n }\n\n if (filePath.endsWith(`-data${sep}objects.json`) || filePath.endsWith(`-data${sep}objects.jsonl`)) {\n ProtectFs.log?.error(`May not access ${(file as PathLike).toString()}`);\n throw new Error('Permission denied');\n }\n if (!readOnly && filePath.startsWith(join(ProtectFs.staticIoBrokerDataDir, 'files'))) {\n ProtectFs.log?.error(`May not write ${(file as PathLike).toString()} - use writeFile instead`);\n throw new Error('Permission denied');\n }\n if (!readOnly && filePath.startsWith(`file://${join(ProtectFs.staticIoBrokerDataDir, 'files')}`)) {\n ProtectFs.log?.error(`May not write ${(file as PathLike).toString()} - use writeFile instead`);\n throw new Error('Permission denied');\n }\n }\n\n access(path: PathLike, mode?: number | NoParamCallback, callback?: NoParamCallback): void {\n ProtectFs.checkProtected(path, true);\n if (typeof callback === 'function') {\n return nodeFS.access(path, mode as number | undefined, callback);\n }\n return nodeFS.access(path, mode as NoParamCallback);\n }\n\n accessSync(path: PathLike, mode?: number): void {\n ProtectFs.checkProtected(path, true);\n return nodeFS.accessSync(path, mode);\n }\n\n cp(\n source: string | URL,\n destination: string | URL,\n opts?: CopyOptions | ((err: NodeJS.ErrnoException | null) => void),\n callback?: (err: NodeJS.ErrnoException | null) => void,\n ): void {\n ProtectFs.checkProtected(source, false);\n ProtectFs.checkProtected(destination, false);\n if (callback) {\n return nodeFS.cp(source, destination, opts as CopyOptions, callback);\n }\n if (typeof opts === 'function') {\n return nodeFS.cp(source, destination, opts);\n }\n return nodeFS.cp(source, destination, opts as (err: NodeJS.ErrnoException | null) => void);\n }\n\n cpSync(source: string | URL, destination: string | URL, opts?: CopySyncOptions): void {\n ProtectFs.checkProtected(source, false);\n ProtectFs.checkProtected(destination, false);\n return nodeFS.cpSync.call(this, source, destination, opts);\n }\n\n readFile(\n path: PathOrFileDescriptor,\n options:\n | (ObjectEncodingOptions & {\n flag?: string | undefined;\n } & Abortable)\n | BufferEncoding\n | undefined\n | null\n | ((err: NodeJS.ErrnoException | null, data: string | NonSharedBuffer) => void),\n callback?: (err: NodeJS.ErrnoException | null, data: string | NonSharedBuffer) => void,\n ): void {\n if (typeof path !== 'number') {\n ProtectFs.checkProtected(path, true);\n }\n if (typeof callback === 'function') {\n return nodeFS.readFile.call(\n this,\n path,\n options as\n | (ObjectEncodingOptions & {\n flag?: string | undefined;\n } & Abortable)\n | BufferEncoding\n | undefined\n | null,\n // @ts-expect-error readFile can accept 3 arguments too\n callback,\n );\n }\n return nodeFS.readFile.call(\n this,\n path,\n options as (err: NodeJS.ErrnoException | null, data: string | NonSharedBuffer) => void,\n );\n }\n\n readFileSync(\n path: PathOrFileDescriptor,\n options?:\n | {\n encoding: BufferEncoding;\n flag?: string | undefined;\n }\n | BufferEncoding,\n ): string | Buffer {\n if (typeof path !== 'number') {\n ProtectFs.checkProtected(path, true);\n }\n return nodeFS.readFileSync.call(this, path, options);\n }\n\n readlink(\n path: PathLike,\n options: EncodingOption | ((err: NodeJS.ErrnoException | null, linkString: string | Buffer) => void),\n callback?: (err: NodeJS.ErrnoException | null, linkString: string | Buffer) => void,\n ): void {\n ProtectFs.checkProtected(path, true);\n if (typeof callback === 'function') {\n // @ts-expect-error should work\n return nodeFS.readlink.call(this, path, options, callback); //\n }\n return nodeFS.readlink.call(\n this,\n path,\n options as (err: NodeJS.ErrnoException | null, linkString: string | Buffer) => void,\n );\n }\n\n readlinkSync(path: PathLike, options?: EncodingOption): string | Buffer {\n ProtectFs.checkProtected(path, true);\n return nodeFS.readlinkSync.call(this, path, options);\n }\n\n symlink(\n target: PathLike,\n path: PathLike,\n type?: 'dir' | 'file' | 'junction' | null | NoParamCallback,\n callback?: NoParamCallback,\n ): void {\n ProtectFs.checkProtected(target, true);\n ProtectFs.checkProtected(path, false);\n if (typeof callback === 'function') {\n // @ts-expect-error should work\n return nodeFS.symlink.call(this, target, path, type as 'dir' | 'file' | 'junction' | null, callback);\n }\n return nodeFS.symlink.call(this, target, path, type as NoParamCallback);\n }\n\n symlinkSync(target: PathLike, path: PathLike, type?: 'dir' | 'file' | 'junction' | null): void {\n ProtectFs.checkProtected(target, true);\n ProtectFs.checkProtected(path, false);\n return nodeFS.symlinkSync.call(this, target, path, type);\n }\n\n writeFile(\n file: PathLike | number,\n data: string | NodeJS.ArrayBufferView,\n options?: WriteFileOptions | NoParamCallback,\n callback?: NoParamCallback,\n ): void {\n if (typeof file !== 'number') {\n ProtectFs.checkProtected(file, false);\n }\n if (typeof callback === 'function') {\n // @ts-expect-error should work\n return nodeFS.writeFile.call(this, file, data, options, callback);\n }\n return nodeFS.writeFile.call(this, file, data, options as NoParamCallback);\n }\n\n writeFileSync(file: PathLike | number, data: string | NodeJS.ArrayBufferView, options?: WriteFileOptions): void {\n if (typeof file !== 'number') {\n ProtectFs.checkProtected(file, false);\n }\n return nodeFS.writeFileSync.call(this, file, data, options);\n }\n\n unlink(path: PathLike, callback?: NoParamCallback): void {\n ProtectFs.checkProtected(path, false);\n return nodeFS.unlink.call(this, path, callback || ((_err: NodeJS.ErrnoException | null) => {}));\n }\n\n unlinkSync(path: PathLike): void {\n ProtectFs.checkProtected(path, false);\n return nodeFS.unlinkSync.call(this, path);\n }\n\n appendFile(\n file: PathLike | number,\n data: string | Uint8Array,\n options?: WriteFileOptions | NoParamCallback,\n callback?: NoParamCallback,\n ): void {\n if (typeof file !== 'number') {\n ProtectFs.checkProtected(file, false);\n }\n if (typeof callback === 'function') {\n // @ts-expect-error should work\n return nodeFS.appendFile.call(this, file, data, options, callback);\n }\n return nodeFS.appendFile.call(this, file, data, options as NoParamCallback);\n }\n\n appendFileSync(file: PathLike | number, data: string | Uint8Array, options?: WriteFileOptions): void {\n if (typeof file !== 'number') {\n ProtectFs.checkProtected(file, false);\n }\n return nodeFS.appendFileSync.call(this, file, data, options);\n }\n\n chmod(path: PathLike, mode: Mode, callback?: NoParamCallback): void {\n ProtectFs.checkProtected(path, false);\n return nodeFS.chmod.call(this, path, mode, callback || ((_err: NodeJS.ErrnoException | null) => {}));\n }\n\n chmodSync(path: PathLike, mode: Mode): void {\n ProtectFs.checkProtected(path, false);\n return nodeFS.chmodSync.call(this, path, mode);\n }\n\n chown(path: PathLike, uid: number, gid: number, callback?: NoParamCallback): void {\n ProtectFs.checkProtected(path, false);\n return nodeFS.chown.call(this, path, uid, gid, callback || ((_err: NodeJS.ErrnoException | null) => {}));\n }\n\n chownSync(path: PathLike, uid: number, gid: number): void {\n ProtectFs.checkProtected(path, false);\n return nodeFS.chownSync.call(this, path, uid, gid);\n }\n\n copyFile(src: PathLike, dest: PathLike, mode: number | NoParamCallback, callback?: NoParamCallback): void {\n ProtectFs.checkProtected(src, true);\n ProtectFs.checkProtected(dest, false);\n // @ts-expect-error should work\n return nodeFS.copyFile.call(this, src, dest, mode, callback);\n }\n\n copyFileSync(src: PathLike, dest: PathLike, mode?: number): void {\n ProtectFs.checkProtected(src, true);\n ProtectFs.checkProtected(dest, false);\n return nodeFS.copyFileSync.call(this, src, dest, mode);\n }\n\n rename(oldPath: PathLike, newPath: PathLike, callback?: NoParamCallback): void {\n ProtectFs.checkProtected(oldPath, false);\n ProtectFs.checkProtected(newPath, false);\n return nodeFS.rename.call(this, oldPath, newPath, callback || ((_err: NodeJS.ErrnoException | null) => {}));\n }\n\n renameSync(oldPath: PathLike, newPath: PathLike): void {\n ProtectFs.checkProtected(oldPath, false);\n ProtectFs.checkProtected(newPath, false);\n return nodeFS.renameSync.call(this, oldPath, newPath);\n }\n\n open(path: PathLike, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void {\n ProtectFs.checkProtected(path, true);\n return nodeFS.open.call(this, path, callback);\n }\n\n openSync(path: PathLike, flags: OpenMode, mode?: Mode | null): number {\n ProtectFs.checkProtected(path, true);\n return nodeFS.openSync.call(this, path, flags, mode);\n }\n\n truncate(path: PathLike, callback?: NoParamCallback): void {\n ProtectFs.checkProtected(path, false);\n return nodeFS.truncate.call(this, path, callback || ((_err: NodeJS.ErrnoException | null) => {}));\n }\n\n truncateSync(path: PathLike): void {\n ProtectFs.checkProtected(path, false);\n return nodeFS.truncateSync.call(this, path);\n }\n\n exists(path: PathLike, callback: (exists: boolean) => void): void {\n ProtectFs.checkProtected(path, true);\n return nodeFS.exists.call(this, path, callback);\n }\n\n existsSync(path: PathLike): boolean {\n ProtectFs.checkProtected(path, true);\n return nodeFS.existsSync.call(this, path);\n }\n\n stat(\n path: PathLike,\n options: StatOptions | undefined | ((err: NodeJS.ErrnoException | null, stats: Stats) => void),\n callback?: (err: NodeJS.ErrnoException | null, stats: Stats) => void,\n ): void {\n ProtectFs.checkProtected(path, true);\n if (typeof callback === 'function') {\n // @ts-expect-error should work\n return nodeFS.stat.call(this, path, options as StatOptions | undefined, callback);\n }\n // @ts-expect-error should work\n return nodeFS.stat.call(this, path, options as (err: NodeJS.ErrnoException | null, stats: Stats) => void);\n }\n\n statSync(path: PathLike, options?: StatOptions): Stats {\n ProtectFs.checkProtected(path, true);\n return nodeFS.statSync.call(this, path, options);\n }\n\n utimes(path: PathLike, atime: TimeLike, mtime: TimeLike, callback?: NoParamCallback): void {\n ProtectFs.checkProtected(path, false);\n return nodeFS.utimes.call(this, path, atime, mtime, callback || ((_err: NodeJS.ErrnoException | null) => {}));\n }\n\n utimesSync(path: PathLike, atime: TimeLike, mtime: TimeLike): void {\n ProtectFs.checkProtected(path, false);\n return nodeFS.utimesSync.call(this, path, atime, mtime);\n }\n\n readdir(\n path: PathLike,\n options:\n | (ObjectEncodingOptions & {\n withFileTypes: true;\n recursive?: boolean | undefined;\n })\n | ((err: NodeJS.ErrnoException | null, files: Dirent[][]) => void),\n callback?: (err: NodeJS.ErrnoException | null, files: Dirent[]) => void,\n ): void {\n ProtectFs.checkProtected(path, true);\n if (typeof callback === 'function') {\n return nodeFS.readdir.call(\n this,\n path,\n options as ObjectEncodingOptions & {\n encoding: 'buffer';\n withFileTypes: true;\n recursive?: boolean | undefined;\n },\n callback,\n );\n }\n // @ts-expect-error should work\n return nodeFS.readdir.call(this, path, options as (err: NodeJS.ErrnoException | null, files: Dirent[]) => void);\n }\n\n readdirSync(\n path: PathLike,\n options?: ObjectEncodingOptions & {\n withFileTypes: true;\n recursive?: boolean | undefined;\n },\n ): Dirent[] {\n ProtectFs.checkProtected(path, true);\n // @ts-expect-error should work\n return nodeFS.readdirSync.call(this, path, options);\n }\n\n createReadStream(path: PathLike, options?: BufferEncoding): ReadStream {\n ProtectFs.checkProtected(path, true);\n return nodeFS.createReadStream.call(this, path, options);\n }\n\n createWriteStream(path: PathLike, options?: BufferEncoding): WriteStream {\n ProtectFs.checkProtected(path, false);\n return nodeFS.createWriteStream.call(this, path, options);\n }\n\n lchmod(path: PathLike, mode: Mode, callback?: NoParamCallback): void {\n ProtectFs.checkProtected(path, false);\n return nodeFS.lchmod.call(this, path, mode, callback || ((_err: NodeJS.ErrnoException | null) => {}));\n }\n\n lchmodSync(path: PathLike, mode: Mode): void {\n ProtectFs.checkProtected(path, false);\n return nodeFS.lchmodSync.call(this, path, mode);\n }\n\n lchown(path: PathLike, uid: number, gid: number, callback?: NoParamCallback): void {\n ProtectFs.checkProtected(path, false);\n return nodeFS.lchown.call(this, path, uid, gid, callback || ((_err: NodeJS.ErrnoException | null) => {}));\n }\n\n lchownSync(path: PathLike, uid: number, gid: number): void {\n ProtectFs.checkProtected(path, false);\n return nodeFS.lchownSync.call(this, path, uid, gid);\n }\n\n link(existingPath: PathLike, newPath: PathLike, callback?: NoParamCallback): void {\n ProtectFs.checkProtected(existingPath, false);\n ProtectFs.checkProtected(newPath, false);\n return nodeFS.link.call(this, existingPath, newPath, callback || ((_err: NodeJS.ErrnoException | null) => {}));\n }\n\n linkSync(existingPath: PathLike, newPath: PathLike): void {\n ProtectFs.checkProtected(existingPath, false);\n ProtectFs.checkProtected(newPath, false);\n return nodeFS.linkSync.call(this, existingPath, newPath);\n }\n\n lstat(\n path: PathLike,\n options: StatOptions | undefined | ((err: NodeJS.ErrnoException | null, stats: Stats) => void),\n callback?: (err: NodeJS.ErrnoException | null, stats: Stats) => void,\n ): void {\n ProtectFs.checkProtected(path, true);\n if (typeof callback === 'function') {\n // @ts-expect-error should work\n return nodeFS.lstat.call(this, path, options as StatOptions | undefined, callback);\n }\n // @ts-expect-error should work\n return nodeFS.lstat.call(this, path, options as (err: NodeJS.ErrnoException | null, stats: Stats) => void);\n }\n\n lstatSync(path: PathLike, options?: StatOptions): Stats {\n ProtectFs.checkProtected(path, true);\n return nodeFS.lstatSync.call(this, path, options);\n }\n\n lutimes(path: PathLike, atime: TimeLike, mtime: TimeLike, callback?: NoParamCallback): void {\n ProtectFs.checkProtected(path, false);\n return nodeFS.lutimes.call(this, path, atime, mtime, callback || ((_err: NodeJS.ErrnoException | null) => {}));\n }\n\n lutimesSync(path: PathLike, atime: TimeLike, mtime: TimeLike): void {\n ProtectFs.checkProtected(path, false);\n return nodeFS.lutimesSync.call(this, path, atime, mtime);\n }\n\n mkdir(\n path: PathLike,\n options:\n | Mode\n | (MakeDirectoryOptions & {\n recursive: true;\n })\n | null\n | undefined\n | ((err: NodeJS.ErrnoException | null, path?: string) => void),\n callback?: (err: NodeJS.ErrnoException | null, path?: string) => void,\n ): void {\n ProtectFs.checkProtected(path, false);\n if (typeof callback === 'function') {\n // @ts-expect-error should work\n return nodeFS.mkdir.call(this, path, options as MakeDirectoryOptions & { recursive?: boolean }, callback);\n }\n return nodeFS.mkdir.call(this, path, options as (err: NodeJS.ErrnoException | null, path?: string) => void);\n }\n\n mkdirSync(\n path: PathLike,\n options?: MakeDirectoryOptions & {\n recursive: true;\n },\n ): string | undefined {\n ProtectFs.checkProtected(path, false);\n return nodeFS.mkdirSync.call(this, path, options);\n }\n\n mkdtemp(\n prefix: string,\n options: EncodingOption | ((err: NodeJS.ErrnoException | null, folder: string) => void),\n callback?: (err: NodeJS.ErrnoException | null, folder: string) => void,\n ): void {\n ProtectFs.checkProtected(prefix, false);\n if (typeof callback === 'function') {\n // @ts-expect-error should work\n return nodeFS.mkdtemp.call(this, prefix, options, callback);\n }\n return nodeFS.mkdtemp.call(\n this,\n prefix,\n options as (err: NodeJS.ErrnoException | null, folder: string) => void,\n );\n }\n\n mkdtempSync(prefix: string, options?: EncodingOption): string | Buffer {\n ProtectFs.checkProtected(prefix, false);\n return nodeFS.mkdtempSync.call(this, prefix, options);\n }\n\n rm(path: PathLike, options?: RmOptions | NoParamCallback, callback?: NoParamCallback): void {\n ProtectFs.checkProtected(path, false);\n if (typeof callback === 'function') {\n return nodeFS.rm.call(this, path, options as RmOptions, callback);\n }\n // @ts-expect-error should work\n return nodeFS.rm.call(this, path, options as NoParamCallback);\n }\n\n rmSync(path: PathLike, options?: RmOptions): void {\n ProtectFs.checkProtected(path, false);\n return nodeFS.rmSync.call(this, path, options);\n }\n\n rmdir(path: PathLike, callback?: NoParamCallback): void {\n ProtectFs.checkProtected(path, false);\n if (typeof callback === 'function') {\n return (nodeFS.rmdir as (...args: unknown[]) => void).call(this, path, callback);\n }\n return nodeFS.rmdirSync.call(this, path);\n }\n\n rmdirSync(path: PathLike): void {\n ProtectFs.checkProtected(path, false);\n return nodeFS.rmdirSync.call(this, path);\n }\n\n watch(\n filename: PathLike,\n options?:\n | (WatchOptions & {\n encoding: 'buffer';\n })\n | 'buffer'\n | WatchListener,\n listener?: WatchListener,\n ): FSWatcher {\n ProtectFs.checkProtected(filename, true);\n if (typeof listener === 'function') {\n // @ts-expect-error should work\n return nodeFS.watch.call(this, filename, options as WatchOptions & { encoding: 'buffer' }, listener);\n }\n\n return nodeFS.watch.call(this, filename, options as WatchListener);\n }\n\n watchFile(filename: PathLike, listener: StatsListener): StatWatcher {\n ProtectFs.checkProtected(filename, true);\n return nodeFS.watchFile.call(this, filename, listener);\n }\n\n unwatchFile(filename: PathLike, listener: StatsListener | BigIntStatsListener): void {\n ProtectFs.checkProtected(filename, true);\n return nodeFS.unwatchFile.call(this, filename, listener as BigIntStatsListener);\n }\n}\n"]} +{"version":3,"file":"protectFs.js","sourceRoot":"","sources":["../../src/lib/protectFs.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,gDAAkC;AAClC,yCAA0D;AAE1D,MAAqB,SAAS;IACT,GAAG,CAAkB;IACrB,eAAe,CAAS;IACzB,QAAQ,CA+DtB;IACc,SAAS,CAAyB;IAClD,MAAM,CAAC,GAAG,GAA2B,IAAI,CAAC;IAC1C,MAAM,CAAC,qBAAqB,GAAW,EAAE,CAAC;IAE1C,YAAY,GAAoB,EAAE,eAAuB;QACrD,IAAI,CAAC,eAAe,GAAG,eAAe,CAAC;QACvC,SAAS,CAAC,qBAAqB,GAAG,eAAe,CAAC;QAElD,IAAI,CAAC,GAAG,GAAG,GAAG,IAAI;YACd,KAAK,EAAE,CAAC,OAAe,EAAQ,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC;YACtD,KAAK,EAAE,CAAC,OAAe,EAAQ,EAAE,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC;YACxD,IAAI,EAAE,CAAC,OAAe,EAAQ,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC;YACtD,IAAI,EAAE,CAAC,O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AC;QACtC,OAAO,MAAM,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IAC7C,CAAC;IAED,KAAK,CACD,QAAkB,EAClB,OAK2B,EAC3B,QAAgC;QAEhC,SAAS,CAAC,cAAc,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC;QACzC,IAAI,OAAO,QAAQ,KAAK,UAAU,EAAE,CAAC;YACjC,+BAA+B;YAC/B,OAAO,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,EAAE,QAAQ,EAAE,OAAgD,EAAE,QAAQ,CAAC,CAAC;QACzG,CAAC;QAED,OAAO,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,EAAE,QAAQ,EAAE,OAAgC,CAAC,CAAC;IAC/E,CAAC;IAED,SAAS,CAAC,QAAkB,EAAE,QAAuB;QACjD,SAAS,CAAC,cAAc,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC;QACzC,OAAO,MAAM,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,EAAE,QAAQ,EAAE,QAAQ,CAAC,CAAC;IAC3D,CAAC;IAED,WAAW,CAAC,QAAkB,EAAE,QAA6C;QACzE,SAAS,CAAC,cAAc,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC;QACzC,OAAO,MAAM,CAAC,WAAW,CAAC,IAAI,CAAC,IAAI,EAAE,QAAQ,EAAE,QAA+B,CAAC,CAAC;IACpF,CAAC;;AAtzBL,4BAuzBC","sourcesContent":["import type {\n BufferEncodingOption,\n CopyOptions,\n Dirent,\n MakeDirectoryOptions,\n Mode,\n ObjectEncodingOptions,\n OpenMode,\n PathLike,\n RmDirOptions,\n RmOptions,\n StatOptions,\n Stats,\n TimeLike,\n CopySyncOptions,\n NoParamCallback,\n PathOrFileDescriptor,\n WriteFileOptions,\n EncodingOption,\n FSWatcher,\n ReadStream,\n StatsListener,\n StatWatcher,\n WatchListener,\n WriteStream,\n BigIntStatsListener,\n WatchOptions,\n} from 'node:fs';\nimport type { Abortable } from 'node:events';\nimport type { FileHandle, FlagAndOpenMode } from 'node:fs/promises';\nimport type { URL } from 'node:url';\nimport type { Stream } from 'node:stream';\n\nimport * as nodeFS from 'node:fs';\nimport { sep, normalize, join, resolve } from 'node:path';\n\nexport default class ProtectFs {\n private readonly log: ioBroker.Logger;\n private readonly ioBrokerDataDir: string;\n public readonly promises: {\n access: (path: PathLike, mode?: number) => Promise;\n cp: (source: string | URL, destination: string | URL, opts?: CopyOptions) => Promise;\n readFile: (\n path: PathLike | FileHandle,\n options:\n | ({\n encoding: BufferEncoding;\n flag?: OpenMode | undefined;\n } & Abortable)\n | BufferEncoding,\n ) => Promise;\n readlink: (path: PathLike, options: BufferEncodingOption) => Promise;\n symlink: (target: PathLike, path: PathLike, type?: string | null) => Promise;\n writeFile: (\n file: PathLike | FileHandle,\n data:\n | string\n | NodeJS.ArrayBufferView\n | Iterable\n | AsyncIterable\n | Stream,\n options?:\n | (ObjectEncodingOptions & {\n mode?: Mode | undefined;\n flag?: OpenMode | undefined;\n flush?: boolean | undefined;\n } & Abortable)\n | BufferEncoding\n | null,\n ) => Promise;\n unlink: (path: PathLike) => Promise;\n appendFile: (\n path: PathLike | FileHandle,\n data: string | Uint8Array,\n options?:\n | (ObjectEncodingOptions & FlagAndOpenMode & { flush?: boolean | undefined })\n | BufferEncoding\n | null,\n ) => Promise;\n chmod: (path: PathLike, mode: Mode) => Promise;\n copyFile: (src: PathLike, dest: PathLike, mode?: number) => Promise;\n rename: (oldPath: PathLike, newPath: PathLike) => Promise;\n open: (path: PathLike, flags?: string | number, mode?: Mode) => Promise;\n truncate: (path: PathLike, len?: number) => Promise;\n stat: (path: PathLike, opts?: StatOptions) => Promise;\n utimes: (path: PathLike, atime: TimeLike, mtime: TimeLike) => Promise;\n readdir: (\n path: PathLike,\n options?: ObjectEncodingOptions & {\n withFileTypes: true;\n recursive?: boolean | undefined;\n },\n ) => Promise;\n lchmod: (path: PathLike, mode: Mode) => Promise;\n lchown: (path: PathLike, uid: number, gid: number) => Promise;\n link: (existingPath: PathLike, newPath: PathLike) => Promise;\n lstat: (path: PathLike, opts?: StatOptions) => Promise;\n lutimes: (path: PathLike, atime: TimeLike, mtime: TimeLike) => Promise;\n mkdir: (path: PathLike, options?: Mode | MakeDirectoryOptions | null) => Promise;\n mkdtemp: (prefix: string, options?: ObjectEncodingOptions | BufferEncoding | null) => Promise;\n rm: (path: PathLike, options?: RmOptions) => Promise;\n rmdir: (path: PathLike, options?: RmDirOptions) => Promise;\n };\n public readonly constants: Record;\n static log: ioBroker.Logger | null = null;\n static staticIoBrokerDataDir: string = '';\n\n constructor(log: ioBroker.Logger, ioBrokerDataDir: string) {\n this.ioBrokerDataDir = ioBrokerDataDir;\n ProtectFs.staticIoBrokerDataDir = ioBrokerDataDir;\n\n this.log = log || {\n silly: (message: string): void => console.log(message),\n debug: (message: string): void => console.debug(message),\n info: (message: string): void => console.info(message),\n warn: (message: string): void => console.warn(message),\n error: (message: string): void => console.error(message),\n level: 'info',\n };\n\n ProtectFs.log = this.log;\n\n this.promises = {\n access: async (path: PathLike, mode?: number): Promise => {\n ProtectFs.checkProtected(path, true);\n return nodeFS.promises.access(path, mode);\n },\n cp: async (source: string | URL, destination: string | URL, opts?: CopyOptions): Promise => {\n ProtectFs.checkProtected(source, false);\n ProtectFs.checkProtected(destination, false);\n return nodeFS.promises.cp(source, destination, opts);\n },\n readFile: async (\n path: PathLike | FileHandle,\n options:\n | ({\n encoding: BufferEncoding;\n flag?: OpenMode | undefined;\n } & Abortable)\n | BufferEncoding,\n ): Promise => {\n ProtectFs.checkProtected(path, true);\n return nodeFS.promises.readFile(path, options); // async function readFile(path, options) {\n },\n readlink: async (path: PathLike, options: BufferEncodingOption): Promise => {\n ProtectFs.checkProtected(path, true);\n return nodeFS.promises.readlink(path, options); // async function readlink(path, options) {\n },\n symlink: async (target: PathLike, path: PathLike, type?: string | null): Promise => {\n ProtectFs.checkProtected(target, true);\n ProtectFs.checkProtected(path, false);\n return nodeFS.promises.symlink(target, path, type); // async function symlink(target, path, type_) {\n },\n writeFile: async (\n file: PathLike | FileHandle,\n data:\n | string\n | NodeJS.ArrayBufferView\n | Iterable\n | AsyncIterable\n | Stream,\n options?:\n | (ObjectEncodingOptions & {\n mode?: Mode | undefined;\n flag?: OpenMode | undefined;\n /**\n * If all data is successfully written to the file, and `flush`\n * is `true`, `filehandle.sync()` is used to flush the data.\n *\n * @default false\n */\n flush?: boolean | undefined;\n } & Abortable)\n | BufferEncoding\n | null,\n ): Promise => {\n ProtectFs.checkProtected(file, true);\n return nodeFS.promises.writeFile.call(this, file, data, options); // async function writeFile(path, data, options) {\n },\n unlink: async (path: PathLike): Promise => {\n ProtectFs.checkProtected(path, false);\n return nodeFS.promises.unlink.call(this, path); // async function unlink(path) {\n },\n appendFile: async (\n path: PathLike | FileHandle,\n data: string | Uint8Array,\n options?:\n | (ObjectEncodingOptions & FlagAndOpenMode & { flush?: boolean | undefined })\n | BufferEncoding\n | null,\n ): Promise => {\n ProtectFs.checkProtected(path, false);\n return nodeFS.promises.appendFile.call(this, path, data, options); // async function appendFile(path, data, options) {\n },\n chmod: async (path: PathLike, mode: Mode): Promise => {\n ProtectFs.checkProtected(path, false);\n return nodeFS.promises.chmod.call(this, path, mode); // async function chmod(path, mode) {\n },\n copyFile: async (src: PathLike, dest: PathLike, mode?: number): Promise => {\n ProtectFs.checkProtected(src, false);\n ProtectFs.checkProtected(dest, false);\n return nodeFS.promises.copyFile.call(this, src, dest, mode); // async function copyFile(src, dest, mode) {\n },\n rename: async (oldPath: PathLike, newPath: PathLike): Promise => {\n ProtectFs.checkProtected(oldPath, false);\n ProtectFs.checkProtected(newPath, false);\n return nodeFS.promises.rename.call(this, oldPath, newPath); // async function rename(oldPath, newPath) {\n },\n open: async (path: PathLike, flags?: string | number, mode?: Mode): Promise => {\n ProtectFs.checkProtected(path, true);\n return nodeFS.promises.open.call(this, path, flags, mode); // async function open(path, flags, mode) {\n },\n truncate: async (path: PathLike, len?: number): Promise => {\n ProtectFs.checkProtected(path, false);\n return nodeFS.promises.truncate.call(this, path, len); // async function truncate(path, len = 0) {\n },\n stat: async (path: PathLike, opts?: StatOptions): Promise => {\n ProtectFs.checkProtected(path, true);\n const result = await nodeFS.promises.stat.call(this, path, opts); // async function stat(path, options = { bigint: false }) {\n return result as Stats;\n },\n utimes: async (path: PathLike, atime: TimeLike, mtime: TimeLike): Promise => {\n ProtectFs.checkProtected(path, false);\n return nodeFS.promises.utimes.call(this, path, atime, mtime); // async function utimes(path, atime, mtime) {\n },\n readdir: async (\n path: PathLike,\n options?: ObjectEncodingOptions & {\n withFileTypes: true;\n recursive?: boolean | undefined;\n },\n ): Promise => {\n ProtectFs.checkProtected(path, true);\n // @ts-expect-error fix later\n return nodeFS.promises.readdir.call(this, path, options || { encoding: null, withFileTypes: true }); // async function readdir(path, options) {\n },\n lchmod: async (path: PathLike, mode: Mode): Promise => {\n ProtectFs.checkProtected(path, false);\n return nodeFS.promises.lchmod.call(this, path, mode); // async function lchmod(path, mode) {\n },\n lchown: async (path: PathLike, uid: number, gid: number): Promise => {\n ProtectFs.checkProtected(path, false);\n return nodeFS.promises.lchown.call(this, path, uid, gid); // async function lchown(path, uid, gid) {\n },\n link: async (existingPath: PathLike, newPath: PathLike): Promise => {\n ProtectFs.checkProtected(existingPath, false);\n ProtectFs.checkProtected(newPath, false);\n return nodeFS.promises.link.call(this, existingPath, newPath); // async function link(existingPath, newPath) {\n },\n lstat: async (path: PathLike, opts?: StatOptions): Promise => {\n ProtectFs.checkProtected(path, true);\n const res = await nodeFS.promises.lstat.call(this, path, opts); // async function lstat(path, options = { bigint: false }) {\n return res as Stats;\n },\n lutimes: async (path: PathLike, atime: TimeLike, mtime: TimeLike): Promise => {\n ProtectFs.checkProtected(path, false);\n return nodeFS.promises.lutimes.call(this, path, atime, mtime); // async function lutimes(path, atime, mtime) {\n },\n mkdir: async (\n path: PathLike,\n options?: Mode | MakeDirectoryOptions | null,\n ): Promise => {\n ProtectFs.checkProtected(path, false);\n return nodeFS.promises.mkdir.call(this, path, options); // async function mkdir(path, options) {\n },\n mkdtemp: async (\n prefix: string,\n options?: ObjectEncodingOptions | BufferEncoding | null,\n ): Promise => {\n ProtectFs.checkProtected(prefix, false);\n const tmp = await nodeFS.promises.mkdtemp.call(this, prefix, options); // async function mkdtemp(prefix, options) {\n return tmp.toString();\n },\n rm: async (path: PathLike, options?: RmOptions): Promise => {\n ProtectFs.checkProtected(path, false);\n return nodeFS.promises.rm.call(this, path, options); // async function rm(path, options) {\n },\n rmdir: async (path: PathLike): Promise => {\n ProtectFs.checkProtected(path, false);\n return nodeFS.promises.rmdir.call(this, path); // async function rmdir(path, options) {\n },\n };\n\n // Add missing constants\n this.constants = nodeFS.constants;\n\n // Add missing functions\n for (const m in nodeFS) {\n if (\n typeof (nodeFS as unknown as Record)[m] === 'function' &&\n Object.hasOwn(nodeFS, m) &&\n !Object.hasOwn(Object.getPrototypeOf(this), 'appendFile')\n ) {\n // console.debug(`Missing function in ProtectFS: ${m} - adding from node:fs`);\n // @ts-expect-error Elsewise we must implement EVERY function in fs\n this[m] = nodeFS[m];\n }\n }\n\n for (const m in nodeFS.promises) {\n if (\n typeof (nodeFS.promises as unknown as Record)[m] === 'function' &&\n Object.hasOwn(nodeFS.promises, m) &&\n !Object.hasOwn(this.promises, m)\n ) {\n // console.debug(`Missing function in ProtectFS: ${m} - adding from node:fs/promises`);\n // @ts-expect-error Elsewise we must implement EVERY function in fs\n this.promises[m] = nodeFS.promises[m];\n }\n }\n }\n\n static checkProtected(file: PathLike | FileHandle, readOnly: boolean): void {\n if ((file as FileHandle).fd) {\n // FileHandle objects bypass path checks — they were already validated at open() time.\n // This is safe because the sandbox only exposes the wrapped fs where open() is protected.\n return;\n }\n let filePath: string;\n try {\n // Use resolve() instead of normalize() to get an absolute path and eliminate .. traversals.\n // Then try realpath to resolve symlinks — fall back to resolved path if file doesn't exist yet.\n const resolved = resolve((file as PathLike).toString());\n try {\n filePath = nodeFS.realpathSync(resolved);\n } catch {\n filePath = resolved;\n }\n } catch {\n filePath = normalize((file as PathLike).toString());\n }\n\n if (filePath.endsWith(`-data${sep}objects.json`) || filePath.endsWith(`-data${sep}objects.jsonl`)) {\n ProtectFs.log?.error(`May not access ${(file as PathLike).toString()}`);\n throw new Error('Permission denied');\n }\n if (!readOnly && filePath.startsWith(join(ProtectFs.staticIoBrokerDataDir, 'files'))) {\n ProtectFs.log?.error(`May not write ${(file as PathLike).toString()} - use writeFile instead`);\n throw new Error('Permission denied');\n }\n if (!readOnly && filePath.startsWith(`file://${join(ProtectFs.staticIoBrokerDataDir, 'files')}`)) {\n ProtectFs.log?.error(`May not write ${(file as PathLike).toString()} - use writeFile instead`);\n throw new Error('Permission denied');\n }\n // Disallow writing into node_modules directories (see #2127)\n if (!readOnly && `${sep}${filePath}${sep}`.includes(`${sep}node_modules${sep}`)) {\n ProtectFs.log?.error(`May not write into node_modules: ${(file as PathLike).toString()}`);\n throw new Error('Permission denied. Writing into node_modules is not allowed');\n }\n }\n\n access(path: PathLike, mode?: number | NoParamCallback, callback?: NoParamCallback): void {\n ProtectFs.checkProtected(path, true);\n if (typeof callback === 'function') {\n return nodeFS.access(path, mode as number | undefined, callback);\n }\n return nodeFS.access(path, mode as NoParamCallback);\n }\n\n accessSync(path: PathLike, mode?: number): void {\n ProtectFs.checkProtected(path, true);\n return nodeFS.accessSync(path, mode);\n }\n\n cp(\n source: string | URL,\n destination: string | URL,\n opts?: CopyOptions | ((err: NodeJS.ErrnoException | null) => void),\n callback?: (err: NodeJS.ErrnoException | null) => void,\n ): void {\n ProtectFs.checkProtected(source, false);\n ProtectFs.checkProtected(destination, false);\n if (callback) {\n return nodeFS.cp(source, destination, opts as CopyOptions, callback);\n }\n if (typeof opts === 'function') {\n return nodeFS.cp(source, destination, opts);\n }\n return nodeFS.cp(source, destination, opts as (err: NodeJS.ErrnoException | null) => void);\n }\n\n cpSync(source: string | URL, destination: string | URL, opts?: CopySyncOptions): void {\n ProtectFs.checkProtected(source, false);\n ProtectFs.checkProtected(destination, false);\n return nodeFS.cpSync.call(this, source, destination, opts);\n }\n\n readFile(\n path: PathOrFileDescriptor,\n options:\n | (ObjectEncodingOptions & {\n flag?: string | undefined;\n } & Abortable)\n | BufferEncoding\n | undefined\n | null\n | ((err: NodeJS.ErrnoException | null, data: string | NonSharedBuffer) => void),\n callback?: (err: NodeJS.ErrnoException | null, data: string | NonSharedBuffer) => void,\n ): void {\n if (typeof path !== 'number') {\n ProtectFs.checkProtected(path, true);\n }\n if (typeof callback === 'function') {\n return nodeFS.readFile.call(\n this,\n path,\n options as\n | (ObjectEncodingOptions & {\n flag?: string | undefined;\n } & Abortable)\n | BufferEncoding\n | undefined\n | null,\n // @ts-expect-error readFile can accept 3 arguments too\n callback,\n );\n }\n return nodeFS.readFile.call(\n this,\n path,\n options as (err: NodeJS.ErrnoException | null, data: string | NonSharedBuffer) => void,\n );\n }\n\n readFileSync(\n path: PathOrFileDescriptor,\n options?:\n | {\n encoding: BufferEncoding;\n flag?: string | undefined;\n }\n | BufferEncoding,\n ): string | Buffer {\n if (typeof path !== 'number') {\n ProtectFs.checkProtected(path, true);\n }\n return nodeFS.readFileSync.call(this, path, options);\n }\n\n readlink(\n path: PathLike,\n options: EncodingOption | ((err: NodeJS.ErrnoException | null, linkString: string | Buffer) => void),\n callback?: (err: NodeJS.ErrnoException | null, linkString: string | Buffer) => void,\n ): void {\n ProtectFs.checkProtected(path, true);\n if (typeof callback === 'function') {\n // @ts-expect-error should work\n return nodeFS.readlink.call(this, path, options, callback); //\n }\n return nodeFS.readlink.call(\n this,\n path,\n options as (err: NodeJS.ErrnoException | null, linkString: string | Buffer) => void,\n );\n }\n\n readlinkSync(path: PathLike, options?: EncodingOption): string | Buffer {\n ProtectFs.checkProtected(path, true);\n return nodeFS.readlinkSync.call(this, path, options);\n }\n\n symlink(\n target: PathLike,\n path: PathLike,\n type?: 'dir' | 'file' | 'junction' | null | NoParamCallback,\n callback?: NoParamCallback,\n ): void {\n ProtectFs.checkProtected(target, true);\n ProtectFs.checkProtected(path, false);\n if (typeof callback === 'function') {\n // @ts-expect-error should work\n return nodeFS.symlink.call(this, target, path, type as 'dir' | 'file' | 'junction' | null, callback);\n }\n return nodeFS.symlink.call(this, target, path, type as NoParamCallback);\n }\n\n symlinkSync(target: PathLike, path: PathLike, type?: 'dir' | 'file' | 'junction' | null): void {\n ProtectFs.checkProtected(target, true);\n ProtectFs.checkProtected(path, false);\n return nodeFS.symlinkSync.call(this, target, path, type);\n }\n\n writeFile(\n file: PathLike | number,\n data: string | NodeJS.ArrayBufferView,\n options?: WriteFileOptions | NoParamCallback,\n callback?: NoParamCallback,\n ): void {\n if (typeof file !== 'number') {\n ProtectFs.checkProtected(file, false);\n }\n if (typeof callback === 'function') {\n // @ts-expect-error should work\n return nodeFS.writeFile.call(this, file, data, options, callback);\n }\n return nodeFS.writeFile.call(this, file, data, options as NoParamCallback);\n }\n\n writeFileSync(file: PathLike | number, data: string | NodeJS.ArrayBufferView, options?: WriteFileOptions): void {\n if (typeof file !== 'number') {\n ProtectFs.checkProtected(file, false);\n }\n return nodeFS.writeFileSync.call(this, file, data, options);\n }\n\n unlink(path: PathLike, callback?: NoParamCallback): void {\n ProtectFs.checkProtected(path, false);\n return nodeFS.unlink.call(this, path, callback || ((_err: NodeJS.ErrnoException | null) => {}));\n }\n\n unlinkSync(path: PathLike): void {\n ProtectFs.checkProtected(path, false);\n return nodeFS.unlinkSync.call(this, path);\n }\n\n appendFile(\n file: PathLike | number,\n data: string | Uint8Array,\n options?: WriteFileOptions | NoParamCallback,\n callback?: NoParamCallback,\n ): void {\n if (typeof file !== 'number') {\n ProtectFs.checkProtected(file, false);\n }\n if (typeof callback === 'function') {\n // @ts-expect-error should work\n return nodeFS.appendFile.call(this, file, data, options, callback);\n }\n return nodeFS.appendFile.call(this, file, data, options as NoParamCallback);\n }\n\n appendFileSync(file: PathLike | number, data: string | Uint8Array, options?: WriteFileOptions): void {\n if (typeof file !== 'number') {\n ProtectFs.checkProtected(file, false);\n }\n return nodeFS.appendFileSync.call(this, file, data, options);\n }\n\n chmod(path: PathLike, mode: Mode, callback?: NoParamCallback): void {\n ProtectFs.checkProtected(path, false);\n return nodeFS.chmod.call(this, path, mode, callback || ((_err: NodeJS.ErrnoException | null) => {}));\n }\n\n chmodSync(path: PathLike, mode: Mode): void {\n ProtectFs.checkProtected(path, false);\n return nodeFS.chmodSync.call(this, path, mode);\n }\n\n chown(path: PathLike, uid: number, gid: number, callback?: NoParamCallback): void {\n ProtectFs.checkProtected(path, false);\n return nodeFS.chown.call(this, path, uid, gid, callback || ((_err: NodeJS.ErrnoException | null) => {}));\n }\n\n chownSync(path: PathLike, uid: number, gid: number): void {\n ProtectFs.checkProtected(path, false);\n return nodeFS.chownSync.call(this, path, uid, gid);\n }\n\n copyFile(src: PathLike, dest: PathLike, mode: number | NoParamCallback, callback?: NoParamCallback): void {\n ProtectFs.checkProtected(src, true);\n ProtectFs.checkProtected(dest, false);\n // @ts-expect-error should work\n return nodeFS.copyFile.call(this, src, dest, mode, callback);\n }\n\n copyFileSync(src: PathLike, dest: PathLike, mode?: number): void {\n ProtectFs.checkProtected(src, true);\n ProtectFs.checkProtected(dest, false);\n return nodeFS.copyFileSync.call(this, src, dest, mode);\n }\n\n rename(oldPath: PathLike, newPath: PathLike, callback?: NoParamCallback): void {\n ProtectFs.checkProtected(oldPath, false);\n ProtectFs.checkProtected(newPath, false);\n return nodeFS.rename.call(this, oldPath, newPath, callback || ((_err: NodeJS.ErrnoException | null) => {}));\n }\n\n renameSync(oldPath: PathLike, newPath: PathLike): void {\n ProtectFs.checkProtected(oldPath, false);\n ProtectFs.checkProtected(newPath, false);\n return nodeFS.renameSync.call(this, oldPath, newPath);\n }\n\n open(path: PathLike, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void {\n ProtectFs.checkProtected(path, true);\n return nodeFS.open.call(this, path, callback);\n }\n\n openSync(path: PathLike, flags: OpenMode, mode?: Mode | null): number {\n ProtectFs.checkProtected(path, true);\n return nodeFS.openSync.call(this, path, flags, mode);\n }\n\n truncate(path: PathLike, callback?: NoParamCallback): void {\n ProtectFs.checkProtected(path, false);\n return nodeFS.truncate.call(this, path, callback || ((_err: NodeJS.ErrnoException | null) => {}));\n }\n\n truncateSync(path: PathLike): void {\n ProtectFs.checkProtected(path, false);\n return nodeFS.truncateSync.call(this, path);\n }\n\n exists(path: PathLike, callback: (exists: boolean) => void): void {\n ProtectFs.checkProtected(path, true);\n return nodeFS.exists.call(this, path, callback);\n }\n\n existsSync(path: PathLike): boolean {\n ProtectFs.checkProtected(path, true);\n return nodeFS.existsSync.call(this, path);\n }\n\n stat(\n path: PathLike,\n options: StatOptions | undefined | ((err: NodeJS.ErrnoException | null, stats: Stats) => void),\n callback?: (err: NodeJS.ErrnoException | null, stats: Stats) => void,\n ): void {\n ProtectFs.checkProtected(path, true);\n if (typeof callback === 'function') {\n // @ts-expect-error should work\n return nodeFS.stat.call(this, path, options as StatOptions | undefined, callback);\n }\n // @ts-expect-error should work\n return nodeFS.stat.call(this, path, options as (err: NodeJS.ErrnoException | null, stats: Stats) => void);\n }\n\n statSync(path: PathLike, options?: StatOptions): Stats {\n ProtectFs.checkProtected(path, true);\n return nodeFS.statSync.call(this, path, options);\n }\n\n utimes(path: PathLike, atime: TimeLike, mtime: TimeLike, callback?: NoParamCallback): void {\n ProtectFs.checkProtected(path, false);\n return nodeFS.utimes.call(this, path, atime, mtime, callback || ((_err: NodeJS.ErrnoException | null) => {}));\n }\n\n utimesSync(path: PathLike, atime: TimeLike, mtime: TimeLike): void {\n ProtectFs.checkProtected(path, false);\n return nodeFS.utimesSync.call(this, path, atime, mtime);\n }\n\n readdir(\n path: PathLike,\n options:\n | (ObjectEncodingOptions & {\n withFileTypes: true;\n recursive?: boolean | undefined;\n })\n | ((err: NodeJS.ErrnoException | null, files: Dirent[][]) => void),\n callback?: (err: NodeJS.ErrnoException | null, files: Dirent[]) => void,\n ): void {\n ProtectFs.checkProtected(path, true);\n if (typeof callback === 'function') {\n return nodeFS.readdir.call(\n this,\n path,\n options as ObjectEncodingOptions & {\n encoding: 'buffer';\n withFileTypes: true;\n recursive?: boolean | undefined;\n },\n callback,\n );\n }\n // @ts-expect-error should work\n return nodeFS.readdir.call(this, path, options as (err: NodeJS.ErrnoException | null, files: Dirent[]) => void);\n }\n\n readdirSync(\n path: PathLike,\n options?: ObjectEncodingOptions & {\n withFileTypes: true;\n recursive?: boolean | undefined;\n },\n ): Dirent[] {\n ProtectFs.checkProtected(path, true);\n // @ts-expect-error should work\n return nodeFS.readdirSync.call(this, path, options);\n }\n\n createReadStream(path: PathLike, options?: BufferEncoding): ReadStream {\n ProtectFs.checkProtected(path, true);\n return nodeFS.createReadStream.call(this, path, options);\n }\n\n createWriteStream(path: PathLike, options?: BufferEncoding): WriteStream {\n ProtectFs.checkProtected(path, false);\n return nodeFS.createWriteStream.call(this, path, options);\n }\n\n lchmod(path: PathLike, mode: Mode, callback?: NoParamCallback): void {\n ProtectFs.checkProtected(path, false);\n return nodeFS.lchmod.call(this, path, mode, callback || ((_err: NodeJS.ErrnoException | null) => {}));\n }\n\n lchmodSync(path: PathLike, mode: Mode): void {\n ProtectFs.checkProtected(path, false);\n return nodeFS.lchmodSync.call(this, path, mode);\n }\n\n lchown(path: PathLike, uid: number, gid: number, callback?: NoParamCallback): void {\n ProtectFs.checkProtected(path, false);\n return nodeFS.lchown.call(this, path, uid, gid, callback || ((_err: NodeJS.ErrnoException | null) => {}));\n }\n\n lchownSync(path: PathLike, uid: number, gid: number): void {\n ProtectFs.checkProtected(path, false);\n return nodeFS.lchownSync.call(this, path, uid, gid);\n }\n\n link(existingPath: PathLike, newPath: PathLike, callback?: NoParamCallback): void {\n ProtectFs.checkProtected(existingPath, false);\n ProtectFs.checkProtected(newPath, false);\n return nodeFS.link.call(this, existingPath, newPath, callback || ((_err: NodeJS.ErrnoException | null) => {}));\n }\n\n linkSync(existingPath: PathLike, newPath: PathLike): void {\n ProtectFs.checkProtected(existingPath, false);\n ProtectFs.checkProtected(newPath, false);\n return nodeFS.linkSync.call(this, existingPath, newPath);\n }\n\n lstat(\n path: PathLike,\n options: StatOptions | undefined | ((err: NodeJS.ErrnoException | null, stats: Stats) => void),\n callback?: (err: NodeJS.ErrnoException | null, stats: Stats) => void,\n ): void {\n ProtectFs.checkProtected(path, true);\n if (typeof callback === 'function') {\n // @ts-expect-error should work\n return nodeFS.lstat.call(this, path, options as StatOptions | undefined, callback);\n }\n // @ts-expect-error should work\n return nodeFS.lstat.call(this, path, options as (err: NodeJS.ErrnoException | null, stats: Stats) => void);\n }\n\n lstatSync(path: PathLike, options?: StatOptions): Stats {\n ProtectFs.checkProtected(path, true);\n return nodeFS.lstatSync.call(this, path, options);\n }\n\n lutimes(path: PathLike, atime: TimeLike, mtime: TimeLike, callback?: NoParamCallback): void {\n ProtectFs.checkProtected(path, false);\n return nodeFS.lutimes.call(this, path, atime, mtime, callback || ((_err: NodeJS.ErrnoException | null) => {}));\n }\n\n lutimesSync(path: PathLike, atime: TimeLike, mtime: TimeLike): void {\n ProtectFs.checkProtected(path, false);\n return nodeFS.lutimesSync.call(this, path, atime, mtime);\n }\n\n mkdir(\n path: PathLike,\n options:\n | Mode\n | (MakeDirectoryOptions & {\n recursive: true;\n })\n | null\n | undefined\n | ((err: NodeJS.ErrnoException | null, path?: string) => void),\n callback?: (err: NodeJS.ErrnoException | null, path?: string) => void,\n ): void {\n ProtectFs.checkProtected(path, false);\n if (typeof callback === 'function') {\n // @ts-expect-error should work\n return nodeFS.mkdir.call(this, path, options as MakeDirectoryOptions & { recursive?: boolean }, callback);\n }\n return nodeFS.mkdir.call(this, path, options as (err: NodeJS.ErrnoException | null, path?: string) => void);\n }\n\n mkdirSync(\n path: PathLike,\n options?: MakeDirectoryOptions & {\n recursive: true;\n },\n ): string | undefined {\n ProtectFs.checkProtected(path, false);\n return nodeFS.mkdirSync.call(this, path, options);\n }\n\n mkdtemp(\n prefix: string,\n options: EncodingOption | ((err: NodeJS.ErrnoException | null, folder: string) => void),\n callback?: (err: NodeJS.ErrnoException | null, folder: string) => void,\n ): void {\n ProtectFs.checkProtected(prefix, false);\n if (typeof callback === 'function') {\n // @ts-expect-error should work\n return nodeFS.mkdtemp.call(this, prefix, options, callback);\n }\n return nodeFS.mkdtemp.call(\n this,\n prefix,\n options as (err: NodeJS.ErrnoException | null, folder: string) => void,\n );\n }\n\n mkdtempSync(prefix: string, options?: EncodingOption): string | Buffer {\n ProtectFs.checkProtected(prefix, false);\n return nodeFS.mkdtempSync.call(this, prefix, options);\n }\n\n rm(path: PathLike, options?: RmOptions | NoParamCallback, callback?: NoParamCallback): void {\n ProtectFs.checkProtected(path, false);\n if (typeof callback === 'function') {\n return nodeFS.rm.call(this, path, options as RmOptions, callback);\n }\n // @ts-expect-error should work\n return nodeFS.rm.call(this, path, options as NoParamCallback);\n }\n\n rmSync(path: PathLike, options?: RmOptions): void {\n ProtectFs.checkProtected(path, false);\n return nodeFS.rmSync.call(this, path, options);\n }\n\n rmdir(path: PathLike, callback?: NoParamCallback): void {\n ProtectFs.checkProtected(path, false);\n if (typeof callback === 'function') {\n return (nodeFS.rmdir as (...args: unknown[]) => void).call(this, path, callback);\n }\n return nodeFS.rmdirSync.call(this, path);\n }\n\n rmdirSync(path: PathLike): void {\n ProtectFs.checkProtected(path, false);\n return nodeFS.rmdirSync.call(this, path);\n }\n\n watch(\n filename: PathLike,\n options?:\n | (WatchOptions & {\n encoding: 'buffer';\n })\n | 'buffer'\n | WatchListener,\n listener?: WatchListener,\n ): FSWatcher {\n ProtectFs.checkProtected(filename, true);\n if (typeof listener === 'function') {\n // @ts-expect-error should work\n return nodeFS.watch.call(this, filename, options as WatchOptions & { encoding: 'buffer' }, listener);\n }\n\n return nodeFS.watch.call(this, filename, options as WatchListener);\n }\n\n watchFile(filename: PathLike, listener: StatsListener): StatWatcher {\n ProtectFs.checkProtected(filename, true);\n return nodeFS.watchFile.call(this, filename, listener);\n }\n\n unwatchFile(filename: PathLike, listener: StatsListener | BigIntStatsListener): void {\n ProtectFs.checkProtected(filename, true);\n return nodeFS.unwatchFile.call(this, filename, listener as BigIntStatsListener);\n }\n}\n"]} \ No newline at end of file diff --git a/build/main.js.map b/build/main.js.map index f171402c9..862448d5b 100644 --- a/build/main.js.map +++ b/build/main.js.map @@ -1 +1 @@ -{"version":3,"file":"main.js","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":";AAAA;;;;;;;;GAQG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,qCAAqD;AACrD,qCAAwF;AACxF,yCAAiD;AACjD,2DAA4D;AAC5D,6CAAkE;AAClE,yCAA8C;AAC9C,wDAAgC;AAEhC,kDAAoC;AACpC,oDAAsC;AACtC,8CAAgC;AAChC,oDAAsC;AACtC,gDAAkC;AAClC,kDAAoC;AACpC,kDAAoC;AACpC,8CAAgC;AAChC,4CAA8B;AAC9B,gDAAkC;AAClC,gDAAkC;AAClC,kEAAoD;AACpD,oDAAsC;AACtC,gDAAkC;AAElC,sCAAsC;AACtC,kDAAoC;AACpC,6CAA+B;AAC/B,sCAAsC;AACtC,yDAA2C;AAC3C,4DAA8C;AAE9C,yDAA6G;AAK7G,yCAAsC;AACtC,gEAAwC;AACxC,uCAAuD;AACvD,2CAAwC;AACxC,uEAAqE;AACrE,6CAAkE;AAClE,+CAAiE;AACjE,iEAAwG;AACxG,uCAAyC;AACzC,2DAM+B;AAe/B,yCAA2C;AAyB3C;;;;GAIG;AACH,MAAM,wBAAwB,GAAa;IACvC,gBAAgB;IAChB,OAAO;IACP,UAAU;IACV,YAAY;IACZ,iBAAiB;IACjB,QAAQ;CACX,CAAC;AAEF,MAAM,WAAW,GAAwB,IAAI,CAAC,KAAK,CAAC,IAAA,sBAAY,EAAC,GAAG,SAAS,kBAAkB,CAAC,CAAC,QAAQ,EAAE,CAAC,CAAC;AAC7G,MAAM,kBAAkB,GAAG,YAAY,CAAC;AAExC,IAAI,aAAiC,CAAC;A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CAAC;YAC1C,OAAO,KAAK,CAAC;QACjB,CAAC;IACL,CAAC;IACD,OAAO,OAAO,CAAC;AACnB,CAAC;AAED,uEAAuE;AACvE,IAAI,OAAO,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;IAC1B,yCAAyC;IACzC,MAAM,CAAC,OAAO,GAAG,CAAC,OAA4C,EAAE,EAAE,CAAC,IAAI,UAAU,CAAC,OAAO,CAAC,CAAC;AAC/F,CAAC;KAAM,CAAC;IACJ,wCAAwC;IACxC,CAAC,GAAG,EAAE,CAAC,IAAI,UAAU,EAAE,CAAC,EAAE,CAAC;AAC/B,CAAC","sourcesContent":["/*\n * Javascript adapter\n *\n * The MIT License (MIT)\n *\n * Copyright (c) 2014-2024 bluefox ,\n *\n * Copyright (c) 2014 hobbyquaker\n */\n\nimport { Script, type ScriptOptions } from 'node:vm';\nimport { readFileSync, existsSync, statSync, writeFileSync, type Stats } from 'node:fs';\nimport { join, sep, normalize } from 'node:path';\nimport { fork, type ForkOptions } from 'node:child_process';\nimport { setTypeScriptResolveOptions, Server } from 'virtual-tsc';\nimport { isDeepStrictEqual } from 'node:util';\nimport prettier from 'prettier';\n\nimport * as dgram from 'node:dgram';\nimport * as crypto from 'node:crypto';\nimport * as dns from 'node:dns';\nimport * as events from 'node:events';\nimport * as http from 'node:http';\nimport * as https from 'node:https';\nimport * as http2 from 'node:http2';\nimport * as net from 'node:net';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport * as util from 'node:util';\nimport * as child_process from 'node:child_process';\nimport * as stream from 'node:stream';\nimport * as zlib from 'node:zlib';\n\n// @ts-expect-error no types available\nimport * as suncalc from 'suncalc2';\nimport * as axios from 'axios';\n// @ts-expect-error no types available\nimport * as wake_on_lan from 'wake_on_lan';\nimport * as nodeSchedule from 'node-schedule';\n\nimport { getAbsoluteDefaultDataDir, Adapter, EXIT_CODES, type AdapterOptions } from '@iobroker/adapter-core';\nimport type SentryPlugin from '@iobroker/plugin-sentry';\nimport type { GetTimesResult } from 'suncalc';\nimport type { CompileResult } from 'virtual-tsc/build/util';\n\nimport { Mirror } from './lib/mirror';\nimport ProtectFs from './lib/protectFs';\nimport { setLanguage, getLanguage } from './lib/words';\nimport { sandBox } from './lib/sandbox';\nimport { requestModuleNameByUrl } from './lib/nodeModulesManagement';\nimport { createEventObject, type EventObj } from './lib/eventObj';\nimport { type AstroEventName, Scheduler } from './lib/scheduler';\nimport { targetTsLib, tsCompilerOptions, jsDeclarationCompilerOptions } from './lib/typescriptSettings';\nimport { hashSource } from './lib/tools';\nimport {\n resolveTypescriptLibs,\n resolveTypings,\n scriptIdToTSFilename,\n transformScriptBeforeCompilation,\n transformGlobalDeclarations,\n} from './lib/typescriptTools';\nimport type {\n FileSubscriptionResult,\n JavascriptContext,\n JavaScriptAdapterConfig,\n JsScript,\n ScriptType,\n SubscriptionResult,\n SubscribeObject,\n JavascriptTimer,\n SandboxType,\n LogMessage,\n DebugState,\n} from './types';\nimport type { PatternEventCompareFunction } from './lib/patternCompareFunctions';\nimport { decryptText } from './lib/crypto';\n\ntype MODULES = {\n fs: ProtectFs;\n 'fs/promises': ProtectFs['promises'];\n dgram: typeof dgram;\n crypto: typeof crypto;\n dns: typeof dns;\n events: typeof events;\n http: typeof http;\n https: typeof https;\n http2: typeof http2;\n net: typeof net;\n os: typeof os;\n path: typeof path;\n util: typeof util;\n child_process: typeof child_process;\n stream: typeof stream;\n zlib: typeof zlib;\n suncalc: typeof suncalc;\n axios: typeof axios;\n wake_on_lan: typeof wake_on_lan;\n nodeSchedule: typeof nodeSchedule;\n};\n\n/**\n * List of forbidden Locations for a mirror directory\n * relative to the default data directory\n * ATTENTION: the same list is also located in index_m.html!!\n */\nconst forbiddenMirrorLocations: string[] = [\n 'backup-objects',\n 'files',\n 'backitup',\n '../backups',\n '../node_modules',\n '../log',\n];\n\nconst packageJson: Record = JSON.parse(readFileSync(`${__dirname}/../package.json`).toString());\nconst SCRIPT_CODE_MARKER = 'script.js.';\n\nlet webstormDebug: string | undefined;\n\nconst isCI = !!process.env.CI;\n\n// ambient declarations for typescript\nlet tsAmbient: Record;\n\n// TypeScript's scripts are only recompiled if their source hash changes.\n// If an adapter update fixes the compilation bugs, a user won't notice until the changes and re-save the script.\n// To avoid that, we also include the\n// adapter version and TypeScript version in the hash\nconst tsSourceHashBase = `versions:adapter=${packageJson.version},typescript=${packageJson.dependencies.typescript}`;\n\n// taken from here: https://stackoverflow.com/questions/11887934/how-to-check-if-dst-daylight-saving-time-is-in-effect-and-if-so-the-offset\nfunction dstOffsetAtDate(dateInput: Date): number {\n const fullYear: number = dateInput.getFullYear() | 0;\n // \"Leap Years are any year that can be exactly divided by 4 (2012, 2016, etc.)\n // except if it can be exactly divided by 100, then it isn't (2100, 2200, etc.)\n // except if it can be exactly divided by 400, then it is (2000, 2400)\"\n // (https://www.mathsisfun.com/leap-years.html).\n const isLeapYear: 1 | 0 = ((fullYear & 3) | ((fullYear / 100) & 3)) === 0 ? 1 : 0;\n // (fullYear & 3) = (fullYear % 4), but faster\n //Alternative:var isLeapYear=(new Date(currentYear,1,29,12)).getDate()===29?1:0\n const fullMonth: number = dateInput.getMonth() | 0;\n return (\n // 1. We know what the time since the Epoch really is\n +dateInput - // same as the dateInput.getTime() method\n // 2. We know what the time since the Epoch at the start of the year is\n +new Date(fullYear, 0) - // day defaults to 1 if not explicitly zeroed\n // 3. Now, subtract what we would expect the time to be if daylight savings\n // did not exist. This yields the time-offset due to daylight savings.\n // Calculate the day of the year in the Gregorian calendar\n // The code below works based upon the facts of signed right shifts\n // • (x) >> n: shifts n and fills in the n highest bits with 0s\n // • (-x) >> n: shifts n and fills in the n highest bits with 1s\n // (This assumes that x is a positive integer)\n ((((-1 + // the first day in the year is day 1\n (31 & (-fullMonth >> 4)) + // January // (-11)>>4 = -1\n ((28 + isLeapYear) & ((1 - fullMonth) >> 4)) + // February\n (31 & ((2 - fullMonth) >> 4)) + // March\n (30 & ((3 - fullMonth) >> 4)) + // April\n (31 & ((4 - fullMonth) >> 4)) + // May\n (30 & ((5 - fullMonth) >> 4)) + // June\n (31 & ((6 - fullMonth) >> 4)) + // July\n (31 & ((7 - fullMonth) >> 4)) + // August\n (30 & ((8 - fullMonth) >> 4)) + // September\n (31 & ((9 - fullMonth) >> 4)) + // October\n (30 & ((10 - fullMonth) >> 4)) + // November\n // There are no months past December: the year rolls into the next.\n // Thus, \"fullMonth\" is 0-based, so it will never be 12 in JavaScript\n\n (dateInput.getDate() | 0)) & // get day of the month\n 0xffff) *\n 24 *\n 60 + // 24 hours in a day, 60 minutes in an hour\n (dateInput.getHours() & 0xff) * 60 + // 60 minutes in an hour\n (dateInput.getMinutes() & 0xff)) |\n 0) *\n 60 *\n 1000 - // 60 seconds in a minute * 1000 milliseconds in a second\n (dateInput.getSeconds() & 0xff) * 1000 - // 1000 milliseconds in a second\n dateInput.getMilliseconds()\n );\n}\n\nconst regExGlobalOld = /_global$/;\nconst regExGlobalNew = /script\\.js\\.global\\./;\n\nfunction checkIsGlobal(obj: ioBroker.ScriptObject): boolean {\n return obj?.common && (regExGlobalOld.test(obj.common.name) || regExGlobalNew.test(obj._id));\n}\n\nfunction fileMatching(sub: FileSubscriptionResult, id: string, fileName: string): boolean {\n if (sub.idRegEx) {\n if (!sub.idRegEx.test(id)) {\n return false;\n }\n } else {\n if (sub.id !== id) {\n return false;\n }\n }\n if (sub.fileRegEx) {\n if (!sub.fileRegEx.test(fileName)) {\n return false;\n }\n } else {\n if (sub.fileNamePattern !== fileName) {\n return false;\n }\n }\n\n return true;\n}\n\nfunction getNextTimeEvent(time: string, useNextDay?: boolean): Date {\n const now: Date = getAstroStartOfDay();\n const [timeHours, timeMinutes] = time.split(':');\n const nTimeHours = parseInt(timeHours, 10);\n const nTimeMinutes = parseInt(timeMinutes, 10);\n if (\n useNextDay &&\n (now.getHours() > nTimeHours || (now.getHours() === nTimeHours && now.getMinutes() > nTimeMinutes))\n ) {\n now.setDate(now.getDate() + 1);\n }\n\n now.setHours(nTimeHours);\n now.setMinutes(nTimeMinutes);\n\n return now;\n}\n\nfunction getAstroStartOfDay(): Date {\n const d = new Date();\n d.setMinutes(0);\n d.setSeconds(0);\n d.setMilliseconds(0);\n d.setTime(d.getTime() - d.getTimezoneOffset() * 60 * 1000);\n d.setUTCHours(0);\n\n return d;\n}\n\nfunction formatHoursMinutesSeconds(date: Date): string {\n const h = String(date.getHours());\n const m = String(date.getMinutes());\n const s = String(date.getSeconds());\n\n return `${h.padStart(2, '0')}:${m.padStart(2, '0')}:${s.padStart(2, '0')}`;\n}\n\n// Due to a npm bug, virtual-tsc may be hoisted to the top level node_modules, but\n// TypeScript may still be in the adapter level (https://npm.community/t/packages-with-peerdependencies-are-incorrectly-hoisted/4794),\n// so we need to tell virtual-tsc where TypeScript is\nsetTypeScriptResolveOptions({\n paths: [require.resolve('typescript')],\n});\n\n// compiler instance for global JS declarations\nconst jsDeclarationServer: Server = new Server(jsDeclarationCompilerOptions, isCI ? false : undefined);\n/**\n * Stores the IDs of script objects whose change should be ignored because\n * the compiled source was just updated\n */\n\nfunction httpStatusText(code: number): string {\n const texts: Record = {\n 400: 'Bad Request',\n 401: 'Unauthorized',\n 403: 'Forbidden',\n 404: 'Not Found',\n 429: 'Too Many Requests / Rate Limit',\n 500: 'Internal Server Error',\n 502: 'Bad Gateway',\n 503: 'Service Unavailable',\n };\n return texts[code] || `Error ${code}`;\n}\n\nclass JavaScript extends Adapter {\n declare public config: JavaScriptAdapterConfig;\n\n private readonly context: JavascriptContext;\n\n private errorLogFunction: {\n error: (msg: string) => void;\n warn: (msg: string) => void;\n info: (msg: string) => void;\n debug: (msg: string) => void;\n silly: (msg: string) => void;\n } = {\n error: (msg: string) => console.error(msg),\n warn: (msg: string) => console.warn(msg),\n info: (msg: string) => console.log(msg),\n debug: (msg: string) => console.debug(msg),\n silly: (msg: string) => console.debug(msg),\n };\n\n private readonly mods: MODULES;\n\n private objectsInitDone = false;\n private statesInitDone = false;\n\n private objects: Record = {};\n private states: Record = {};\n private readonly interimStateValues: Record = {};\n private readonly stateIds: string[] = [];\n private readonly subscriptions: SubscriptionResult[] = [];\n private readonly subscriptionsFile: FileSubscriptionResult[] = [];\n private readonly subscriptionsObject: SubscribeObject[] = [];\n private readonly subscribedPatterns: Record = {};\n private readonly subscribedPatternsFile: Record = {};\n private readonly adapterSubs: Record = {};\n private readonly timers: { [scriptName: string]: JavascriptTimer[] } = {};\n private readonly _enums: string[] = [];\n private readonly names: { [name: string]: string | string[] } = {}; // name: id\n private readonly scripts: Record = {};\n private password: string = '';\n private readonly messageBusHandlers: Record<\n string,\n Record void }[]>\n > = {};\n private readonly logSubscriptions: Record<\n string,\n {\n sandbox: SandboxType;\n cb: (info: LogMessage) => void;\n id: number;\n severity: ioBroker.LogLevel | '*';\n }[]\n > = {};\n private readonly tempDirectories: { [scriptName: string]: string } = {}; // name: path\n private readonly folderCreationVerifiedObjects: Record = {};\n\n /** if logs are subscribed or not */\n private logSubscribed = false;\n\n private timeSettings: {\n format12: boolean;\n leadingZeros: boolean;\n } = { format12: false, leadingZeros: true };\n\n private dayScheduleTimer: NodeJS.Timeout | null = null; // schedule for astrological day\n private sunScheduleTimer: NodeJS.Timeout | null = null; // schedule for sun moment times\n private timeScheduleTimer: NodeJS.Timeout | null = null; // schedule for astrological day\n\n private activeStr = ''; // enabled state prefix\n\n private mirror: Mirror | undefined;\n\n private stopCounters: Record = {};\n\n private setStateCountCheckInterval: NodeJS.Timeout | null = null;\n\n private globalScript = '';\n /** Generated declarations for global TypeScripts */\n private globalDeclarations = '';\n // Remember which definitions the global scripts\n // have access to, because it depends on the compilation order\n private knownGlobalDeclarationsByScript: Record = {};\n private globalScriptLines = 0;\n // compiler instance for typescript\n private tsServer: Server;\n\n private readonly ignoreObjectChange: Set = new Set();\n\n private debugState: DebugState = {\n scriptName: '',\n child: null,\n promiseOnEnd: null,\n paused: false,\n started: 0,\n running: false,\n };\n\n constructor(options: Partial = {}) {\n options = {\n ...options,\n name: 'javascript', // adapter name\n useFormatDate: true,\n /**\n * If the JS-Controller catches an unhandled error, this will be called,\n * so we have a chance to handle it ourselves.\n */\n error: (err: Error): boolean => {\n // Identify unhandled errors originating from callbacks in scripts\n // These are not caught by wrapping the execution code in try-catch\n if (err && typeof err.stack === 'string') {\n const scriptCodeMarkerIndex = err.stack.indexOf(SCRIPT_CODE_MARKER);\n if (scriptCodeMarkerIndex > -1) {\n // This is a script error\n let scriptName = err.stack.substring(scriptCodeMarkerIndex);\n scriptName = scriptName.substring(0, scriptName.indexOf(':'));\n this.logError(scriptName, 'Error:', err);\n\n // Leave the script running for now\n // signal to the JS-Controller that we handled the error ourselves\n return true;\n }\n // check if a path contains adaptername but not own node_module\n // this regex matched \"iobroker.javascript/\" if NOT followed by \"node_modules\"\n if (!err.stack.match(/iobroker\\.javascript[/\\\\](?!.*node_modules).*/g)) {\n // This is an error without any info on origin (mostly async errors like connection errors)\n // also consider it as being from a script\n this.log.error(\n 'An error happened which is most likely from one of your scripts, but the originating script could not be detected.',\n );\n this.log.error(`Error: ${err.message}`);\n this.log.error(err.stack);\n\n // signal to the JS-Controller that we handled the error ourselves\n return true;\n }\n }\n\n return false;\n },\n };\n\n super(options as AdapterOptions);\n\n this.on('objectChange', this.onObjectChange.bind(this));\n this.on('stateChange', this.onStateChange.bind(this));\n this.on('ready', this.onReady.bind(this));\n this.on('message', this.onMessage.bind(this));\n this.on('unload', this.onUnload.bind(this));\n this.on('fileChange', this.onFileChange.bind(this));\n this.on('log', this.onLog.bind(this));\n\n this.mods = {\n fs: {} as ProtectFs,\n 'fs/promises': {} as ProtectFs['promises'],\n dgram,\n crypto,\n dns,\n events,\n http,\n https,\n http2,\n net,\n os,\n path,\n util,\n child_process,\n stream,\n zlib,\n\n suncalc,\n axios,\n wake_on_lan,\n nodeSchedule,\n };\n\n // check the webstorm debug and just debug modes\n let debugMode: string | undefined;\n if (process.argv) {\n for (let a = 1; a < process.argv.length; a++) {\n if (process.argv[a].startsWith('--webstorm')) {\n webstormDebug = process.argv[a].replace(/^(.*?=\\s*)/, '');\n }\n if (process.argv[a] === '--debugScript') {\n if (!process.argv[a + 1]) {\n console.log('No script name provided');\n process.exit(300);\n } else {\n debugMode = process.argv[a + 1];\n }\n }\n }\n }\n\n this.context = {\n mods: this.mods,\n objects: this.objects,\n states: this.states,\n interimStateValues: this.interimStateValues,\n stateIds: this.stateIds,\n errorLogFunction: this.errorLogFunction,\n subscriptions: this.subscriptions,\n subscriptionsFile: this.subscriptionsFile,\n subscriptionsObject: this.subscriptionsObject,\n subscribedPatterns: this.subscribedPatterns,\n subscribedPatternsFile: this.subscribedPatternsFile,\n adapterSubs: this.adapterSubs,\n cacheObjectEnums: {},\n timers: this.timers,\n enums: this._enums,\n names: this.names,\n scripts: this.scripts,\n messageBusHandlers: this.messageBusHandlers,\n logSubscriptions: this.logSubscriptions,\n tempDirectories: this.tempDirectories,\n folderCreationVerifiedObjects: this.folderCreationVerifiedObjects,\n\n isEnums: false, // If some subscription wants enum\n channels: null,\n devices: null,\n logWithLineInfo: this.logWithLineInfo.bind(this),\n scheduler: null,\n timerId: 0,\n rulesOpened: null, // opened rules\n language: this.language || 'en',\n\n updateLogSubscriptions: this.updateLogSubscriptions.bind(this),\n convertBackStringifiedValues: this.convertBackStringifiedValues.bind(this),\n updateObjectContext: this.updateObjectContext.bind(this),\n prepareStateObject: this.prepareStateObject.bind(this),\n debugMode,\n getAbsoluteDefaultDataDir,\n adapter: this as unknown as ioBroker.Adapter,\n logError: this.logError.bind(this),\n allowSelfSignedCerts: false,\n };\n\n this.tsServer = new Server(tsCompilerOptions, this.tsLog);\n }\n\n async onObjectChange(id: string, obj?: ioBroker.Object | null): Promise {\n // Check if we should ignore this change (once!) because we just updated the compiled sources\n if (this.ignoreObjectChange.has(id)) {\n // Update the cached script object and do nothing more\n this.objects[id] = obj as ioBroker.Object;\n this.ignoreObjectChange.delete(id);\n return;\n }\n\n // When still in initializing: already remember current values,\n // but data structures are initialized elsewhere\n if (!this.objectsInitDone) {\n if (obj) {\n this.objects[id] = obj;\n }\n return;\n }\n\n if (id.startsWith('enum.')) {\n // clear cache\n this.context.cacheObjectEnums = {};\n\n // update this._enums array\n if (obj) {\n // If new\n if (!this._enums.includes(id)) {\n this._enums.push(id);\n this._enums.sort();\n }\n } else {\n const pos = this._enums.indexOf(id);\n // if deleted\n if (pos !== -1) {\n this._enums.splice(pos, 1);\n }\n }\n }\n\n if (id === 'system.config' && obj?.common?.language) {\n // set language for debug messages\n setLanguage(obj.common.language);\n this.language = obj.common.language;\n this.context.language = this.language as ioBroker.Languages;\n }\n\n // update stored time format for variables.dayTime\n if (id === `${this.namespace}.variables.dayTime` && obj?.native) {\n this.timeSettings.format12 = obj.native.format12 || false;\n this.timeSettings.leadingZeros = obj.native.leadingZeros === undefined ? true : obj.native.leadingZeros;\n }\n\n // send changes to the disk mirror\n this.mirror?.onObjectChange(id, obj as ioBroker.ScriptObject | null);\n\n const formerObj = this.objects[id];\n\n this.updateObjectContext(id, obj); // Update all Meta object data\n\n // for the alias object changes on the state objects, we need to manually update the\n // state cache value, because the new value is only published on the next change\n if (obj?.type === 'state' && id.startsWith('alias.0.')) {\n // execute async for speed\n this.getForeignStateAsync(id)\n .then(state => {\n if (state) {\n this.states[id] = state;\n } else if (this.states[id] !== undefined) {\n delete this.states[id];\n }\n })\n .catch(() => {\n /* ignore */\n });\n }\n\n this.subscriptionsObject.forEach(sub => {\n // ToDo: implement comparing with id.0.* too\n if (sub.pattern === id) {\n try {\n sub.callback(id, obj);\n } catch (err: any) {\n this.log.error(`Error in callback: ${err.toString()}`);\n }\n }\n });\n\n // handle Script object updates\n if (!obj && formerObj?.type === 'script') {\n // Object Deleted just now\n if (checkIsGlobal(formerObj)) {\n // it was a global Script, and it was enabled and is now deleted => restart adapter\n if (formerObj.common.enabled) {\n this.log.info(`Active global Script ${id} deleted. Restart instance.`);\n this.restart();\n }\n } else if (formerObj.common?.engine === `system.adapter.${this.namespace}`) {\n // It was a non-global Script and deleted => stop and remove it\n await this.stopScript(id);\n\n // delete scriptEnabled.blabla variable\n const idActive = `scriptEnabled.${id.substring(SCRIPT_CODE_MARKER.length)}`;\n await this.delStateAsync(idActive);\n await this.delObjectAsync(idActive);\n\n // delete scriptProblem.blabla variable\n const idProblem = `scriptProblem.${id.substring(SCRIPT_CODE_MARKER.length)}`;\n await this.delStateAsync(idProblem);\n await this.delObjectAsync(idProblem);\n }\n } else if (!formerObj && obj?.type === 'script') {\n // New script that does not exist before\n if (checkIsGlobal(obj)) {\n // new global script added => restart adapter\n if (obj.common.enabled) {\n this.log.info(`Active global Script ${id} created. Restart instance.`);\n this.restart();\n }\n } else if (obj.common?.engine === `system.adapter.${this.namespace}`) {\n // new non-global script - create states for scripts\n await this.createActiveObject(id, !!obj.common.enabled);\n await this.createProblemObject(id);\n if (obj.common.enabled) {\n // if enabled => Start a script\n await this.loadScriptById(id);\n }\n }\n } else if (obj?.type === 'script' && formerObj?.common) {\n // Script changed ...\n if (checkIsGlobal(obj)) {\n if (obj.common.enabled || formerObj.common.enabled) {\n this.log.info(`Global Script ${id} updated. Restart instance.`);\n this.restart();\n }\n } else {\n // No global script\n if (obj.common?.engine === `system.adapter.${this.namespace}`) {\n // create states for scripts\n await this.createActiveObject(id, !!obj.common.enabled);\n await this.createProblemObject(id);\n }\n\n if (\n (formerObj.common.enabled && !obj.common.enabled) ||\n (formerObj.common.engine === `system.adapter.${this.namespace}` &&\n obj.common.engine !== `system.adapter.${this.namespace}`)\n ) {\n // Script disabled\n if (formerObj.common.enabled && formerObj.common.engine === `system.adapter.${this.namespace}`) {\n // Remove it from executing\n await this.stopScript(id);\n }\n } else if (\n (!formerObj.common.enabled && obj.common.enabled) ||\n (formerObj.common.engine !== `system.adapter.${this.namespace}` &&\n obj.common.engine === `system.adapter.${this.namespace}`)\n ) {\n // Script enabled\n\n if (obj.common.enabled && obj.common.engine === `system.adapter.${this.namespace}`) {\n // Start script\n await this.loadScriptById(id);\n }\n } else {\n // if (obj.common.source !== formerObj.common.source) {\n // Source changed => restart the script\n this.stopCounters[id] = this.stopCounters[id] ? this.stopCounters[id] + 1 : 1;\n void this.stopScript(id).then(() => {\n // only start again after stop when \"last\" object change to prevent problems on\n // multiple changes in fast frequency\n if (!--this.stopCounters[id]) {\n void this.loadScriptById(id);\n }\n });\n }\n }\n }\n }\n\n onStateChange(id: string, state?: ioBroker.State | null): void {\n if (this.interimStateValues[id] !== undefined) {\n // any update invalidates the remembered interim value\n delete this.interimStateValues[id];\n }\n if (!id || id.startsWith('messagebox.') || id.startsWith('log.')) {\n return;\n }\n\n if (id === `${this.namespace}.debug.to` && state && !state.ack) {\n if (!this.context.debugMode) {\n this.debugSendToInspector(state.val);\n }\n return;\n }\n\n // When still in initializing: already remember current values,\n // but data structures are initialized elsewhere\n if (!this.statesInitDone) {\n if (state) {\n this.states[id] = state;\n }\n return;\n }\n\n const oldState: ioBroker.State | null | undefined = this.states[id];\n if (state) {\n if (oldState) {\n // enable or disable script\n if (!state.ack && id.startsWith(this.activeStr) && this.objects[id]?.native?.script) {\n void this.extendForeignObject(this.objects[id].native.script, {\n common: { enabled: state.val },\n });\n }\n\n // monitor if the adapter is alive and send all subscriptions once more, after the adapter goes online\n if (/*oldState && */ oldState.val === false && state.val && id.endsWith('.alive')) {\n if (this.adapterSubs[id]) {\n const parts = id.split('.');\n const a = `${parts[2]}.${parts[3]}`;\n for (let t = 0; t < this.adapterSubs[id].length; t++) {\n this.log.info(`Detected coming adapter \"${a}\". Send subscribe: ${this.adapterSubs[id][t]}`);\n this.sendTo(a, 'subscribe', this.adapterSubs[id][t]);\n }\n }\n }\n } else if (/*!oldState && */ !this.stateIds.includes(id)) {\n this.stateIds.push(id);\n this.stateIds.sort();\n }\n this.states[id] = state;\n } else {\n if (oldState) {\n delete this.states[id];\n }\n state = {} as ioBroker.State;\n const pos = this.stateIds.indexOf(id);\n if (pos !== -1) {\n this.stateIds.splice(pos, 1);\n }\n }\n const _eventObj = createEventObject(\n this.context,\n id,\n this.convertBackStringifiedValues(id, state),\n this.convertBackStringifiedValues(id, oldState),\n );\n\n // if this state matches any subscriptions\n for (let i = 0, l = this.subscriptions.length; i < l; i++) {\n const sub = this.subscriptions[i];\n if (sub?.patternCompareFunctions && patternMatching(_eventObj, sub.patternCompareFunctions)) {\n try {\n sub.callback(_eventObj);\n } catch (err: any) {\n this.log.error(`Error in callback: ${err.toString()}`);\n }\n }\n }\n }\n\n onFileChange(id: string, fileName: string, size: number | null): void {\n // if this file matches any subscriptions\n for (let i = 0, l = this.subscriptionsFile.length; i < l; i++) {\n const sub = this.subscriptionsFile[i];\n if (sub && fileMatching(sub, id, fileName)) {\n try {\n sub.callback(id, fileName, size, sub.withFile);\n } catch (err: any) {\n this.log.error(`Error in callback: ${err.toString()}`);\n }\n }\n }\n }\n\n async onUnload(callback: () => void): Promise {\n await this.debugStop();\n this.stopTimeSchedules();\n if (this.setStateCountCheckInterval) {\n clearInterval(this.setStateCountCheckInterval);\n this.setStateCountCheckInterval = null;\n }\n await this.stopAllScripts();\n if (typeof callback === 'function') {\n callback();\n }\n }\n\n async onReady(): Promise {\n this.errorLogFunction = this.log;\n this.context.errorLogFunction = this.log;\n\n this.config.maxSetStatePerMinute = parseInt(this.config.maxSetStatePerMinute as unknown as string, 10) || 1000;\n this.config.maxTriggersPerScript = parseInt(this.config.maxTriggersPerScript as unknown as string, 10) || 100;\n\n if (this.supportsFeature?.('PLUGINS')) {\n const sentryInstance: InstanceType = this.getPluginInstance('sentry') as InstanceType<\n typeof SentryPlugin\n >;\n if (sentryInstance) {\n const Sentry = sentryInstance.getSentryObject();\n Sentry?.withScope(scope => {\n scope.addEventProcessor((event, _hint) => {\n if (event.exception?.values?.[0]) {\n const eventData = event.exception.values[0];\n if (\n eventData.stacktrace?.frames &&\n Array.isArray(eventData.stacktrace.frames) &&\n eventData.stacktrace.frames.length\n ) {\n // Exclude event if script Marker is included\n if (\n eventData.stacktrace.frames.find(frame =>\n frame.filename?.includes(SCRIPT_CODE_MARKER),\n )\n ) {\n return null;\n }\n // Exclude event if own directory is included but not inside own node_modules\n const ownNodeModulesDir = join(__dirname, 'node_modules');\n if (\n !eventData.stacktrace.frames.find(\n frame =>\n frame.filename?.includes(__dirname) &&\n !frame.filename.includes(ownNodeModulesDir),\n )\n ) {\n return null;\n }\n // We have exception data and did not sort it out, so report it\n return event;\n }\n }\n\n // No exception in it ... do not report\n return null;\n });\n });\n }\n }\n\n await this.main();\n }\n\n onMessage(obj: ioBroker.Message): void {\n switch (obj?.command) {\n // process messageTo commands\n case 'toScript':\n case 'jsMessageBus':\n if (\n obj.message &&\n (obj.message.instance === null ||\n obj.message.instance === undefined ||\n `javascript.${obj.message.instance}` === this.namespace ||\n obj.message.instance === this.namespace)\n ) {\n Object.keys(this.messageBusHandlers).forEach(name => {\n // the script name could be script.js.xxx or only xxx\n if (\n (!obj.message.script || obj.message.script === name) &&\n this.messageBusHandlers[name][obj.message.message]\n ) {\n this.messageBusHandlers[name][obj.message.message].forEach(handler => {\n const sandbox = handler.sandbox;\n\n sandbox.verbose && sandbox.log(`onMessage: ${JSON.stringify(obj.message)}`, 'info');\n\n try {\n if (obj.callback) {\n handler.cb.call(sandbox, obj.message.data, (result: any) => {\n if (sandbox.verbose) {\n sandbox.log(`onMessage result: ${JSON.stringify(result)}`, 'info');\n }\n\n this.sendTo(obj.from, obj.command, result, obj.callback);\n });\n } else {\n handler.cb.call(sandbox, obj.message.data, (result: any) => {\n sandbox.verbose &&\n sandbox.log(`onMessage result: ${JSON.stringify(result)}`, 'info');\n });\n }\n } catch (err: unknown) {\n void this.setState(\n `scriptProblem.${name.substring(SCRIPT_CODE_MARKER.length)}`,\n true,\n true,\n );\n this.logError(name, 'Error in callback:', err as Error);\n }\n });\n }\n });\n }\n break;\n\n case 'loadTypings': {\n // Load typings for the editor\n const typings: Record = {};\n\n // try to load TypeScript lib files from disk\n try {\n const typescriptLibs = resolveTypescriptLibs(targetTsLib);\n Object.assign(typings, typescriptLibs);\n } catch {\n /* ok, no lib then */\n }\n\n // provide the already-loaded ioBroker typings and global script declarations\n Object.assign(typings, tsAmbient);\n\n // also provide the known global declarations for each global script\n for (const globalScriptPaths of Object.keys(this.knownGlobalDeclarationsByScript)) {\n typings[`${globalScriptPaths}.d.ts`] = this.knownGlobalDeclarationsByScript[globalScriptPaths];\n }\n\n if (obj.callback) {\n this.sendTo(obj.from, obj.command, { typings }, obj.callback);\n }\n break;\n }\n\n case 'calcAstroAll': {\n if (obj.message) {\n const sunriseOffset =\n parseInt(\n obj.message.sunriseOffset === undefined\n ? this.config.sunriseOffset\n : obj.message.sunriseOffset,\n 10,\n ) || 0;\n const sunsetOffset =\n parseInt(\n obj.message.sunsetOffset === undefined\n ? this.config.sunsetOffset\n : obj.message.sunsetOffset,\n 10,\n ) || 0;\n const longitude =\n parseFloat(\n obj.message.longitude === undefined ? this.config.longitude : obj.message.longitude,\n ) || 0;\n const latitude =\n parseFloat(obj.message.latitude === undefined ? this.config.latitude : obj.message.latitude) ||\n 0;\n const today = getAstroStartOfDay();\n let astroEvents: GetTimesResult & { nextSunrise: Date; nextSunset: Date } = {} as GetTimesResult & {\n nextSunrise: Date;\n nextSunset: Date;\n };\n try {\n astroEvents = this.mods.suncalc.getTimes(today, latitude, longitude);\n } catch (err: unknown) {\n this.log.error(`Cannot calculate astro data: ${err as Error}`);\n }\n if (astroEvents) {\n try {\n astroEvents.nextSunrise = this.getAstroEvent(\n today,\n obj.message.sunriseEvent || this.config.sunriseEvent,\n obj.message.sunriseLimitStart || this.config.sunriseLimitStart,\n obj.message.sunriseLimitEnd || this.config.sunriseLimitEnd,\n sunriseOffset,\n false,\n latitude,\n longitude,\n true,\n );\n astroEvents.nextSunset = this.getAstroEvent(\n today,\n obj.message.sunsetEvent || this.config.sunsetEvent,\n obj.message.sunsetLimitStart || this.config.sunsetLimitStart,\n obj.message.sunsetLimitEnd || this.config.sunsetLimitEnd,\n sunsetOffset,\n true,\n latitude,\n longitude,\n true,\n );\n } catch (err: unknown) {\n this.log.error(`Cannot calculate astro data: ${err as Error}`);\n }\n }\n\n const result: Record = {};\n const keys = Object.keys(astroEvents).sort(\n (a, b) =>\n (astroEvents as unknown as Record)[a] -\n (astroEvents as unknown as Record)[b],\n );\n keys.forEach(key => {\n const validDate =\n (astroEvents as unknown as Record)[key] !== null &&\n !isNaN((astroEvents as unknown as Record)[key].getTime());\n\n result[key] = {\n isValidDate: validDate,\n serverTime: validDate\n ? formatHoursMinutesSeconds((astroEvents as unknown as Record)[key])\n : 'n/a',\n date: validDate\n ? (astroEvents as unknown as Record)[key].toISOString()\n : 'n/a',\n };\n });\n\n if (obj.callback) {\n this.sendTo(obj.from, obj.command, result, obj.callback);\n }\n }\n break;\n }\n\n case 'calcAstro': {\n if (obj.message) {\n const longitude =\n parseFloat(\n obj.message.longitude === undefined ? this.config.longitude : obj.message.longitude,\n ) || 0;\n const latitude =\n parseFloat(obj.message.latitude === undefined ? this.config.latitude : obj.message.latitude) ||\n 0;\n const today = getAstroStartOfDay();\n\n const sunriseEvent = obj.message?.sunriseEvent || this.config.sunriseEvent;\n const sunriseLimitStart = obj.message?.sunriseLimitStart || this.config.sunriseLimitStart;\n const sunriseLimitEnd = obj.message?.sunriseLimitEnd || this.config.sunriseLimitEnd;\n const sunriseOffset =\n parseInt(\n obj.message.sunriseOffset === undefined\n ? this.config.sunriseOffset\n : obj.message.sunriseOffset,\n 10,\n ) || 0;\n const nextSunrise = this.getAstroEvent(\n today,\n sunriseEvent,\n sunriseLimitStart,\n sunriseLimitEnd,\n sunriseOffset,\n false,\n latitude,\n longitude,\n true,\n );\n\n const sunsetEvent = obj.message?.sunsetEvent || this.config.sunsetEvent;\n const sunsetLimitStart = obj.message?.sunsetLimitStart || this.config.sunsetLimitStart;\n const sunsetLimitEnd = obj.message?.sunsetLimitEnd || this.config.sunsetLimitEnd;\n const sunsetOffset =\n parseInt(\n obj.message.sunsetOffset === undefined\n ? this.config.sunsetOffset\n : obj.message.sunsetOffset,\n 10,\n ) || 0;\n const nextSunset = this.getAstroEvent(\n today,\n sunsetEvent,\n sunsetLimitStart,\n sunsetLimitEnd,\n sunsetOffset,\n true,\n latitude,\n longitude,\n true,\n );\n\n const validDateSunrise = nextSunrise !== null && !isNaN(nextSunrise.getTime());\n const validDateSunset = nextSunset !== null && !isNaN(nextSunset.getTime());\n\n this.log.debug(\n `calcAstro sunrise: ${sunriseEvent} -> start ${sunriseLimitStart}, end: ${sunriseLimitEnd}, offset: ${sunriseOffset} - ${validDateSunrise ? nextSunrise.toISOString() : 'n/a'}`,\n );\n this.log.debug(\n `calcAstro sunset: ${sunsetEvent} -> start ${sunsetLimitStart}, end: ${sunsetLimitEnd}, offset: ${sunsetOffset} - ${validDateSunset ? nextSunset.toISOString() : 'n/a'}`,\n );\n\n if (obj.callback) {\n this.sendTo(\n obj.from,\n obj.command,\n {\n nextSunrise: {\n isValidDate: validDateSunrise,\n serverTime: validDateSunrise ? formatHoursMinutesSeconds(nextSunrise) : 'n/a',\n date: nextSunrise.toISOString(),\n },\n nextSunset: {\n isValidDate: validDateSunset,\n serverTime: validDateSunset ? formatHoursMinutesSeconds(nextSunset) : 'n/a',\n date: nextSunset.toISOString(),\n },\n },\n obj.callback,\n );\n }\n }\n break;\n }\n\n case 'debug': {\n if (!this.context.debugMode) {\n this.debugStart(obj.message);\n }\n break;\n }\n\n case 'debugStop': {\n if (!this.context.debugMode) {\n void this.debugStop().then(() => console.log('stopped'));\n }\n break;\n }\n\n case 'rulesOn': {\n this.context.rulesOpened = obj.message;\n console.log(`Enable messaging for ${this.context.rulesOpened}`);\n break;\n }\n\n case 'rulesOff': {\n // maybe if (context.rulesOpened === obj.message)\n console.log(`Disable messaging for ${this.context.rulesOpened}`);\n this.context.rulesOpened = null;\n break;\n }\n\n case 'getIoBrokerDataDir': {\n if (obj.callback) {\n this.sendTo(\n obj.from,\n obj.command,\n {\n dataDir: getAbsoluteDefaultDataDir(),\n sep,\n },\n obj.callback,\n );\n }\n break;\n }\n\n case 'chatCompletion': {\n // Proxy chat completion requests to an OpenAI-compatible API endpoint\n if (obj.callback) {\n const baseUrl = (obj.message?.baseUrl || '').trim();\n const apiKey = (obj.message?.apiKey || '').trim();\n const chatModel = (obj.message?.model || '').trim();\n const messages = obj.message?.messages;\n const provider = (obj.message?.provider || 'openai').trim();\n // Anthropic, Gemini, and DeepSeek always require an API key; OpenAI-compatible allows empty key with custom base URL\n if (\n !apiKey &&\n (provider === 'anthropic' || provider === 'gemini' || provider === 'deepseek' || !baseUrl)\n ) {\n this.sendTo(obj.from, obj.command, { error: 'No API key provided' }, obj.callback);\n break;\n }\n if (!chatModel || !messages) {\n this.sendTo(obj.from, obj.command, { error: 'Model and messages are required' }, obj.callback);\n break;\n }\n\n let url: string;\n const chatHeaders: Record = {\n 'Content-Type': 'application/json',\n };\n let bodyObj: Record;\n\n if (provider === 'anthropic') {\n url = 'https://api.anthropic.com/v1/messages';\n chatHeaders['x-api-key'] = apiKey;\n chatHeaders['anthropic-version'] = '2023-06-01';\n const systemMessages = messages.filter((m: { role: string }) => m.role === 'system');\n const nonSystemMessages = messages.filter((m: { role: string }) => m.role !== 'system');\n const systemText = systemMessages.map((m: { content: string }) => m.content).join('\\n\\n');\n bodyObj = {\n model: chatModel,\n max_tokens: 8192,\n stream: false,\n ...(systemText ? { system: systemText } : {}),\n messages: nonSystemMessages,\n };\n } else if (provider === 'gemini') {\n url = 'https://generativelanguage.googleapis.com/v1beta/openai/chat/completions';\n if (apiKey) {\n chatHeaders.Authorization = `Bearer ${apiKey}`;\n }\n bodyObj = { model: chatModel, messages, stream: false };\n } else if (provider === 'deepseek') {\n url = 'https://api.deepseek.com/chat/completions';\n chatHeaders.Authorization = `Bearer ${apiKey}`;\n bodyObj = { model: chatModel, messages, stream: false };\n } else {\n url = `${baseUrl || 'https://api.openai.com/v1'}/chat/completions`;\n if (apiKey) {\n chatHeaders.Authorization = `Bearer ${apiKey}`;\n }\n bodyObj = {\n model: chatModel,\n messages,\n stream: false,\n // Disable thinking/reasoning for local models to save context and speed\n ...(baseUrl ? { reasoning_effort: 'none' } : {}),\n };\n }\n\n const body = JSON.stringify(bodyObj);\n const bodyBuffer = Buffer.from(body, 'utf8');\n chatHeaders['Content-Length'] = bodyBuffer.length;\n\n let urlObj: URL;\n try {\n urlObj = new URL(url);\n } catch {\n this.sendTo(obj.from, obj.command, { error: `Invalid API URL: ${url}` }, obj.callback);\n break;\n }\n const isHttps = urlObj.protocol === 'https:';\n const requestModule = isHttps ? https : http;\n\n const req = requestModule.request(\n url,\n {\n method: 'POST',\n headers: chatHeaders,\n timeout: 600000,\n ...(isHttps && this.config.allowSelfSignedCerts ? { rejectUnauthorized: false } : {}),\n },\n res => {\n let data = '';\n res.on('data', (chunk: Buffer) => {\n data += chunk.toString();\n });\n res.on('end', () => {\n if (res.statusCode === 200) {\n try {\n const parsed = JSON.parse(data);\n const content =\n provider === 'anthropic'\n ? parsed.content?.[0]?.text || ''\n : parsed.choices?.[0]?.message?.content || '';\n if (!content) {\n this.sendTo(\n obj.from,\n obj.command,\n { error: 'Empty response from API' },\n obj.callback,\n );\n } else {\n this.sendTo(\n obj.from,\n obj.command,\n { success: true, content },\n obj.callback,\n );\n }\n } catch {\n this.sendTo(\n obj.from,\n obj.command,\n { error: 'Invalid JSON response from API' },\n obj.callback,\n );\n }\n } else {\n let detail = '';\n try {\n const errParsed = JSON.parse(data);\n detail = errParsed.error?.message || data.substring(0, 200);\n } catch {\n detail = data.substring(0, 200);\n }\n this.sendTo(\n obj.from,\n obj.command,\n {\n error: `${detail || httpStatusText(res.statusCode || 0)} (${res.statusCode})`,\n },\n obj.callback,\n );\n }\n });\n },\n );\n\n req.on('error', (err: Error) => {\n this.sendTo(\n obj.from,\n obj.command,\n { error: `Connection failed: ${err.message}` },\n obj.callback,\n );\n });\n\n req.on('timeout', () => {\n req.destroy();\n this.sendTo(obj.from, obj.command, { error: 'Connection timeout (600s)' }, obj.callback);\n });\n\n req.write(bodyBuffer);\n req.end();\n }\n break;\n }\n\n case 'testApiConnection': {\n // Test connection to an OpenAI-compatible API endpoint\n if (obj.callback) {\n const baseUrl = (obj.message?.baseUrl || '').trim();\n const apiKey = (obj.message?.apiKey || '').trim();\n const provider = (obj.message?.provider || 'openai').trim();\n // Anthropic, Gemini, and DeepSeek always require an API key; OpenAI-compatible allows empty key with custom base URL\n if (\n !apiKey &&\n (provider === 'anthropic' || provider === 'gemini' || provider === 'deepseek' || !baseUrl)\n ) {\n this.sendTo(obj.from, obj.command, { error: 'No API key provided' }, obj.callback);\n break;\n }\n\n let url: string;\n const testHeaders: Record = {\n 'Content-Type': 'application/json',\n };\n\n if (provider === 'anthropic') {\n url = 'https://api.anthropic.com/v1/models';\n testHeaders['x-api-key'] = apiKey;\n testHeaders['anthropic-version'] = '2023-06-01';\n } else if (provider === 'gemini') {\n url = 'https://generativelanguage.googleapis.com/v1beta/openai/models';\n if (apiKey) {\n testHeaders.Authorization = `Bearer ${apiKey}`;\n }\n } else if (provider === 'deepseek') {\n url = 'https://api.deepseek.com/models';\n testHeaders.Authorization = `Bearer ${apiKey}`;\n } else {\n url = `${baseUrl || 'https://api.openai.com/v1'}/models`;\n if (apiKey) {\n testHeaders.Authorization = `Bearer ${apiKey}`;\n }\n }\n\n let urlObj: URL;\n try {\n urlObj = new URL(url);\n } catch {\n this.sendTo(obj.from, obj.command, { error: `Invalid API URL: ${url}` }, obj.callback);\n break;\n }\n const isHttps = urlObj.protocol === 'https:';\n const requestModule = isHttps ? https : http;\n\n const req = requestModule.request(\n url,\n {\n method: 'GET',\n headers: testHeaders,\n timeout: 10000,\n ...(isHttps && this.config.allowSelfSignedCerts ? { rejectUnauthorized: false } : {}),\n },\n res => {\n let data = '';\n res.on('data', (chunk: Buffer) => {\n data += chunk.toString();\n });\n res.on('end', () => {\n if (res.statusCode === 200) {\n try {\n const parsed = JSON.parse(data);\n const models: string[] = (parsed.data || [])\n .map((m: { id: string }) =>\n m.id.startsWith('models/') ? m.id.substring(7) : m.id,\n )\n .sort();\n this.sendTo(\n obj.from,\n obj.command,\n { success: true, models, count: models.length },\n obj.callback,\n );\n } catch {\n this.sendTo(\n obj.from,\n obj.command,\n { error: 'Invalid JSON response from API' },\n obj.callback,\n );\n }\n } else if (res.statusCode === 401) {\n this.sendTo(\n obj.from,\n obj.command,\n { error: 'Invalid API key (401)' },\n obj.callback,\n );\n } else if (res.statusCode === 403) {\n this.sendTo(obj.from, obj.command, { error: 'Access denied (403)' }, obj.callback);\n } else {\n // Include response body for debugging\n let detail = '';\n try {\n const errParsed = JSON.parse(data);\n detail = errParsed.error?.message || data.substring(0, 200);\n } catch {\n detail = data.substring(0, 200);\n }\n this.sendTo(\n obj.from,\n obj.command,\n {\n error: `${detail || httpStatusText(res.statusCode || 0)} (${res.statusCode})`,\n },\n obj.callback,\n );\n }\n });\n },\n );\n\n req.on('error', (err: Error) => {\n this.sendTo(\n obj.from,\n obj.command,\n { error: `Connection failed: ${err.message}` },\n obj.callback,\n );\n });\n\n req.on('timeout', () => {\n req.destroy();\n this.sendTo(obj.from, obj.command, { error: 'Connection timeout (10s)' }, obj.callback);\n });\n\n req.end();\n }\n break;\n }\n\n case 'prettier': {\n // Format the code with Prettier\n if (obj.message && typeof obj.message.code === 'string') {\n try {\n prettier\n .format(obj.message.code, {\n parser: obj.message.type === 'typescript' ? 'babel-ts' : 'babel',\n printWidth: 120,\n semi: true,\n tabWidth: 4,\n useTabs: false,\n trailingComma: 'all',\n singleQuote: true,\n singleAttributePerLine: true,\n endOfLine: 'lf',\n bracketSpacing: true,\n arrowParens: 'avoid',\n quoteProps: 'as-needed',\n })\n .then(formattedCode => {\n if (obj.callback) {\n this.sendTo(obj.from, obj.command, { code: formattedCode }, obj.callback);\n } else {\n this.logWithLineInfo(`Formatted code:\\n${formattedCode}`);\n }\n })\n .catch(e => {\n this.logError('Prettier', 'Error formatting code:', e as Error);\n this.sendTo(obj.from, obj.command, { error: (e as Error).toString() }, obj.callback);\n });\n } catch (e) {\n this.logError('Prettier', 'Error formatting code:', e as Error);\n this.sendTo(obj.from, obj.command, { error: (e as Error).toString() }, obj.callback);\n }\n } else {\n this.sendTo(obj.from, obj.command, { error: 'No code provided' }, obj.callback);\n }\n break;\n }\n }\n }\n\n onLog(msg: any): void {\n Object.keys(this.logSubscriptions).forEach((name: string): void =>\n this.logSubscriptions[name].forEach(handler => {\n if (\n typeof handler.cb === 'function' &&\n (handler.severity === '*' || handler.severity === msg.severity)\n ) {\n handler.sandbox.logHandler = handler.severity || '*';\n handler.cb.call(handler.sandbox, msg);\n handler.sandbox.logHandler = undefined;\n }\n }),\n );\n }\n\n logError(scriptName: string, msg: string, e: Error, offs?: number): void {\n const stack = e.stack ? e.stack.toString().split('\\n') : e ? e.toString() : '';\n if (!msg.includes('\\n')) {\n msg = msg.replace(/[: ]*$/, ': ');\n }\n if (!msg.endsWith(' ')) {\n msg += ':';\n }\n if (!scriptName.startsWith(SCRIPT_CODE_MARKER)) {\n scriptName = SCRIPT_CODE_MARKER + scriptName;\n }\n\n this.errorLogFunction.error(`${scriptName}: ${msg}${this.fixLineNo(stack[0])}`);\n for (let i = offs || 1; i < stack.length; i++) {\n if (!stack[i]) {\n continue;\n }\n if (stack[i].match(/runInNewContext|javascript\\.js:/)) {\n break;\n }\n this.errorLogFunction.error(`${scriptName}: ${this.fixLineNo(stack[i])}`);\n }\n }\n\n logWithLineInfo(msg: string): void {\n this.errorLogFunction.warn(msg);\n\n // get current error stack\n const stack = new Error().stack?.split('\\n');\n\n if (stack) {\n for (let i = 3; i < stack.length; i++) {\n if (!stack[i]) {\n continue;\n }\n if (stack[i].match(/runInContext|runInNewContext|javascript\\.js:/)) {\n break;\n }\n this.errorLogFunction.warn(this.fixLineNo(stack[i]));\n }\n }\n }\n\n async main(): Promise {\n // Patch the font as it sometimes is wrong\n if (!this.context.debugMode) {\n if (await this.patchFont()) {\n this.log.debug('Font patched');\n }\n }\n\n this.log.debug(`config.subscribe (Do not subscribe all states on start): ${this.config.subscribe}`);\n\n // correct jsonConfig for admin\n const instObj: ioBroker.InstanceObject | null | undefined = await this.getForeignObjectAsync(\n `system.adapter.${this.namespace}`,\n );\n if (instObj?.common) {\n if (instObj.common.adminUI?.config !== 'json') {\n if (instObj.common.adminUI) {\n instObj.common.adminUI.config = 'json';\n } else {\n instObj.common.adminUI = { config: 'json' };\n }\n void this.setForeignObject(instObj._id, instObj);\n }\n }\n\n if (webstormDebug) {\n this.errorLogFunction = {\n error: console.error,\n warn: console.warn,\n info: console.info,\n debug: console.log,\n silly: console.log,\n };\n this.context.errorLogFunction = this.errorLogFunction;\n }\n this.activeStr = `${this.namespace}.scriptEnabled.`;\n\n this.mods.fs = new ProtectFs(this.log, getAbsoluteDefaultDataDir());\n this.mods['fs/promises'] = this.mods.fs.promises; // to avoid require('fs/promises');\n\n // try to read TS declarations\n try {\n tsAmbient = {\n 'javascript.d.ts': readFileSync(this.mods.path.join(__dirname, 'lib/javascript.d.ts'), 'utf8'),\n };\n this.tsServer.provideAmbientDeclarations(tsAmbient);\n jsDeclarationServer.provideAmbientDeclarations(tsAmbient);\n } catch (err: unknown) {\n this.log.warn(`Could not read TypeScript ambient declarations: ${err as Error}`);\n // This should not happen, so send an error report to Sentry\n if (this.supportsFeature && this.supportsFeature('PLUGINS')) {\n const sentryInstance = this.getPluginInstance('sentry');\n if (sentryInstance) {\n const sentryObject = sentryInstance.getSentryObject();\n sentryObject?.captureException(err as Error);\n }\n }\n // Keep the adapter from crashing when the included typings cannot be read\n tsAmbient = {};\n }\n\n await this.installLibraries();\n // Load the TS declarations for Node.js and all 3rd party modules\n this.loadTypeScriptDeclarations();\n\n await this.getData();\n this.context.scheduler = new Scheduler(\n this.log,\n Date,\n this.mods.suncalc,\n this.config.latitude,\n this.config.longitude,\n );\n await this.dayTimeSchedules();\n await this.sunTimeSchedules();\n await this.timeSchedule();\n\n // Store allowSelfSignedCerts on the context, so sandbox HTTP functions can use it\n // without setting the global process.env.NODE_TLS_REJECT_UNAUTHORIZED (which affects all adapters in compact mode)\n this.context.allowSelfSignedCerts = this.config.allowSelfSignedCerts;\n\n const doc = await this.getObjectViewAsync('script', 'javascript', {});\n if (doc?.rows?.length) {\n // assemble global script\n for (let g = 0; g < doc.rows.length; g++) {\n const obj = doc.rows[g].value;\n if (checkIsGlobal(obj)) {\n if (obj && obj.common) {\n const engineType = (obj.common.engineType || '').toLowerCase();\n\n if (obj.common.enabled) {\n if (engineType.startsWith('typescript')) {\n // TypeScript\n this.log.info(`${obj._id}: compiling TypeScript source...`);\n // In order to compile global TypeScript, we need to do some transformations\n // 1. For top-level-await, some statements must be wrapped in an immediately-invoked async function\n // 2. If any global script uses `import`, the declarations are no longer visible if they are not exported with `declare global`\n const transformedSource = transformScriptBeforeCompilation(obj.common.source, true);\n // The source code must be transformed in order to support top level await\n // Global scripts must not be treated as a module, otherwise their methods\n // cannot be found by the normal scripts\n // We need to hash both global declarations that are known until now\n // AND the script source, because changing either can change the compilation output\n const sourceHash: string = hashSource(\n tsSourceHashBase + this.globalDeclarations + transformedSource,\n );\n\n let compiled: string | undefined;\n let declarations: string | undefined;\n // If we already stored the compiled source code and the original source hash,\n // use the hash to check whether we can rely on the compiled source code or\n // if we need to compile it again\n if (\n typeof obj.common.compiled === 'string' &&\n typeof obj.common.sourceHash === 'string' &&\n sourceHash === obj.common.sourceHash\n ) {\n // We can reuse the stored source\n compiled = obj.common.compiled;\n declarations = obj.common.declarations;\n this.log.info(\n `${obj._id}: source code did not change, using cached compilation result...`,\n );\n } else {\n // We don't have a hashed source code, or the original source changed, compile it\n const filename = scriptIdToTSFilename(obj._id);\n let tsCompiled: CompileResult;\n try {\n tsCompiled = this.tsServer.compile(filename, transformedSource);\n } catch (err: unknown) {\n this.log.error(`${obj._id}: TypeScript compilation failed:\\n${err as Error}`);\n continue;\n }\n\n const errors = tsCompiled.diagnostics\n .map(diag => `${diag.annotatedSource}\\n`)\n .join('\\n');\n\n if (tsCompiled.success) {\n if (errors.length > 0) {\n this.log.warn(\n `${obj._id}: TypeScript compilation completed with errors:\\n${errors}`,\n );\n } else {\n this.log.info(`${obj._id}: TypeScript compilation successful`);\n }\n compiled = tsCompiled.result;\n // Global scripts that have been transformed to support `import` need to have their declarations transformed aswell\n declarations = transformGlobalDeclarations(tsCompiled.declarations || '');\n\n const newCommon: {\n compiled: string | undefined;\n declarations?: string;\n sourceHash: string;\n } = {\n sourceHash,\n compiled,\n };\n if (declarations) {\n newCommon.declarations = declarations;\n }\n\n // Store the compiled source and the original source hash, so we don't need to do the work again next time\n this.ignoreObjectChange.add(obj._id); // ignore the next change and don't restart scripts\n void this.extendForeignObject(obj._id, {\n common: newCommon,\n });\n } else {\n this.log.error(`${obj._id}: TypeScript compilation failed:\\n${errors}`);\n continue;\n }\n }\n this.globalScript += `${compiled}\\n`;\n // if declarations were generated, remember them\n if (declarations != null) {\n this.provideDeclarationsForGlobalScript(obj._id, declarations);\n }\n } else {\n // javascript\n const sourceCode = obj.common.source;\n this.globalScript += `${sourceCode}\\n`;\n\n // try to compile the declarations so TypeScripts can use\n // functions defined in global JavaScripts\n const filename = scriptIdToTSFilename(obj._id);\n let tsCompiled: CompileResult;\n try {\n tsCompiled = jsDeclarationServer.compile(filename, sourceCode);\n } catch (err: unknown) {\n this.log.warn(\n `${obj._id}: Error while generating type declarations, skipping:\\n${err as Error}`,\n );\n continue;\n }\n // if declarations were generated, remember them\n if (tsCompiled.success && tsCompiled.declarations != null) {\n this.provideDeclarationsForGlobalScript(obj._id, tsCompiled.declarations);\n }\n }\n }\n }\n }\n }\n }\n\n this.globalScript = this.globalScript.replace(/\\r\\n/g, '\\n');\n this.globalScriptLines = this.globalScript.split(/\\n/g).length - 1;\n\n if (doc?.rows?.length) {\n // load all scripts\n for (let i = 0; i < doc.rows.length; i++) {\n if (!checkIsGlobal(doc.rows[i].value)) {\n void this.loadScript(doc.rows[i].value);\n }\n }\n }\n\n if (this.config.mirrorPath?.trim()) {\n this.config.mirrorInstance = parseInt(this.config.mirrorInstance as unknown as string, 10) || 0;\n if (this.instance === this.config.mirrorInstance) {\n const ioBDataDir = getAbsoluteDefaultDataDir() + sep;\n this.config.mirrorPath = normalize(this.config.mirrorPath);\n let mirrorForbidden = false;\n for (let dir of forbiddenMirrorLocations) {\n dir = join(ioBDataDir, dir) + sep;\n if (dir.includes(this.config.mirrorPath) || this.config.mirrorPath.startsWith(dir)) {\n this.log.error(`The Mirror directory is not allowed to be a central ioBroker directory!`);\n this.log.error(`Directory ${this.config.mirrorPath} is not allowed to mirror files!`);\n mirrorForbidden = true;\n break;\n }\n }\n if (!mirrorForbidden) {\n this.mirror = new Mirror({\n adapter: this,\n log: this.log,\n diskRoot: this.config.mirrorPath,\n });\n }\n }\n }\n\n // CHeck setState counter per minute and stop a script if too high\n this.setStateCountCheckInterval = setInterval(() => {\n Object.keys(this.scripts).forEach(id => {\n if (!this.scripts[id]) {\n return;\n }\n const currentSetStatePerMinuteCounter = this.scripts[id].setStatePerMinuteCounter;\n this.scripts[id].setStatePerMinuteCounter = 0;\n if (currentSetStatePerMinuteCounter > this.config.maxSetStatePerMinute) {\n this.scripts[id].setStatePerMinuteProblemCounter++;\n this.log.debug(\n `${id}: Script has reached the maximum of ${this.config.maxSetStatePerMinute} setState calls per minute in ${this.scripts[id].setStatePerMinuteProblemCounter} consecutive minutes`,\n );\n // Allow \"too high counters\" for 1 minute for script starts or such and only\n // stop the script when lasts longer\n if (this.scripts[id].setStatePerMinuteProblemCounter > 1) {\n this.log.error(\n `${id}: Script is calling setState more than ${this.config.maxSetStatePerMinute} times per minute! Stopping Script now! Please check your script!`,\n );\n void this.stopScript(id);\n }\n } else if (this.scripts[id].setStatePerMinuteProblemCounter > 0) {\n this.scripts[id].setStatePerMinuteProblemCounter--;\n this.log.debug(\n `Script ${id} has NOT reached the maximum of ${this.config.maxSetStatePerMinute} setState calls per minute. Decrease problem counter to ${this.scripts[id].setStatePerMinuteProblemCounter}`,\n );\n }\n });\n }, 60000);\n }\n\n private loadTypeScriptDeclarations(): void {\n // try to load the typings on disk for all 3rd party modules\n const packages = [\n 'node', // this provides auto-completion for most builtins\n '@iobroker/types', // this provides auto-completion for most builtins\n ];\n // Also include user-selected libraries (but only those that are also installed)\n if (typeof this.config?.libraries === 'string' && typeof this.config.libraryTypings === 'string') {\n const installedLibs = this.config.libraries\n .split(/[,;\\s]+/)\n .map(s => s.trim().split('@')[0])\n .filter(s => !!s);\n\n const wantsTypings = this.config.libraryTypings\n .split(/[,;\\s]+/)\n .map(s => s.trim())\n .filter(s => !!s);\n // Add all installed libraries the user has requested typings for to the list of packages\n for (const lib of installedLibs) {\n if (wantsTypings.includes(lib) && !packages.includes(lib)) {\n packages.push(lib);\n }\n }\n // Some packages have submodules (e.g., rxjs/operators) that are not exposed through the main entry point\n // If typings are requested for them, also add them if the base module is installed\n for (const lib of wantsTypings) {\n // Extract the package name and check if we need to add it\n if (!lib.includes('/')) {\n continue;\n }\n const pkgName = lib.substring(0, lib.indexOf('/'));\n\n if (installedLibs.includes(pkgName) && !packages.includes(lib)) {\n packages.push(lib);\n }\n }\n }\n for (const pkg of packages) {\n let pkgTypings = resolveTypings(\n pkg,\n this.getAdapterScopedPackageIdentifier ? this.getAdapterScopedPackageIdentifier(pkg) : pkg,\n // node needs ambient typings, so we don't wrap it in declare module\n pkg !== 'node',\n );\n if (!pkgTypings) {\n // Create the empty dummy declarations so users don't get the \"not found\" error\n // for installed packages\n if (pkg.includes('/')) {\n pkgTypings = {\n [`node_modules/${pkg}/index.d.ts`]: `declare module \"${pkg}\";`,\n };\n } else {\n pkgTypings = {\n [`node_modules/@types/${pkg}/index.d.ts`]: `declare module \"${pkg}\";`,\n };\n }\n }\n this.log.debug(`Loaded TypeScript definitions for \"${pkg}\": ${JSON.stringify(Object.keys(pkgTypings))}`);\n // remember the declarations for the editor\n Object.assign(tsAmbient, pkgTypings);\n // and give the language servers access to them\n this.tsServer.provideAmbientDeclarations(pkgTypings);\n jsDeclarationServer.provideAmbientDeclarations(pkgTypings);\n }\n }\n\n updateObjectContext(id: string, obj: ioBroker.Object | null | undefined): void {\n if (obj) {\n // add state to state ID's list\n if (obj.type === 'state') {\n if (!this.stateIds.includes(id)) {\n this.stateIds.push(id);\n this.stateIds.sort();\n }\n if (this.context.devices && this.context.channels) {\n const parts = id.split('.');\n parts.pop();\n const chn = parts.join('.');\n this.context.channels[chn] ||= [];\n this.context.channels[chn].push(id);\n\n parts.pop();\n const dev = parts.join('.');\n this.context.devices[dev] ||= [];\n this.context.devices[dev].push(id);\n }\n }\n } else {\n // delete object from state ID's list\n const pos = this.stateIds.indexOf(id);\n if (pos !== -1) {\n this.stateIds.splice(pos, 1);\n }\n if (this.context.devices && this.context.channels) {\n const parts = id.split('.');\n parts.pop();\n const chn = parts.join('.');\n if (this.context.channels[chn]) {\n const posChn = this.context.channels[chn].indexOf(id);\n posChn !== -1 && this.context.channels[chn].splice(posChn, 1);\n }\n\n parts.pop();\n const dev = parts.join('.');\n if (this.context.devices[dev]) {\n const posDev = this.context.devices[dev].indexOf(id);\n posDev !== -1 && this.context.devices[dev].splice(posDev, 1);\n }\n }\n\n delete this.folderCreationVerifiedObjects[id];\n }\n\n if (!obj && this.objects[id]) {\n // objects were deleted\n this.removeFromNames(id);\n delete this.objects[id];\n } else if (obj && !this.objects[id]) {\n // object was added\n this.objects[id] = obj;\n this.addToNames(obj);\n } else if (obj && this.objects[id].common) {\n // Object just changed\n this.objects[id] = obj;\n\n const n = this.getName(id);\n let nn = this.objects[id].common ? this.objects[id].common.name : '';\n\n if (nn && typeof nn === 'object') {\n nn = nn[getLanguage()] || nn.en;\n }\n\n if (n !== nn) {\n if (n) {\n this.removeFromNames(id);\n }\n if (nn) {\n this.addToNames(obj);\n }\n }\n }\n }\n\n async stopAllScripts(): Promise {\n const scripts = Object.keys(this.scripts);\n const promises: Promise[] = [];\n for (let i = 0; i < scripts.length; i++) {\n promises.push(this.stopScript(scripts[i]));\n }\n return Promise.all(promises).then(() => {});\n }\n\n convertBackStringifiedValues(\n id: string,\n state: ioBroker.State | null | undefined,\n ): ioBroker.State | null | undefined {\n if (\n state &&\n typeof state.val === 'string' &&\n this.objects[id]?.common &&\n (this.objects[id].common.type === 'array' || this.objects[id].common.type === 'object')\n ) {\n try {\n state.val = JSON.parse(state.val);\n } catch (err: any) {\n if (id.startsWith('javascript.') || id.startsWith('0_userdata.0')) {\n this.log.info(\n `Could not parse value for id \"${id}\" into ${this.objects[id].common.type}: ${err.toString()}`,\n );\n } else {\n this.log.debug(\n `Could not parse value for id \"${id}\" into ${this.objects[id].common.type}: ${err.toString()}`,\n );\n }\n }\n }\n return state;\n }\n\n prepareStateObjectSimple(id: string, state: ioBroker.StateValue, isAck: boolean): ioBroker.State {\n // otherwise, assume that the given state is the value to be set\n const oState: ioBroker.State = { val: state, ack: isAck } as ioBroker.State;\n\n return this.prepareStateObject(id, oState);\n }\n\n prepareStateObject(id: string, state: ioBroker.SettableState | null): ioBroker.State {\n let oState: ioBroker.State;\n\n if (state && typeof state === 'object') {\n oState = state as ioBroker.State;\n } else {\n oState = { val: null } as ioBroker.State;\n }\n\n if (this.config.subscribe) {\n return oState;\n }\n // set other values to have a full state object\n // mirrors logic from statesInRedis\n if (oState.ts === undefined) {\n oState.ts = Date.now();\n }\n\n if (oState.q === undefined) {\n oState.q = 0;\n }\n\n oState.from =\n typeof oState.from === 'string' && oState.from !== '' ? oState.from : `system.adapter.${this.namespace}`;\n\n if (oState.lc === undefined) {\n const formerStateValue = this.interimStateValues[id] || this.states[id];\n if (!formerStateValue) {\n oState.lc = oState.ts;\n } else {\n // isDeepStrictEqual works on objects and primitive values\n const hasChanged = !isDeepStrictEqual(formerStateValue.val, oState.val);\n if (!formerStateValue.lc || hasChanged) {\n oState.lc = oState.ts;\n } else {\n oState.lc = formerStateValue.lc;\n }\n }\n }\n\n return oState;\n }\n\n async getData(): Promise {\n await this.subscribeForeignObjectsAsync('*');\n\n if (!this.config.subscribe) {\n await this.subscribeForeignStatesAsync('*');\n } else {\n await this.subscribeStatesAsync('debug.to');\n await this.subscribeStatesAsync('scriptEnabled.*');\n }\n\n this.log.info('requesting all states');\n\n const statesPromise = this.getForeignStatesAsync('*')\n .then(res => {\n if (!res) {\n this.log.error(`Could not initialize states: no result`);\n this.terminate(EXIT_CODES.START_IMMEDIATELY_AFTER_STOP);\n return;\n }\n if (!this.config.subscribe) {\n this.states = Object.assign(res, this.states);\n this.context.states = this.states;\n\n this.addGetProperty(this.states);\n }\n\n // remember all IDs\n for (const id in res) {\n if (Object.prototype.hasOwnProperty.call(res, id)) {\n this.stateIds.push(id);\n }\n }\n this.statesInitDone = true;\n this.log.info('received all states');\n })\n .catch((err: any) => {\n this.log.error(`Could not initialize states: ${err?.message || 'no result'}`);\n this.terminate(EXIT_CODES.START_IMMEDIATELY_AFTER_STOP);\n });\n\n this.log.info('requesting all objects');\n\n const objectsPromise = this.getObjectListAsync({ include_docs: true })\n .then(res => {\n if (!res?.rows) {\n this.log.error(`Could not initialize objects: no result`);\n this.terminate(EXIT_CODES.START_IMMEDIATELY_AFTER_STOP);\n return;\n }\n this.objects = {};\n this.context.objects = this.objects;\n for (let i = 0; i < res.rows.length; i++) {\n if (!res.rows[i].doc) {\n this.log.debug(`Got empty object for index ${i} (${res.rows[i].id})`);\n continue;\n }\n if (this.objects[res.rows[i].doc._id] === undefined) {\n // If was already there, ignore\n this.objects[res.rows[i].doc._id] = res.rows[i].doc;\n }\n this.objects[res.rows[i].doc._id].type === 'enum' && this._enums.push(res.rows[i].doc._id);\n\n // Collect all names\n this.addToNames(this.objects[res.rows[i].doc._id]);\n }\n this.addGetProperty(this.objects);\n\n const systemConfig = this.objects['system.config'];\n this.password = systemConfig?.native?.javascriptPassword\n ? this.decrypt(systemConfig?.native.javascriptPassword)\n : '';\n\n // set language for debug messages\n if (systemConfig?.common?.language) {\n setLanguage(systemConfig.common.language);\n this.language = systemConfig.common.language;\n this.context.language = this.language as ioBroker.Languages;\n } else if (this.language) {\n setLanguage(this.language);\n this.context.language = this.language;\n }\n\n // try to use system coordinates\n if (this.config.useSystemGPS) {\n if (systemConfig?.common?.latitude || systemConfig?.common?.longitude) {\n this.config.latitude = systemConfig.common.latitude;\n this.config.longitude = systemConfig.common.longitude;\n } else if (this.latitude && this.longitude) {\n this.config.latitude = this.latitude;\n this.config.longitude = this.longitude;\n }\n }\n this.config.latitude = parseFloat(this.config.latitude as unknown as string);\n this.config.longitude = parseFloat(this.config.longitude as unknown as string);\n\n if (isNaN(this.config.latitude)) {\n this.log.warn(`Configured latitude is not a number - check (instance/system) configuration`);\n } else if (this.config.latitude < -90 || this.config.latitude > 90) {\n this.log.warn(\n `Configured latitude \"${this.config.latitude}\" is invalid - check (instance/system) configuration`,\n );\n }\n\n if (isNaN(this.config.longitude)) {\n this.log.warn(`Configured longitude is not a number - check (instance/system) configuration`);\n } else if (this.config.longitude < -180 || this.config.longitude > 180) {\n this.log.warn(\n `Configured longitude \"${this.config.longitude}\" is invalid - check (instance/system) configuration`,\n );\n }\n\n this.config.sunriseEvent ||= 'nightEnd';\n this.config.sunriseOffset ||= 0;\n this.config.sunriseLimitStart ||= '06:00';\n this.config.sunriseLimitEnd ||= '12:00';\n\n this.config.sunsetEvent ||= 'dusk';\n this.config.sunsetOffset ||= 0;\n this.config.sunsetLimitStart ||= '18:00';\n this.config.sunsetLimitEnd ||= '23:00';\n\n this.objectsInitDone = true;\n this.log.info('received all objects');\n })\n .catch((err: any) => {\n this.log.error(`Could not initialize objects: ${err?.message || 'no result'}`);\n this.terminate(EXIT_CODES.START_IMMEDIATELY_AFTER_STOP);\n });\n\n return Promise.all([statesPromise, objectsPromise]).then(() => {});\n }\n\n async createActiveObject(id: string, enabled: boolean): Promise {\n const idActive = `${this.namespace}.scriptEnabled.${id.substring(SCRIPT_CODE_MARKER.length)}`;\n\n if (!this.objects[idActive]) {\n this.objects[idActive] = {\n _id: idActive,\n common: {\n name: `scriptEnabled.${id.substring(SCRIPT_CODE_MARKER.length)}`,\n desc: 'controls script activity',\n type: 'boolean',\n write: true,\n read: true,\n role: 'switch.active',\n },\n native: {\n script: id,\n },\n type: 'state',\n };\n try {\n await this.setForeignObjectAsync(idActive, this.objects[idActive]);\n const intermediateStateValue = this.prepareStateObjectSimple(idActive, enabled, true);\n await this.setForeignStateAsync(idActive, enabled, true);\n if (enabled && !this.config.subscribe) {\n this.interimStateValues[idActive] = intermediateStateValue;\n }\n } catch {\n // ignore\n }\n } else {\n const state = await this.getForeignStateAsync(idActive);\n if (state && state.val !== enabled) {\n const intermediateStateValue = this.prepareStateObjectSimple(idActive, enabled, true);\n await this.setForeignStateAsync(idActive, enabled, true);\n if (enabled && !this.config.subscribe) {\n this.interimStateValues[idActive] = intermediateStateValue;\n }\n }\n }\n }\n\n async createProblemObject(id: string): Promise {\n const idProblem = `${this.namespace}.scriptProblem.${id.substring(SCRIPT_CODE_MARKER.length)}`;\n\n if (!this.objects[idProblem]) {\n this.objects[idProblem] = {\n _id: idProblem,\n common: {\n name: `scriptProblem.${id.substring(SCRIPT_CODE_MARKER.length)}`,\n desc: 'Script has a problem',\n type: 'boolean',\n expert: true,\n write: false,\n read: true,\n role: 'indicator.error',\n },\n native: {\n script: id,\n },\n type: 'state',\n };\n try {\n await this.setForeignObjectAsync(idProblem, this.objects[idProblem]);\n await this.setForeignStateAsync(idProblem, false, true);\n } catch {\n // ignore\n }\n } else {\n const state = await this.getForeignStateAsync(idProblem);\n if (state && state.val !== false) {\n await this.setForeignStateAsync(idProblem, false, true);\n }\n }\n }\n\n addToNames(obj: ioBroker.Object): void {\n const id = obj._id;\n\n if (obj.common?.name) {\n let name = obj.common.name;\n if (name && typeof name === 'object') {\n name = name[getLanguage()] || name.en;\n }\n if (!name || typeof name !== 'string') {\n // TODO, take name in current language\n return;\n }\n\n if (!this.names[name]) {\n this.names[name] = id;\n } else {\n // convert to array\n if (!Array.isArray(this.names[name])) {\n this.names[name] = [this.names[name] as string];\n }\n\n (this.names[name] as string[]).push(id);\n }\n }\n }\n\n removeFromNames(id: string): void {\n const n = this.getName(id);\n\n if (n) {\n if (Array.isArray(this.names[n])) {\n const pos = this.names[n].indexOf(id);\n if (pos > -1) {\n this.names[n].splice(pos, 1);\n\n if (this.names[n].length === 1) {\n this.names[n] = this.names[n][0];\n }\n }\n } else {\n delete this.names[n];\n }\n }\n }\n\n getName(id: string): string | null {\n for (const n in this.names) {\n if (this.names[n] && Array.isArray(this.names[n])) {\n if (this.names[n].includes(id)) {\n return n;\n }\n } else if (this.names[n] === id) {\n return n;\n }\n }\n\n return null;\n }\n\n async installNpm(npmLib: string): Promise {\n return new Promise((resolve, reject) => {\n const path = __dirname;\n\n // Also, set the working directory (cwd) of the process instead of using --prefix\n // because that has ugly bugs on Windows\n const cmd = `npm install ${npmLib} --omit=dev`;\n this.log.info(`Installing ${npmLib} into ${__dirname} - cmd: ${cmd}`);\n\n // System call used for update of js-controller itself,\n // because during the installation the npm packet will be deleted too, but some files must be loaded even during the installation process.\n const child = this.mods.child_process.exec(cmd, {\n windowsHide: true,\n cwd: path,\n });\n\n child.stdout?.on('data', buf => this.log.info(buf.toString('utf8')));\n\n child.stderr?.on('data', buf => this.log.error(buf.toString('utf8')));\n\n child.on('err', err => {\n this.log.error(`Cannot install ${npmLib}: ${err}`);\n reject(new Error(`Cannot install ${npmLib}: ${err}`));\n });\n child.on('error', err => {\n this.log.error(`Cannot install ${npmLib}: ${err}`);\n reject(new Error(`Cannot install ${npmLib}: ${err}`));\n });\n\n child.on('exit', (code: number /* , signal */) => {\n if (code) {\n this.log.error(`Cannot install ${npmLib}: ${code}`);\n reject(new Error(`Cannot install ${npmLib}: ${code}`));\n }\n // command succeeded\n resolve(code);\n });\n });\n }\n\n async installLibraries(): Promise {\n if (typeof this.config?.libraries !== 'string') {\n this.config.libraries = '';\n }\n\n const libraries: string[] = this.config.libraries\n .split(/[,;\\s]+/)\n .map(d => d.trim())\n .filter(d => d);\n\n this.log.debug(`Custom libraries in config: \"${this.config.libraries}\": ${JSON.stringify(libraries)}`);\n\n let installedNodeModules: string[] = [];\n const keepModules: string[] = [];\n\n // js-controller >= 6.x\n if (typeof this.listInstalledNodeModules === 'function') {\n installedNodeModules = await this.listInstalledNodeModules();\n\n this.log.debug(`Found installed libraries: ${JSON.stringify(installedNodeModules)}`);\n }\n\n for (const lib of libraries) {\n let depName = lib;\n let version = 'latest';\n\n if (depName.includes('@') && depName.lastIndexOf('@') > 0) {\n const parts = depName.split('@');\n version = parts.pop() ?? 'latest';\n depName = parts.join('@');\n }\n\n /** The real module name, because the dependency can be a URL too */\n let moduleName = depName;\n\n if (URL.canParse(depName)) {\n moduleName = await requestModuleNameByUrl(depName);\n\n this.log.debug(`Found custom library in config: \"${moduleName}@${version}\" (from ${depName})`);\n } else {\n this.log.debug(`Found custom library in config: \"${moduleName}@${version}\"`);\n }\n\n keepModules.push(moduleName);\n\n // js-controller >= 6.x\n if (typeof this.installNodeModule === 'function') {\n try {\n const result = await this.installNodeModule(depName, { version });\n if (result.success) {\n this.log.debug(`Installed custom library: \"${moduleName}@${version}\"`);\n\n const importedModule: any = await this.importNodeModule(moduleName);\n (this.mods as Record)[moduleName] = importedModule.default ?? importedModule;\n } else {\n this.log.warn(`Cannot install custom npm package \"${moduleName}@${version}\"`);\n }\n } catch (err: unknown) {\n this.log.warn(`Cannot install custom npm package \"${moduleName}@${version}\": ${err as Error}`);\n }\n } else if (!existsSync(`${__dirname}/node_modules/${depName}/package.json`)) {\n // js-controller < 6.x\n this.log.info(`Installing custom library (legacy mode): \"${lib}\"`);\n\n try {\n await this.installNpm(lib);\n this.log.info(`Installed custom npm package (legacy mode): \"${lib}\"`);\n } catch (err: any) {\n this.log.warn(`Cannot install custom npm package \"${lib}\" (legacy mode): ${err.toString()}`);\n }\n }\n }\n\n // js-controller >= 6.x\n if (typeof this.uninstallNodeModule === 'function') {\n for (const installedNodeModule of installedNodeModules) {\n if (!keepModules.includes(installedNodeModule)) {\n try {\n await this.uninstallNodeModule(installedNodeModule);\n\n this.log.info(`Removed custom npm package: \"${installedNodeModule}\"`);\n } catch (err: any) {\n this.log.warn(`Cannot remove custom npm package ${installedNodeModule}: ${err.toString()}`);\n }\n }\n }\n }\n }\n\n createVM(source: string, name: string, wrapAsync: boolean): false | JsScript {\n if (this.context.debugMode && name !== this.context.debugMode) {\n return false;\n }\n\n if (!this.context.debugMode) {\n const logSubscriptionsText =\n \"\\n;\\nlog(`registered ${__engine.__subscriptions} subscription${__engine.__subscriptions === 1 ? '' : 's'},\" +\n \" ${__engine.__schedules} schedule${__engine.__schedules === 1 ? '' : 's'},\" +\n \" ${__engine.__subscriptionsMessage} message${__engine.__subscriptionsMessage === 1 ? '' : 's'},\" +\n \" ${__engine.__subscriptionsLog} log${__engine.__subscriptionsLog === 1 ? '' : 's'}\" +\n \" and ${__engine.__subscriptionsFile} file subscription${__engine.__subscriptionsFile === 1 ? '' : 's'}`);\\n\";\n\n if (wrapAsync) {\n source = `(async () => {\\n${source}\\n${logSubscriptionsText}\\n})();`;\n } else {\n if (source.endsWith('export {};\\n')) {\n // If the source ends with \"export {};\" place the log subscriptions before it\n source = source.slice(0, -11); // remove \"export {};\\n\"\n source = `${source}\\n${logSubscriptionsText}\\nexport {};\\n`;\n } else {\n source = `${source}\\n${logSubscriptionsText}`;\n }\n }\n } else {\n if (wrapAsync) {\n source = `(async () => {debugger;\\n${source}\\n})();`;\n } else {\n source = `debugger;${source}`;\n }\n }\n\n try {\n const options: ScriptOptions = {\n filename: name,\n // displayErrors: true,\n // lineOffset: this.globalScriptLines\n };\n return {\n script: new Script(source, options),\n } as JsScript;\n } catch (err: unknown) {\n this.logError(name, `compile failed at`, err as Error);\n return false;\n }\n }\n\n execute(script: JsScript, name: string, engineType: ScriptType, verbose: boolean, debug: boolean): void {\n script.intervals = [];\n script.timeouts = [];\n script.schedules = [];\n script.wizards = [];\n script.name = name;\n script.engineType = engineType;\n script._id = Math.floor(Math.random() * 0xffffffff);\n script.subscribes = {};\n script.subscribesFile = {};\n script.setStatePerMinuteCounter = 0;\n script.setStatePerMinuteProblemCounter = 0;\n void this.setState(`scriptProblem.${name.substring(SCRIPT_CODE_MARKER.length)}`, {\n val: false,\n ack: true,\n expire: 1000,\n });\n\n const sandbox = sandBox(script, name, verbose, debug, this.context);\n\n try {\n script.script.runInNewContext(sandbox, {\n filename: name,\n displayErrors: true,\n // lineOffset: this.globalScriptLines\n });\n } catch (err: unknown) {\n void this.setState(`scriptProblem.${name.substring(SCRIPT_CODE_MARKER.length)}`, {\n val: true,\n ack: true,\n c: 'execute',\n });\n this.logError(name, 'Error by run:', err as Error);\n }\n }\n\n unsubscribe(id: string | RegExp | string[]): void {\n if (!id) {\n this.log.warn('unsubscribe: empty name');\n return;\n }\n\n if (Array.isArray(id)) {\n id.forEach(sub => unsubscribe(sub));\n return;\n }\n\n if (id.constructor && id.constructor.name === 'RegExp') {\n // adapter.log.warn('unsubscribe: todo - process regexp');\n return;\n }\n\n if (typeof id !== 'string') {\n this.log.error(`unsubscribe: invalid type of id - ${typeof id}`);\n return;\n }\n const parts = id.split('.');\n const _adapter = `system.adapter.${parts[0]}.${parts[1]}`;\n if (this.objects[_adapter]?.common?.subscribable) {\n const a = `${parts[0]}.${parts[1]}`;\n const alive = `system.adapter.${a}.alive`;\n if (this.adapterSubs[alive]) {\n const pos = this.adapterSubs[alive].indexOf(id);\n if (pos !== -1) {\n this.adapterSubs[alive].splice(pos, 1);\n }\n if (!this.adapterSubs[alive].length) {\n delete this.adapterSubs[alive];\n }\n }\n this.sendTo(a, 'unsubscribe', id);\n }\n }\n\n // Analyze if logs are still required or not\n updateLogSubscriptions(): void {\n let found = false;\n // go through all scripts and check if some script still requires logs\n Object.keys(this.logSubscriptions).forEach(scriptName => {\n if (!this.logSubscriptions?.[scriptName] || !this.logSubscriptions[scriptName].length) {\n delete this.logSubscriptions[scriptName];\n } else {\n found = true;\n }\n });\n\n if (this.requireLog) {\n if (found && !this.logSubscribed) {\n this.logSubscribed = true;\n void this.requireLog(this.logSubscribed);\n this.log.info(`Subscribed to log messages (found logSubscriptions)`);\n } else if (!found && this.logSubscribed) {\n this.logSubscribed = false;\n void this.requireLog(this.logSubscribed);\n this.log.info(`Unsubscribed from log messages (not found logSubscriptions)`);\n }\n }\n }\n\n async stopScript(name: string): Promise {\n this.log.info(`${name}: Stopping script`);\n\n await this.setState(`scriptEnabled.${name.substring(SCRIPT_CODE_MARKER.length)}`, false, true);\n\n if (this.messageBusHandlers[name]) {\n delete this.messageBusHandlers[name];\n }\n\n if (this.tempDirectories[name]) {\n try {\n this.mods.fs.rmSync(this.tempDirectories[name], { recursive: true });\n\n this.log.debug(`${name}: Removed temp directory: ${this.tempDirectories[name]}`);\n } catch {\n this.log.warn(`${name}: Unable to remove temp directory: ${this.tempDirectories[name]}`);\n }\n\n delete this.tempDirectories[name];\n }\n\n if (this.logSubscriptions[name]) {\n delete this.logSubscriptions[name];\n this.updateLogSubscriptions();\n }\n\n if (this.scripts[name]) {\n // Remove from subscriptions\n this.context.isEnums = false;\n if (this.config.subscribe) {\n // check all subscribed IDs\n Object.keys(this.scripts[name].subscribes).forEach(id => {\n if (this.subscribedPatterns[id]) {\n this.subscribedPatterns[id] -= this.scripts[name].subscribes[id];\n if (this.subscribedPatterns[id] <= 0) {\n this.unsubscribeForeignStates(id);\n delete this.subscribedPatterns[id];\n if (this.states[id]) {\n delete this.states[id];\n }\n }\n }\n });\n }\n\n for (let i = this.subscriptions.length - 1; i >= 0; i--) {\n if (this.subscriptions[i].name === name) {\n const sub = this.subscriptions.splice(i, 1)[0];\n if (sub?.pattern.id) {\n this.unsubscribe(sub.pattern.id);\n }\n } else {\n if (\n (!this.context.isEnums && this.subscriptions[i].pattern.enumName) ||\n this.subscriptions[i].pattern.enumId\n ) {\n this.context.isEnums = true;\n }\n }\n }\n\n // check all subscribed files\n Object.keys(this.scripts[name].subscribesFile).forEach(key => {\n if (this.subscribedPatternsFile[key]) {\n this.subscribedPatternsFile[key] -= this.scripts[name].subscribesFile[key];\n if (this.subscribedPatternsFile[key] <= 0) {\n const [id, file] = key.split('$%$');\n void this.unsubscribeForeignFiles(id, file);\n delete this.subscribedPatternsFile[key];\n }\n }\n });\n for (let i = this.subscriptionsFile.length - 1; i >= 0; i--) {\n if (this.subscriptionsFile[i].name === name) {\n this.subscriptionsFile.splice(i, 1);\n }\n }\n\n for (let i = this.subscriptionsObject.length - 1; i >= 0; i--) {\n if (this.subscriptionsObject[i].name === name) {\n const sub = this.subscriptionsObject.splice(i, 1)[0];\n if (sub) {\n this.unsubscribeForeignObjects(sub.pattern);\n }\n }\n }\n\n // Stop all timeouts\n for (let i = 0; i < this.scripts[name].timeouts.length; i++) {\n clearTimeout(this.scripts[name].timeouts[i]);\n }\n // Stop all intervals\n for (let i = 0; i < this.scripts[name].intervals.length; i++) {\n clearInterval(this.scripts[name].intervals[i]);\n }\n // Stop all scheduled jobs\n for (let i = 0; i < this.scripts[name].schedules.length; i++) {\n if (this.scripts[name].schedules[i]) {\n const _name = this.scripts[name].schedules[i].name;\n if (!this.mods.nodeSchedule.cancelJob(this.scripts[name].schedules[i])) {\n this.log.error(`${name}: Error by canceling scheduled job \"${_name}\"`);\n }\n }\n }\n\n // Stop all time wizards jobs\n if (this.context.scheduler) {\n for (let i = 0; i < this.scripts[name].wizards.length; i++) {\n if (this.scripts[name].wizards[i]) {\n this.context.scheduler.remove(this.scripts[name].wizards[i]);\n }\n }\n }\n\n // if callback for on stop\n if (typeof this.scripts[name].onStopCb === 'function') {\n this.scripts[name].onStopTimeout =\n parseInt(this.scripts[name].onStopTimeout as unknown as string, 10) || 1000;\n\n await new Promise(resolve => {\n let timeout: NodeJS.Timeout | null = setTimeout(() => {\n if (timeout) {\n timeout = null;\n resolve(true);\n }\n }, this.scripts[name].onStopTimeout);\n\n try {\n this.scripts[name].onStopCb(() => {\n if (timeout) {\n clearTimeout(timeout);\n timeout = null;\n resolve(true);\n }\n });\n } catch (err: unknown) {\n this.log.error(`${name}: error in onStop callback: ${err as Error}`);\n }\n });\n }\n\n delete this.scripts[name];\n return true;\n }\n return false;\n }\n\n async prepareScript(obj: ioBroker.ScriptObject): Promise {\n if (obj?.common?.enabled && this.debugState.scriptName === obj._id) {\n const id = obj._id;\n await this.debugStop();\n this.log.info(`${id}: Debugging was stopped, because started in normal mode`);\n return this.prepareScript(obj);\n }\n\n if (\n obj?.common?.source &&\n (obj.common.enabled || this.context.debugMode === obj._id) &&\n obj.common.engine === `system.adapter.${this.namespace}`\n ) {\n const name = obj._id;\n\n if (this.password && obj.native?.protected) {\n obj.common.source = decryptText(this.password, obj.common.source);\n }\n\n const nameId = name.substring(SCRIPT_CODE_MARKER.length);\n if (!nameId.length || nameId.endsWith('.')) {\n this.log.error(`${name}: Script name \"${name}\" is invalid!`);\n return false;\n }\n const idActive = `scriptEnabled.${nameId}`;\n if (!this.config.subscribe) {\n this.interimStateValues[idActive] = this.prepareStateObjectSimple(\n `${this.namespace}.${idActive}`,\n true,\n true,\n );\n }\n await this.setState(idActive, true, true);\n obj.common.engineType ||= '' as 'TypeScript/ts' | 'Blockly' | 'Rules' | 'Javascript/js';\n\n if (\n (obj.common.engineType as ScriptType).toLowerCase().startsWith('javascript') ||\n (obj.common.engineType as ScriptType) === 'Blockly' ||\n (obj.common.engineType as ScriptType) === 'Rules'\n ) {\n // Javascript\n this.log.info(`${name}: start JavaScript (${obj.common.engineType})`);\n\n let sourceFn = name;\n if (webstormDebug) {\n const fn = name.replace(/^script\\.js\\./, '').replace(/\\./g, '/');\n sourceFn = this.mods.path.join(webstormDebug, `${fn}.js`);\n }\n const createdScript = this.createVM(`${this.globalScript}\\n${obj.common.source}`, sourceFn, true);\n if (!createdScript) {\n return false;\n }\n this.scripts[name] = createdScript;\n this.execute(\n this.scripts[name],\n sourceFn,\n obj.common.engineType as ScriptType,\n obj.common.verbose,\n obj.common.debug,\n );\n return true;\n }\n\n if (obj.common.engineType.toLowerCase().startsWith('typescript')) {\n // TypeScript\n this.log.info(`${name}: Compiling TypeScript source`);\n // The source code must be transformed in order to support top level await\n // and to force TypeScript to compile the code as a module\n const transformedSource = transformScriptBeforeCompilation(obj.common.source, false);\n // We need to hash both global declarations that are known until now\n // AND the script source, because changing either can change the compilation output\n const sourceHash = hashSource(tsSourceHashBase + this.globalDeclarations + transformedSource);\n\n let compiled: string;\n // If we already stored the compiled source code and the original source hash,\n // use the hash to check whether we can rely on the compiled source code or\n // if we need to compile it again\n if (\n typeof obj.common.compiled === 'string' &&\n typeof obj.common.sourceHash === 'string' &&\n sourceHash === obj.common.sourceHash\n ) {\n // We can reuse the stored source\n compiled = obj.common.compiled;\n this.log.info(`${name}: source code did not change, using cached compilation result...`);\n } else {\n // We don't have a hashed source code, or the original source changed, compile it\n const filename = scriptIdToTSFilename(name);\n let tsCompiled: CompileResult;\n try {\n tsCompiled = this.tsServer.compile(filename, transformedSource);\n } catch (err: unknown) {\n this.log.error(`${obj._id}: TypeScript compilation failed:\\n${err as Error}`);\n return false;\n }\n\n const errors = tsCompiled.diagnostics.map(diag => `${diag.annotatedSource}\\n`).join('\\n');\n\n if (tsCompiled.success) {\n if (errors.length > 0) {\n this.log.warn(`${name}: TypeScript compilation had errors:\\n${errors}`);\n } else {\n this.log.info(`${name}: TypeScript compilation successful`);\n }\n compiled = tsCompiled.result || '';\n\n // Store the compiled source and the original source hash, so we don't need to do the work again next time\n this.ignoreObjectChange.add(name); // ignore the next change and don't restart scripts\n await this.extendForeignObjectAsync(name, {\n common: {\n sourceHash,\n compiled,\n },\n });\n } else {\n this.log.error(`${name}: TypeScript compilation failed:\\n${errors}`);\n return false;\n }\n }\n const createdScript: JsScript | false = this.createVM(`${this.globalScript}\\n${compiled}`, name, false);\n if (!createdScript) {\n return false;\n }\n this.scripts[name] = createdScript;\n this.execute(\n this.scripts[name],\n name,\n obj.common.engineType as ScriptType,\n obj.common.verbose,\n obj.common.debug,\n );\n return true;\n }\n\n this.log.warn(`${obj._id}: Unknown engine type: ${obj.common.engineType}`);\n return false;\n }\n\n let _name: string;\n if (obj?._id) {\n _name = obj._id;\n const scriptIdName = _name.substring(SCRIPT_CODE_MARKER.length);\n\n if (!scriptIdName.length || scriptIdName.endsWith('.')) {\n this.log.error(`${obj._id}: Script name \"${_name}\" is invalid!`);\n return false;\n }\n await this.setState(`scriptEnabled.${scriptIdName}`, false, true);\n }\n if (!obj) {\n this.log.error('Invalid script');\n }\n return false;\n }\n\n async loadScriptById(id: string): Promise {\n let obj: ioBroker.ScriptObject | null | undefined;\n try {\n obj = (await this.getForeignObjectAsync(id)) as ioBroker.ScriptObject | null | undefined;\n } catch (err: any) {\n this.log.error(`${id}: Invalid script: ${err}`);\n }\n if (!obj) {\n return false;\n }\n return this.loadScript(obj);\n }\n\n async loadScript(nameOrObject: ioBroker.ScriptObject): Promise {\n // create states for scripts\n await this.createActiveObject(nameOrObject._id, !!nameOrObject?.common?.enabled);\n await this.createProblemObject(nameOrObject._id);\n return this.prepareScript(nameOrObject);\n }\n\n getAstroEvent(\n date: Date,\n astroEvent: AstroEventName,\n start: string,\n end: string,\n offsetMinutes: number | string,\n isDayEnd: boolean,\n latitude: number,\n longitude: number,\n useNextDay?: boolean,\n ): Date {\n let ts: Date = this.mods.suncalc.getTimes(date, latitude, longitude)[astroEvent];\n\n if (!ts || ts.getTime().toString() === 'NaN') {\n ts = isDayEnd ? getNextTimeEvent(end, useNextDay) : getNextTimeEvent(start, useNextDay);\n }\n ts.setMilliseconds(0);\n ts.setMinutes(ts.getMinutes() + (parseInt(offsetMinutes as unknown as string, 10) || 0));\n\n const [timeHoursStart, timeMinutesStart] = start.split(':');\n const nTimeHoursStart = parseInt(timeHoursStart, 10);\n const nTimeMinutesStart = parseInt(timeMinutesStart, 10) || 0;\n\n if (\n ts.getHours() < nTimeHoursStart ||\n (ts.getHours() === nTimeHoursStart && ts.getMinutes() < nTimeMinutesStart)\n ) {\n ts = getNextTimeEvent(start, useNextDay);\n ts.setSeconds(0);\n }\n\n const [timeHoursEnd, timeMinutesEnd] = end.split(':');\n const nTimeHoursEnd = parseInt(timeHoursEnd, 10);\n const nTimeMinutesEnd = parseInt(timeMinutesEnd, 10) || 0;\n\n if (ts.getHours() > nTimeHoursEnd || (ts.getHours() === nTimeHoursEnd && ts.getMinutes() > nTimeMinutesEnd)) {\n ts = getNextTimeEvent(end, useNextDay);\n ts.setSeconds(0);\n }\n\n // if event in the past\n if (date > ts && useNextDay) {\n // take the next day\n ts.setDate(ts.getDate() + 1);\n }\n return ts;\n }\n\n async timeSchedule(): Promise {\n const now = new Date();\n let hours = now.getHours();\n const minutes = now.getMinutes();\n if (this.timeSettings.format12) {\n if (hours > 12) {\n hours -= 12;\n }\n }\n let sHours: string;\n if (this.timeSettings.leadingZeros) {\n sHours = hours.toString().padStart(2, '0');\n } else {\n sHours = hours.toString();\n }\n\n await this.setState('variables.dayTime', {\n val: `${sHours}:${minutes.toString().padStart(2, '0')}`,\n ack: true,\n });\n\n now.setMinutes(now.getMinutes() + 1);\n now.setSeconds(0);\n now.setMilliseconds(0);\n const interval = now.getTime() - Date.now();\n this.timeScheduleTimer = setTimeout(() => this.timeSchedule(), interval);\n }\n\n async dayTimeSchedules(): Promise {\n // get astrological event\n if (\n this.config.latitude === undefined ||\n this.config.longitude === undefined ||\n (this.config.latitude as unknown as string) === '' ||\n (this.config.longitude as unknown as string) === '' ||\n this.config.latitude === null ||\n this.config.longitude === null\n ) {\n this.log.error('Longitude or latitude does not set. Cannot use astro.');\n return;\n }\n\n // Calculate the next event today\n const todayDate = getAstroStartOfDay();\n const nowDate = new Date();\n\n const todaySunrise = this.getAstroEvent(\n todayDate,\n this.config.sunriseEvent,\n this.config.sunriseLimitStart,\n this.config.sunriseLimitEnd,\n this.config.sunriseOffset,\n false,\n this.config.latitude,\n this.config.longitude,\n );\n const todaySunset = this.getAstroEvent(\n todayDate,\n this.config.sunsetEvent,\n this.config.sunsetLimitStart,\n this.config.sunsetLimitEnd,\n this.config.sunsetOffset,\n true,\n this.config.latitude,\n this.config.longitude,\n );\n\n // Sunrise\n let sunriseTimeout = todaySunrise.getTime() - nowDate.getTime();\n if (sunriseTimeout < 0 || sunriseTimeout > 3600000) {\n sunriseTimeout = 3600000;\n }\n\n // Sunset\n let sunsetTimeout = todaySunset.getTime() - nowDate.getTime();\n if (sunsetTimeout < 0 || sunsetTimeout > 3600000) {\n sunsetTimeout = 3600000;\n }\n\n const isDayTime: ioBroker.State | null | undefined = await this.getStateAsync('variables.isDayTime');\n let isDay: boolean;\n if (sunriseTimeout < 5000) {\n isDay = true;\n } else if (sunsetTimeout < 5000) {\n isDay = false;\n } else {\n // check if in between\n isDay = nowDate.getTime() > todaySunrise.getTime() - 60000 && nowDate <= todaySunset;\n }\n\n const valDayTime = isDayTime ? !!isDayTime.val : false;\n if (valDayTime !== isDay || isDayTime === null) {\n await this.setState('variables.isDayTime', isDay, true);\n }\n\n const dayLightSaving: ioBroker.State | null | undefined =\n await this.getStateAsync('variables.isDaylightSaving');\n const isDayLightSaving = dstOffsetAtDate(nowDate) !== 0;\n const val = dayLightSaving ? !!dayLightSaving.val : false;\n\n if (val !== isDayLightSaving || dayLightSaving === null) {\n await this.setState('variables.isDaylightSaving', isDayLightSaving, true);\n }\n\n let nextTimeout = sunriseTimeout;\n if (sunriseTimeout > sunsetTimeout) {\n nextTimeout = sunsetTimeout;\n }\n nextTimeout = nextTimeout - 3000;\n if (nextTimeout < 3000) {\n nextTimeout = 3000;\n }\n\n this.dayScheduleTimer = setTimeout(() => this.dayTimeSchedules(), nextTimeout);\n }\n\n stopTimeSchedules(): void {\n if (this.dayScheduleTimer) {\n clearTimeout(this.dayScheduleTimer);\n this.dayScheduleTimer = null;\n }\n if (this.sunScheduleTimer) {\n clearTimeout(this.sunScheduleTimer);\n this.sunScheduleTimer = null;\n }\n if (this.timeScheduleTimer) {\n clearTimeout(this.timeScheduleTimer);\n this.timeScheduleTimer = null;\n }\n }\n\n async patchFont(): Promise {\n let stat: Stats | undefined;\n let dbFile: Buffer | undefined;\n let fileName = `${__dirname}/../admin/vs/base/browser/ui/codicons/codicon/codicon.ttf`;\n let jsonFileName = `${__dirname}/../admin/vsFont/codicon.json`;\n try {\n if (existsSync(fileName)) {\n stat = statSync(fileName);\n }\n if (!stat) {\n jsonFileName = `${__dirname}/admin/vsFont/codicon.json`;\n fileName = `${__dirname}/admin/vs/base/browser/ui/codicons/codicon/codicon.ttf`;\n if (existsSync(fileName)) {\n stat = statSync(fileName);\n }\n }\n const _dbFile = await this.readFileAsync(\n 'javascript.admin',\n `vs/base/browser/ui/codicons/codicon/codicon.ttf`,\n );\n if (_dbFile?.file) {\n dbFile = _dbFile.file as Buffer;\n }\n } catch {\n // ignore\n }\n\n if (stat?.size !== 73452 || dbFile?.byteLength !== 73452) {\n try {\n const buffer = Buffer.from(JSON.parse(readFileSync(jsonFileName).toString()), 'base64');\n\n const jszip = await import('jszip');\n const zip = await jszip.loadAsync(buffer);\n let data: ArrayBuffer | undefined;\n if (zip) {\n data = await zip.file('codicon.ttf')?.async('arraybuffer');\n if (data?.byteLength !== 73452) {\n this.log.error(`Cannot patch font: invalid font file!`);\n return false;\n }\n } else {\n this.log.error(`Cannot patch font: invalid font file!`);\n return false;\n }\n writeFileSync(fileName, Buffer.from(data));\n // upload this file\n await this.writeFileAsync(\n 'javascript.admin',\n 'vs/base/browser/ui/codicons/codicon/codicon.ttf',\n Buffer.from(data),\n );\n return true;\n } catch (err: unknown) {\n this.log.error(`Cannot patch font: ${err as Error}`);\n return false;\n }\n }\n return false;\n }\n\n async sunTimeSchedules(): Promise {\n if (this.config.createAstroStates) {\n if (!isNaN(this.config.longitude) && !isNaN(this.config.longitude)) {\n const calcDate = getAstroStartOfDay();\n\n const times = this.mods.suncalc.getTimes(calcDate, this.config.latitude, this.config.longitude);\n\n this.log.debug(`[sunTimeSchedules] Times: ${JSON.stringify(times)}`);\n\n for (const t in times) {\n try {\n const objId = `variables.astro.${t}`;\n\n await this.setObjectNotExistsAsync(objId, {\n type: 'state',\n common: {\n name: `Astro ${t}`,\n type: 'string',\n role: 'value',\n read: true,\n write: false,\n },\n native: {},\n });\n\n if (times[t] !== null && !isNaN(times[t].getTime())) {\n const timeFormatted = formatHoursMinutesSeconds(times[t]);\n await this.setState(objId, {\n val: timeFormatted,\n c: times[t].toISOString(),\n ack: true,\n });\n } else {\n await this.setState(objId, { val: null, c: 'n/a', ack: true, q: 0x01 });\n }\n } catch (err: unknown) {\n this.log.error(\n `[sunTimeSchedules] Unable to set state for astro time \"${t}\" (${times[t].getTime()}): ${err as Error}`,\n );\n }\n }\n\n const todayDate = new Date();\n todayDate.setHours(0);\n todayDate.setMinutes(0);\n todayDate.setSeconds(1);\n todayDate.setMilliseconds(0);\n todayDate.setDate(todayDate.getDate() + 1);\n\n this.log.debug(`[sunTimeSchedules] Next: ${todayDate.toISOString()}`);\n this.sunScheduleTimer = setTimeout(() => this.sunTimeSchedules(), todayDate.getTime() - Date.now());\n }\n } else {\n // remove astro states if disabled\n this.delObject('variables.astro', { recursive: true });\n }\n }\n\n /**\n * Redirects the virtual-tsc log output to the ioBroker log\n */\n tsLog = (message: string, severity?: ioBroker.LogLevel): void => {\n // shift the severities around, we don't care about the small details\n if (!severity || severity === 'info') {\n severity = 'debug';\n } else if (severity === 'debug') {\n // Don't spam build logs on Travis\n if (isCI) {\n return;\n }\n severity = 'silly';\n }\n\n if (this?.log) {\n this.log[severity](message);\n } else {\n console.log(`[${severity.toUpperCase()}] ${message}`);\n }\n };\n\n addGetProperty(object: Record): void {\n try {\n Object.defineProperty(object, 'get', {\n value: function (id: string): any {\n return this[id] || this[`${this.namespace}.${id}`];\n },\n enumerable: false,\n });\n } catch {\n console.error('Cannot install get property');\n }\n }\n\n /**\n * Add declarations for global scripts\n *\n * @param scriptID - The current script the declarations were generated from\n * @param declarations - Declarations from a script\n */\n provideDeclarationsForGlobalScript(scriptID: string, declarations: string): void {\n // Remember which declarations this global script had access to;\n // we need this so the editor doesn't show a duplicate identifier error\n if (this.globalDeclarations != null && this.globalDeclarations !== '') {\n this.knownGlobalDeclarationsByScript[scriptID] = this.globalDeclarations;\n }\n // and concatenate the global declarations for the next scripts\n this.globalDeclarations += `${declarations}\\n`;\n // remember all previously generated global declarations,\n // so global scripts can reference each other\n const globalDeclarationPath = 'global.d.ts';\n tsAmbient[globalDeclarationPath] = this.globalDeclarations;\n // make sure the next script compilation has access to the updated declarations\n this.tsServer.provideAmbientDeclarations({\n [globalDeclarationPath]: this.globalDeclarations,\n });\n jsDeclarationServer.provideAmbientDeclarations({\n [globalDeclarationPath]: this.globalDeclarations,\n });\n }\n\n fixLineNo(line: string): string {\n if (line.includes('javascript.js:')) {\n return line;\n }\n if (!/scripts?\\.js[.\\\\/]/.test(line)) {\n return line;\n }\n if (/:(\\d+):/.test(line)) {\n line = line.replace(\n /:(\\d+):/,\n (_$0, $1) => `:${$1 > this.globalScriptLines + 1 ? $1 - this.globalScriptLines - 1 : $1}:`,\n ); // one line for 'async function ()'\n } else {\n line = line.replace(\n /:(\\d+)$/,\n (_$0, $1) => `:${$1 > this.globalScriptLines + 1 ? $1 - this.globalScriptLines - 1 : $1}`,\n ); // one line for 'async function ()'\n }\n return line;\n }\n\n async debugStop(): Promise {\n if (this.debugState.child) {\n this.debugSendToInspector({ cmd: 'end' });\n this.debugState.endTimeout = setTimeout(() => {\n this.debugState.endTimeout = null;\n this.debugState.child?.kill('SIGTERM');\n }, 500);\n this.debugState.promiseOnEnd ||= Promise.resolve(0);\n } else {\n this.debugState.promiseOnEnd = Promise.resolve(0);\n }\n\n await this.debugState.promiseOnEnd;\n\n this.debugState.child = null;\n this.debugState.running = false;\n this.debugState.scriptName = '';\n if (this.debugState.endTimeout) {\n clearTimeout(this.debugState.endTimeout);\n this.debugState.endTimeout = null;\n }\n }\n\n async debugDisableScript(id: string | undefined): Promise {\n if (id) {\n const obj = this.objects[id];\n if (obj?.common?.enabled) {\n await this.extendForeignObjectAsync(obj._id, { common: { enabled: false } });\n }\n }\n }\n\n debugSendToInspector(message: any): void {\n if (this.debugState.child) {\n try {\n this.log.info(`send to debugger: ${message}`);\n this.debugState.child.send(message);\n } catch {\n void this.debugStop().then(() =>\n this.log.info(\n `${this.debugState.scriptName}: Debugging was stopped, because started in normal mode`,\n ),\n );\n }\n } else {\n this.log.error(`${this.debugState.scriptName}: Cannot send command to terminated inspector`);\n void this.setState(\n 'debug.from',\n JSON.stringify({ cmd: 'error', error: `Cannot send command to terminated inspector`, id: 1 }),\n true,\n );\n }\n }\n\n debugStart(data: { breakOnStart?: boolean; scriptName?: string; adapter?: string }): void {\n if (Date.now() - this.debugState.started < 1000) {\n console.log('Start ignored');\n return;\n }\n\n this.debugState.started = Date.now();\n // stop the script if it's running\n void this.debugDisableScript(data.scriptName)\n .then(() => this.debugStop())\n .then(() => {\n if (data.adapter) {\n this.debugState.adapterInstance = data.adapter;\n this.debugState.scriptName = '';\n } else {\n this.debugState.adapterInstance = '';\n this.debugState.scriptName = data.scriptName as string;\n }\n\n this.debugState.breakOnStart = data.breakOnStart;\n\n this.debugState.promiseOnEnd = new Promise(resolve => {\n const options: ForkOptions = {\n stdio: ['ignore', 'inherit', 'inherit', 'ipc'],\n //stdio: ['pipe', 'pipe', 'pipe', 'ipc']\n };\n const args: string[] = [];\n if (this.debugState.adapterInstance) {\n args.push('--breakOnStart');\n }\n\n this.debugState.child = fork(`${__dirname}/lib/inspect.js`, args, options);\n\n /*debugState.child.stdout.setEncoding('utf8');\n debugState.child.stderr.setEncoding('utf8');\n debugState.child.stdout.on('data', childPrint);\n debugState.child.stderr.on('data', childPrint);*/\n\n this.debugState.child?.on(\n 'message',\n (\n message:\n | string\n | {\n cmd: 'ready' | 'watched' | 'paused' | 'resumed' | 'log' | 'readyToDebug';\n severity?: string;\n text?: string;\n scriptId?: string;\n script?: string;\n },\n ) => {\n let oMessage: {\n cmd: 'ready' | 'watched' | 'paused' | 'resumed' | 'log' | 'readyToDebug';\n severity?: string;\n text?: string;\n scriptId?: string;\n script?: string;\n };\n if (typeof message === 'string') {\n try {\n oMessage = JSON.parse(message);\n } catch {\n return this.log.error(`Cannot parse message from inspector: ${message}`);\n }\n } else {\n oMessage = message;\n }\n\n if (oMessage.cmd !== 'ready') {\n void this.setState('debug.from', JSON.stringify(oMessage), true);\n }\n\n switch (oMessage.cmd) {\n case 'ready': {\n this.debugSendToInspector({\n cmd: 'start',\n scriptName: this.debugState.scriptName,\n adapterInstance: this.debugState.adapterInstance,\n instance: this.instance,\n });\n break;\n }\n\n case 'watched': {\n //console.log(`WATCHED: ${JSON.stringify(oMessage)}`);\n break;\n }\n\n case 'paused': {\n this.debugState.paused = true;\n console.log(`host: PAUSED`);\n break;\n }\n\n case 'resumed': {\n this.debugState.paused = false;\n //console.log(`STARTED`);\n break;\n }\n\n case 'log': {\n console.log(`[${oMessage.severity}] ${oMessage.text}`);\n break;\n }\n\n case 'readyToDebug': {\n console.log(\n `host: readyToDebug (set breakpoints): [${oMessage.scriptId}] ${oMessage.script}`,\n );\n break;\n }\n }\n },\n );\n this.debugState.child?.on('error', error => {\n this.log.error(`Cannot start inspector: ${error}`);\n void this.setState('debug.from', JSON.stringify({ cmd: 'error', error }), true);\n });\n\n this.debugState.child?.on('exit', async (code: number): Promise => {\n if (code) {\n await this.setState(\n 'debug.from',\n JSON.stringify({ cmd: 'error', error: `invalid response code: ${code}` }),\n true,\n );\n }\n await this.setState('debug.from', JSON.stringify({ cmd: 'debugStopped', code }), true);\n this.debugState.child = null;\n resolve(code);\n });\n });\n });\n }\n}\n\nfunction patternMatching(\n event: EventObj,\n patternFunctions: PatternEventCompareFunction[] & { logic?: 'and' | 'or' },\n): boolean {\n let matched = false;\n for (let i = 0, len = patternFunctions.length; i < len; i++) {\n if (patternFunctions[i](event)) {\n if (patternFunctions.logic === 'or') {\n return true;\n }\n matched = true;\n } else if (patternFunctions.logic === 'and') {\n return false;\n }\n }\n return matched;\n}\n\n// If started as allInOne mode => return function to create an instance\nif (require.main !== module) {\n // Export the constructor in compact mode\n module.exports = (options: Partial | undefined) => new JavaScript(options);\n} else {\n // otherwise start the instance directly\n (() => new JavaScript())();\n}\n"]} +{"version":3,"file":"main.js","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":";AAAA;;;;;;;;GAQG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,qCAAqD;AACrD,qC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,KAAe,EACf,gBAA0E;IAE1E,IAAI,OAAO,GAAG,KAAK,CAAC;IACpB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,GAAG,GAAG,gBAAgB,CAAC,MAAM,EAAE,CAAC,GAAG,GAAG,EAAE,CAAC,EAAE,EAAE,CAAC;QAC1D,IAAI,gBAAgB,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,EAAE,CAAC;YAC7B,IAAI,gBAAgB,CAAC,KAAK,KAAK,IAAI,EAAE,CAAC;gBAClC,OAAO,IAAI,CAAC;YAChB,CAAC;YACD,OAAO,GAAG,IAAI,CAAC;QACnB,CAAC;aAAM,IAAI,gBAAgB,CAAC,KAAK,KAAK,KAAK,EAAE,CAAC;YAC1C,OAAO,KAAK,CAAC;QACjB,CAAC;IACL,CAAC;IACD,OAAO,OAAO,CAAC;AACnB,CAAC;AAED,uEAAuE;AACvE,IAAI,OAAO,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;IAC1B,yCAAyC;IACzC,MAAM,CAAC,OAAO,GAAG,CAAC,OAA4C,EAAE,EAAE,CAAC,IAAI,UAAU,CAAC,OAAO,CAAC,CAAC;AAC/F,CAAC;KAAM,CAAC;IACJ,wCAAwC;IACxC,CAAC,GAAG,EAAE,CAAC,IAAI,UAAU,EAAE,CAAC,EAAE,CAAC;AAC/B,CAAC","sourcesContent":["/*\n * Javascript adapter\n *\n * The MIT License (MIT)\n *\n * Copyright (c) 2014-2024 bluefox ,\n *\n * Copyright (c) 2014 hobbyquaker\n */\n\nimport { Script, type ScriptOptions } from 'node:vm';\nimport { readFileSync, existsSync, statSync, writeFileSync, type Stats } from 'node:fs';\nimport { join, sep, normalize } from 'node:path';\nimport { fork, type ForkOptions } from 'node:child_process';\nimport { setTypeScriptResolveOptions, Server } from 'virtual-tsc';\nimport { isDeepStrictEqual } from 'node:util';\nimport prettier from 'prettier';\n\nimport * as dgram from 'node:dgram';\nimport * as crypto from 'node:crypto';\nimport * as dns from 'node:dns';\nimport * as events from 'node:events';\nimport * as http from 'node:http';\nimport * as https from 'node:https';\nimport * as http2 from 'node:http2';\nimport * as net from 'node:net';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport * as util from 'node:util';\nimport * as child_process from 'node:child_process';\nimport * as stream from 'node:stream';\nimport * as zlib from 'node:zlib';\n\n// @ts-expect-error no types available\nimport * as suncalc from 'suncalc2';\nimport * as axios from 'axios';\n// @ts-expect-error no types available\nimport * as wake_on_lan from 'wake_on_lan';\nimport * as nodeSchedule from 'node-schedule';\n\nimport { getAbsoluteDefaultDataDir, Adapter, EXIT_CODES, type AdapterOptions } from '@iobroker/adapter-core';\nimport type SentryPlugin from '@iobroker/plugin-sentry';\nimport type { GetTimesResult } from 'suncalc';\nimport type { CompileResult } from 'virtual-tsc/build/util';\n\nimport { Mirror } from './lib/mirror';\nimport ProtectFs from './lib/protectFs';\nimport { setLanguage, getLanguage } from './lib/words';\nimport { sandBox } from './lib/sandbox';\nimport { requestModuleNameByUrl } from './lib/nodeModulesManagement';\nimport { createEventObject, type EventObj } from './lib/eventObj';\nimport { type AstroEventName, Scheduler } from './lib/scheduler';\nimport { targetTsLib, tsCompilerOptions, jsDeclarationCompilerOptions } from './lib/typescriptSettings';\nimport { hashSource } from './lib/tools';\nimport {\n resolveTypescriptLibs,\n resolveTypings,\n scriptIdToTSFilename,\n transformScriptBeforeCompilation,\n transformGlobalDeclarations,\n} from './lib/typescriptTools';\nimport type {\n FileSubscriptionResult,\n JavascriptContext,\n JavaScriptAdapterConfig,\n JsScript,\n ScriptType,\n SubscriptionResult,\n SubscribeObject,\n JavascriptTimer,\n SandboxType,\n LogMessage,\n DebugState,\n} from './types';\nimport type { PatternEventCompareFunction } from './lib/patternCompareFunctions';\nimport { decryptText } from './lib/crypto';\n\ntype MODULES = {\n fs: ProtectFs;\n 'fs/promises': ProtectFs['promises'];\n dgram: typeof dgram;\n crypto: typeof crypto;\n dns: typeof dns;\n events: typeof events;\n http: typeof http;\n https: typeof https;\n http2: typeof http2;\n net: typeof net;\n os: typeof os;\n path: typeof path;\n util: typeof util;\n child_process: typeof child_process;\n stream: typeof stream;\n zlib: typeof zlib;\n suncalc: typeof suncalc;\n axios: typeof axios;\n wake_on_lan: typeof wake_on_lan;\n nodeSchedule: typeof nodeSchedule;\n};\n\n/**\n * List of forbidden Locations for a mirror directory\n * relative to the default data directory\n * ATTENTION: the same list is also located in index_m.html!!\n */\nconst forbiddenMirrorLocations: string[] = [\n 'backup-objects',\n 'files',\n 'backitup',\n '../backups',\n '../node_modules',\n '../log',\n];\n\nconst packageJson: Record = JSON.parse(readFileSync(`${__dirname}/../package.json`).toString());\nconst SCRIPT_CODE_MARKER = 'script.js.';\n\nlet webstormDebug: string | undefined;\n\nconst isCI = !!process.env.CI;\n\n// ambient declarations for typescript\nlet tsAmbient: Record;\n\n// TypeScript's scripts are only recompiled if their source hash changes.\n// If an adapter update fixes the compilation bugs, a user won't notice until the changes and re-save the script.\n// To avoid that, we also include the\n// adapter version and TypeScript version in the hash\nconst tsSourceHashBase = `versions:adapter=${packageJson.version},typescript=${packageJson.dependencies.typescript}`;\n\n// taken from here: https://stackoverflow.com/questions/11887934/how-to-check-if-dst-daylight-saving-time-is-in-effect-and-if-so-the-offset\nfunction dstOffsetAtDate(dateInput: Date): number {\n const fullYear: number = dateInput.getFullYear() | 0;\n // \"Leap Years are any year that can be exactly divided by 4 (2012, 2016, etc.)\n // except if it can be exactly divided by 100, then it isn't (2100, 2200, etc.)\n // except if it can be exactly divided by 400, then it is (2000, 2400)\"\n // (https://www.mathsisfun.com/leap-years.html).\n const isLeapYear: 1 | 0 = ((fullYear & 3) | ((fullYear / 100) & 3)) === 0 ? 1 : 0;\n // (fullYear & 3) = (fullYear % 4), but faster\n //Alternative:var isLeapYear=(new Date(currentYear,1,29,12)).getDate()===29?1:0\n const fullMonth: number = dateInput.getMonth() | 0;\n return (\n // 1. We know what the time since the Epoch really is\n +dateInput - // same as the dateInput.getTime() method\n // 2. We know what the time since the Epoch at the start of the year is\n +new Date(fullYear, 0) - // day defaults to 1 if not explicitly zeroed\n // 3. Now, subtract what we would expect the time to be if daylight savings\n // did not exist. This yields the time-offset due to daylight savings.\n // Calculate the day of the year in the Gregorian calendar\n // The code below works based upon the facts of signed right shifts\n // • (x) >> n: shifts n and fills in the n highest bits with 0s\n // • (-x) >> n: shifts n and fills in the n highest bits with 1s\n // (This assumes that x is a positive integer)\n ((((-1 + // the first day in the year is day 1\n (31 & (-fullMonth >> 4)) + // January // (-11)>>4 = -1\n ((28 + isLeapYear) & ((1 - fullMonth) >> 4)) + // February\n (31 & ((2 - fullMonth) >> 4)) + // March\n (30 & ((3 - fullMonth) >> 4)) + // April\n (31 & ((4 - fullMonth) >> 4)) + // May\n (30 & ((5 - fullMonth) >> 4)) + // June\n (31 & ((6 - fullMonth) >> 4)) + // July\n (31 & ((7 - fullMonth) >> 4)) + // August\n (30 & ((8 - fullMonth) >> 4)) + // September\n (31 & ((9 - fullMonth) >> 4)) + // October\n (30 & ((10 - fullMonth) >> 4)) + // November\n // There are no months past December: the year rolls into the next.\n // Thus, \"fullMonth\" is 0-based, so it will never be 12 in JavaScript\n\n (dateInput.getDate() | 0)) & // get day of the month\n 0xffff) *\n 24 *\n 60 + // 24 hours in a day, 60 minutes in an hour\n (dateInput.getHours() & 0xff) * 60 + // 60 minutes in an hour\n (dateInput.getMinutes() & 0xff)) |\n 0) *\n 60 *\n 1000 - // 60 seconds in a minute * 1000 milliseconds in a second\n (dateInput.getSeconds() & 0xff) * 1000 - // 1000 milliseconds in a second\n dateInput.getMilliseconds()\n );\n}\n\nconst regExGlobalOld = /_global$/;\nconst regExGlobalNew = /script\\.js\\.global\\./;\n\nfunction checkIsGlobal(obj: ioBroker.ScriptObject): boolean {\n return obj?.common && (regExGlobalOld.test(obj.common.name) || regExGlobalNew.test(obj._id));\n}\n\nfunction fileMatching(sub: FileSubscriptionResult, id: string, fileName: string): boolean {\n if (sub.idRegEx) {\n if (!sub.idRegEx.test(id)) {\n return false;\n }\n } else {\n if (sub.id !== id) {\n return false;\n }\n }\n if (sub.fileRegEx) {\n if (!sub.fileRegEx.test(fileName)) {\n return false;\n }\n } else {\n if (sub.fileNamePattern !== fileName) {\n return false;\n }\n }\n\n return true;\n}\n\nfunction getNextTimeEvent(time: string, useNextDay?: boolean): Date {\n const now: Date = getAstroStartOfDay();\n const [timeHours, timeMinutes] = time.split(':');\n const nTimeHours = parseInt(timeHours, 10);\n const nTimeMinutes = parseInt(timeMinutes, 10);\n if (\n useNextDay &&\n (now.getHours() > nTimeHours || (now.getHours() === nTimeHours && now.getMinutes() > nTimeMinutes))\n ) {\n now.setDate(now.getDate() + 1);\n }\n\n now.setHours(nTimeHours);\n now.setMinutes(nTimeMinutes);\n\n return now;\n}\n\nfunction getAstroStartOfDay(): Date {\n const d = new Date();\n d.setMinutes(0);\n d.setSeconds(0);\n d.setMilliseconds(0);\n d.setTime(d.getTime() - d.getTimezoneOffset() * 60 * 1000);\n d.setUTCHours(0);\n\n return d;\n}\n\nfunction formatHoursMinutesSeconds(date: Date): string {\n const h = String(date.getHours());\n const m = String(date.getMinutes());\n const s = String(date.getSeconds());\n\n return `${h.padStart(2, '0')}:${m.padStart(2, '0')}:${s.padStart(2, '0')}`;\n}\n\n// Due to a npm bug, virtual-tsc may be hoisted to the top level node_modules, but\n// TypeScript may still be in the adapter level (https://npm.community/t/packages-with-peerdependencies-are-incorrectly-hoisted/4794),\n// so we need to tell virtual-tsc where TypeScript is\nsetTypeScriptResolveOptions({\n paths: [require.resolve('typescript')],\n});\n\n// compiler instance for global JS declarations\nconst jsDeclarationServer: Server = new Server(jsDeclarationCompilerOptions, isCI ? false : undefined);\n/**\n * Stores the IDs of script objects whose change should be ignored because\n * the compiled source was just updated\n */\n\nfunction httpStatusText(code: number): string {\n const texts: Record = {\n 400: 'Bad Request',\n 401: 'Unauthorized',\n 403: 'Forbidden',\n 404: 'Not Found',\n 429: 'Too Many Requests / Rate Limit',\n 500: 'Internal Server Error',\n 502: 'Bad Gateway',\n 503: 'Service Unavailable',\n };\n return texts[code] || `Error ${code}`;\n}\n\nclass JavaScript extends Adapter {\n declare public config: JavaScriptAdapterConfig;\n\n private readonly context: JavascriptContext;\n\n private errorLogFunction: {\n error: (msg: string) => void;\n warn: (msg: string) => void;\n info: (msg: string) => void;\n debug: (msg: string) => void;\n silly: (msg: string) => void;\n } = {\n error: (msg: string) => console.error(msg),\n warn: (msg: string) => console.warn(msg),\n info: (msg: string) => console.log(msg),\n debug: (msg: string) => console.debug(msg),\n silly: (msg: string) => console.debug(msg),\n };\n\n private readonly mods: MODULES;\n\n private objectsInitDone = false;\n private statesInitDone = false;\n\n private objects: Record = {};\n private states: Record = {};\n private readonly interimStateValues: Record = {};\n private readonly stateIds: string[] = [];\n private readonly subscriptions: SubscriptionResult[] = [];\n private readonly subscriptionsFile: FileSubscriptionResult[] = [];\n private readonly subscriptionsObject: SubscribeObject[] = [];\n private readonly subscribedPatterns: Record = {};\n private readonly subscribedPatternsFile: Record = {};\n private readonly adapterSubs: Record = {};\n private readonly timers: { [scriptName: string]: JavascriptTimer[] } = {};\n private readonly _enums: string[] = [];\n private readonly names: { [name: string]: string | string[] } = {}; // name: id\n private readonly scripts: Record = {};\n private password: string = '';\n private readonly messageBusHandlers: Record<\n string,\n Record void }[]>\n > = {};\n private readonly logSubscriptions: Record<\n string,\n {\n sandbox: SandboxType;\n cb: (info: LogMessage) => void;\n id: number;\n severity: ioBroker.LogLevel | '*';\n }[]\n > = {};\n private readonly tempDirectories: { [scriptName: string]: string } = {}; // name: path\n private readonly folderCreationVerifiedObjects: Record = {};\n\n /** if logs are subscribed or not */\n private logSubscribed = false;\n\n private timeSettings: {\n format12: boolean;\n leadingZeros: boolean;\n } = { format12: false, leadingZeros: true };\n\n private dayScheduleTimer: NodeJS.Timeout | null = null; // schedule for astrological day\n private sunScheduleTimer: NodeJS.Timeout | null = null; // schedule for sun moment times\n private timeScheduleTimer: NodeJS.Timeout | null = null; // schedule for astrological day\n\n private activeStr = ''; // enabled state prefix\n\n private mirror: Mirror | undefined;\n\n private stopCounters: Record = {};\n\n private setStateCountCheckInterval: NodeJS.Timeout | null = null;\n\n private globalScript = '';\n /** Generated declarations for global TypeScripts */\n private globalDeclarations = '';\n // Remember which definitions the global scripts\n // have access to, because it depends on the compilation order\n private knownGlobalDeclarationsByScript: Record = {};\n private globalScriptLines = 0;\n // compiler instance for typescript\n private tsServer: Server;\n\n private readonly ignoreObjectChange: Set = new Set();\n\n private debugState: DebugState = {\n scriptName: '',\n child: null,\n promiseOnEnd: null,\n paused: false,\n started: 0,\n running: false,\n };\n\n constructor(options: Partial = {}) {\n options = {\n ...options,\n name: 'javascript', // adapter name\n useFormatDate: true,\n /**\n * If the JS-Controller catches an unhandled error, this will be called,\n * so we have a chance to handle it ourselves.\n */\n error: (err: Error): boolean => {\n // Identify unhandled errors originating from callbacks in scripts\n // These are not caught by wrapping the execution code in try-catch\n if (err && typeof err.stack === 'string') {\n const scriptCodeMarkerIndex = err.stack.indexOf(SCRIPT_CODE_MARKER);\n if (scriptCodeMarkerIndex > -1) {\n // This is a script error\n let scriptName = err.stack.substring(scriptCodeMarkerIndex);\n scriptName = scriptName.substring(0, scriptName.indexOf(':'));\n this.logError(scriptName, 'Error:', err);\n\n // Leave the script running for now\n // signal to the JS-Controller that we handled the error ourselves\n return true;\n }\n // check if a path contains adaptername but not own node_module\n // this regex matched \"iobroker.javascript/\" if NOT followed by \"node_modules\"\n if (!err.stack.match(/iobroker\\.javascript[/\\\\](?!.*node_modules).*/g)) {\n // This is an error without any info on origin (mostly async errors like connection errors)\n // also consider it as being from a script\n this.log.error(\n 'An error happened which is most likely from one of your scripts, but the originating script could not be detected.',\n );\n this.log.error(`Error: ${err.message}`);\n this.log.error(err.stack);\n\n // signal to the JS-Controller that we handled the error ourselves\n return true;\n }\n }\n\n return false;\n },\n };\n\n super(options as AdapterOptions);\n\n this.on('objectChange', this.onObjectChange.bind(this));\n this.on('stateChange', this.onStateChange.bind(this));\n this.on('ready', this.onReady.bind(this));\n this.on('message', this.onMessage.bind(this));\n this.on('unload', this.onUnload.bind(this));\n this.on('fileChange', this.onFileChange.bind(this));\n this.on('log', this.onLog.bind(this));\n\n this.mods = {\n fs: {} as ProtectFs,\n 'fs/promises': {} as ProtectFs['promises'],\n dgram,\n crypto,\n dns,\n events,\n http,\n https,\n http2,\n net,\n os,\n path,\n util,\n child_process,\n stream,\n zlib,\n\n suncalc,\n axios,\n wake_on_lan,\n nodeSchedule,\n };\n\n // check the webstorm debug and just debug modes\n let debugMode: string | undefined;\n if (process.argv) {\n for (let a = 1; a < process.argv.length; a++) {\n if (process.argv[a].startsWith('--webstorm')) {\n webstormDebug = process.argv[a].replace(/^(.*?=\\s*)/, '');\n }\n if (process.argv[a] === '--debugScript') {\n if (!process.argv[a + 1]) {\n console.log('No script name provided');\n process.exit(300);\n } else {\n debugMode = process.argv[a + 1];\n }\n }\n }\n }\n\n this.context = {\n mods: this.mods,\n objects: this.objects,\n states: this.states,\n interimStateValues: this.interimStateValues,\n stateIds: this.stateIds,\n errorLogFunction: this.errorLogFunction,\n subscriptions: this.subscriptions,\n subscriptionsFile: this.subscriptionsFile,\n subscriptionsObject: this.subscriptionsObject,\n subscribedPatterns: this.subscribedPatterns,\n subscribedPatternsFile: this.subscribedPatternsFile,\n adapterSubs: this.adapterSubs,\n cacheObjectEnums: {},\n timers: this.timers,\n enums: this._enums,\n names: this.names,\n scripts: this.scripts,\n messageBusHandlers: this.messageBusHandlers,\n logSubscriptions: this.logSubscriptions,\n tempDirectories: this.tempDirectories,\n folderCreationVerifiedObjects: this.folderCreationVerifiedObjects,\n\n isEnums: false, // If some subscription wants enum\n channels: null,\n devices: null,\n logWithLineInfo: this.logWithLineInfo.bind(this),\n scheduler: null,\n timerId: 0,\n rulesOpened: null, // opened rules\n language: this.language || 'en',\n\n updateLogSubscriptions: this.updateLogSubscriptions.bind(this),\n convertBackStringifiedValues: this.convertBackStringifiedValues.bind(this),\n updateObjectContext: this.updateObjectContext.bind(this),\n prepareStateObject: this.prepareStateObject.bind(this),\n debugMode,\n getAbsoluteDefaultDataDir,\n adapter: this as unknown as ioBroker.Adapter,\n logError: this.logError.bind(this),\n allowSelfSignedCerts: false,\n };\n\n this.tsServer = new Server(tsCompilerOptions, this.tsLog);\n }\n\n async onObjectChange(id: string, obj?: ioBroker.Object | null): Promise {\n // Check if we should ignore this change (once!) because we just updated the compiled sources\n if (this.ignoreObjectChange.has(id)) {\n // Update the cached script object and do nothing more\n this.objects[id] = obj as ioBroker.Object;\n this.ignoreObjectChange.delete(id);\n return;\n }\n\n // When still in initializing: already remember current values,\n // but data structures are initialized elsewhere\n if (!this.objectsInitDone) {\n if (obj) {\n this.objects[id] = obj;\n }\n return;\n }\n\n if (id.startsWith('enum.')) {\n // clear cache\n this.context.cacheObjectEnums = {};\n\n // update this._enums array\n if (obj) {\n // If new\n if (!this._enums.includes(id)) {\n this._enums.push(id);\n this._enums.sort();\n }\n } else {\n const pos = this._enums.indexOf(id);\n // if deleted\n if (pos !== -1) {\n this._enums.splice(pos, 1);\n }\n }\n }\n\n if (id === 'system.config' && obj?.common?.language) {\n // set language for debug messages\n setLanguage(obj.common.language);\n this.language = obj.common.language;\n this.context.language = this.language as ioBroker.Languages;\n }\n\n // update stored time format for variables.dayTime\n if (id === `${this.namespace}.variables.dayTime` && obj?.native) {\n this.timeSettings.format12 = obj.native.format12 || false;\n this.timeSettings.leadingZeros = obj.native.leadingZeros === undefined ? true : obj.native.leadingZeros;\n }\n\n // send changes to the disk mirror\n this.mirror?.onObjectChange(id, obj as ioBroker.ScriptObject | null);\n\n const formerObj = this.objects[id];\n\n this.updateObjectContext(id, obj); // Update all Meta object data\n\n // for the alias object changes on the state objects, we need to manually update the\n // state cache value, because the new value is only published on the next change\n if (obj?.type === 'state' && id.startsWith('alias.0.')) {\n // execute async for speed\n this.getForeignStateAsync(id)\n .then(state => {\n if (state) {\n this.states[id] = state;\n } else if (this.states[id] !== undefined) {\n delete this.states[id];\n }\n })\n .catch(() => {\n /* ignore */\n });\n }\n\n this.subscriptionsObject.forEach(sub => {\n // ToDo: implement comparing with id.0.* too\n if (sub.pattern === id) {\n try {\n sub.callback(id, obj);\n } catch (err: any) {\n this.log.error(`Error in callback: ${err.toString()}`);\n }\n }\n });\n\n // handle Script object updates\n if (!obj && formerObj?.type === 'script') {\n // Object Deleted just now\n if (checkIsGlobal(formerObj)) {\n // it was a global Script, and it was enabled and is now deleted => restart adapter\n if (formerObj.common.enabled) {\n this.log.info(`Active global Script ${id} deleted. Restart instance.`);\n this.restart();\n }\n } else if (formerObj.common?.engine === `system.adapter.${this.namespace}`) {\n // It was a non-global Script and deleted => stop and remove it\n await this.stopScript(id);\n\n // delete scriptEnabled.blabla variable\n const idActive = `scriptEnabled.${id.substring(SCRIPT_CODE_MARKER.length)}`;\n await this.delStateAsync(idActive);\n await this.delObjectAsync(idActive);\n\n // delete scriptProblem.blabla variable\n const idProblem = `scriptProblem.${id.substring(SCRIPT_CODE_MARKER.length)}`;\n await this.delStateAsync(idProblem);\n await this.delObjectAsync(idProblem);\n }\n } else if (!formerObj && obj?.type === 'script') {\n // New script that does not exist before\n if (checkIsGlobal(obj)) {\n // new global script added => restart adapter\n if (obj.common.enabled) {\n this.log.info(`Active global Script ${id} created. Restart instance.`);\n this.restart();\n }\n } else if (obj.common?.engine === `system.adapter.${this.namespace}`) {\n // new non-global script - create states for scripts\n await this.createActiveObject(id, !!obj.common.enabled);\n await this.createProblemObject(id);\n if (obj.common.enabled) {\n // if enabled => Start a script\n await this.loadScriptById(id);\n }\n }\n } else if (obj?.type === 'script' && formerObj?.common) {\n // Script changed ...\n if (checkIsGlobal(obj)) {\n if (obj.common.enabled || formerObj.common.enabled) {\n this.log.info(`Global Script ${id} updated. Restart instance.`);\n this.restart();\n }\n } else {\n // No global script\n if (obj.common?.engine === `system.adapter.${this.namespace}`) {\n // create states for scripts\n await this.createActiveObject(id, !!obj.common.enabled);\n await this.createProblemObject(id);\n }\n\n if (\n (formerObj.common.enabled && !obj.common.enabled) ||\n (formerObj.common.engine === `system.adapter.${this.namespace}` &&\n obj.common.engine !== `system.adapter.${this.namespace}`)\n ) {\n // Script disabled\n if (formerObj.common.enabled && formerObj.common.engine === `system.adapter.${this.namespace}`) {\n // Remove it from executing\n await this.stopScript(id);\n }\n } else if (\n (!formerObj.common.enabled && obj.common.enabled) ||\n (formerObj.common.engine !== `system.adapter.${this.namespace}` &&\n obj.common.engine === `system.adapter.${this.namespace}`)\n ) {\n // Script enabled\n\n if (obj.common.enabled && obj.common.engine === `system.adapter.${this.namespace}`) {\n // Start script\n await this.loadScriptById(id);\n }\n } else {\n // if (obj.common.source !== formerObj.common.source) {\n // Source changed => restart the script\n this.stopCounters[id] = this.stopCounters[id] ? this.stopCounters[id] + 1 : 1;\n void this.stopScript(id).then(() => {\n // only start again after stop when \"last\" object change to prevent problems on\n // multiple changes in fast frequency\n if (!--this.stopCounters[id]) {\n void this.loadScriptById(id);\n }\n });\n }\n }\n }\n }\n\n onStateChange(id: string, state?: ioBroker.State | null): void {\n if (this.interimStateValues[id] !== undefined) {\n // any update invalidates the remembered interim value\n delete this.interimStateValues[id];\n }\n if (!id || id.startsWith('messagebox.') || id.startsWith('log.')) {\n return;\n }\n\n if (id === `${this.namespace}.debug.to` && state && !state.ack) {\n if (!this.context.debugMode) {\n this.debugSendToInspector(state.val);\n }\n return;\n }\n\n // When still in initializing: already remember current values,\n // but data structures are initialized elsewhere\n if (!this.statesInitDone) {\n if (state) {\n this.states[id] = state;\n }\n return;\n }\n\n const oldState: ioBroker.State | null | undefined = this.states[id];\n if (state) {\n if (oldState) {\n // enable or disable script\n if (!state.ack && id.startsWith(this.activeStr) && this.objects[id]?.native?.script) {\n void this.extendForeignObject(this.objects[id].native.script, {\n common: { enabled: state.val },\n });\n }\n\n // monitor if the adapter is alive and send all subscriptions once more, after the adapter goes online\n if (/*oldState && */ oldState.val === false && state.val && id.endsWith('.alive')) {\n if (this.adapterSubs[id]) {\n const parts = id.split('.');\n const a = `${parts[2]}.${parts[3]}`;\n for (let t = 0; t < this.adapterSubs[id].length; t++) {\n this.log.info(`Detected coming adapter \"${a}\". Send subscribe: ${this.adapterSubs[id][t]}`);\n this.sendTo(a, 'subscribe', this.adapterSubs[id][t]);\n }\n }\n }\n } else if (/*!oldState && */ !this.stateIds.includes(id)) {\n this.stateIds.push(id);\n this.stateIds.sort();\n }\n this.states[id] = state;\n } else {\n if (oldState) {\n delete this.states[id];\n }\n state = {} as ioBroker.State;\n const pos = this.stateIds.indexOf(id);\n if (pos !== -1) {\n this.stateIds.splice(pos, 1);\n }\n }\n const _eventObj = createEventObject(\n this.context,\n id,\n this.convertBackStringifiedValues(id, state),\n this.convertBackStringifiedValues(id, oldState),\n );\n\n // if this state matches any subscriptions\n for (let i = 0, l = this.subscriptions.length; i < l; i++) {\n const sub = this.subscriptions[i];\n if (sub?.patternCompareFunctions && patternMatching(_eventObj, sub.patternCompareFunctions)) {\n try {\n sub.callback(_eventObj);\n } catch (err: any) {\n this.log.error(`Error in callback: ${err.toString()}`);\n }\n }\n }\n }\n\n onFileChange(id: string, fileName: string, size: number | null): void {\n // if this file matches any subscriptions\n for (let i = 0, l = this.subscriptionsFile.length; i < l; i++) {\n const sub = this.subscriptionsFile[i];\n if (sub && fileMatching(sub, id, fileName)) {\n try {\n sub.callback(id, fileName, size, sub.withFile);\n } catch (err: any) {\n this.log.error(`Error in callback: ${err.toString()}`);\n }\n }\n }\n }\n\n async onUnload(callback: () => void): Promise {\n await this.debugStop();\n this.stopTimeSchedules();\n if (this.setStateCountCheckInterval) {\n clearInterval(this.setStateCountCheckInterval);\n this.setStateCountCheckInterval = null;\n }\n await this.stopAllScripts();\n if (typeof callback === 'function') {\n callback();\n }\n }\n\n async onReady(): Promise {\n this.errorLogFunction = this.log;\n this.context.errorLogFunction = this.log;\n\n this.config.maxSetStatePerMinute = parseInt(this.config.maxSetStatePerMinute as unknown as string, 10) || 1000;\n this.config.maxTriggersPerScript = parseInt(this.config.maxTriggersPerScript as unknown as string, 10) || 100;\n\n if (this.supportsFeature?.('PLUGINS')) {\n const sentryInstance: InstanceType = this.getPluginInstance('sentry') as InstanceType<\n typeof SentryPlugin\n >;\n if (sentryInstance) {\n const Sentry = sentryInstance.getSentryObject();\n Sentry?.withScope(scope => {\n scope.addEventProcessor((event, _hint) => {\n if (event.exception?.values?.[0]) {\n const eventData = event.exception.values[0];\n if (\n eventData.stacktrace?.frames &&\n Array.isArray(eventData.stacktrace.frames) &&\n eventData.stacktrace.frames.length\n ) {\n // Exclude event if script Marker is included\n if (\n eventData.stacktrace.frames.find(frame =>\n frame.filename?.includes(SCRIPT_CODE_MARKER),\n )\n ) {\n return null;\n }\n // Exclude event if own directory is included but not inside own node_modules\n const ownNodeModulesDir = join(__dirname, 'node_modules');\n if (\n !eventData.stacktrace.frames.find(\n frame =>\n frame.filename?.includes(__dirname) &&\n !frame.filename.includes(ownNodeModulesDir),\n )\n ) {\n return null;\n }\n // We have exception data and did not sort it out, so report it\n return event;\n }\n }\n\n // No exception in it ... do not report\n return null;\n });\n });\n }\n }\n\n await this.main();\n }\n\n onMessage(obj: ioBroker.Message): void {\n switch (obj?.command) {\n // process messageTo commands\n case 'toScript':\n case 'jsMessageBus':\n if (\n obj.message &&\n (obj.message.instance === null ||\n obj.message.instance === undefined ||\n `javascript.${obj.message.instance}` === this.namespace ||\n obj.message.instance === this.namespace)\n ) {\n Object.keys(this.messageBusHandlers).forEach(name => {\n // the script name could be script.js.xxx or only xxx\n if (\n (!obj.message.script || obj.message.script === name) &&\n this.messageBusHandlers[name][obj.message.message]\n ) {\n this.messageBusHandlers[name][obj.message.message].forEach(handler => {\n const sandbox = handler.sandbox;\n\n sandbox.verbose && sandbox.log(`onMessage: ${JSON.stringify(obj.message)}`, 'info');\n\n try {\n if (obj.callback) {\n handler.cb.call(sandbox, obj.message.data, (result: any) => {\n if (sandbox.verbose) {\n sandbox.log(`onMessage result: ${JSON.stringify(result)}`, 'info');\n }\n\n this.sendTo(obj.from, obj.command, result, obj.callback);\n });\n } else {\n handler.cb.call(sandbox, obj.message.data, (result: any) => {\n sandbox.verbose &&\n sandbox.log(`onMessage result: ${JSON.stringify(result)}`, 'info');\n });\n }\n } catch (err: unknown) {\n void this.setState(\n `scriptProblem.${name.substring(SCRIPT_CODE_MARKER.length)}`,\n true,\n true,\n );\n this.logError(name, 'Error in callback:', err as Error);\n }\n });\n }\n });\n }\n break;\n\n case 'loadTypings': {\n // Load typings for the editor\n const typings: Record = {};\n\n // try to load TypeScript lib files from disk\n try {\n const typescriptLibs = resolveTypescriptLibs(targetTsLib);\n Object.assign(typings, typescriptLibs);\n } catch {\n /* ok, no lib then */\n }\n\n // provide the already-loaded ioBroker typings and global script declarations\n Object.assign(typings, tsAmbient);\n\n // also provide the known global declarations for each global script\n for (const globalScriptPaths of Object.keys(this.knownGlobalDeclarationsByScript)) {\n typings[`${globalScriptPaths}.d.ts`] = this.knownGlobalDeclarationsByScript[globalScriptPaths];\n }\n\n if (obj.callback) {\n this.sendTo(obj.from, obj.command, { typings }, obj.callback);\n }\n break;\n }\n\n case 'calcAstroAll': {\n if (obj.message) {\n const sunriseOffset =\n parseInt(\n obj.message.sunriseOffset === undefined\n ? this.config.sunriseOffset\n : obj.message.sunriseOffset,\n 10,\n ) || 0;\n const sunsetOffset =\n parseInt(\n obj.message.sunsetOffset === undefined\n ? this.config.sunsetOffset\n : obj.message.sunsetOffset,\n 10,\n ) || 0;\n const longitude =\n parseFloat(\n obj.message.longitude === undefined ? this.config.longitude : obj.message.longitude,\n ) || 0;\n const latitude =\n parseFloat(obj.message.latitude === undefined ? this.config.latitude : obj.message.latitude) ||\n 0;\n const today = getAstroStartOfDay();\n let astroEvents: GetTimesResult & { nextSunrise: Date; nextSunset: Date } = {} as GetTimesResult & {\n nextSunrise: Date;\n nextSunset: Date;\n };\n try {\n astroEvents = this.mods.suncalc.getTimes(today, latitude, longitude);\n } catch (err: unknown) {\n this.log.error(`Cannot calculate astro data: ${err as Error}`);\n }\n if (astroEvents) {\n try {\n astroEvents.nextSunrise = this.getAstroEvent(\n today,\n obj.message.sunriseEvent || this.config.sunriseEvent,\n obj.message.sunriseLimitStart || this.config.sunriseLimitStart,\n obj.message.sunriseLimitEnd || this.config.sunriseLimitEnd,\n sunriseOffset,\n false,\n latitude,\n longitude,\n true,\n );\n astroEvents.nextSunset = this.getAstroEvent(\n today,\n obj.message.sunsetEvent || this.config.sunsetEvent,\n obj.message.sunsetLimitStart || this.config.sunsetLimitStart,\n obj.message.sunsetLimitEnd || this.config.sunsetLimitEnd,\n sunsetOffset,\n true,\n latitude,\n longitude,\n true,\n );\n } catch (err: unknown) {\n this.log.error(`Cannot calculate astro data: ${err as Error}`);\n }\n }\n\n const result: Record = {};\n const keys = Object.keys(astroEvents).sort(\n (a, b) =>\n (astroEvents as unknown as Record)[a] -\n (astroEvents as unknown as Record)[b],\n );\n keys.forEach(key => {\n const validDate =\n (astroEvents as unknown as Record)[key] !== null &&\n !isNaN((astroEvents as unknown as Record)[key].getTime());\n\n result[key] = {\n isValidDate: validDate,\n serverTime: validDate\n ? formatHoursMinutesSeconds((astroEvents as unknown as Record)[key])\n : 'n/a',\n date: validDate\n ? (astroEvents as unknown as Record)[key].toISOString()\n : 'n/a',\n };\n });\n\n if (obj.callback) {\n this.sendTo(obj.from, obj.command, result, obj.callback);\n }\n }\n break;\n }\n\n case 'calcAstro': {\n if (obj.message) {\n const longitude =\n parseFloat(\n obj.message.longitude === undefined ? this.config.longitude : obj.message.longitude,\n ) || 0;\n const latitude =\n parseFloat(obj.message.latitude === undefined ? this.config.latitude : obj.message.latitude) ||\n 0;\n const today = getAstroStartOfDay();\n\n const sunriseEvent = obj.message?.sunriseEvent || this.config.sunriseEvent;\n const sunriseLimitStart = obj.message?.sunriseLimitStart || this.config.sunriseLimitStart;\n const sunriseLimitEnd = obj.message?.sunriseLimitEnd || this.config.sunriseLimitEnd;\n const sunriseOffset =\n parseInt(\n obj.message.sunriseOffset === undefined\n ? this.config.sunriseOffset\n : obj.message.sunriseOffset,\n 10,\n ) || 0;\n const nextSunrise = this.getAstroEvent(\n today,\n sunriseEvent,\n sunriseLimitStart,\n sunriseLimitEnd,\n sunriseOffset,\n false,\n latitude,\n longitude,\n true,\n );\n\n const sunsetEvent = obj.message?.sunsetEvent || this.config.sunsetEvent;\n const sunsetLimitStart = obj.message?.sunsetLimitStart || this.config.sunsetLimitStart;\n const sunsetLimitEnd = obj.message?.sunsetLimitEnd || this.config.sunsetLimitEnd;\n const sunsetOffset =\n parseInt(\n obj.message.sunsetOffset === undefined\n ? this.config.sunsetOffset\n : obj.message.sunsetOffset,\n 10,\n ) || 0;\n const nextSunset = this.getAstroEvent(\n today,\n sunsetEvent,\n sunsetLimitStart,\n sunsetLimitEnd,\n sunsetOffset,\n true,\n latitude,\n longitude,\n true,\n );\n\n const validDateSunrise = nextSunrise !== null && !isNaN(nextSunrise.getTime());\n const validDateSunset = nextSunset !== null && !isNaN(nextSunset.getTime());\n\n this.log.debug(\n `calcAstro sunrise: ${sunriseEvent} -> start ${sunriseLimitStart}, end: ${sunriseLimitEnd}, offset: ${sunriseOffset} - ${validDateSunrise ? nextSunrise.toISOString() : 'n/a'}`,\n );\n this.log.debug(\n `calcAstro sunset: ${sunsetEvent} -> start ${sunsetLimitStart}, end: ${sunsetLimitEnd}, offset: ${sunsetOffset} - ${validDateSunset ? nextSunset.toISOString() : 'n/a'}`,\n );\n\n if (obj.callback) {\n this.sendTo(\n obj.from,\n obj.command,\n {\n nextSunrise: {\n isValidDate: validDateSunrise,\n serverTime: validDateSunrise ? formatHoursMinutesSeconds(nextSunrise) : 'n/a',\n date: nextSunrise.toISOString(),\n },\n nextSunset: {\n isValidDate: validDateSunset,\n serverTime: validDateSunset ? formatHoursMinutesSeconds(nextSunset) : 'n/a',\n date: nextSunset.toISOString(),\n },\n },\n obj.callback,\n );\n }\n }\n break;\n }\n\n case 'debug': {\n if (!this.context.debugMode) {\n this.debugStart(obj.message);\n }\n break;\n }\n\n case 'debugStop': {\n if (!this.context.debugMode) {\n void this.debugStop().then(() => console.log('stopped'));\n }\n break;\n }\n\n case 'rulesOn': {\n this.context.rulesOpened = obj.message;\n console.log(`Enable messaging for ${this.context.rulesOpened}`);\n break;\n }\n\n case 'rulesOff': {\n // maybe if (context.rulesOpened === obj.message)\n console.log(`Disable messaging for ${this.context.rulesOpened}`);\n this.context.rulesOpened = null;\n break;\n }\n\n case 'getIoBrokerDataDir': {\n if (obj.callback) {\n this.sendTo(\n obj.from,\n obj.command,\n {\n dataDir: getAbsoluteDefaultDataDir(),\n sep,\n },\n obj.callback,\n );\n }\n break;\n }\n\n case 'chatCompletion': {\n // Proxy chat completion requests to an OpenAI-compatible API endpoint\n if (obj.callback) {\n const baseUrl = (obj.message?.baseUrl || '').trim();\n const apiKey = (obj.message?.apiKey || '').trim();\n const chatModel = (obj.message?.model || '').trim();\n const messages = obj.message?.messages;\n const provider = (obj.message?.provider || 'openai').trim();\n // Anthropic, Gemini, and DeepSeek always require an API key; OpenAI-compatible allows empty key with custom base URL\n if (\n !apiKey &&\n (provider === 'anthropic' || provider === 'gemini' || provider === 'deepseek' || !baseUrl)\n ) {\n this.sendTo(obj.from, obj.command, { error: 'No API key provided' }, obj.callback);\n break;\n }\n if (!chatModel || !messages) {\n this.sendTo(obj.from, obj.command, { error: 'Model and messages are required' }, obj.callback);\n break;\n }\n\n let url: string;\n const chatHeaders: Record = {\n 'Content-Type': 'application/json',\n };\n let bodyObj: Record;\n\n if (provider === 'anthropic') {\n url = 'https://api.anthropic.com/v1/messages';\n chatHeaders['x-api-key'] = apiKey;\n chatHeaders['anthropic-version'] = '2023-06-01';\n const systemMessages = messages.filter((m: { role: string }) => m.role === 'system');\n const nonSystemMessages = messages.filter((m: { role: string }) => m.role !== 'system');\n const systemText = systemMessages.map((m: { content: string }) => m.content).join('\\n\\n');\n bodyObj = {\n model: chatModel,\n max_tokens: 8192,\n stream: false,\n ...(systemText ? { system: systemText } : {}),\n messages: nonSystemMessages,\n };\n } else if (provider === 'gemini') {\n url = 'https://generativelanguage.googleapis.com/v1beta/openai/chat/completions';\n if (apiKey) {\n chatHeaders.Authorization = `Bearer ${apiKey}`;\n }\n bodyObj = { model: chatModel, messages, stream: false };\n } else if (provider === 'deepseek') {\n url = 'https://api.deepseek.com/chat/completions';\n chatHeaders.Authorization = `Bearer ${apiKey}`;\n bodyObj = { model: chatModel, messages, stream: false };\n } else {\n url = `${baseUrl || 'https://api.openai.com/v1'}/chat/completions`;\n if (apiKey) {\n chatHeaders.Authorization = `Bearer ${apiKey}`;\n }\n bodyObj = {\n model: chatModel,\n messages,\n stream: false,\n // Disable thinking/reasoning for local models to save context and speed\n ...(baseUrl ? { reasoning_effort: 'none' } : {}),\n };\n }\n\n const body = JSON.stringify(bodyObj);\n const bodyBuffer = Buffer.from(body, 'utf8');\n chatHeaders['Content-Length'] = bodyBuffer.length;\n\n let urlObj: URL;\n try {\n urlObj = new URL(url);\n } catch {\n this.sendTo(obj.from, obj.command, { error: `Invalid API URL: ${url}` }, obj.callback);\n break;\n }\n const isHttps = urlObj.protocol === 'https:';\n const requestModule = isHttps ? https : http;\n\n const req = requestModule.request(\n url,\n {\n method: 'POST',\n headers: chatHeaders,\n timeout: 600000,\n ...(isHttps && this.config.allowSelfSignedCerts ? { rejectUnauthorized: false } : {}),\n },\n res => {\n let data = '';\n res.on('data', (chunk: Buffer) => {\n data += chunk.toString();\n });\n res.on('end', () => {\n if (res.statusCode === 200) {\n try {\n const parsed = JSON.parse(data);\n const content =\n provider === 'anthropic'\n ? parsed.content?.[0]?.text || ''\n : parsed.choices?.[0]?.message?.content || '';\n if (!content) {\n this.sendTo(\n obj.from,\n obj.command,\n { error: 'Empty response from API' },\n obj.callback,\n );\n } else {\n this.sendTo(\n obj.from,\n obj.command,\n { success: true, content },\n obj.callback,\n );\n }\n } catch {\n this.sendTo(\n obj.from,\n obj.command,\n { error: 'Invalid JSON response from API' },\n obj.callback,\n );\n }\n } else {\n let detail = '';\n try {\n const errParsed = JSON.parse(data);\n detail = errParsed.error?.message || data.substring(0, 200);\n } catch {\n detail = data.substring(0, 200);\n }\n this.sendTo(\n obj.from,\n obj.command,\n {\n error: `${detail || httpStatusText(res.statusCode || 0)} (${res.statusCode})`,\n },\n obj.callback,\n );\n }\n });\n },\n );\n\n req.on('error', (err: Error) => {\n this.sendTo(\n obj.from,\n obj.command,\n { error: `Connection failed: ${err.message}` },\n obj.callback,\n );\n });\n\n req.on('timeout', () => {\n req.destroy();\n this.sendTo(obj.from, obj.command, { error: 'Connection timeout (600s)' }, obj.callback);\n });\n\n req.write(bodyBuffer);\n req.end();\n }\n break;\n }\n\n case 'testApiConnection': {\n // Test connection to an OpenAI-compatible API endpoint\n if (obj.callback) {\n const baseUrl = (obj.message?.baseUrl || '').trim();\n const apiKey = (obj.message?.apiKey || '').trim();\n const provider = (obj.message?.provider || 'openai').trim();\n // Anthropic, Gemini, and DeepSeek always require an API key; OpenAI-compatible allows empty key with custom base URL\n if (\n !apiKey &&\n (provider === 'anthropic' || provider === 'gemini' || provider === 'deepseek' || !baseUrl)\n ) {\n this.sendTo(obj.from, obj.command, { error: 'No API key provided' }, obj.callback);\n break;\n }\n\n let url: string;\n const testHeaders: Record = {\n 'Content-Type': 'application/json',\n };\n\n if (provider === 'anthropic') {\n url = 'https://api.anthropic.com/v1/models';\n testHeaders['x-api-key'] = apiKey;\n testHeaders['anthropic-version'] = '2023-06-01';\n } else if (provider === 'gemini') {\n url = 'https://generativelanguage.googleapis.com/v1beta/openai/models';\n if (apiKey) {\n testHeaders.Authorization = `Bearer ${apiKey}`;\n }\n } else if (provider === 'deepseek') {\n url = 'https://api.deepseek.com/models';\n testHeaders.Authorization = `Bearer ${apiKey}`;\n } else {\n url = `${baseUrl || 'https://api.openai.com/v1'}/models`;\n if (apiKey) {\n testHeaders.Authorization = `Bearer ${apiKey}`;\n }\n }\n\n let urlObj: URL;\n try {\n urlObj = new URL(url);\n } catch {\n this.sendTo(obj.from, obj.command, { error: `Invalid API URL: ${url}` }, obj.callback);\n break;\n }\n const isHttps = urlObj.protocol === 'https:';\n const requestModule = isHttps ? https : http;\n\n const req = requestModule.request(\n url,\n {\n method: 'GET',\n headers: testHeaders,\n timeout: 10000,\n ...(isHttps && this.config.allowSelfSignedCerts ? { rejectUnauthorized: false } : {}),\n },\n res => {\n let data = '';\n res.on('data', (chunk: Buffer) => {\n data += chunk.toString();\n });\n res.on('end', () => {\n if (res.statusCode === 200) {\n try {\n const parsed = JSON.parse(data);\n const models: string[] = (parsed.data || [])\n .map((m: { id: string }) =>\n m.id.startsWith('models/') ? m.id.substring(7) : m.id,\n )\n .sort();\n this.sendTo(\n obj.from,\n obj.command,\n { success: true, models, count: models.length },\n obj.callback,\n );\n } catch {\n this.sendTo(\n obj.from,\n obj.command,\n { error: 'Invalid JSON response from API' },\n obj.callback,\n );\n }\n } else if (res.statusCode === 401) {\n this.sendTo(\n obj.from,\n obj.command,\n { error: 'Invalid API key (401)' },\n obj.callback,\n );\n } else if (res.statusCode === 403) {\n this.sendTo(obj.from, obj.command, { error: 'Access denied (403)' }, obj.callback);\n } else {\n // Include response body for debugging\n let detail = '';\n try {\n const errParsed = JSON.parse(data);\n detail = errParsed.error?.message || data.substring(0, 200);\n } catch {\n detail = data.substring(0, 200);\n }\n this.sendTo(\n obj.from,\n obj.command,\n {\n error: `${detail || httpStatusText(res.statusCode || 0)} (${res.statusCode})`,\n },\n obj.callback,\n );\n }\n });\n },\n );\n\n req.on('error', (err: Error) => {\n this.sendTo(\n obj.from,\n obj.command,\n { error: `Connection failed: ${err.message}` },\n obj.callback,\n );\n });\n\n req.on('timeout', () => {\n req.destroy();\n this.sendTo(obj.from, obj.command, { error: 'Connection timeout (10s)' }, obj.callback);\n });\n\n req.end();\n }\n break;\n }\n\n case 'prettier': {\n // Format the code with Prettier\n if (obj.message && typeof obj.message.code === 'string') {\n try {\n prettier\n .format(obj.message.code, {\n parser: obj.message.type === 'typescript' ? 'babel-ts' : 'babel',\n printWidth: 120,\n semi: true,\n tabWidth: 4,\n useTabs: false,\n trailingComma: 'all',\n singleQuote: true,\n singleAttributePerLine: true,\n endOfLine: 'lf',\n bracketSpacing: true,\n arrowParens: 'avoid',\n quoteProps: 'as-needed',\n })\n .then(formattedCode => {\n if (obj.callback) {\n this.sendTo(obj.from, obj.command, { code: formattedCode }, obj.callback);\n } else {\n this.logWithLineInfo(`Formatted code:\\n${formattedCode}`);\n }\n })\n .catch(e => {\n this.logError('Prettier', 'Error formatting code:', e as Error);\n this.sendTo(obj.from, obj.command, { error: (e as Error).toString() }, obj.callback);\n });\n } catch (e) {\n this.logError('Prettier', 'Error formatting code:', e as Error);\n this.sendTo(obj.from, obj.command, { error: (e as Error).toString() }, obj.callback);\n }\n } else {\n this.sendTo(obj.from, obj.command, { error: 'No code provided' }, obj.callback);\n }\n break;\n }\n }\n }\n\n onLog(msg: any): void {\n Object.keys(this.logSubscriptions).forEach((name: string): void =>\n this.logSubscriptions[name].forEach(handler => {\n if (\n typeof handler.cb === 'function' &&\n (handler.severity === '*' || handler.severity === msg.severity)\n ) {\n handler.sandbox.logHandler = handler.severity || '*';\n handler.cb.call(handler.sandbox, msg);\n handler.sandbox.logHandler = undefined;\n }\n }),\n );\n }\n\n logError(scriptName: string, msg: string, e: Error, offs?: number): void {\n const stack = e.stack ? e.stack.toString().split('\\n') : e ? e.toString() : '';\n if (!msg.includes('\\n')) {\n msg = msg.replace(/[: ]*$/, ': ');\n }\n if (!msg.endsWith(' ')) {\n msg += ':';\n }\n if (!scriptName.startsWith(SCRIPT_CODE_MARKER)) {\n scriptName = SCRIPT_CODE_MARKER + scriptName;\n }\n\n this.errorLogFunction.error(`${scriptName}: ${msg}${this.fixLineNo(stack[0])}`);\n for (let i = offs || 1; i < stack.length; i++) {\n if (!stack[i]) {\n continue;\n }\n if (stack[i].match(/runInNewContext|javascript\\.js:/)) {\n break;\n }\n this.errorLogFunction.error(`${scriptName}: ${this.fixLineNo(stack[i])}`);\n }\n }\n\n logWithLineInfo(msg: string): void {\n this.errorLogFunction.warn(msg);\n\n // get current error stack\n const stack = new Error().stack?.split('\\n');\n\n if (stack) {\n for (let i = 3; i < stack.length; i++) {\n if (!stack[i]) {\n continue;\n }\n if (stack[i].match(/runInContext|runInNewContext|javascript\\.js:/)) {\n break;\n }\n this.errorLogFunction.warn(this.fixLineNo(stack[i]));\n }\n }\n }\n\n async main(): Promise {\n // Patch the font as it sometimes is wrong\n if (!this.context.debugMode) {\n if (await this.patchFont()) {\n this.log.debug('Font patched');\n }\n }\n\n this.log.debug(`config.subscribe (Do not subscribe all states on start): ${this.config.subscribe}`);\n\n // correct jsonConfig for admin\n const instObj: ioBroker.InstanceObject | null | undefined = await this.getForeignObjectAsync(\n `system.adapter.${this.namespace}`,\n );\n if (instObj?.common) {\n if (instObj.common.adminUI?.config !== 'json') {\n if (instObj.common.adminUI) {\n instObj.common.adminUI.config = 'json';\n } else {\n instObj.common.adminUI = { config: 'json' };\n }\n void this.setForeignObject(instObj._id, instObj);\n }\n }\n\n if (webstormDebug) {\n this.errorLogFunction = {\n error: console.error,\n warn: console.warn,\n info: console.info,\n debug: console.log,\n silly: console.log,\n };\n this.context.errorLogFunction = this.errorLogFunction;\n }\n this.activeStr = `${this.namespace}.scriptEnabled.`;\n\n this.mods.fs = new ProtectFs(this.log, getAbsoluteDefaultDataDir());\n this.mods['fs/promises'] = this.mods.fs.promises; // to avoid require('fs/promises');\n\n // try to read TS declarations\n try {\n tsAmbient = {\n 'javascript.d.ts': readFileSync(this.mods.path.join(__dirname, 'lib/javascript.d.ts'), 'utf8'),\n };\n this.tsServer.provideAmbientDeclarations(tsAmbient);\n jsDeclarationServer.provideAmbientDeclarations(tsAmbient);\n } catch (err: unknown) {\n this.log.warn(`Could not read TypeScript ambient declarations: ${err as Error}`);\n // This should not happen, so send an error report to Sentry\n if (this.supportsFeature && this.supportsFeature('PLUGINS')) {\n const sentryInstance = this.getPluginInstance('sentry');\n if (sentryInstance) {\n const sentryObject = sentryInstance.getSentryObject();\n sentryObject?.captureException(err as Error);\n }\n }\n // Keep the adapter from crashing when the included typings cannot be read\n tsAmbient = {};\n }\n\n await this.installLibraries();\n // Load the TS declarations for Node.js and all 3rd party modules\n this.loadTypeScriptDeclarations();\n\n await this.getData();\n this.context.scheduler = new Scheduler(\n this.log,\n Date,\n this.mods.suncalc,\n this.config.latitude,\n this.config.longitude,\n );\n await this.dayTimeSchedules();\n await this.sunTimeSchedules();\n await this.timeSchedule();\n\n // Store allowSelfSignedCerts on the context, so sandbox HTTP functions can use it\n // without setting the global process.env.NODE_TLS_REJECT_UNAUTHORIZED (which affects all adapters in compact mode)\n this.context.allowSelfSignedCerts = this.config.allowSelfSignedCerts;\n\n const doc = await this.getObjectViewAsync('script', 'javascript', {});\n if (doc?.rows?.length) {\n // assemble global script\n for (let g = 0; g < doc.rows.length; g++) {\n const obj = doc.rows[g].value;\n if (checkIsGlobal(obj)) {\n if (obj && obj.common) {\n const engineType = (obj.common.engineType || '').toLowerCase();\n\n if (obj.common.enabled) {\n if (engineType.startsWith('typescript')) {\n // TypeScript\n this.log.info(`${obj._id}: compiling TypeScript source...`);\n // In order to compile global TypeScript, we need to do some transformations\n // 1. For top-level-await, some statements must be wrapped in an immediately-invoked async function\n // 2. If any global script uses `import`, the declarations are no longer visible if they are not exported with `declare global`\n const transformedSource = transformScriptBeforeCompilation(obj.common.source, true);\n // The source code must be transformed in order to support top level await\n // Global scripts must not be treated as a module, otherwise their methods\n // cannot be found by the normal scripts\n // We need to hash both global declarations that are known until now\n // AND the script source, because changing either can change the compilation output\n const sourceHash: string = hashSource(\n tsSourceHashBase + this.globalDeclarations + transformedSource,\n );\n\n let compiled: string | undefined;\n let declarations: string | undefined;\n // If we already stored the compiled source code and the original source hash,\n // use the hash to check whether we can rely on the compiled source code or\n // if we need to compile it again\n if (\n typeof obj.common.compiled === 'string' &&\n typeof obj.common.sourceHash === 'string' &&\n sourceHash === obj.common.sourceHash\n ) {\n // We can reuse the stored source\n compiled = obj.common.compiled;\n declarations = obj.common.declarations;\n this.log.info(\n `${obj._id}: source code did not change, using cached compilation result...`,\n );\n } else {\n // We don't have a hashed source code, or the original source changed, compile it\n const filename = scriptIdToTSFilename(obj._id);\n let tsCompiled: CompileResult;\n try {\n tsCompiled = this.tsServer.compile(filename, transformedSource);\n } catch (err: unknown) {\n this.log.error(`${obj._id}: TypeScript compilation failed:\\n${err as Error}`);\n continue;\n }\n\n const errors = tsCompiled.diagnostics\n .map(diag => `${diag.annotatedSource}\\n`)\n .join('\\n');\n\n if (tsCompiled.success) {\n if (errors.length > 0) {\n this.log.warn(\n `${obj._id}: TypeScript compilation completed with errors:\\n${errors}`,\n );\n } else {\n this.log.info(`${obj._id}: TypeScript compilation successful`);\n }\n compiled = tsCompiled.result;\n // Global scripts that have been transformed to support `import` need to have their declarations transformed aswell\n declarations = transformGlobalDeclarations(tsCompiled.declarations || '');\n\n const newCommon: {\n compiled: string | undefined;\n declarations?: string;\n sourceHash: string;\n } = {\n sourceHash,\n compiled,\n };\n if (declarations) {\n newCommon.declarations = declarations;\n }\n\n // Store the compiled source and the original source hash, so we don't need to do the work again next time\n this.ignoreObjectChange.add(obj._id); // ignore the next change and don't restart scripts\n void this.extendForeignObject(obj._id, {\n common: newCommon,\n });\n } else {\n this.log.error(`${obj._id}: TypeScript compilation failed:\\n${errors}`);\n continue;\n }\n }\n this.globalScript += `${compiled}\\n`;\n // if declarations were generated, remember them\n if (declarations != null) {\n this.provideDeclarationsForGlobalScript(obj._id, declarations);\n }\n } else {\n // javascript\n const sourceCode = obj.common.source;\n this.globalScript += `${sourceCode}\\n`;\n\n // try to compile the declarations so TypeScripts can use\n // functions defined in global JavaScripts\n const filename = scriptIdToTSFilename(obj._id);\n let tsCompiled: CompileResult;\n try {\n tsCompiled = jsDeclarationServer.compile(filename, sourceCode);\n } catch (err: unknown) {\n this.log.warn(\n `${obj._id}: Error while generating type declarations, skipping:\\n${err as Error}`,\n );\n continue;\n }\n // if declarations were generated, remember them\n if (tsCompiled.success && tsCompiled.declarations != null) {\n this.provideDeclarationsForGlobalScript(obj._id, tsCompiled.declarations);\n }\n }\n }\n }\n }\n }\n }\n\n this.globalScript = this.globalScript.replace(/\\r\\n/g, '\\n');\n this.globalScriptLines = this.globalScript.split(/\\n/g).length - 1;\n\n if (doc?.rows?.length) {\n // load all scripts\n for (let i = 0; i < doc.rows.length; i++) {\n if (!checkIsGlobal(doc.rows[i].value)) {\n void this.loadScript(doc.rows[i].value);\n }\n }\n }\n\n if (this.config.mirrorPath?.trim()) {\n this.config.mirrorInstance = parseInt(this.config.mirrorInstance as unknown as string, 10) || 0;\n if (this.instance === this.config.mirrorInstance) {\n const ioBDataDir = getAbsoluteDefaultDataDir() + sep;\n this.config.mirrorPath = normalize(this.config.mirrorPath);\n let mirrorForbidden = false;\n for (let dir of forbiddenMirrorLocations) {\n dir = join(ioBDataDir, dir) + sep;\n if (dir.includes(this.config.mirrorPath) || this.config.mirrorPath.startsWith(dir)) {\n this.log.error(`The Mirror directory is not allowed to be a central ioBroker directory!`);\n this.log.error(`Directory ${this.config.mirrorPath} is not allowed to mirror files!`);\n mirrorForbidden = true;\n break;\n }\n }\n if (!mirrorForbidden) {\n this.mirror = new Mirror({\n adapter: this,\n log: this.log,\n diskRoot: this.config.mirrorPath,\n });\n }\n }\n }\n\n // CHeck setState counter per minute and stop a script if too high\n this.setStateCountCheckInterval = setInterval(() => {\n Object.keys(this.scripts).forEach(id => {\n if (!this.scripts[id]) {\n return;\n }\n const currentSetStatePerMinuteCounter = this.scripts[id].setStatePerMinuteCounter;\n this.scripts[id].setStatePerMinuteCounter = 0;\n if (currentSetStatePerMinuteCounter > this.config.maxSetStatePerMinute) {\n this.scripts[id].setStatePerMinuteProblemCounter++;\n this.log.debug(\n `${id}: Script has reached the maximum of ${this.config.maxSetStatePerMinute} setState calls per minute in ${this.scripts[id].setStatePerMinuteProblemCounter} consecutive minutes`,\n );\n // Allow \"too high counters\" for 1 minute for script starts or such and only\n // stop the script when lasts longer\n if (this.scripts[id].setStatePerMinuteProblemCounter > 1) {\n this.log.error(\n `${id}: Script is calling setState more than ${this.config.maxSetStatePerMinute} times per minute! Stopping Script now! Please check your script!`,\n );\n void this.stopScript(id);\n }\n } else if (this.scripts[id].setStatePerMinuteProblemCounter > 0) {\n this.scripts[id].setStatePerMinuteProblemCounter--;\n this.log.debug(\n `Script ${id} has NOT reached the maximum of ${this.config.maxSetStatePerMinute} setState calls per minute. Decrease problem counter to ${this.scripts[id].setStatePerMinuteProblemCounter}`,\n );\n }\n });\n }, 60000);\n }\n\n private loadTypeScriptDeclarations(): void {\n // try to load the typings on disk for all 3rd party modules\n const packages = [\n 'node', // this provides auto-completion for most builtins\n '@iobroker/types', // this provides auto-completion for most builtins\n ];\n // Also include user-selected libraries (but only those that are also installed)\n if (typeof this.config?.libraries === 'string' && typeof this.config.libraryTypings === 'string') {\n const installedLibs = this.config.libraries\n .split(/[,;\\s]+/)\n .map(s => s.trim().split('@')[0])\n .filter(s => !!s);\n\n const wantsTypings = this.config.libraryTypings\n .split(/[,;\\s]+/)\n .map(s => s.trim())\n .filter(s => !!s);\n // Add all installed libraries the user has requested typings for to the list of packages\n for (const lib of installedLibs) {\n if (wantsTypings.includes(lib) && !packages.includes(lib)) {\n packages.push(lib);\n }\n }\n // Some packages have submodules (e.g., rxjs/operators) that are not exposed through the main entry point\n // If typings are requested for them, also add them if the base module is installed\n for (const lib of wantsTypings) {\n // Extract the package name and check if we need to add it\n if (!lib.includes('/')) {\n continue;\n }\n const pkgName = lib.substring(0, lib.indexOf('/'));\n\n if (installedLibs.includes(pkgName) && !packages.includes(lib)) {\n packages.push(lib);\n }\n }\n }\n for (const pkg of packages) {\n let pkgTypings = resolveTypings(\n pkg,\n this.getAdapterScopedPackageIdentifier ? this.getAdapterScopedPackageIdentifier(pkg) : pkg,\n // node needs ambient typings, so we don't wrap it in declare module\n pkg !== 'node',\n );\n if (!pkgTypings) {\n // Create the empty dummy declarations so users don't get the \"not found\" error\n // for installed packages\n if (pkg.includes('/')) {\n pkgTypings = {\n [`node_modules/${pkg}/index.d.ts`]: `declare module \"${pkg}\";`,\n };\n } else {\n pkgTypings = {\n [`node_modules/@types/${pkg}/index.d.ts`]: `declare module \"${pkg}\";`,\n };\n }\n }\n this.log.debug(`Loaded TypeScript definitions for \"${pkg}\": ${JSON.stringify(Object.keys(pkgTypings))}`);\n // remember the declarations for the editor\n Object.assign(tsAmbient, pkgTypings);\n // and give the language servers access to them\n this.tsServer.provideAmbientDeclarations(pkgTypings);\n jsDeclarationServer.provideAmbientDeclarations(pkgTypings);\n }\n }\n\n updateObjectContext(id: string, obj: ioBroker.Object | null | undefined): void {\n if (obj) {\n // add state to state ID's list\n if (obj.type === 'state') {\n if (!this.stateIds.includes(id)) {\n this.stateIds.push(id);\n this.stateIds.sort();\n }\n if (this.context.devices && this.context.channels) {\n const parts = id.split('.');\n parts.pop();\n const chn = parts.join('.');\n this.context.channels[chn] ||= [];\n this.context.channels[chn].push(id);\n\n parts.pop();\n const dev = parts.join('.');\n this.context.devices[dev] ||= [];\n this.context.devices[dev].push(id);\n }\n }\n } else {\n // delete object from state ID's list\n const pos = this.stateIds.indexOf(id);\n if (pos !== -1) {\n this.stateIds.splice(pos, 1);\n }\n if (this.context.devices && this.context.channels) {\n const parts = id.split('.');\n parts.pop();\n const chn = parts.join('.');\n if (this.context.channels[chn]) {\n const posChn = this.context.channels[chn].indexOf(id);\n posChn !== -1 && this.context.channels[chn].splice(posChn, 1);\n }\n\n parts.pop();\n const dev = parts.join('.');\n if (this.context.devices[dev]) {\n const posDev = this.context.devices[dev].indexOf(id);\n posDev !== -1 && this.context.devices[dev].splice(posDev, 1);\n }\n }\n\n delete this.folderCreationVerifiedObjects[id];\n }\n\n if (!obj && this.objects[id]) {\n // objects were deleted\n this.removeFromNames(id);\n delete this.objects[id];\n } else if (obj && !this.objects[id]) {\n // object was added\n this.objects[id] = obj;\n this.addToNames(obj);\n } else if (obj && this.objects[id].common) {\n // Object just changed\n this.objects[id] = obj;\n\n const n = this.getName(id);\n let nn = this.objects[id].common ? this.objects[id].common.name : '';\n\n if (nn && typeof nn === 'object') {\n nn = nn[getLanguage()] || nn.en;\n }\n\n if (n !== nn) {\n if (n) {\n this.removeFromNames(id);\n }\n if (nn) {\n this.addToNames(obj);\n }\n }\n }\n }\n\n async stopAllScripts(): Promise {\n const scripts = Object.keys(this.scripts);\n const promises: Promise[] = [];\n for (let i = 0; i < scripts.length; i++) {\n promises.push(this.stopScript(scripts[i]));\n }\n return Promise.all(promises).then(() => {});\n }\n\n convertBackStringifiedValues(\n id: string,\n state: ioBroker.State | null | undefined,\n ): ioBroker.State | null | undefined {\n if (\n state &&\n typeof state.val === 'string' &&\n this.objects[id]?.common &&\n (this.objects[id].common.type === 'array' || this.objects[id].common.type === 'object')\n ) {\n try {\n state.val = JSON.parse(state.val);\n } catch (err: any) {\n if (id.startsWith('javascript.') || id.startsWith('0_userdata.0')) {\n this.log.info(\n `Could not parse value for id \"${id}\" into ${this.objects[id].common.type}: ${err.toString()}`,\n );\n } else {\n this.log.debug(\n `Could not parse value for id \"${id}\" into ${this.objects[id].common.type}: ${err.toString()}`,\n );\n }\n }\n }\n return state;\n }\n\n prepareStateObjectSimple(id: string, state: ioBroker.StateValue, isAck: boolean): ioBroker.State {\n // otherwise, assume that the given state is the value to be set\n const oState: ioBroker.State = { val: state, ack: isAck } as ioBroker.State;\n\n return this.prepareStateObject(id, oState);\n }\n\n prepareStateObject(id: string, state: ioBroker.SettableState | null): ioBroker.State {\n let oState: ioBroker.State;\n\n if (state && typeof state === 'object') {\n oState = state as ioBroker.State;\n } else {\n oState = { val: null } as ioBroker.State;\n }\n\n if (this.config.subscribe) {\n return oState;\n }\n // set other values to have a full state object\n // mirrors logic from statesInRedis\n if (oState.ts === undefined) {\n oState.ts = Date.now();\n }\n\n if (oState.q === undefined) {\n oState.q = 0;\n }\n\n oState.from =\n typeof oState.from === 'string' && oState.from !== '' ? oState.from : `system.adapter.${this.namespace}`;\n\n if (oState.lc === undefined) {\n const formerStateValue = this.interimStateValues[id] || this.states[id];\n if (!formerStateValue) {\n oState.lc = oState.ts;\n } else {\n // isDeepStrictEqual works on objects and primitive values\n const hasChanged = !isDeepStrictEqual(formerStateValue.val, oState.val);\n if (!formerStateValue.lc || hasChanged) {\n oState.lc = oState.ts;\n } else {\n oState.lc = formerStateValue.lc;\n }\n }\n }\n\n return oState;\n }\n\n async getData(): Promise {\n await this.subscribeForeignObjectsAsync('*');\n\n if (!this.config.subscribe) {\n await this.subscribeForeignStatesAsync('*');\n } else {\n await this.subscribeStatesAsync('debug.to');\n await this.subscribeStatesAsync('scriptEnabled.*');\n }\n\n this.log.info('requesting all states');\n\n const statesPromise = this.getForeignStatesAsync('*')\n .then(res => {\n if (!res) {\n this.log.error(`Could not initialize states: no result`);\n this.terminate(EXIT_CODES.START_IMMEDIATELY_AFTER_STOP);\n return;\n }\n if (!this.config.subscribe) {\n this.states = Object.assign(res, this.states);\n this.context.states = this.states;\n\n this.addGetProperty(this.states);\n }\n\n // remember all IDs\n for (const id in res) {\n if (Object.prototype.hasOwnProperty.call(res, id)) {\n this.stateIds.push(id);\n }\n }\n this.statesInitDone = true;\n this.log.info('received all states');\n })\n .catch((err: any) => {\n this.log.error(`Could not initialize states: ${err?.message || 'no result'}`);\n this.terminate(EXIT_CODES.START_IMMEDIATELY_AFTER_STOP);\n });\n\n this.log.info('requesting all objects');\n\n const objectsPromise = this.getObjectListAsync({ include_docs: true })\n .then(res => {\n if (!res?.rows) {\n this.log.error(`Could not initialize objects: no result`);\n this.terminate(EXIT_CODES.START_IMMEDIATELY_AFTER_STOP);\n return;\n }\n this.objects = {};\n this.context.objects = this.objects;\n for (let i = 0; i < res.rows.length; i++) {\n if (!res.rows[i].doc) {\n this.log.debug(`Got empty object for index ${i} (${res.rows[i].id})`);\n continue;\n }\n if (this.objects[res.rows[i].doc._id] === undefined) {\n // If was already there, ignore\n this.objects[res.rows[i].doc._id] = res.rows[i].doc;\n }\n this.objects[res.rows[i].doc._id].type === 'enum' && this._enums.push(res.rows[i].doc._id);\n\n // Collect all names\n this.addToNames(this.objects[res.rows[i].doc._id]);\n }\n this.addGetProperty(this.objects);\n\n const systemConfig = this.objects['system.config'];\n this.password = systemConfig?.native?.javascriptPassword\n ? this.decrypt(systemConfig?.native.javascriptPassword)\n : '';\n\n // set language for debug messages\n if (systemConfig?.common?.language) {\n setLanguage(systemConfig.common.language);\n this.language = systemConfig.common.language;\n this.context.language = this.language as ioBroker.Languages;\n } else if (this.language) {\n setLanguage(this.language);\n this.context.language = this.language;\n }\n\n // try to use system coordinates\n if (this.config.useSystemGPS) {\n if (systemConfig?.common?.latitude || systemConfig?.common?.longitude) {\n this.config.latitude = systemConfig.common.latitude;\n this.config.longitude = systemConfig.common.longitude;\n } else if (this.latitude && this.longitude) {\n this.config.latitude = this.latitude;\n this.config.longitude = this.longitude;\n }\n }\n this.config.latitude = parseFloat(this.config.latitude as unknown as string);\n this.config.longitude = parseFloat(this.config.longitude as unknown as string);\n\n if (isNaN(this.config.latitude)) {\n this.log.warn(`Configured latitude is not a number - check (instance/system) configuration`);\n } else if (this.config.latitude < -90 || this.config.latitude > 90) {\n this.log.warn(\n `Configured latitude \"${this.config.latitude}\" is invalid - check (instance/system) configuration`,\n );\n }\n\n if (isNaN(this.config.longitude)) {\n this.log.warn(`Configured longitude is not a number - check (instance/system) configuration`);\n } else if (this.config.longitude < -180 || this.config.longitude > 180) {\n this.log.warn(\n `Configured longitude \"${this.config.longitude}\" is invalid - check (instance/system) configuration`,\n );\n }\n\n this.config.sunriseEvent ||= 'nightEnd';\n this.config.sunriseOffset ||= 0;\n this.config.sunriseLimitStart ||= '06:00';\n this.config.sunriseLimitEnd ||= '12:00';\n\n this.config.sunsetEvent ||= 'dusk';\n this.config.sunsetOffset ||= 0;\n this.config.sunsetLimitStart ||= '18:00';\n this.config.sunsetLimitEnd ||= '23:00';\n\n this.objectsInitDone = true;\n this.log.info('received all objects');\n })\n .catch((err: any) => {\n this.log.error(`Could not initialize objects: ${err?.message || 'no result'}`);\n this.terminate(EXIT_CODES.START_IMMEDIATELY_AFTER_STOP);\n });\n\n return Promise.all([statesPromise, objectsPromise]).then(() => {});\n }\n\n async createActiveObject(id: string, enabled: boolean): Promise {\n const idActive = `${this.namespace}.scriptEnabled.${id.substring(SCRIPT_CODE_MARKER.length)}`;\n\n if (!this.objects[idActive]) {\n this.objects[idActive] = {\n _id: idActive,\n common: {\n name: `scriptEnabled.${id.substring(SCRIPT_CODE_MARKER.length)}`,\n desc: 'controls script activity',\n type: 'boolean',\n write: true,\n read: true,\n role: 'switch.active',\n },\n native: {\n script: id,\n },\n type: 'state',\n };\n try {\n await this.setForeignObjectAsync(idActive, this.objects[idActive]);\n const intermediateStateValue = this.prepareStateObjectSimple(idActive, enabled, true);\n await this.setForeignStateAsync(idActive, enabled, true);\n if (enabled && !this.config.subscribe) {\n this.interimStateValues[idActive] = intermediateStateValue;\n }\n } catch {\n // ignore\n }\n } else {\n const state = await this.getForeignStateAsync(idActive);\n if (state && state.val !== enabled) {\n const intermediateStateValue = this.prepareStateObjectSimple(idActive, enabled, true);\n await this.setForeignStateAsync(idActive, enabled, true);\n if (enabled && !this.config.subscribe) {\n this.interimStateValues[idActive] = intermediateStateValue;\n }\n }\n }\n }\n\n async createProblemObject(id: string): Promise {\n const idProblem = `${this.namespace}.scriptProblem.${id.substring(SCRIPT_CODE_MARKER.length)}`;\n\n if (!this.objects[idProblem]) {\n this.objects[idProblem] = {\n _id: idProblem,\n common: {\n name: `scriptProblem.${id.substring(SCRIPT_CODE_MARKER.length)}`,\n desc: 'Script has a problem',\n type: 'boolean',\n expert: true,\n write: false,\n read: true,\n role: 'indicator.error',\n },\n native: {\n script: id,\n },\n type: 'state',\n };\n try {\n await this.setForeignObjectAsync(idProblem, this.objects[idProblem]);\n await this.setForeignStateAsync(idProblem, false, true);\n } catch {\n // ignore\n }\n } else {\n const state = await this.getForeignStateAsync(idProblem);\n if (state && state.val !== false) {\n await this.setForeignStateAsync(idProblem, false, true);\n }\n }\n }\n\n addToNames(obj: ioBroker.Object): void {\n const id = obj._id;\n\n if (obj.common?.name) {\n let name = obj.common.name;\n if (name && typeof name === 'object') {\n name = name[getLanguage()] || name.en;\n }\n if (!name || typeof name !== 'string') {\n // TODO, take name in current language\n return;\n }\n\n if (!this.names[name]) {\n this.names[name] = id;\n } else {\n // convert to array\n if (!Array.isArray(this.names[name])) {\n this.names[name] = [this.names[name] as string];\n }\n\n (this.names[name] as string[]).push(id);\n }\n }\n }\n\n removeFromNames(id: string): void {\n const n = this.getName(id);\n\n if (n) {\n if (Array.isArray(this.names[n])) {\n const pos = this.names[n].indexOf(id);\n if (pos > -1) {\n this.names[n].splice(pos, 1);\n\n if (this.names[n].length === 1) {\n this.names[n] = this.names[n][0];\n }\n }\n } else {\n delete this.names[n];\n }\n }\n }\n\n getName(id: string): string | null {\n for (const n in this.names) {\n if (this.names[n] && Array.isArray(this.names[n])) {\n if (this.names[n].includes(id)) {\n return n;\n }\n } else if (this.names[n] === id) {\n return n;\n }\n }\n\n return null;\n }\n\n async installNpm(npmLib: string): Promise {\n return new Promise((resolve, reject) => {\n const path = __dirname;\n\n // Also, set the working directory (cwd) of the process instead of using --prefix\n // because that has ugly bugs on Windows\n const cmd = `npm install ${npmLib} --omit=dev`;\n this.log.info(`Installing ${npmLib} into ${__dirname} - cmd: ${cmd}`);\n\n // System call used for update of js-controller itself,\n // because during the installation the npm packet will be deleted too, but some files must be loaded even during the installation process.\n const child = this.mods.child_process.exec(cmd, {\n windowsHide: true,\n cwd: path,\n });\n\n child.stdout?.on('data', buf => this.log.info(buf.toString('utf8')));\n\n child.stderr?.on('data', buf => this.log.error(buf.toString('utf8')));\n\n child.on('err', err => {\n this.log.error(`Cannot install ${npmLib}: ${err}`);\n reject(new Error(`Cannot install ${npmLib}: ${err}`));\n });\n child.on('error', err => {\n this.log.error(`Cannot install ${npmLib}: ${err}`);\n reject(new Error(`Cannot install ${npmLib}: ${err}`));\n });\n\n child.on('exit', (code: number /* , signal */) => {\n if (code) {\n this.log.error(`Cannot install ${npmLib}: ${code}`);\n reject(new Error(`Cannot install ${npmLib}: ${code}`));\n }\n // command succeeded\n resolve(code);\n });\n });\n }\n\n async installLibraries(): Promise {\n if (typeof this.config?.libraries !== 'string') {\n this.config.libraries = '';\n }\n\n const libraries: string[] = this.config.libraries\n .split(/[,;\\s]+/)\n .map(d => d.trim())\n .filter(d => d);\n\n this.log.debug(`Custom libraries in config: \"${this.config.libraries}\": ${JSON.stringify(libraries)}`);\n\n let installedNodeModules: string[] = [];\n const keepModules: string[] = [];\n\n // js-controller >= 6.x\n if (typeof this.listInstalledNodeModules === 'function') {\n installedNodeModules = await this.listInstalledNodeModules();\n\n this.log.debug(`Found installed libraries: ${JSON.stringify(installedNodeModules)}`);\n }\n\n for (const lib of libraries) {\n let depName = lib;\n let version = 'latest';\n\n if (depName.includes('@') && depName.lastIndexOf('@') > 0) {\n const parts = depName.split('@');\n version = parts.pop() ?? 'latest';\n depName = parts.join('@');\n }\n\n /** The real module name, because the dependency can be a URL too */\n let moduleName = depName;\n\n if (URL.canParse(depName)) {\n moduleName = await requestModuleNameByUrl(depName);\n\n this.log.debug(`Found custom library in config: \"${moduleName}@${version}\" (from ${depName})`);\n } else {\n this.log.debug(`Found custom library in config: \"${moduleName}@${version}\"`);\n }\n\n keepModules.push(moduleName);\n\n // js-controller >= 6.x\n if (typeof this.installNodeModule === 'function') {\n try {\n const result = await this.installNodeModule(depName, { version });\n if (result.success) {\n this.log.debug(`Installed custom library: \"${moduleName}@${version}\"`);\n\n const importedModule: any = await this.importNodeModule(moduleName);\n (this.mods as Record)[moduleName] = importedModule.default ?? importedModule;\n } else {\n this.log.warn(`Cannot install custom npm package \"${moduleName}@${version}\"`);\n }\n } catch (err: unknown) {\n this.log.warn(`Cannot install custom npm package \"${moduleName}@${version}\": ${err as Error}`);\n }\n } else if (!existsSync(`${__dirname}/node_modules/${depName}/package.json`)) {\n // js-controller < 6.x\n this.log.info(`Installing custom library (legacy mode): \"${lib}\"`);\n\n try {\n await this.installNpm(lib);\n this.log.info(`Installed custom npm package (legacy mode): \"${lib}\"`);\n } catch (err: any) {\n this.log.warn(`Cannot install custom npm package \"${lib}\" (legacy mode): ${err.toString()}`);\n }\n }\n }\n\n // js-controller >= 6.x\n if (typeof this.uninstallNodeModule === 'function') {\n for (const installedNodeModule of installedNodeModules) {\n if (!keepModules.includes(installedNodeModule)) {\n try {\n await this.uninstallNodeModule(installedNodeModule);\n\n this.log.info(`Removed custom npm package: \"${installedNodeModule}\"`);\n } catch (err: any) {\n this.log.warn(`Cannot remove custom npm package ${installedNodeModule}: ${err.toString()}`);\n }\n }\n }\n }\n }\n\n createVM(source: string, name: string, wrapAsync: boolean): false | JsScript {\n if (this.context.debugMode && name !== this.context.debugMode) {\n return false;\n }\n\n if (!this.context.debugMode) {\n const logSubscriptionsText =\n \"\\n;\\nlog(`registered ${__engine.__subscriptions} subscription${__engine.__subscriptions === 1 ? '' : 's'},\" +\n \" ${__engine.__schedules} schedule${__engine.__schedules === 1 ? '' : 's'},\" +\n \" ${__engine.__subscriptionsMessage} message${__engine.__subscriptionsMessage === 1 ? '' : 's'},\" +\n \" ${__engine.__subscriptionsLog} log${__engine.__subscriptionsLog === 1 ? '' : 's'}\" +\n \" and ${__engine.__subscriptionsFile} file subscription${__engine.__subscriptionsFile === 1 ? '' : 's'}`);\\n\";\n\n if (wrapAsync) {\n source = `(async () => {\\n${source}\\n${logSubscriptionsText}\\n})();`;\n } else {\n if (source.endsWith('export {};\\n')) {\n // If the source ends with \"export {};\" place the log subscriptions before it\n source = source.slice(0, -11); // remove \"export {};\\n\"\n source = `${source}\\n${logSubscriptionsText}\\nexport {};\\n`;\n } else {\n source = `${source}\\n${logSubscriptionsText}`;\n }\n }\n } else {\n if (wrapAsync) {\n source = `(async () => {debugger;\\n${source}\\n})();`;\n } else {\n source = `debugger;${source}`;\n }\n }\n\n try {\n const options: ScriptOptions = {\n filename: name,\n // displayErrors: true,\n // lineOffset: this.globalScriptLines\n };\n return {\n script: new Script(source, options),\n } as JsScript;\n } catch (err: unknown) {\n this.logError(name, `compile failed at`, err as Error);\n return false;\n }\n }\n\n execute(script: JsScript, name: string, engineType: ScriptType, verbose: boolean, debug: boolean): void {\n script.intervals = [];\n script.timeouts = [];\n script.schedules = [];\n script.wizards = [];\n script.name = name;\n script.engineType = engineType;\n script._id = Math.floor(Math.random() * 0xffffffff);\n script.subscribes = {};\n script.subscribesFile = {};\n script.setStatePerMinuteCounter = 0;\n script.setStatePerMinuteProblemCounter = 0;\n void this.setState(`scriptProblem.${name.substring(SCRIPT_CODE_MARKER.length)}`, {\n val: false,\n ack: true,\n expire: 1000,\n });\n\n const sandbox = sandBox(script, name, verbose, debug, this.context);\n\n try {\n script.script.runInNewContext(sandbox, {\n filename: name,\n displayErrors: true,\n // lineOffset: this.globalScriptLines\n });\n } catch (err: unknown) {\n void this.setState(`scriptProblem.${name.substring(SCRIPT_CODE_MARKER.length)}`, {\n val: true,\n ack: true,\n c: 'execute',\n });\n this.logError(name, 'Error by run:', err as Error);\n }\n }\n\n unsubscribe(id: string | RegExp | string[]): void {\n if (!id) {\n this.log.warn('unsubscribe: empty name');\n return;\n }\n\n if (Array.isArray(id)) {\n id.forEach(sub => unsubscribe(sub));\n return;\n }\n\n if (id.constructor && id.constructor.name === 'RegExp') {\n // adapter.log.warn('unsubscribe: todo - process regexp');\n return;\n }\n\n if (typeof id !== 'string') {\n this.log.error(`unsubscribe: invalid type of id - ${typeof id}`);\n return;\n }\n const parts = id.split('.');\n const _adapter = `system.adapter.${parts[0]}.${parts[1]}`;\n if (this.objects[_adapter]?.common?.subscribable) {\n const a = `${parts[0]}.${parts[1]}`;\n const alive = `system.adapter.${a}.alive`;\n if (this.adapterSubs[alive]) {\n const pos = this.adapterSubs[alive].indexOf(id);\n if (pos !== -1) {\n this.adapterSubs[alive].splice(pos, 1);\n }\n if (!this.adapterSubs[alive].length) {\n delete this.adapterSubs[alive];\n }\n }\n this.sendTo(a, 'unsubscribe', id);\n }\n }\n\n // Analyze if logs are still required or not\n updateLogSubscriptions(): void {\n let found = false;\n // go through all scripts and check if some script still requires logs\n Object.keys(this.logSubscriptions).forEach(scriptName => {\n if (!this.logSubscriptions?.[scriptName] || !this.logSubscriptions[scriptName].length) {\n delete this.logSubscriptions[scriptName];\n } else {\n found = true;\n }\n });\n\n if (this.requireLog) {\n if (found && !this.logSubscribed) {\n this.logSubscribed = true;\n void this.requireLog(this.logSubscribed);\n this.log.info(`Subscribed to log messages (found logSubscriptions)`);\n } else if (!found && this.logSubscribed) {\n this.logSubscribed = false;\n void this.requireLog(this.logSubscribed);\n this.log.info(`Unsubscribed from log messages (not found logSubscriptions)`);\n }\n }\n }\n\n async stopScript(name: string): Promise {\n this.log.info(`${name}: Stopping script`);\n\n await this.setState(`scriptEnabled.${name.substring(SCRIPT_CODE_MARKER.length)}`, false, true);\n\n if (this.messageBusHandlers[name]) {\n delete this.messageBusHandlers[name];\n }\n\n if (this.tempDirectories[name]) {\n try {\n this.mods.fs.rmSync(this.tempDirectories[name], { recursive: true });\n\n this.log.debug(`${name}: Removed temp directory: ${this.tempDirectories[name]}`);\n } catch {\n this.log.warn(`${name}: Unable to remove temp directory: ${this.tempDirectories[name]}`);\n }\n\n delete this.tempDirectories[name];\n }\n\n if (this.logSubscriptions[name]) {\n delete this.logSubscriptions[name];\n this.updateLogSubscriptions();\n }\n\n if (this.scripts[name]) {\n // Remove from subscriptions\n this.context.isEnums = false;\n if (this.config.subscribe) {\n // check all subscribed IDs\n Object.keys(this.scripts[name].subscribes).forEach(id => {\n if (this.subscribedPatterns[id]) {\n this.subscribedPatterns[id] -= this.scripts[name].subscribes[id];\n if (this.subscribedPatterns[id] <= 0) {\n this.unsubscribeForeignStates(id);\n delete this.subscribedPatterns[id];\n if (this.states[id]) {\n delete this.states[id];\n }\n }\n }\n });\n }\n\n for (let i = this.subscriptions.length - 1; i >= 0; i--) {\n if (this.subscriptions[i].name === name) {\n const sub = this.subscriptions.splice(i, 1)[0];\n if (sub?.pattern.id) {\n this.unsubscribe(sub.pattern.id);\n }\n } else {\n if (\n (!this.context.isEnums && this.subscriptions[i].pattern.enumName) ||\n this.subscriptions[i].pattern.enumId\n ) {\n this.context.isEnums = true;\n }\n }\n }\n\n // check all subscribed files\n Object.keys(this.scripts[name].subscribesFile).forEach(key => {\n if (this.subscribedPatternsFile[key]) {\n this.subscribedPatternsFile[key] -= this.scripts[name].subscribesFile[key];\n if (this.subscribedPatternsFile[key] <= 0) {\n const [id, file] = key.split('$%$');\n void this.unsubscribeForeignFiles(id, file);\n delete this.subscribedPatternsFile[key];\n }\n }\n });\n for (let i = this.subscriptionsFile.length - 1; i >= 0; i--) {\n if (this.subscriptionsFile[i].name === name) {\n this.subscriptionsFile.splice(i, 1);\n }\n }\n\n for (let i = this.subscriptionsObject.length - 1; i >= 0; i--) {\n if (this.subscriptionsObject[i].name === name) {\n const sub = this.subscriptionsObject.splice(i, 1)[0];\n if (sub) {\n this.unsubscribeForeignObjects(sub.pattern);\n }\n }\n }\n\n // Stop all timeouts\n for (let i = 0; i < this.scripts[name].timeouts.length; i++) {\n clearTimeout(this.scripts[name].timeouts[i]);\n }\n // Stop all intervals\n for (let i = 0; i < this.scripts[name].intervals.length; i++) {\n clearInterval(this.scripts[name].intervals[i]);\n }\n // Stop all delayed states (setStateDelayed timers)\n for (const stateId of Object.keys(this.timers)) {\n if (this.timers[stateId]) {\n for (let i = this.timers[stateId].length - 1; i >= 0; i--) {\n if (this.timers[stateId][i].scriptName === name) {\n clearTimeout(this.timers[stateId][i].t);\n this.timers[stateId].splice(i, 1);\n }\n }\n if (!this.timers[stateId].length) {\n delete this.timers[stateId];\n }\n }\n }\n // Stop all scheduled jobs\n for (let i = 0; i < this.scripts[name].schedules.length; i++) {\n if (this.scripts[name].schedules[i]) {\n const _name = this.scripts[name].schedules[i].name;\n if (!this.mods.nodeSchedule.cancelJob(this.scripts[name].schedules[i])) {\n this.log.error(`${name}: Error by canceling scheduled job \"${_name}\"`);\n }\n }\n }\n\n // Stop all time wizards jobs\n if (this.context.scheduler) {\n for (let i = 0; i < this.scripts[name].wizards.length; i++) {\n if (this.scripts[name].wizards[i]) {\n this.context.scheduler.remove(this.scripts[name].wizards[i]);\n }\n }\n }\n\n // if callback for on stop\n if (typeof this.scripts[name].onStopCb === 'function') {\n this.scripts[name].onStopTimeout =\n parseInt(this.scripts[name].onStopTimeout as unknown as string, 10) || 1000;\n\n await new Promise(resolve => {\n let timeout: NodeJS.Timeout | null = setTimeout(() => {\n if (timeout) {\n timeout = null;\n resolve(true);\n }\n }, this.scripts[name].onStopTimeout);\n\n try {\n this.scripts[name].onStopCb(() => {\n if (timeout) {\n clearTimeout(timeout);\n timeout = null;\n resolve(true);\n }\n });\n } catch (err: unknown) {\n this.log.error(`${name}: error in onStop callback: ${err as Error}`);\n }\n });\n }\n\n delete this.scripts[name];\n return true;\n }\n return false;\n }\n\n async prepareScript(obj: ioBroker.ScriptObject): Promise {\n if (obj?.common?.enabled && this.debugState.scriptName === obj._id) {\n const id = obj._id;\n await this.debugStop();\n this.log.info(`${id}: Debugging was stopped, because started in normal mode`);\n return this.prepareScript(obj);\n }\n\n if (\n obj?.common?.source &&\n (obj.common.enabled || this.context.debugMode === obj._id) &&\n obj.common.engine === `system.adapter.${this.namespace}`\n ) {\n const name = obj._id;\n\n if (this.password && obj.native?.protected) {\n obj.common.source = decryptText(this.password, obj.common.source);\n }\n\n const nameId = name.substring(SCRIPT_CODE_MARKER.length);\n if (!nameId.length || nameId.endsWith('.')) {\n this.log.error(`${name}: Script name \"${name}\" is invalid!`);\n return false;\n }\n const idActive = `scriptEnabled.${nameId}`;\n if (!this.config.subscribe) {\n this.interimStateValues[idActive] = this.prepareStateObjectSimple(\n `${this.namespace}.${idActive}`,\n true,\n true,\n );\n }\n await this.setState(idActive, true, true);\n obj.common.engineType ||= '' as 'TypeScript/ts' | 'Blockly' | 'Rules' | 'Javascript/js';\n\n if (\n (obj.common.engineType as ScriptType).toLowerCase().startsWith('javascript') ||\n (obj.common.engineType as ScriptType) === 'Blockly' ||\n (obj.common.engineType as ScriptType) === 'Rules'\n ) {\n // Javascript\n this.log.info(`${name}: start JavaScript (${obj.common.engineType})`);\n\n let sourceFn = name;\n if (webstormDebug) {\n const fn = name.replace(/^script\\.js\\./, '').replace(/\\./g, '/');\n sourceFn = this.mods.path.join(webstormDebug, `${fn}.js`);\n }\n const createdScript = this.createVM(`${this.globalScript}\\n${obj.common.source}`, sourceFn, true);\n if (!createdScript) {\n return false;\n }\n this.scripts[name] = createdScript;\n this.execute(\n this.scripts[name],\n sourceFn,\n obj.common.engineType as ScriptType,\n obj.common.verbose,\n obj.common.debug,\n );\n return true;\n }\n\n if (obj.common.engineType.toLowerCase().startsWith('typescript')) {\n // TypeScript\n this.log.info(`${name}: Compiling TypeScript source`);\n // The source code must be transformed in order to support top level await\n // and to force TypeScript to compile the code as a module\n const transformedSource = transformScriptBeforeCompilation(obj.common.source, false);\n // We need to hash both global declarations that are known until now\n // AND the script source, because changing either can change the compilation output\n const sourceHash = hashSource(tsSourceHashBase + this.globalDeclarations + transformedSource);\n\n let compiled: string;\n // If we already stored the compiled source code and the original source hash,\n // use the hash to check whether we can rely on the compiled source code or\n // if we need to compile it again\n if (\n typeof obj.common.compiled === 'string' &&\n typeof obj.common.sourceHash === 'string' &&\n sourceHash === obj.common.sourceHash\n ) {\n // We can reuse the stored source\n compiled = obj.common.compiled;\n this.log.info(`${name}: source code did not change, using cached compilation result...`);\n } else {\n // We don't have a hashed source code, or the original source changed, compile it\n const filename = scriptIdToTSFilename(name);\n let tsCompiled: CompileResult;\n try {\n tsCompiled = this.tsServer.compile(filename, transformedSource);\n } catch (err: unknown) {\n this.log.error(`${obj._id}: TypeScript compilation failed:\\n${err as Error}`);\n return false;\n }\n\n const errors = tsCompiled.diagnostics.map(diag => `${diag.annotatedSource}\\n`).join('\\n');\n\n if (tsCompiled.success) {\n if (errors.length > 0) {\n this.log.warn(`${name}: TypeScript compilation had errors:\\n${errors}`);\n } else {\n this.log.info(`${name}: TypeScript compilation successful`);\n }\n compiled = tsCompiled.result || '';\n\n // Store the compiled source and the original source hash, so we don't need to do the work again next time\n this.ignoreObjectChange.add(name); // ignore the next change and don't restart scripts\n await this.extendForeignObjectAsync(name, {\n common: {\n sourceHash,\n compiled,\n },\n });\n } else {\n this.log.error(`${name}: TypeScript compilation failed:\\n${errors}`);\n return false;\n }\n }\n const createdScript: JsScript | false = this.createVM(`${this.globalScript}\\n${compiled}`, name, false);\n if (!createdScript) {\n return false;\n }\n this.scripts[name] = createdScript;\n this.execute(\n this.scripts[name],\n name,\n obj.common.engineType as ScriptType,\n obj.common.verbose,\n obj.common.debug,\n );\n return true;\n }\n\n this.log.warn(`${obj._id}: Unknown engine type: ${obj.common.engineType}`);\n return false;\n }\n\n let _name: string;\n if (obj?._id) {\n _name = obj._id;\n const scriptIdName = _name.substring(SCRIPT_CODE_MARKER.length);\n\n if (!scriptIdName.length || scriptIdName.endsWith('.')) {\n this.log.error(`${obj._id}: Script name \"${_name}\" is invalid!`);\n return false;\n }\n await this.setState(`scriptEnabled.${scriptIdName}`, false, true);\n }\n if (!obj) {\n this.log.error('Invalid script');\n }\n return false;\n }\n\n async loadScriptById(id: string): Promise {\n let obj: ioBroker.ScriptObject | null | undefined;\n try {\n obj = (await this.getForeignObjectAsync(id)) as ioBroker.ScriptObject | null | undefined;\n } catch (err: any) {\n this.log.error(`${id}: Invalid script: ${err}`);\n }\n if (!obj) {\n return false;\n }\n return this.loadScript(obj);\n }\n\n async loadScript(nameOrObject: ioBroker.ScriptObject): Promise {\n // create states for scripts\n await this.createActiveObject(nameOrObject._id, !!nameOrObject?.common?.enabled);\n await this.createProblemObject(nameOrObject._id);\n return this.prepareScript(nameOrObject);\n }\n\n getAstroEvent(\n date: Date,\n astroEvent: AstroEventName,\n start: string,\n end: string,\n offsetMinutes: number | string,\n isDayEnd: boolean,\n latitude: number,\n longitude: number,\n useNextDay?: boolean,\n ): Date {\n let ts: Date = this.mods.suncalc.getTimes(date, latitude, longitude)[astroEvent];\n\n if (!ts || ts.getTime().toString() === 'NaN') {\n ts = isDayEnd ? getNextTimeEvent(end, useNextDay) : getNextTimeEvent(start, useNextDay);\n }\n ts.setMilliseconds(0);\n ts.setMinutes(ts.getMinutes() + (parseInt(offsetMinutes as unknown as string, 10) || 0));\n\n const [timeHoursStart, timeMinutesStart] = start.split(':');\n const nTimeHoursStart = parseInt(timeHoursStart, 10);\n const nTimeMinutesStart = parseInt(timeMinutesStart, 10) || 0;\n\n if (\n ts.getHours() < nTimeHoursStart ||\n (ts.getHours() === nTimeHoursStart && ts.getMinutes() < nTimeMinutesStart)\n ) {\n ts = getNextTimeEvent(start, useNextDay);\n ts.setSeconds(0);\n }\n\n const [timeHoursEnd, timeMinutesEnd] = end.split(':');\n const nTimeHoursEnd = parseInt(timeHoursEnd, 10);\n const nTimeMinutesEnd = parseInt(timeMinutesEnd, 10) || 0;\n\n if (ts.getHours() > nTimeHoursEnd || (ts.getHours() === nTimeHoursEnd && ts.getMinutes() > nTimeMinutesEnd)) {\n ts = getNextTimeEvent(end, useNextDay);\n ts.setSeconds(0);\n }\n\n // if event in the past\n if (date > ts && useNextDay) {\n // take the next day\n ts.setDate(ts.getDate() + 1);\n }\n return ts;\n }\n\n async timeSchedule(): Promise {\n const now = new Date();\n let hours = now.getHours();\n const minutes = now.getMinutes();\n if (this.timeSettings.format12) {\n if (hours > 12) {\n hours -= 12;\n }\n }\n let sHours: string;\n if (this.timeSettings.leadingZeros) {\n sHours = hours.toString().padStart(2, '0');\n } else {\n sHours = hours.toString();\n }\n\n await this.setState('variables.dayTime', {\n val: `${sHours}:${minutes.toString().padStart(2, '0')}`,\n ack: true,\n });\n\n now.setMinutes(now.getMinutes() + 1);\n now.setSeconds(0);\n now.setMilliseconds(0);\n const interval = now.getTime() - Date.now();\n this.timeScheduleTimer = setTimeout(() => this.timeSchedule(), interval);\n }\n\n async dayTimeSchedules(): Promise {\n // get astrological event\n if (\n this.config.latitude === undefined ||\n this.config.longitude === undefined ||\n (this.config.latitude as unknown as string) === '' ||\n (this.config.longitude as unknown as string) === '' ||\n this.config.latitude === null ||\n this.config.longitude === null\n ) {\n this.log.error('Longitude or latitude does not set. Cannot use astro.');\n return;\n }\n\n // Calculate the next event today\n const todayDate = getAstroStartOfDay();\n const nowDate = new Date();\n\n const todaySunrise = this.getAstroEvent(\n todayDate,\n this.config.sunriseEvent,\n this.config.sunriseLimitStart,\n this.config.sunriseLimitEnd,\n this.config.sunriseOffset,\n false,\n this.config.latitude,\n this.config.longitude,\n );\n const todaySunset = this.getAstroEvent(\n todayDate,\n this.config.sunsetEvent,\n this.config.sunsetLimitStart,\n this.config.sunsetLimitEnd,\n this.config.sunsetOffset,\n true,\n this.config.latitude,\n this.config.longitude,\n );\n\n // Sunrise\n let sunriseTimeout = todaySunrise.getTime() - nowDate.getTime();\n if (sunriseTimeout < 0 || sunriseTimeout > 3600000) {\n sunriseTimeout = 3600000;\n }\n\n // Sunset\n let sunsetTimeout = todaySunset.getTime() - nowDate.getTime();\n if (sunsetTimeout < 0 || sunsetTimeout > 3600000) {\n sunsetTimeout = 3600000;\n }\n\n const isDayTime: ioBroker.State | null | undefined = await this.getStateAsync('variables.isDayTime');\n let isDay: boolean;\n if (sunriseTimeout < 5000) {\n isDay = true;\n } else if (sunsetTimeout < 5000) {\n isDay = false;\n } else {\n // check if in between\n isDay = nowDate.getTime() > todaySunrise.getTime() - 60000 && nowDate <= todaySunset;\n }\n\n const valDayTime = isDayTime ? !!isDayTime.val : false;\n if (valDayTime !== isDay || isDayTime === null) {\n await this.setState('variables.isDayTime', isDay, true);\n }\n\n const dayLightSaving: ioBroker.State | null | undefined =\n await this.getStateAsync('variables.isDaylightSaving');\n const isDayLightSaving = dstOffsetAtDate(nowDate) !== 0;\n const val = dayLightSaving ? !!dayLightSaving.val : false;\n\n if (val !== isDayLightSaving || dayLightSaving === null) {\n await this.setState('variables.isDaylightSaving', isDayLightSaving, true);\n }\n\n let nextTimeout = sunriseTimeout;\n if (sunriseTimeout > sunsetTimeout) {\n nextTimeout = sunsetTimeout;\n }\n nextTimeout = nextTimeout - 3000;\n if (nextTimeout < 3000) {\n nextTimeout = 3000;\n }\n\n this.dayScheduleTimer = setTimeout(() => this.dayTimeSchedules(), nextTimeout);\n }\n\n stopTimeSchedules(): void {\n if (this.dayScheduleTimer) {\n clearTimeout(this.dayScheduleTimer);\n this.dayScheduleTimer = null;\n }\n if (this.sunScheduleTimer) {\n clearTimeout(this.sunScheduleTimer);\n this.sunScheduleTimer = null;\n }\n if (this.timeScheduleTimer) {\n clearTimeout(this.timeScheduleTimer);\n this.timeScheduleTimer = null;\n }\n }\n\n async patchFont(): Promise {\n let stat: Stats | undefined;\n let dbFile: Buffer | undefined;\n let fileName = `${__dirname}/../admin/vs/base/browser/ui/codicons/codicon/codicon.ttf`;\n let jsonFileName = `${__dirname}/../admin/vsFont/codicon.json`;\n try {\n if (existsSync(fileName)) {\n stat = statSync(fileName);\n }\n if (!stat) {\n jsonFileName = `${__dirname}/admin/vsFont/codicon.json`;\n fileName = `${__dirname}/admin/vs/base/browser/ui/codicons/codicon/codicon.ttf`;\n if (existsSync(fileName)) {\n stat = statSync(fileName);\n }\n }\n const _dbFile = await this.readFileAsync(\n 'javascript.admin',\n `vs/base/browser/ui/codicons/codicon/codicon.ttf`,\n );\n if (_dbFile?.file) {\n dbFile = _dbFile.file as Buffer;\n }\n } catch {\n // ignore\n }\n\n if (stat?.size !== 73452 || dbFile?.byteLength !== 73452) {\n try {\n const buffer = Buffer.from(JSON.parse(readFileSync(jsonFileName).toString()), 'base64');\n\n const jszip = await import('jszip');\n const zip = await jszip.loadAsync(buffer);\n let data: ArrayBuffer | undefined;\n if (zip) {\n data = await zip.file('codicon.ttf')?.async('arraybuffer');\n if (data?.byteLength !== 73452) {\n this.log.error(`Cannot patch font: invalid font file!`);\n return false;\n }\n } else {\n this.log.error(`Cannot patch font: invalid font file!`);\n return false;\n }\n writeFileSync(fileName, Buffer.from(data));\n // upload this file\n await this.writeFileAsync(\n 'javascript.admin',\n 'vs/base/browser/ui/codicons/codicon/codicon.ttf',\n Buffer.from(data),\n );\n return true;\n } catch (err: unknown) {\n this.log.error(`Cannot patch font: ${err as Error}`);\n return false;\n }\n }\n return false;\n }\n\n async sunTimeSchedules(): Promise {\n if (this.config.createAstroStates) {\n if (!isNaN(this.config.longitude) && !isNaN(this.config.longitude)) {\n const calcDate = getAstroStartOfDay();\n\n const times = this.mods.suncalc.getTimes(calcDate, this.config.latitude, this.config.longitude);\n\n this.log.debug(`[sunTimeSchedules] Times: ${JSON.stringify(times)}`);\n\n for (const t in times) {\n try {\n const objId = `variables.astro.${t}`;\n\n await this.setObjectNotExistsAsync(objId, {\n type: 'state',\n common: {\n name: `Astro ${t}`,\n type: 'string',\n role: 'value',\n read: true,\n write: false,\n },\n native: {},\n });\n\n if (times[t] !== null && !isNaN(times[t].getTime())) {\n const timeFormatted = formatHoursMinutesSeconds(times[t]);\n await this.setState(objId, {\n val: timeFormatted,\n c: times[t].toISOString(),\n ack: true,\n });\n } else {\n await this.setState(objId, { val: null, c: 'n/a', ack: true, q: 0x01 });\n }\n } catch (err: unknown) {\n this.log.error(\n `[sunTimeSchedules] Unable to set state for astro time \"${t}\" (${times[t].getTime()}): ${err as Error}`,\n );\n }\n }\n\n const todayDate = new Date();\n todayDate.setHours(0);\n todayDate.setMinutes(0);\n todayDate.setSeconds(1);\n todayDate.setMilliseconds(0);\n todayDate.setDate(todayDate.getDate() + 1);\n\n this.log.debug(`[sunTimeSchedules] Next: ${todayDate.toISOString()}`);\n this.sunScheduleTimer = setTimeout(() => this.sunTimeSchedules(), todayDate.getTime() - Date.now());\n }\n } else {\n // remove astro states if disabled\n this.delObject('variables.astro', { recursive: true });\n }\n }\n\n /**\n * Redirects the virtual-tsc log output to the ioBroker log\n */\n tsLog = (message: string, severity?: ioBroker.LogLevel): void => {\n // shift the severities around, we don't care about the small details\n if (!severity || severity === 'info') {\n severity = 'debug';\n } else if (severity === 'debug') {\n // Don't spam build logs on Travis\n if (isCI) {\n return;\n }\n severity = 'silly';\n }\n\n if (this?.log) {\n this.log[severity](message);\n } else {\n console.log(`[${severity.toUpperCase()}] ${message}`);\n }\n };\n\n addGetProperty(object: Record): void {\n try {\n Object.defineProperty(object, 'get', {\n value: function (id: string): any {\n return this[id] || this[`${this.namespace}.${id}`];\n },\n enumerable: false,\n });\n } catch {\n console.error('Cannot install get property');\n }\n }\n\n /**\n * Add declarations for global scripts\n *\n * @param scriptID - The current script the declarations were generated from\n * @param declarations - Declarations from a script\n */\n provideDeclarationsForGlobalScript(scriptID: string, declarations: string): void {\n // Remember which declarations this global script had access to;\n // we need this so the editor doesn't show a duplicate identifier error\n if (this.globalDeclarations != null && this.globalDeclarations !== '') {\n this.knownGlobalDeclarationsByScript[scriptID] = this.globalDeclarations;\n }\n // and concatenate the global declarations for the next scripts\n this.globalDeclarations += `${declarations}\\n`;\n // remember all previously generated global declarations,\n // so global scripts can reference each other\n const globalDeclarationPath = 'global.d.ts';\n tsAmbient[globalDeclarationPath] = this.globalDeclarations;\n // make sure the next script compilation has access to the updated declarations\n this.tsServer.provideAmbientDeclarations({\n [globalDeclarationPath]: this.globalDeclarations,\n });\n jsDeclarationServer.provideAmbientDeclarations({\n [globalDeclarationPath]: this.globalDeclarations,\n });\n }\n\n fixLineNo(line: string): string {\n if (line.includes('javascript.js:')) {\n return line;\n }\n if (!/scripts?\\.js[.\\\\/]/.test(line)) {\n return line;\n }\n if (/:(\\d+):/.test(line)) {\n line = line.replace(\n /:(\\d+):/,\n (_$0, $1) => `:${$1 > this.globalScriptLines + 1 ? $1 - this.globalScriptLines - 1 : $1}:`,\n ); // one line for 'async function ()'\n } else {\n line = line.replace(\n /:(\\d+)$/,\n (_$0, $1) => `:${$1 > this.globalScriptLines + 1 ? $1 - this.globalScriptLines - 1 : $1}`,\n ); // one line for 'async function ()'\n }\n return line;\n }\n\n async debugStop(): Promise {\n if (this.debugState.child) {\n this.debugSendToInspector({ cmd: 'end' });\n this.debugState.endTimeout = setTimeout(() => {\n this.debugState.endTimeout = null;\n this.debugState.child?.kill('SIGTERM');\n }, 500);\n this.debugState.promiseOnEnd ||= Promise.resolve(0);\n } else {\n this.debugState.promiseOnEnd = Promise.resolve(0);\n }\n\n await this.debugState.promiseOnEnd;\n\n this.debugState.child = null;\n this.debugState.running = false;\n this.debugState.scriptName = '';\n if (this.debugState.endTimeout) {\n clearTimeout(this.debugState.endTimeout);\n this.debugState.endTimeout = null;\n }\n }\n\n async debugDisableScript(id: string | undefined): Promise {\n if (id) {\n const obj = this.objects[id];\n if (obj?.common?.enabled) {\n await this.extendForeignObjectAsync(obj._id, { common: { enabled: false } });\n }\n }\n }\n\n debugSendToInspector(message: any): void {\n if (this.debugState.child) {\n try {\n this.log.info(`send to debugger: ${message}`);\n this.debugState.child.send(message);\n } catch {\n void this.debugStop().then(() =>\n this.log.info(\n `${this.debugState.scriptName}: Debugging was stopped, because started in normal mode`,\n ),\n );\n }\n } else {\n this.log.error(`${this.debugState.scriptName}: Cannot send command to terminated inspector`);\n void this.setState(\n 'debug.from',\n JSON.stringify({ cmd: 'error', error: `Cannot send command to terminated inspector`, id: 1 }),\n true,\n );\n }\n }\n\n debugStart(data: { breakOnStart?: boolean; scriptName?: string; adapter?: string }): void {\n if (Date.now() - this.debugState.started < 1000) {\n console.log('Start ignored');\n return;\n }\n\n this.debugState.started = Date.now();\n // stop the script if it's running\n void this.debugDisableScript(data.scriptName)\n .then(() => this.debugStop())\n .then(() => {\n if (data.adapter) {\n this.debugState.adapterInstance = data.adapter;\n this.debugState.scriptName = '';\n } else {\n this.debugState.adapterInstance = '';\n this.debugState.scriptName = data.scriptName as string;\n }\n\n this.debugState.breakOnStart = data.breakOnStart;\n\n this.debugState.promiseOnEnd = new Promise(resolve => {\n const options: ForkOptions = {\n stdio: ['ignore', 'inherit', 'inherit', 'ipc'],\n //stdio: ['pipe', 'pipe', 'pipe', 'ipc']\n };\n const args: string[] = [];\n if (this.debugState.adapterInstance) {\n args.push('--breakOnStart');\n }\n\n this.debugState.child = fork(`${__dirname}/lib/inspect.js`, args, options);\n\n /*debugState.child.stdout.setEncoding('utf8');\n debugState.child.stderr.setEncoding('utf8');\n debugState.child.stdout.on('data', childPrint);\n debugState.child.stderr.on('data', childPrint);*/\n\n this.debugState.child?.on(\n 'message',\n (\n message:\n | string\n | {\n cmd: 'ready' | 'watched' | 'paused' | 'resumed' | 'log' | 'readyToDebug';\n severity?: string;\n text?: string;\n scriptId?: string;\n script?: string;\n },\n ) => {\n let oMessage: {\n cmd: 'ready' | 'watched' | 'paused' | 'resumed' | 'log' | 'readyToDebug';\n severity?: string;\n text?: string;\n scriptId?: string;\n script?: string;\n };\n if (typeof message === 'string') {\n try {\n oMessage = JSON.parse(message);\n } catch {\n return this.log.error(`Cannot parse message from inspector: ${message}`);\n }\n } else {\n oMessage = message;\n }\n\n if (oMessage.cmd !== 'ready') {\n void this.setState('debug.from', JSON.stringify(oMessage), true);\n }\n\n switch (oMessage.cmd) {\n case 'ready': {\n this.debugSendToInspector({\n cmd: 'start',\n scriptName: this.debugState.scriptName,\n adapterInstance: this.debugState.adapterInstance,\n instance: this.instance,\n });\n break;\n }\n\n case 'watched': {\n //console.log(`WATCHED: ${JSON.stringify(oMessage)}`);\n break;\n }\n\n case 'paused': {\n this.debugState.paused = true;\n console.log(`host: PAUSED`);\n break;\n }\n\n case 'resumed': {\n this.debugState.paused = false;\n //console.log(`STARTED`);\n break;\n }\n\n case 'log': {\n console.log(`[${oMessage.severity}] ${oMessage.text}`);\n break;\n }\n\n case 'readyToDebug': {\n console.log(\n `host: readyToDebug (set breakpoints): [${oMessage.scriptId}] ${oMessage.script}`,\n );\n break;\n }\n }\n },\n );\n this.debugState.child?.on('error', error => {\n this.log.error(`Cannot start inspector: ${error}`);\n void this.setState('debug.from', JSON.stringify({ cmd: 'error', error }), true);\n });\n\n this.debugState.child?.on('exit', async (code: number): Promise => {\n if (code) {\n await this.setState(\n 'debug.from',\n JSON.stringify({ cmd: 'error', error: `invalid response code: ${code}` }),\n true,\n );\n }\n await this.setState('debug.from', JSON.stringify({ cmd: 'debugStopped', code }), true);\n this.debugState.child = null;\n resolve(code);\n });\n });\n });\n }\n}\n\nfunction patternMatching(\n event: EventObj,\n patternFunctions: PatternEventCompareFunction[] & { logic?: 'and' | 'or' },\n): boolean {\n let matched = false;\n for (let i = 0, len = patternFunctions.length; i < len; i++) {\n if (patternFunctions[i](event)) {\n if (patternFunctions.logic === 'or') {\n return true;\n }\n matched = true;\n } else if (patternFunctions.logic === 'and') {\n return false;\n }\n }\n return matched;\n}\n\n// If started as allInOne mode => return function to create an instance\nif (require.main !== module) {\n // Export the constructor in compact mode\n module.exports = (options: Partial | undefined) => new JavaScript(options);\n} else {\n // otherwise start the instance directly\n (() => new JavaScript())();\n}\n"]} \ No newline at end of file diff --git a/src-admin/package-lock.json b/src-admin/package-lock.json index ea0774479..10ef5037f 100644 --- a/src-admin/package-lock.json +++ b/src-admin/package-lock.json @@ -133,7 +133,6 @@ "integrity": "sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@babel/code-frame": "^7.29.0", "@babel/generator": "^7.29.0", @@ -1693,7 +1692,6 @@ "integrity": "sha512-yjvtXoFcrPLGtgKRxFaH6OQPtcLPhkloC0BML6rBG5UeldR0nPULR/2E2BfXdo5JNV7j7lOzrrLX2Qf/iSidow==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@babel/runtime": "^7.26.0", "@mui/core-downloads-tracker": "^6.5.0", @@ -1848,6 +1846,7 @@ "integrity": "sha512-OJM+9nj5JIyPUvsZ5ZjaeC9PfktmK+W5YaVLToLR8L0lB/DGmv1gcKE43ssNLSvpoW71Hct0necfade6+kW3zQ==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@babel/runtime": "^7.28.4", "@mui/utils": "^7.3.3", @@ -1876,6 +1875,7 @@ "integrity": "sha512-8vVje9rdEr1rY8oIkYgP+Su5Kwl6ik7O3jQ0wl78JGSmiZhRHV+vkjooGdKD8pbtZbutXFVTWQYshu2b3sG9zw==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@babel/runtime": "^7.28.4" }, @@ -1894,6 +1894,7 @@ "integrity": "sha512-kwNAUh7bLZ7mRz9JZ+6qfRnnxbE4Zuc+RzXnhSpRSxjTlSTj7b4JxRLXpG+MVtPVtqks5k/XC8No1Vs3x4Z2gg==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@babel/runtime": "^7.28.4", "@mui/types": "^7.4.7", @@ -1925,6 +1926,7 @@ "integrity": "sha512-CmFxvRJIBCEaWdilhXMw/5wFJ1+FT9f3xt+m2pPXhHPeVIbBg9MnMvNSJjdALvnQJMPw8jLhrUtXmN7QAZV2fw==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@babel/runtime": "^7.28.4", "@emotion/cache": "^11.14.0", @@ -1960,6 +1962,7 @@ "integrity": "sha512-Lqq3emZr5IzRLKaHPuMaLBDVaGvxoh6z7HMWd1RPKawBM5uMRaQ4ImsmmgXWtwJdfZux5eugfDhXJUo2mliS8Q==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@babel/runtime": "^7.28.4", "@mui/private-theming": "^7.3.3", @@ -2001,6 +2004,7 @@ "integrity": "sha512-8vVje9rdEr1rY8oIkYgP+Su5Kwl6ik7O3jQ0wl78JGSmiZhRHV+vkjooGdKD8pbtZbutXFVTWQYshu2b3sG9zw==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@babel/runtime": "^7.28.4" }, @@ -2019,6 +2023,7 @@ "integrity": "sha512-kwNAUh7bLZ7mRz9JZ+6qfRnnxbE4Zuc+RzXnhSpRSxjTlSTj7b4JxRLXpG+MVtPVtqks5k/XC8No1Vs3x4Z2gg==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@babel/runtime": "^7.28.4", "@mui/types": "^7.4.7", @@ -3010,7 +3015,6 @@ "integrity": "sha512-z9VXpC7MWrhfWipitjNdgCauoMLRdIILQsAEV+ZesIzBq/oUlxk0m3ApZuMFCXdnS4U7KrI+l3WRUEGQ8K1QKw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@types/prop-types": "*", "csstype": "^3.2.2" @@ -3259,7 +3263,6 @@ } ], "license": "MIT", - "peer": true, "dependencies": { "baseline-browser-mapping": "^2.9.0", "caniuse-lite": "^1.0.30001759", @@ -3588,7 +3591,6 @@ "integrity": "sha512-Ukq0owbQXxa/U3EGtsdVBkR1w7KOQ5gIBqdH2hkvknzZPYvBxb/aa6E8L7tmjFtkwZBu3UXBbjIgPo/Ez4xaNg==", "dev": true, "license": "MIT", - "peer": true, "funding": { "type": "github", "url": "https://github.com/sponsors/kossnocorp" @@ -4755,8 +4757,7 @@ "resolved": "https://registry.npmjs.org/leaflet/-/leaflet-1.9.4.tgz", "integrity": "sha512-nxS1ynzJOmOlHp+iL3FyWqK89GtNL8U8rvlMOsQdTTssxZwCXh8N2NB3GDQOL+YR3XnWyZAxwQixURb+FA74PA==", "dev": true, - "license": "BSD-2-Clause", - "peer": true + "license": "BSD-2-Clause" }, "node_modules/lie": { "version": "3.3.0", @@ -5477,7 +5478,6 @@ "integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "loose-envify": "^1.1.0" }, @@ -5552,7 +5552,6 @@ "integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "loose-envify": "^1.1.0", "scheduler": "^0.23.2" @@ -5826,7 +5825,6 @@ "integrity": "sha512-3GuObel8h7Kqdjt0gxkEzaifHTqLVW56Y/bjN7PSQtkKr0w3V/QYSdt6QWYtd7A1xUtYQigtdUfgj1RvWVtorw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@types/estree": "1.0.8" }, @@ -6367,7 +6365,6 @@ "integrity": "sha512-w+N7Hifpc3gRjZ63vYBXA56dvvRlNWRczTdmCBBa+CotUzAPf5b7YMdMR/8CQoeYE5LX3W4wj6RYTgonm1b9DA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "esbuild": "^0.27.0", "fdir": "^6.5.0", @@ -6514,7 +6511,6 @@ "integrity": "sha512-LZNJgPzfKR+/J3cHkxcpHKpKKvGfDZVPS4hfJCc4cCG0CgYzvlD6yE/S3CIL/Yt91ak327YCpiF/0MyeZHEHKA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@colors/colors": "^1.6.0", "@dabh/diagnostics": "^2.0.8", @@ -6644,7 +6640,6 @@ "integrity": "sha512-8VbfWfHLbbwu3+N6OKsOMpBdT4kXPDDB9cJk2bJ6mh9ucxdlnNvH1e+roYkKmN9Nxw2yjz7VzeO9oOz2zJ04Pw==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=10.0.0" }, diff --git a/src-editor/package-lock.json b/src-editor/package-lock.json index 555688baa..b590f929c 100644 --- a/src-editor/package-lock.json +++ b/src-editor/package-lock.json @@ -169,7 +169,6 @@ "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.0.tgz", "integrity": "sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==", "license": "MIT", - "peer": true, "dependencies": { "@babel/code-frame": "^7.29.0", "@babel/generator": "^7.29.0", @@ -231,6 +230,7 @@ "resolved": "https://registry.npmjs.org/@babel/helper-annotate-as-pure/-/helper-annotate-as-pure-7.27.3.tgz", "integrity": "sha512-fXSwMQqitTGeHLBC08Eq5yXz2m37E4pJX1qAU1+2cNedz/ifv/bVXft90VeSav5nFO61EcNgwr0aJxbyPaWBPg==", "license": "MIT", + "peer": true, "dependencies": { "@babel/types": "^7.27.3" }, @@ -371,6 +371,7 @@ "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-jsx/-/plugin-syntax-jsx-7.28.6.tgz", "integrity": "sha512-wgEmr06G6sIpqr8YDwA2dSRTE3bJ+V0IfpzfSY3Lfgd7YWOaAdlykvJi13ZKBt8cZHfgH1IXN+CL656W3uUa4w==", "license": "MIT", + "peer": true, "dependencies": { "@babel/helper-plugin-utils": "^7.28.6" }, @@ -594,7 +595,6 @@ } ], "license": "MIT", - "peer": true, "engines": { "node": ">=18" }, @@ -617,7 +617,6 @@ } ], "license": "MIT", - "peer": true, "engines": { "node": ">=18" } @@ -785,7 +784,8 @@ "version": "0.8.5", "resolved": "https://registry.npmjs.org/@emotion/stylis/-/stylis-0.8.5.tgz", "integrity": "sha512-h6KtPihKFn3T9fuIrwvXXUOwlx3rfUvfZIcP5a6rh8Y7zjE3O06hT5Ss4S/YI1AYhuZ1kjaE/5EaOOI2NqSylQ==", - "license": "MIT" + "license": "MIT", + "peer": true }, "node_modules/@emotion/unitless": { "version": "0.10.0", @@ -1844,7 +1844,6 @@ "resolved": "https://registry.npmjs.org/@mui/material/-/material-6.5.0.tgz", "integrity": "sha512-yjvtXoFcrPLGtgKRxFaH6OQPtcLPhkloC0BML6rBG5UeldR0nPULR/2E2BfXdo5JNV7j7lOzrrLX2Qf/iSidow==", "license": "MIT", - "peer": true, "dependencies": { "@babel/runtime": "^7.26.0", "@mui/core-downloads-tracker": "^6.5.0", @@ -2001,6 +2000,7 @@ "resolved": "https://registry.npmjs.org/@mui/private-theming/-/private-theming-7.3.9.tgz", "integrity": "sha512-ErIyRQvsiQEq7Yvcvfw9UDHngaqjMy9P3JDPnRAaKG5qhpl2C4tX/W1S4zJvpu+feihmZJStjIyvnv6KDbIrlw==", "license": "MIT", + "peer": true, "dependencies": { "@babel/runtime": "^7.28.6", "@mui/utils": "^7.3.9", @@ -2028,6 +2028,7 @@ "resolved": "https://registry.npmjs.org/@mui/types/-/types-7.4.12.tgz", "integrity": "sha512-iKNAF2u9PzSIj40CjvKJWxFXJo122jXVdrmdh0hMYd+FR+NuJMkr/L88XwWLCRiJ5P1j+uyac25+Kp6YC4hu6w==", "license": "MIT", + "peer": true, "dependencies": { "@babel/runtime": "^7.28.6" }, @@ -2045,6 +2046,7 @@ "resolved": "https://registry.npmjs.org/@mui/utils/-/utils-7.3.9.tgz", "integrity": "sha512-U6SdZaGbfb65fqTsH3V5oJdFj9uYwyLE2WVuNvmbggTSDBb8QHrFsqY8BN3taK9t3yJ8/BPHD/kNvLNyjwM7Yw==", "license": "MIT", + "peer": true, "dependencies": { "@babel/runtime": "^7.28.6", "@mui/types": "^7.4.12", @@ -2074,13 +2076,15 @@ "version": "19.2.4", "resolved": "https://registry.npmjs.org/react-is/-/react-is-19.2.4.tgz", "integrity": "sha512-W+EWGn2v0ApPKgKKCy/7s7WHXkboGcsrXE+2joLyVxkbyVQfO3MUEaUQDHoSmb8TFFrSKYa9mw64WZHNHSDzYA==", - "license": "MIT" + "license": "MIT", + "peer": true }, "node_modules/@mui/styled-engine": { "version": "7.3.9", "resolved": "https://registry.npmjs.org/@mui/styled-engine/-/styled-engine-7.3.9.tgz", "integrity": "sha512-JqujWt5bX4okjUPGpVof/7pvgClqh7HvIbsIBIOOlCh2u3wG/Bwp4+E1bc1dXSwkrkp9WUAoNdI5HEC+5HKvMw==", "license": "MIT", + "peer": true, "dependencies": { "@babel/runtime": "^7.28.6", "@emotion/cache": "^11.14.0", @@ -2115,6 +2119,7 @@ "resolved": "https://registry.npmjs.org/@mui/system/-/system-7.3.9.tgz", "integrity": "sha512-aL1q9am8XpRrSabv9qWf5RHhJICJql34wnrc1nz0MuOglPRYF/liN+c8VqZdTvUn9qg+ZjRVbKf4sJVFfIDtmg==", "license": "MIT", + "peer": true, "dependencies": { "@babel/runtime": "^7.28.6", "@mui/private-theming": "^7.3.9", @@ -2155,6 +2160,7 @@ "resolved": "https://registry.npmjs.org/@mui/types/-/types-7.4.12.tgz", "integrity": "sha512-iKNAF2u9PzSIj40CjvKJWxFXJo122jXVdrmdh0hMYd+FR+NuJMkr/L88XwWLCRiJ5P1j+uyac25+Kp6YC4hu6w==", "license": "MIT", + "peer": true, "dependencies": { "@babel/runtime": "^7.28.6" }, @@ -2172,6 +2178,7 @@ "resolved": "https://registry.npmjs.org/@mui/utils/-/utils-7.3.9.tgz", "integrity": "sha512-U6SdZaGbfb65fqTsH3V5oJdFj9uYwyLE2WVuNvmbggTSDBb8QHrFsqY8BN3taK9t3yJ8/BPHD/kNvLNyjwM7Yw==", "license": "MIT", + "peer": true, "dependencies": { "@babel/runtime": "^7.28.6", "@mui/types": "^7.4.12", @@ -2201,7 +2208,8 @@ "version": "19.2.4", "resolved": "https://registry.npmjs.org/react-is/-/react-is-19.2.4.tgz", "integrity": "sha512-W+EWGn2v0ApPKgKKCy/7s7WHXkboGcsrXE+2joLyVxkbyVQfO3MUEaUQDHoSmb8TFFrSKYa9mw64WZHNHSDzYA==", - "license": "MIT" + "license": "MIT", + "peer": true }, "node_modules/@mui/types": { "version": "7.2.24", @@ -3427,7 +3435,6 @@ "resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.28.tgz", "integrity": "sha512-z9VXpC7MWrhfWipitjNdgCauoMLRdIILQsAEV+ZesIzBq/oUlxk0m3ApZuMFCXdnS4U7KrI+l3WRUEGQ8K1QKw==", "license": "MIT", - "peer": true, "dependencies": { "@types/prop-types": "*", "csstype": "^3.2.2" @@ -3632,6 +3639,7 @@ "resolved": "https://registry.npmjs.org/babel-plugin-styled-components/-/babel-plugin-styled-components-2.1.4.tgz", "integrity": "sha512-Xgp9g+A/cG47sUyRwwYxGM4bR/jDRg5N6it/8+HxCnbT5XNKSKDT9xm4oag/osgqjC2It/vH0yXsomOG6k558g==", "license": "MIT", + "peer": true, "dependencies": { "@babel/helper-annotate-as-pure": "^7.22.5", "@babel/helper-module-imports": "^7.22.5", @@ -3648,6 +3656,7 @@ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", "license": "MIT", + "peer": true, "engines": { "node": ">=8.6" }, @@ -3688,7 +3697,6 @@ "resolved": "https://registry.npmjs.org/blockly/-/blockly-11.2.2.tgz", "integrity": "sha512-YJW9jMz4qoBXzOOUqxWBOHL35QhOOTAg2a6sVAFJh+/uNTXW0z506JS7qkqZI4PQ9fnUhDqmhF8a0qWSTL1tjg==", "license": "Apache-2.0", - "peer": true, "dependencies": { "jsdom": "25.0.1" }, @@ -3727,7 +3735,6 @@ } ], "license": "MIT", - "peer": true, "dependencies": { "baseline-browser-mapping": "^2.9.0", "caniuse-lite": "^1.0.30001759", @@ -3787,6 +3794,7 @@ "resolved": "https://registry.npmjs.org/camelize/-/camelize-1.0.1.tgz", "integrity": "sha512-dU+Tx2fsypxTgtLoE36npi3UqcjSSMNYfkqgmoEhtZrraP5VWq0K7FkWVTYa8eMPtnU/G2txVsfdCJTn9uzpuQ==", "license": "MIT", + "peer": true, "funding": { "url": "https://github.com/sponsors/ljharb" } @@ -4076,6 +4084,7 @@ "resolved": "https://registry.npmjs.org/css-color-keywords/-/css-color-keywords-1.0.0.tgz", "integrity": "sha512-FyyrDHZKEjXDpNJYvVsV960FiqQyXc/LlYmsxl2BcdMb2WPx0OGRVgTg55rPSyLSNMqP52R9r8geSp7apN3Ofg==", "license": "ISC", + "peer": true, "engines": { "node": ">=4" } @@ -4085,6 +4094,7 @@ "resolved": "https://registry.npmjs.org/css-to-react-native/-/css-to-react-native-3.2.0.tgz", "integrity": "sha512-e8RKaLXMOFii+02mOlqwjbD00KSEKqblnpO9e++1aXS1fPQOpS1YoqdVHBqPjHNoxeF2mimzVqawm2KCbEdtHQ==", "license": "MIT", + "peer": true, "dependencies": { "camelize": "^1.0.0", "css-color-keywords": "^1.0.0", @@ -4919,6 +4929,7 @@ "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", "license": "MIT", + "peer": true, "engines": { "node": ">=4" } @@ -5739,7 +5750,6 @@ "resolved": "https://registry.npmjs.org/monaco-editor/-/monaco-editor-0.55.1.tgz", "integrity": "sha512-jz4x+TJNFHwHtwuV9vA9rMujcZRb0CEilTEwG2rRSpe/A7Jdkuj8xPKttCgOh+v/lkHy7HsZ64oj+q3xoAFl9A==", "license": "MIT", - "peer": true, "dependencies": { "dompurify": "3.2.7", "marked": "14.0.0" @@ -6116,7 +6126,8 @@ "version": "4.2.0", "resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz", "integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==", - "license": "MIT" + "license": "MIT", + "peer": true }, "node_modules/process-nextick-args": { "version": "2.0.1", @@ -6147,7 +6158,6 @@ "resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz", "integrity": "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==", "license": "MIT", - "peer": true, "dependencies": { "loose-envify": "^1.4.0", "object-assign": "^4.1.1", @@ -6212,7 +6222,6 @@ "resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz", "integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==", "license": "MIT", - "peer": true, "dependencies": { "loose-envify": "^1.1.0" }, @@ -6347,7 +6356,6 @@ "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz", "integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==", "license": "MIT", - "peer": true, "dependencies": { "loose-envify": "^1.1.0", "scheduler": "^0.23.2" @@ -6466,7 +6474,8 @@ "version": "18.3.1", "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.3.1.tgz", "integrity": "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==", - "license": "MIT" + "license": "MIT", + "peer": true }, "node_modules/react-json-view": { "version": "1.21.3", @@ -6786,7 +6795,6 @@ "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.52.5.tgz", "integrity": "sha512-3GuObel8h7Kqdjt0gxkEzaifHTqLVW56Y/bjN7PSQtkKr0w3V/QYSdt6QWYtd7A1xUtYQigtdUfgj1RvWVtorw==", "license": "MIT", - "peer": true, "dependencies": { "@types/estree": "1.0.8" }, @@ -6892,7 +6900,6 @@ "resolved": "https://registry.npmjs.org/sass/-/sass-1.98.0.tgz", "integrity": "sha512-+4N/u9dZ4PrgzGgPlKnaaRQx64RO0JBKs9sDhQ2pLgN6JQZ25uPQZKQYaBJU48Kd5BxgXoJ4e09Dq7nMcOUW3A==", "license": "MIT", - "peer": true, "dependencies": { "chokidar": "^4.0.0", "immutable": "^5.1.5", @@ -6970,7 +6977,8 @@ "version": "1.1.0", "resolved": "https://registry.npmjs.org/shallowequal/-/shallowequal-1.1.0.tgz", "integrity": "sha512-y0m1JoUZSlPAjXVtPPW70aZWfIL/dSP7AFkRnniLCrK/8MDKog3TySTBmckD+RObVxH0v4Tox67+F14PdED2oQ==", - "license": "MIT" + "license": "MIT", + "peer": true }, "node_modules/shebang-command": { "version": "2.0.0", @@ -7145,6 +7153,7 @@ "resolved": "https://registry.npmjs.org/styled-components/-/styled-components-5.3.11.tgz", "integrity": "sha512-uuzIIfnVkagcVHv9nE0VPlHPSCmXIUGKfJ42LNjxCCTDTL5sgnJ8Z7GZBq0EnLYGln77tPpEpExt2+qa+cZqSw==", "license": "MIT", + "peer": true, "dependencies": { "@babel/helper-module-imports": "^7.0.0", "@babel/traverse": "^7.4.5", @@ -7174,7 +7183,8 @@ "version": "0.7.5", "resolved": "https://registry.npmjs.org/@emotion/unitless/-/unitless-0.7.5.tgz", "integrity": "sha512-OWORNpfjMsSSUBVrRBVGECkhWcULOAJz9ZW8uK9qgxD+87M7jHRcvh/A96XXNhXTLmKcoYSQtBEX7lHMO7YRwg==", - "license": "MIT" + "license": "MIT", + "peer": true }, "node_modules/stylis": { "version": "4.2.0", @@ -7192,6 +7202,7 @@ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", "license": "MIT", + "peer": true, "dependencies": { "has-flag": "^3.0.0" }, @@ -7558,7 +7569,6 @@ "resolved": "https://registry.npmjs.org/vite/-/vite-7.3.1.tgz", "integrity": "sha512-w+N7Hifpc3gRjZ63vYBXA56dvvRlNWRczTdmCBBa+CotUzAPf5b7YMdMR/8CQoeYE5LX3W4wj6RYTgonm1b9DA==", "license": "MIT", - "peer": true, "dependencies": { "esbuild": "^0.27.0", "fdir": "^6.5.0", @@ -7763,7 +7773,6 @@ "resolved": "https://registry.npmjs.org/winston/-/winston-3.19.0.tgz", "integrity": "sha512-LZNJgPzfKR+/J3cHkxcpHKpKKvGfDZVPS4hfJCc4cCG0CgYzvlD6yE/S3CIL/Yt91ak327YCpiF/0MyeZHEHKA==", "license": "MIT", - "peer": true, "dependencies": { "@colors/colors": "^1.6.0", "@dabh/diagnostics": "^2.0.8", @@ -7885,7 +7894,6 @@ "resolved": "https://registry.npmjs.org/ws/-/ws-8.18.3.tgz", "integrity": "sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg==", "license": "MIT", - "peer": true, "engines": { "node": ">=10.0.0" }, diff --git a/src-editor/public/google-blockly/own/blocks_words.js b/src-editor/public/google-blockly/own/blocks_words.js index 6a5d08055..0af65e7ba 100644 --- a/src-editor/public/google-blockly/own/blocks_words.js +++ b/src-editor/public/google-blockly/own/blocks_words.js @@ -17,6 +17,13 @@ Blockly.Words['loglevel_error'] = { en: 'error', Blockly.Words['with_results'] = { en: 'with results', de: 'mit Ergebnissen', ru: 'анализировать результаты', pt: 'com resultados', nl: 'met resultaten', fr: 'avec des résultats', it: 'con risultati', es: 'con resultados', pl: 'z wynikami', uk: 'з результатами', 'zh-cn': '处理返回值' }; +// --- OID DISPLAY MODES ---------------------------------------- +Blockly.Words['oid_display_name'] = { en: 'Show name', de: 'Name anzeigen', ru: 'Показать имя', pt: 'Mostrar nome', nl: 'Naam tonen', fr: 'Afficher le nom', it: 'Mostra nome', es: 'Mostrar nombre', pl: 'Pokaż nazwę', uk: 'Показати назву', 'zh-cn': '显示名称' }; +Blockly.Words['oid_display_path'] = { en: 'Show name path', de: 'Namenspfad anzeigen', ru: 'Показать путь имён', pt: 'Mostrar caminho do nome', nl: 'Naampad tonen', fr: 'Afficher le chemin du nom', it: 'Mostra percorso nome', es: 'Mostrar ruta de nombre', pl: 'Pokaż ścieżkę nazwy', uk: 'Показати шлях назви', 'zh-cn': '显示名称路径' }; +Blockly.Words['oid_display_id'] = { en: 'Show ID', de: 'ID anzeigen', ru: 'Показать ID', pt: 'Mostrar ID', nl: 'ID tonen', fr: 'Afficher l\'ID', it: 'Mostra ID', es: 'Mostrar ID', pl: 'Pokaż ID', uk: 'Показати ID', 'zh-cn': '显示ID' }; +Blockly.Words['oid_display_full_id'] = { en: 'Show full ID', de: 'Vollständige ID anzeigen', ru: 'Показать полный ID', pt: 'Mostrar ID completo', nl: 'Volledige ID tonen', fr: 'Afficher l\'ID complet', it: 'Mostra ID completo', es: 'Mostrar ID completo', pl: 'Pokaż pełne ID', uk: 'Показати повний ID', 'zh-cn': '显示完整ID' }; +Blockly.Words['oid_show_icon'] = { en: 'Show icon', de: 'Icon anzeigen', ru: 'Показать значок', pt: 'Mostrar ícone', nl: 'Pictogram tonen', fr: 'Afficher l\'icône', it: 'Mostra icona', es: 'Mostrar icono', pl: 'Pokaż ikonę', uk: 'Показати значок', 'zh-cn': '显示图标' }; + // --- OBJECT -------------------------------------------------- Blockly.Words['Object'] = { en: 'Object', de: 'Objekt', ru: 'Объект', pt: 'Objeto', nl: 'Doel', fr: 'Objet', it: 'Oggetto', es: 'Objeto', pl: 'Obiekt', uk: 'Об\'єкт', 'zh-cn': '对象' }; diff --git a/src-editor/public/google-blockly/own/field_oid.js b/src-editor/public/google-blockly/own/field_oid.js index 00765db8d..526c85a6e 100644 --- a/src-editor/public/google-blockly/own/field_oid.js +++ b/src-editor/public/google-blockly/own/field_oid.js @@ -19,6 +19,7 @@ class FieldOID extends Blockly.Field { this.CURSOR = 'pointer'; this.SERIALIZABLE = true; this.spellcheck_ = false; + this.maxDisplayLength = 200; } dispose() { @@ -26,6 +27,235 @@ class FieldOID extends Blockly.Field { super.dispose(); } + initView() { + super.initView(); + const id = this.getValue(); + if (id) { + this.updateIcon_(id); + } + } + + static _resolveObjectName(id) { + const objects = window.main.objects; + if (!objects || !objects[id] || !objects[id].common || !objects[id].common.name) { + return null; + } + let name = objects[id].common.name; + if (typeof name === 'object') { + name = name[systemLang] || name.en; + } + return name || null; + } + + static computeDisplayText(id, maxLen) { + const mode = FieldOID.displayMode; + const objects = window.main.objects; + let text; + + switch (mode) { + case 1: { // Path: all parent names joined with "." + const parts = id.split('.'); + const names = []; + for (let i = 0; i < parts.length; i++) { + const ancestorId = parts.slice(0, i + 1).join('.'); + const name = FieldOID._resolveObjectName(ancestorId); + names.push(name || parts[i]); + } + text = names.join('.'); + break; + } + case 2: // State ID: last segment only + text = id.split('.').pop() || id; + break; + case 3: // Full ID + text = id; + break; + default: { // Mode 0: Name (current behavior) + text = FieldOID._resolveObjectName(id) || id; + break; + } + } + + // Append type suffix for non-state objects + if (objects && objects[id]?.type && !['state', 'meta', 'script'].includes(objects[id].type)) { + text += ` (${objects[id].type})`; + } + + if (maxLen && text.length > maxLen) { + text = text.substring(0, maxLen - 2) + '\u2026'; + } + + // Replace whitespace with non-breaking spaces so the text doesn't collapse. + text = text.replace(/\s/g, Blockly.Field.NBSP); + + return text || Blockly.Field.NBSP; + } + + refreshDisplay() { + const id = this.getValue(); + if (id) { + this._idName = FieldOID.computeDisplayText(id, this.maxDisplayLength); + this.updateIcon_(id); + this.forceRerender(); + // For path mode, async-fetch parent objects to resolve names + if (FieldOID.displayMode === 1) { + this._resolvePathNamesAsync(id); + } + } + } + + _resolvePathNamesAsync(id) { + if (typeof window.main.getObject !== 'function') return; + const objects = window.main.objects; + const parts = id.split('.'); + let pending = 0; + let updated = false; + for (let i = 0; i < parts.length; i++) { + const ancestorId = parts.slice(0, i + 1).join('.'); + if (objects[ancestorId]) continue; // already cached + pending++; + window.main.getObject(ancestorId, (err, obj) => { + if (obj) { + objects[obj._id] = objects[obj._id] || obj; + updated = true; + } + pending--; + if (pending === 0 && updated) { + this._idName = FieldOID.computeDisplayText(id, this.maxDisplayLength); + this.forceRerender(); + } + }); + } + } + + _getIconOffset() { + return (FieldOID.showIcon && this._iconElement) ? 20 : 0; + } + + // Override Blockly's size + position to account for icon + updateSize_(margin) { + const constants = this.getConstants(); + const xPad = margin !== undefined ? margin : + (this.isFullBlockField() ? 0 : constants.FIELD_BORDER_RECT_X_PADDING); + const iconOffset = this._getIconOffset(); + + let textWidth = 0; + if (this.textElement_) { + textWidth = this.textElement_.getComputedTextLength(); + } + + let totalWidth = 2 * xPad + textWidth + iconOffset; + let totalHeight = constants.FIELD_TEXT_HEIGHT; + if (!this.isFullBlockField()) { + totalHeight = Math.max(totalHeight, constants.FIELD_BORDER_RECT_HEIGHT); + } + + this.size_.height = totalHeight; + this.size_.width = totalWidth; + + this.positionTextElement_(xPad + iconOffset, textWidth); + this.positionBorderRect_(); + } + + updateIcon_(id) { + if (!this.fieldGroup_) { + return; + } + if (!FieldOID.showIcon) { + if (this._iconElement) { + this._iconElement.remove(); + this._iconElement = null; + this._iconUrl = null; + } + return; + } + // First try synchronous resolve with cached objects + const iconUrl = FieldOID.resolveIcon(id); + if (iconUrl) { + this._applyIcon(iconUrl); + } + // Then async-fetch parent objects to find a closer (more specific) icon + this._resolveIconAsync(id); + } + + _applyIcon(iconUrl) { + if (!this.fieldGroup_) return; + if (this._iconUrl === iconUrl && this._iconElement) { + return; + } + this._iconUrl = iconUrl; + const iconSize = 16; + if (!this._iconElement) { + this._iconElement = document.createElementNS('http://www.w3.org/2000/svg', 'image'); + this._iconElement.setAttribute('width', String(iconSize)); + this._iconElement.setAttribute('height', String(iconSize)); + if (this.textElement_) { + this.fieldGroup_.insertBefore(this._iconElement, this.textElement_); + } else { + this.fieldGroup_.appendChild(this._iconElement); + } + } + this._iconElement.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', iconUrl); + this._positionIcon(); + } + + _positionIcon() { + if (!this._iconElement || !this.textElement_) return; + const iconSize = 16; + try { + // Position icon at the start of the field content area + const constants = this.getConstants(); + const xPad = this.borderRect_ ? constants.FIELD_BORDER_RECT_X_PADDING : 0; + this._iconElement.setAttribute('x', String(xPad + 2)); + + // Vertically center icon with text + const textBBox = this.textElement_.getBBox(); + if (textBBox.height > 0) { + const textMidY = textBBox.y + textBBox.height / 2; + this._iconElement.setAttribute('y', String(textMidY - iconSize / 2)); + } + } catch (e) { + // getBBox can fail if element is not in DOM yet + } + } + + _resolveIconAsync(id) { + if (!FieldOID.showIcon || typeof window.main.getObject !== 'function') { + return; + } + const objects = window.main.objects; + const parts = id.split('.'); + const adapterName = parts[0]; + // Fetch ancestors from state level up to adapter instance level + // Start from the state itself, go up - first icon found wins + let remaining = parts.length; + const tryNext = (idx) => { + if (idx < 1) return; + const ancestorId = parts.slice(0, idx).join('.'); + // Already in cache? + if (objects[ancestorId]) { + if (objects[ancestorId].common && objects[ancestorId].common.icon) { + this._applyIcon(FieldOID._buildIconUrl(objects[ancestorId].common.icon, adapterName)); + return; // Found closest icon, stop + } + tryNext(idx - 1); // No icon here, try parent + return; + } + // Fetch this ancestor + window.main.getObject(ancestorId, (err, obj) => { + if (obj) { + objects[obj._id] = objects[obj._id] || obj; + if (obj.common && obj.common.icon) { + this._applyIcon(FieldOID._buildIconUrl(obj.common.icon, adapterName)); + return; // Found closest icon, stop + } + } + tryNext(idx - 1); // Try parent + }); + }; + tryNext(remaining); + } + setValue(id) { if (id === null) { return; // No change if null. @@ -38,50 +268,26 @@ class FieldOID extends Blockly.Field { window.main.getObject(id, (err, obj) => { if (obj) { objects[obj._id] = objects[obj._id] || obj; - let text = objects[obj._id].common && objects[obj._id].common.name && objects[obj._id].common.name; + const text = FieldOID.computeDisplayText(id, this.maxDisplayLength); if (text) { - if (typeof text === 'object') { - text = text[systemLang] || text.en; - } - if (text.length > this.maxDisplayLength) { - // Truncate displayed string and add an ellipsis ('...'). - text = text.substring(0, this.maxDisplayLength - 2) + '\u2026'; - } - if (objects && objects[id] && objects[id]?.type && !['state', 'meta', 'script'].includes(objects[id].type)) { - text += ` (${objects[id].type})`; - } - // Replace whitespace with non-breaking spaces so the text doesn't collapse. - text = text.replace(/\s/g, Blockly.Field.NBSP); - - if (text) { - this._idName = text; - this.forceRerender(); - } + this._idName = text; + this.forceRerender(); + } + // Resolve parent names for path mode + if (FieldOID.displayMode === 1) { + this._resolvePathNamesAsync(id); } } }); } else { - let text = objects && objects[id] && objects[id].common && objects[id].common.name ? objects[id].common.name : id; - if (typeof text === 'object') { - text = text[systemLang] || text.en; + this._idName = FieldOID.computeDisplayText(id, this.maxDisplayLength); + // Resolve parent names for path mode + if (FieldOID.displayMode === 1) { + this._resolvePathNamesAsync(id); } - if (text.length > this.maxDisplayLength) { - // Truncate the displayed string and add an ellipsis ('...'). - text = text.substring(0, this.maxDisplayLength - 2) + '\u2026'; - } - if (objects && objects[id] && objects[id]?.type && !['state', 'meta', 'script'].includes(objects[id].type)) { - text += ` (${objects[id].type})`; - } - // Replace whitespace with non-breaking spaces so the text doesn't collapse. - text = text.replace(/\s/g, Blockly.Field.NBSP); - - if (!text) { - // Prevent the field from disappearing if empty. - text = Blockly.Field.NBSP; - } - this._idName = text; } + this.updateIcon_(id); super.setValue(id); super.setTooltip(id); } @@ -98,7 +304,6 @@ class FieldOID extends Blockly.Field { } // Replace whitespace with non-breaking spaces so the text doesn't collapse. text = text.replace(/\s/g, Blockly.Field.NBSP); - if (this.sourceBlock_.RTL) { // The SVG is LTR, force text to be RTL. text += '\u200F'; @@ -214,6 +419,75 @@ class FieldOID extends Blockly.Field { } } +FieldOID.DISPLAY_MODE_KEYS = ['oid_display_name', 'oid_display_path', 'oid_display_id', 'oid_display_full_id']; +FieldOID.displayMode = parseInt(localStorage.getItem('Blockly.FieldOID.displayMode') || '0', 10) || 0; +FieldOID.showIcon = localStorage.getItem('Blockly.FieldOID.showIcon') === 'true'; + +FieldOID._buildIconUrl = function (icon, adapterName) { + if (!icon) return null; + // base64 data URIs and absolute URLs are used as-is + if (icon.startsWith('data:') || icon.startsWith('http://') || icon.startsWith('https://') || icon.startsWith('/')) { + return icon; + } + return '/adapter/' + adapterName + '/' + icon; +}; + +FieldOID.resolveIcon = function (id) { + const objects = window.main.objects; + if (!objects) return null; + const parts = id.split('.'); + const adapterName = parts[0]; + // Walk up the object hierarchy looking for common.icon + for (let i = parts.length; i >= 1; i--) { + const ancestorId = parts.slice(0, i).join('.'); + const obj = objects[ancestorId]; + if (obj && obj.common && obj.common.icon) { + return FieldOID._buildIconUrl(obj.common.icon, adapterName); + } + } + // Fallback: check system.adapter.{adapterName}.{instance} (e.g. system.adapter.zigbee2mqtt.0) + if (parts.length >= 2) { + const instanceId = 'system.adapter.' + parts[0] + '.' + parts[1]; + const sysInstance = objects[instanceId]; + if (sysInstance && sysInstance.common && sysInstance.common.icon) { + return FieldOID._buildIconUrl(sysInstance.common.icon, adapterName); + } + } + return null; +}; + +FieldOID.setDisplayMode = function (mode, workspace) { + FieldOID.displayMode = mode; + localStorage.setItem('Blockly.FieldOID.displayMode', String(mode)); + + const blocks = workspace.getAllBlocks(false); + for (const block of blocks) { + for (const input of block.inputList) { + for (const field of input.fieldRow) { + if (field instanceof FieldOID) { + field.refreshDisplay(); + } + } + } + } +}; + +FieldOID.setShowIcon = function (show, workspace) { + FieldOID.showIcon = show; + localStorage.setItem('Blockly.FieldOID.showIcon', String(show)); + + const blocks = workspace.getAllBlocks(false); + for (const block of blocks) { + for (const input of block.inputList) { + for (const field of input.fieldRow) { + if (field instanceof FieldOID) { + field.refreshDisplay(); + } + } + } + } +}; + Blockly.FieldOID = FieldOID; //Blockly.Field.register('field_oid', FieldOID); diff --git a/src-editor/src/Components/BlocklyEditor.tsx b/src-editor/src/Components/BlocklyEditor.tsx index 533d70d7b..63322c5fc 100644 --- a/src-editor/src/Components/BlocklyEditor.tsx +++ b/src-editor/src/Components/BlocklyEditor.tsx @@ -76,6 +76,7 @@ class BlocklyEditor extends React.Component void; + private resizeObserver: ResizeObserver | null = null; private didUpdate: ReturnType | null = null; private lastCommand = ''; private lastSearch: string; @@ -406,6 +407,197 @@ class BlocklyEditor extends React.Component${xml}`; + } + xml = xml.replace(/[\n\r]/g, '').replace(/.*<\/variables>/g, ''); + + const aiDom = BlocklyEditor.Blockly.utils.xml.textToDom(xml); + const aiTopBlocks = Array.from(aiDom.querySelectorAll(':scope > block')) as Element[]; + if (aiTopBlocks.length === 0) { + return; + } + + // Create fingerprints for matching: block type + direct field values + const fingerprint = (blockEl: Element): string => { + const type = blockEl.getAttribute('type') || ''; + const fields: string[] = []; + for (const child of Array.from(blockEl.children)) { + if (child.tagName === 'field') { + fields.push(`${child.getAttribute('name')}=${child.textContent}`); + } + if (child.tagName === 'mutation') { + fields.push(`mut:${child.outerHTML}`); + } + } + return `${type}|${fields.join(',')}`; + }; + + // Fingerprint workspace blocks via their XML serialization + const wsFingerprint = (block: any): string => { + const type: string = block.type || ''; + const fields: string[] = []; + for (const input of block.inputList || []) { + for (const field of input.fieldRow || []) { + if (field.name && field.getValue) { + fields.push(`${field.name}=${field.getValue()}`); + } + } + } + if (block.mutationToDom) { + try { + const mutation = block.mutationToDom(); + if (mutation) { + fields.push(`mut:${mutation.outerHTML}`); + } + } catch { + /* ignore */ + } + } + return `${type}|${fields.join(',')}`; + }; + + // Build fingerprints for AI blocks + const aiFps = aiTopBlocks.map(b => fingerprint(b)); + + // Get current workspace top-level blocks and their fingerprints + const wsTopBlocks = this.blocklyWorkspace.getTopBlocks(false); + const wsFps = wsTopBlocks.map((b: any) => wsFingerprint(b)); + const wsMatched = new Array(wsTopBlocks.length).fill(false); + + // Match AI blocks to workspace blocks by fingerprint (type + fields) + // Store the position of matched blocks for replacement + const matchPositions: Array<{ x: number; y: number } | null> = []; + for (let ai = 0; ai < aiFps.length; ai++) { + let found = false; + // First try exact fingerprint match + for (let ws = 0; ws < wsFps.length; ws++) { + if (!wsMatched[ws] && aiFps[ai] === wsFps[ws]) { + wsMatched[ws] = true; + const pos = wsTopBlocks[ws].getRelativeToSurfaceXY(); + matchPositions.push({ x: pos.x, y: pos.y }); + found = true; + break; + } + } + if (!found) { + // Fallback: match by block type only + const aiType = aiTopBlocks[ai].getAttribute('type') || ''; + for (let ws = 0; ws < wsTopBlocks.length; ws++) { + if (!wsMatched[ws] && wsTopBlocks[ws].type === aiType) { + wsMatched[ws] = true; + const pos = wsTopBlocks[ws].getRelativeToSurfaceXY(); + matchPositions.push({ x: pos.x, y: pos.y }); + found = true; + break; + } + } + } + if (!found) { + matchPositions.push(null); // New block, no position yet + } + } + + // Start undo group - use window.Blockly for full API access + const Blockly = (window as any).Blockly; + const groupId = Blockly.utils.idGenerator.genUid(); + Blockly.Events.setGroup(groupId); + + window.scripts.loading = true; + + // Delete matched workspace blocks (they will be replaced) + for (let ws = 0; ws < wsTopBlocks.length; ws++) { + if (wsMatched[ws]) { + wsTopBlocks[ws].dispose(false); + } + } + + // Auto-arrange AI blocks that share positions + if (aiTopBlocks.length > 1) { + const positions = new Set(); + for (const block of aiTopBlocks) { + positions.add(`${block.getAttribute('x') || '0'},${block.getAttribute('y') || '0'}`); + } + if (positions.size === 1) { + let yOff = 10; + for (const block of aiTopBlocks) { + block.setAttribute('x', '10'); + block.setAttribute('y', String(yOff)); + yOff += 200; + } + } + } + + // Append all AI blocks to workspace + BlocklyEditor.Blockly.Xml.appendDomToWorkspace(aiDom, this.blocklyWorkspace); + + // Position the newly added blocks + const allTopBlocks = this.blocklyWorkspace.getTopBlocks(false); + const newBlocks = allTopBlocks.slice(-aiTopBlocks.length); + + // Calculate bottom of existing blocks for new block placement + let maxY = 10; + for (const block of allTopBlocks.slice(0, -aiTopBlocks.length)) { + const pos = block.getRelativeToSurfaceXY(); + const hw = block.getHeightWidth(); + maxY = Math.max(maxY, pos.y + hw.height + 30); + } + + for (let i = 0; i < newBlocks.length; i++) { + const pos = matchPositions[i]; + if (pos) { + // Matched block: place at original position + const cur = newBlocks[i].getRelativeToSurfaceXY(); + newBlocks[i].moveBy(pos.x - cur.x, pos.y - cur.y); + } else { + // New block: place below existing blocks + const cur = newBlocks[i].getRelativeToSurfaceXY(); + newBlocks[i].moveBy(10 - cur.x, maxY - cur.y); + maxY += newBlocks[i].getHeightWidth().height + 20; + } + } + + window.scripts.loading = false; + + // End undo group + Blockly.Events.setGroup(false); + + this.onBlocklyChanged(); + } catch (e) { + window.scripts.loading = false; + (window as any).Blockly?.Events?.setGroup(false); + console.error('Error applying AI blocks:', e); + } + } + + /** Get the current workspace XML (used by AI Chat) */ + public getWorkspaceXml(): string { + if (!this.blocklyWorkspace) { + return ''; + } + const dom = BlocklyEditor.Blockly.Xml.workspaceToDom(this.blocklyWorkspace); + return BlocklyEditor.Blockly.Xml.domToPrettyText(dom); + } + blocklyCode2JSCode(oneWay?: boolean): string { if (!this.blocklyWorkspace) { return ''; @@ -481,8 +673,43 @@ class BlocklyEditor extends React.Component block')) as Element[]; + if (topBlocksList.length > 1) { + // Check if all blocks share the same position (likely AI-generated) + const positions = new Set(); + for (const block of topBlocksList) { + positions.add(`${block.getAttribute('x') || '0'},${block.getAttribute('y') || '0'}`); + } + if (positions.size === 1) { + // All at same position - space them out with rough estimates + let yOffset = parseInt(topBlocksList[0].getAttribute('y') || '0', 10); + for (const block of topBlocksList) { + block.setAttribute('y', String(yOffset)); + yOffset += 200; + } + } + } + BlocklyEditor.Blockly.Xml.appendDomToWorkspace(xmlBlocks, this.blocklyWorkspace); + // Refine layout: re-stack the newly added blocks with actual heights + if (topBlocksList.length > 1) { + const wsTopBlocks = this.blocklyWorkspace.getTopBlocks(false); + // The last N blocks are the ones we just added + const newBlocks = wsTopBlocks.slice(-topBlocksList.length); + if (newBlocks.length > 1) { + let currentY = newBlocks[0].getRelativeToSurfaceXY().y; + for (const block of newBlocks) { + const pos = block.getRelativeToSurfaceXY(); + block.moveBy(0, currentY - pos.y); + currentY += block.getHeightWidth().height + 20; + } + } + } + window.scripts.loading = false; this.onBlocklyChanged(); @@ -535,6 +762,11 @@ class BlocklyEditor extends React.Component this.onResize()); + this.resizeObserver.observe(this.blockly); + } toolboxText = toolboxText || (await this.getToolbox()); toolboxXml = toolboxXml || BlocklyEditor.Blockly.utils.xml.textToDom(toolboxText); @@ -610,6 +842,30 @@ class BlocklyEditor extends React.Component void) | undefined; + // Blockly's configureContextMenu uses internal types not easily importable + (workspace as unknown as { configureContextMenu: (options: unknown[], e: Event) => void }).configureContextMenu = (menuOptions: unknown[], _e: Event) => { + if (origConfigureContextMenu) { + origConfigureContextMenu.call(workspace, menuOptions, _e); + } + const FieldOID = window.Blockly.FieldOID!; + const keys = FieldOID.DISPLAY_MODE_KEYS; + for (let index = 0; index < keys.length; index++) { + const label = BlocklyEditor.Blockly.Words?.[keys[index]]?.[I18n.getLanguage()] || BlocklyEditor.Blockly.Words?.[keys[index]]?.en || keys[index]; + menuOptions.push({ + text: `${FieldOID.displayMode === index ? '\u2713 ' : ' '}${label}`, + enabled: true, + callback: () => FieldOID.setDisplayMode(index, workspace), + scope: { workspace }, + weight: 200 + index, + }); + } + }; + } + this.updateBackground(); setTimeout(() => this.searchId(), 200); // select found blocks } @@ -633,6 +889,10 @@ class BlocklyEditor extends React.Component FlyoutDefinition; }; + FieldOID?: { + DISPLAY_MODE_KEYS: string[]; + displayMode: number; + showIcon: boolean; + setDisplayMode: (mode: number, workspace: WorkspaceSvg) => void; + setShowIcon: (show: boolean, workspace: WorkspaceSvg) => void; + }; }; } } @@ -647,6 +654,30 @@ class BlocklyEditor extends React.Component void) | undefined; + // Blockly's configureContextMenu uses internal types not easily importable + (workspace as unknown as { configureContextMenu: (options: unknown[], e: Event) => void }).configureContextMenu = (menuOptions: unknown[], _e: Event) => { + if (origConfigureContextMenu) { + origConfigureContextMenu.call(workspace, menuOptions, _e); + } + const FieldOID = window.Blockly.FieldOID!; + const keys = FieldOID.DISPLAY_MODE_KEYS; + for (let index = 0; index < keys.length; index++) { + const label = window.Blockly.Words?.[keys[index]]?.[I18n.getLanguage()] || window.Blockly.Words?.[keys[index]]?.en || keys[index]; + menuOptions.push({ + text: `${FieldOID.displayMode === index ? '\u2713 ' : ' '}${label}`, + enabled: true, + callback: () => FieldOID.setDisplayMode(index, workspace), + scope: { workspace }, + weight: 200 + index, + }); + } + }; + } + this.updateBackground(); setTimeout(() => this.searchId(), 200); // select found blocks } diff --git a/src-editor/src/Components/blockly-plugins/index.ts b/src-editor/src/Components/blockly-plugins/index.ts index 1985b9717..4b87b4f48 100644 --- a/src-editor/src/Components/blockly-plugins/index.ts +++ b/src-editor/src/Components/blockly-plugins/index.ts @@ -81,6 +81,13 @@ export interface BlocklyType { createBlockDefinitionsFromJsonArray: (jsonArray: any[]) => Record; defineBlocks: (blocks: { [key: string]: any }) => void; }; + FieldOID?: { + DISPLAY_MODE_KEYS: string[]; + displayMode: number; + showIcon: boolean; + setDisplayMode: (mode: number, workspace: WorkspaceSvgType) => void; + setShowIcon: (show: boolean, workspace: WorkspaceSvgType) => void; + }; } declare global { diff --git a/src-editor/src/Editor.tsx b/src-editor/src/Editor.tsx index 6863f33e3..91e667e35 100644 --- a/src-editor/src/Editor.tsx +++ b/src-editor/src/Editor.tsx @@ -12,6 +12,7 @@ import { Menu, MenuItem, Checkbox, + Divider, Dialog, DialogTitle, DialogContent, @@ -64,6 +65,13 @@ import ImgBlockly2Js from './assets/blockly2js.svg'; import ImgRules2Js from './assets/rules2js.svg'; import ImgRules from './assets/rules.svg'; +import ImgOidName from './assets/oid-name.svg'; +import ImgOidNamePath from './assets/oid-name-path.svg'; +import ImgOidId from './assets/oid-id.svg'; +import ImgOidIdFull from './assets/oid-id-full.svg'; + +const OID_DISPLAY_MODE_ICONS = [ImgOidName, ImgOidNamePath, ImgOidId, ImgOidIdFull]; + import { I18n, DialogCron, @@ -276,6 +284,9 @@ interface EditorState { confirm: string; askAboutDebug: boolean; menuDebugAnchorEl: null | HTMLElement; + menuOidDisplayAnchorEl: null | HTMLElement; + oidDisplayMode: number; + oidShowIcon: boolean; triggerPrettier: number; openAiDialog: boolean; scriptConflict: string; @@ -361,6 +372,9 @@ class Editor extends React.Component { instancesLoaded: false, isTourOpen: window.localStorage.getItem('tour') !== 'true', menuDebugAnchorEl: null, + menuOidDisplayAnchorEl: null, + oidDisplayMode: parseInt(window.localStorage.getItem('Blockly.FieldOID.displayMode') || '0', 10) || 0, + oidShowIcon: window.localStorage.getItem('Blockly.FieldOID.showIcon') === 'true', menuOpened: !!this.props.menuOpened, menuTabsOpened: false, openAiDialog: false, @@ -1435,6 +1449,77 @@ class Editor extends React.Component { ) : null}
+ + {this.state.blockly && !this.state.showCompiledCode && ( + this.setState({ menuOidDisplayAnchorEl: e.currentTarget })} + size="medium" + > + OID + + )} + this.setState({ menuOidDisplayAnchorEl: null })} + > + {OID_DISPLAY_MODE_ICONS.map((icon, index) => ( + { + this.setState({ oidDisplayMode: index, menuOidDisplayAnchorEl: null }); + const workspace = window.scripts?.blocklyWorkspace; + if (workspace && window.Blockly?.FieldOID?.setDisplayMode) { + window.Blockly.FieldOID.setDisplayMode(index, workspace); + } + }} + > + + {(() => { + const key = window.Blockly?.FieldOID?.DISPLAY_MODE_KEYS?.[index]; + const fallback = ['Show name', 'Show name path', 'Show ID', 'Show full ID']; + if (!key) return fallback[index]; + return window.Blockly?.Words?.[key]?.[I18n.getLanguage()] || window.Blockly?.Words?.[key]?.en || fallback[index]; + })()} + + ))} + + { + const newVal = !this.state.oidShowIcon; + this.setState({ oidShowIcon: newVal }); + const workspace = window.scripts?.blocklyWorkspace; + if (workspace && window.Blockly?.FieldOID?.setShowIcon) { + window.Blockly.FieldOID.setShowIcon(newVal, workspace); + } + }} + > + + {(() => { + const key = 'oid_show_icon'; + return window.Blockly?.Words?.[key]?.[I18n.getLanguage()] || window.Blockly?.Words?.[key]?.en || 'Show icon'; + })()} + + + {!this.props.debugInstance && !this.state.showCompiledCode && ( + + + ID + + + + diff --git a/src-editor/src/assets/oid-id.svg b/src-editor/src/assets/oid-id.svg new file mode 100644 index 000000000..3cad71f61 --- /dev/null +++ b/src-editor/src/assets/oid-id.svg @@ -0,0 +1,5 @@ + + + + ID + diff --git a/src-editor/src/assets/oid-name-path.svg b/src-editor/src/assets/oid-name-path.svg new file mode 100644 index 000000000..717cf20c5 --- /dev/null +++ b/src-editor/src/assets/oid-name-path.svg @@ -0,0 +1,8 @@ + + + + Name + + + + diff --git a/src-editor/src/assets/oid-name.svg b/src-editor/src/assets/oid-name.svg new file mode 100644 index 000000000..2bca8b31e --- /dev/null +++ b/src-editor/src/assets/oid-name.svg @@ -0,0 +1,5 @@ + + + + Name + diff --git a/src-editor/src/i18n/de.json b/src-editor/src/i18n/de.json index 9fcebcc10..624a40515 100644 --- a/src-editor/src/i18n/de.json +++ b/src-editor/src/i18n/de.json @@ -400,4 +400,6 @@ "Request failed: %s": "Anfrage fehlgeschlagen: %s", "Retry": "Erneut versuchen", "No running javascript instance found": "Keine laufende JavaScript-Instanz gefunden" +, + "OID display mode": "OID-Anzeigemodus" } \ No newline at end of file diff --git a/src-editor/src/i18n/en.json b/src-editor/src/i18n/en.json index 57027793b..cc4cea00c 100644 --- a/src-editor/src/i18n/en.json +++ b/src-editor/src/i18n/en.json @@ -400,4 +400,6 @@ "Request failed: %s": "Request failed: %s", "Retry": "Retry", "No running javascript instance found": "No running javascript instance found" +, + "OID display mode": "OID display mode" } \ No newline at end of file diff --git a/src-editor/src/i18n/es.json b/src-editor/src/i18n/es.json index 7afdbfa4e..ad258f241 100644 --- a/src-editor/src/i18n/es.json +++ b/src-editor/src/i18n/es.json @@ -400,4 +400,6 @@ "Request failed: %s": "Solicitud fallida: %s", "Retry": "Reintentar", "No running javascript instance found": "No se encontró ninguna instancia de JavaScript en ejecución" +, + "OID display mode": "Modo de visualización OID" } \ No newline at end of file diff --git a/src-editor/src/i18n/fr.json b/src-editor/src/i18n/fr.json index 7c396723a..4faeac07a 100644 --- a/src-editor/src/i18n/fr.json +++ b/src-editor/src/i18n/fr.json @@ -400,4 +400,6 @@ "Request failed: %s": "Requête échouée : %s", "Retry": "Réessayer", "No running javascript instance found": "Aucune instance JavaScript en cours d'exécution trouvée" +, + "OID display mode": "Mode d'affichage OID" } \ No newline at end of file diff --git a/src-editor/src/i18n/it.json b/src-editor/src/i18n/it.json index 705bd125d..10e293ed8 100644 --- a/src-editor/src/i18n/it.json +++ b/src-editor/src/i18n/it.json @@ -400,4 +400,6 @@ "Request failed: %s": "Richiesta fallita: %s", "Retry": "Riprova", "No running javascript instance found": "Nessuna istanza JavaScript in esecuzione trovata" +, + "OID display mode": "Modalità di visualizzazione OID" } \ No newline at end of file diff --git a/src-editor/src/i18n/nl.json b/src-editor/src/i18n/nl.json index 1b193bfda..4e21d48aa 100644 --- a/src-editor/src/i18n/nl.json +++ b/src-editor/src/i18n/nl.json @@ -400,4 +400,6 @@ "Request failed: %s": "Verzoek mislukt: %s", "Retry": "Opnieuw proberen", "No running javascript instance found": "Geen draaiende JavaScript-instantie gevonden" +, + "OID display mode": "OID-weergavemodus" } \ No newline at end of file diff --git a/src-editor/src/i18n/pl.json b/src-editor/src/i18n/pl.json index 001b6e9a4..712e49f20 100644 --- a/src-editor/src/i18n/pl.json +++ b/src-editor/src/i18n/pl.json @@ -400,4 +400,6 @@ "Request failed: %s": "Żądanie nie powiodło się: %s", "Retry": "Ponów próbę", "No running javascript instance found": "Nie znaleziono uruchomionej instancji JavaScript" +, + "OID display mode": "Tryb wyświetlania OID" } \ No newline at end of file diff --git a/src-editor/src/i18n/pt.json b/src-editor/src/i18n/pt.json index 9b177ca2c..4c867ba3f 100644 --- a/src-editor/src/i18n/pt.json +++ b/src-editor/src/i18n/pt.json @@ -400,4 +400,6 @@ "Request failed: %s": "Solicitação falhou: %s", "Retry": "Tentar novamente", "No running javascript instance found": "Nenhuma instância JavaScript em execução encontrada" +, + "OID display mode": "Modo de exibição OID" } \ No newline at end of file diff --git a/src-editor/src/i18n/ru.json b/src-editor/src/i18n/ru.json index e7b405a3d..9ce36a905 100644 --- a/src-editor/src/i18n/ru.json +++ b/src-editor/src/i18n/ru.json @@ -400,4 +400,6 @@ "Request failed: %s": "Запрос не удался: %s", "Retry": "Повторить", "No running javascript instance found": "Не найден работающий экземпляр JavaScript" +, + "OID display mode": "Режим отображения OID" } \ No newline at end of file diff --git a/src-editor/src/i18n/uk.json b/src-editor/src/i18n/uk.json index a4f9e6582..97a734958 100644 --- a/src-editor/src/i18n/uk.json +++ b/src-editor/src/i18n/uk.json @@ -400,4 +400,6 @@ "Request failed: %s": "Запит не вдався: %s", "Retry": "Повторити", "No running javascript instance found": "Не знайдено запущеного екземпляра JavaScript" +, + "OID display mode": "Режим відображення OID" } \ No newline at end of file diff --git a/src-editor/src/i18n/zh-cn.json b/src-editor/src/i18n/zh-cn.json index 0c2fc0d7a..e0a0da2da 100644 --- a/src-editor/src/i18n/zh-cn.json +++ b/src-editor/src/i18n/zh-cn.json @@ -400,4 +400,6 @@ "Request failed: %s": "请求失败:%s", "Retry": "重试", "No running javascript instance found": "未找到正在运行的 JavaScript 实例" +, + "OID display mode": "OID显示模式" } \ No newline at end of file