diff --git a/CLAUDE.md b/CLAUDE.md deleted file mode 100644 index 5e7e62f1..00000000 --- a/CLAUDE.md +++ /dev/null @@ -1,93 +0,0 @@ -# CLAUDE.md - -This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. - -## Project Overview - -ioBroker.javascript is a JavaScript/TypeScript/Blockly script engine adapter for the ioBroker home automation platform. It runs as a daemon adapter that executes user-written scripts in a sandboxed environment, with a web-based editor UI (Monaco + Blockly) and an admin configuration panel. - -## Build Commands - -```bash -# Full build (backend TypeScript + both frontends) -npm run build - -# Backend only (TypeScript → build/) -npm run build-backend - -# Editor UI only (src-editor → admin/) -npm run build-editor - -# Admin config UI only (src-admin → admin/custom/) -npm run admin-build - -# Install all dependencies (root + src-editor + src-admin) -npm run npm -``` - -## Testing - -```bash -# All tests (declaration checks + integration) -npm test - -# Individual test suites -npm run test:declarations # TypeScript declaration compilation checks -npm run test:integration # Mocha integration tests (test/testFunctions.js etc.) -npm run test:scheduler # Scheduler/cron tests only -npm run test:package # Package structure validation - -# Run a single test file directly -npx mocha test/testScheduler.js --exit -``` - -Test framework is Mocha, configured via `.mocharc.json`. Tests are in `test/`. - -## Linting - -```bash -npm run lint # Lint backend (root) only -npm run lint-all # Lint root + src-editor + src-admin -``` - -ESLint uses `@iobroker/eslint-config` (flat config in `eslint.config.mjs`). Prettier config extends `@iobroker/eslint-config/prettier.config.mjs`. The root ESLint config only covers `src/` — frontend directories have their own configs. - -## Architecture - -### Three codebases in one repo - -1. **Backend adapter** (`src/` → compiled to `build/`): Node.js TypeScript, compiled to CommonJS. Entry point is `src/main.ts`. Runs as an ioBroker adapter daemon. - -2. **Script editor UI** (`src-editor/`): React + TypeScript app built with Vite. Contains the Monaco code editor, Blockly visual editor, script management sidebar, log viewer, and OpenAI integration. Built output is copied to `admin/` by `tasks.js`. - -3. **Admin config UI** (`src-admin/`): React + TypeScript app built with Vite. Provides adapter configuration via `@iobroker/json-config`. Built output goes to `admin/custom/`. - -Each frontend has its own `package.json`, `node_modules`, and ESLint config. The build orchestration in `tasks.js` handles cleanup, npm installs, compilation, and copying built assets to `admin/`. - -### Key backend modules (`src/lib/`) - -- **`sandbox.ts`** (~244KB) — The script execution sandbox. Provides all global functions available to user scripts (`getState`, `setState`, `on`, `schedule`, `createState`, `httpGet`, etc.). This is the core of the adapter. -- **`scheduler.ts`** — Cron and astro-based scheduling engine (sunrise/sunset events via suncalc2). -- **`protectFs.ts`** — Filesystem access control for sandboxed scripts. -- **`debugger.ts`** — Script debugging support. -- **`mirror.ts`** — Mirrors scripts to/from the filesystem. -- **`javascript.d.ts`** (~140KB) — Complete TypeScript type definitions for the script API, used for editor autocompletion. -- **`typescriptTools.ts`** — TypeScript compilation for user scripts (via `virtual-tsc`). - -### Build orchestration (`tasks.js`) - -Custom Node.js build script using `@iobroker/build-tools`. Supports granular steps via CLI flags (`--0-clean`, `--1-npm`, `--2-build`, `--3-copy`, `--4-patch`). The `npm run build` command runs backend compilation first, then `node tasks` for the full frontend build pipeline. - -### Adapter configuration - -`io-package.json` defines adapter metadata, native configuration defaults, instance objects (astro variables, debug states), and ioBroker dependency requirements (js-controller >=5.0.19, admin >=7.6.1). - -## TypeScript Configuration - -- Backend targets ES2022, compiled to CommonJS (`tsconfig.build.json`) -- `@types/node` major version should match the lowest supported Node.js version -- Frontend apps target Chrome 89+ (Vite build config) - -## CI/CD - -GitHub Actions (`.github/workflows/test-and-release.yml`) runs lint, build, and adapter tests across Node 18/20/22/24 on Ubuntu, Windows, and macOS. Releases are automated via `@alcalzone/release-script` with NPM publish and GitHub release creation. diff --git a/README.md b/README.md index 1ece4f1c..683673bc 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,21 @@ Executes Javascript, Typescript Scripts. -### **WORK IN PROGRESS** +### WORK IN PROGRESS +* 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 +* Human-readable HTTP error messages with API response details +* Two-step AI code generation: plan first, then generate code +* Collapsible plan view in AI code generator UI +* Status display during generation ("Planning..." / "Generating code...") +* Optimized prompts with code examples for better results with small local models +* Compact API reference (docs-compact.md) for reduced context usage +* Disable reasoning/thinking for local models (reasoning_effort: none) +* TODO_DEVICE_ID placeholder when a required device is not in the device list +* Node 25 compatibility: replaced deprecated rmdirSync with rmSync in build tasks +* Flexible result area height in AI code generator (no extra scrollbar) +* Added translations for all 11 languages * (@GermanBluefox) Added support for plain import/export * (@GermanBluefox) Correcting error in configuration * (@GermanBluefox) disallow writing into node_modules folder by scripts diff --git a/admin/assets/OpenAiDialog-BliYIniL.js b/admin/assets/OpenAiDialog-BliYIniL.js new file mode 100644 index 00000000..f9d3550a --- /dev/null +++ b/admin/assets/OpenAiDialog-BliYIniL.js @@ -0,0 +1,89 @@ +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: +${JSON.stringify(i)} + +I need a plan for this task: ${h} + +Answer with max 6 lines. Use FULL device IDs from the list above (e.g. zigbee2mqtt.0.0xa4c1383f5ef5fb07.state). No explanation. No reasoning. +1. IDs: +2. Trigger: +3. Condition: +4. Actions: +5. Else: +6. Extra: +Values are boolean (true/false) or numbers, not strings. Use .state not .state_toggle.`}]});if(k.error){R(k.error),E(!1);return}let s=(k.content||"").trim();s=s.replace(/[\s\S]*?<\/think>/gi,"").trim(),s=s.replace(/<\|endoftext\|>/g,"").trim(),s=s.replace(/<\|im_start\|>[\s\S]*?<\|im_end\|>/g,"").trim(),N(s),E(o.I18n.t("Generating code..."));const Y=await e.socket.sendTo(T,"chatCompletion",{timeout:6e5,apiKey:p,baseUrl:u,model:C,provider:m,messages:[{role:"system",content:`You write ioBroker JavaScript adapter scripts. +Copy EXACTLY this syntax. Do NOT change the callback signature. +IMPORTANT: Write all code at top level. NEVER use console.log (use log instead). NEVER define functions with the function keyword. + +// CORRECT: on() always has ONE callback argument called obj +on('zigbee.0.sensor.state', (obj) => { + // obj.state.val = the new value (boolean or number) + // obj.id = the state ID that changed + setState('zigbee.0.lamp.state', obj.state.val); + log('Changed to ' + obj.state.val); +}); + +// CORRECT: on() with filter +on({id: /zigbee.0..*.state$/, change: 'ne'}, (obj) => { + if (obj.state.val === true) { + setState('zigbee.0.other.state', true); + } +}); + +// Other correct examples: +setState('id', true); +setState('id', 50); +const val = getState('id').val; +schedule('0 7 * * *', () => { log('runs daily at 07:00'); }); +schedule('0 22 * * *', () => { setState('id', false); }); + +// CORRECT Telegram: always use sendTo, NEVER setState on telegram +sendTo('telegram.0', 'send', {text: 'Alert: ' + someValue}); + +// CORRECT httpGet: res.data is a STRING, parse JSON with JSON.parse +httpGet('https://api.example.com/data', (err, res) => { + const data = JSON.parse(res.data); + log('Temperature: ' + data.main.temp); +}); + +$('state[state.id=*.state](rooms=Room)').each((id) => { setState(id, false); }); +createState('name', 0, {type: 'number', name: 'Name'}); +setStateDelayed('id', true, false, 5000); +log(formatDate(new Date(), 'DD.MM.YYYY hh:mm')); + +WRONG: on('id', (id, state) => {}) CORRECT: on('id', (obj) => {}) +WRONG: set('id', true) CORRECT: setState('id', true) +WRONG: adapter.setState('id', true) CORRECT: setState('id', true) +WRONG: obj.val or newState.val CORRECT: obj.state.val +WRONG: on('change', {id: 'x'}, cb) CORRECT: on({id: 'x', change: 'ne'}, cb) +WRONG: setState('telegram.0', text) CORRECT: sendTo('telegram.0', 'send', {text: text}) +WRONG: res.body.main.temp CORRECT: JSON.parse(res.data).main.temp +WRONG: function myFunc() {} CORRECT: write code directly, no function definitions +WRONG: setTimeout(fn, ms) CORRECT: schedule('cron', () => {}) or setStateDelayed() +Values are boolean (true/false) or numbers, NEVER strings like 'ON'/'OFF'. +NEVER use: function keyword, require, import, setInterval, setTimeout, console.log, debug(). + +All available functions (use syntax from examples above): +on(pattern, (obj)=>{}) | once(pattern, (obj)=>{}) | unsubscribe(handler) +setState(id, val) | getState(id).val | setStateChanged(id, val) | setStateDelayed(id, val, ack, ms) | clearStateDelayed(id) +existsState(id) | existsObject(id) | getObject(id) | setObject(id, obj) | extendObject(id, obj) | deleteObject(id) +createState(name, initVal, {type,name,role}) | deleteState(name) | createAlias(name, alias) +schedule(cron, ()=>{}) | clearSchedule(obj) | scheduleById(id, (obj)=>{}) | getSchedules() +sendTo(adapter, cmd, msg) | sendToHost(host, cmd, msg) +$('selector').each((id)=>{}) | $('selector').setState(val) | $('selector').getState() +log(text) | formatDate(date, 'DD.MM.YYYY hh:mm') | formatTimeDiff(ms) | formatValue(val, decimals) +getDateObject(str) | getAstroDate(pattern) | isAstroDay() | compareTime(start, end, op) +exec(cmd, (err,stdout,stderr)=>{}) | httpGet(url, (err,res)=>{}) | httpPost(url, data, (err,res)=>{}) +readFile(adapter, name, (err,data)=>{}) | writeFile(adapter, name, data, cb) | delFile(adapter, name, cb) +onFile(id, name, withFile, cb) | offFile(id, name) | onStop(cb, timeout) +getHistory(inst, {id,start,end,aggregate,count}, cb) | getEnums(name) | getIdByName(name) +wait(ms) | toInt(val) | toFloat(val) | toBoolean(val) +messageTo(target, data) | onMessage(name, cb) | onLog(severity, cb) +setInterval(cb, ms) | clearInterval(id) | setTimeout(cb, ms) | clearTimeout(id) +runScript(name) | startScript(name) | stopScript(name) | isScriptActive(name)`},{role:"user",content:`TASK: ${h} + +PLAN: +${s} + +Write the ioBroker script. Use the exact state IDs from the plan. If the plan contains TODO_DEVICE_ID, keep it as a placeholder with a comment so the user can fill in the correct ID. Write comments in ${_e[o.I18n.getLanguage()]||"English"}. Return ONLY code.`}]});if(Y.error)R(Y.error);else{let j=Y.content||"";j=j.replace(/[\s\S]*?<\/think>/gi,""),j=j.replace(/<\|endoftext\|>/g,""),j=j.replace(/<\|im_start\|>[\s\S]*?<\|im_end\|>/g,""),j=j.replace(/<\|im_start\|>[\s\S]*/g,"");const O=j.match(/```(?:javascript|js|typescript)?\n?([\s\S]*?)```/m);let X;if(O)X=O[1].trim();else{const ce=j.split(` +`),F=[];let J=!1;for(const x of ce){const f=x.trim();!J&&f===""||(!J&&(f.startsWith("//")||f.startsWith("const ")||f.startsWith("let ")||f.startsWith("var ")||f.startsWith("function ")||f.startsWith("async ")||f.startsWith("await ")||f.startsWith("if ")||f.startsWith("for ")||f.startsWith("on(")||f.startsWith("schedule(")||f.startsWith("setState")||f.startsWith("getState")||f.startsWith("createState")||f.startsWith("$")||f.startsWith("'use strict'")||f.startsWith('"use strict"'))&&(J=!0),J&&F.push(x))}for(;F.length>0;){const x=F[F.length-1].trim();if(x===""||x.length>0&&!x.startsWith("//")&&!x.startsWith("*")&&!x.startsWith("}")&&!x.startsWith(");")&&!x.endsWith(";")&&!x.endsWith("}")&&!x.endsWith(")")&&!x.endsWith(",")&&!x.endsWith("{")&&/^[A-Z]/.test(x))F.pop();else break}X=F.join(` +`).trim()}r(X||"")}}catch(k){console.error("Chat request failed:",k),R(o.I18n.t("Request failed: %s",String(k)))}E(!1)},[h,C,e.runningInstances,e.socket]);return n.jsxs(ee,{maxWidth:"lg",sx:{"& .MuiDialog-paper":{height:"calc(100% - 100px)"}},open:!0,onClose:()=>e.onClose(),fullWidth:!0,children:[q&&n.jsxs(ee,{maxWidth:"lg",open:!0,onClose:()=>U(!1),fullWidth:!0,children:[n.jsx(te,{children:o.I18n.t("No API key found")}),n.jsxs(se,{style:{display:"flex",flexDirection:"column",gap:8},children:[n.jsx("div",{children:o.I18n.t("You have to enter at least one API key in the configuration of javascript adapter.")}),n.jsx(K,{variant:"contained",onClick:()=>{const i=Object.keys(e.runningInstances);window.open(`../../#tab-instances/config/${i[0]||"system.adapter.javascript.0"}`,"_blank"),U(!1)},children:o.I18n.t("Open configuration")})]}),n.jsx(ne,{children:n.jsx(K,{variant:"contained",startIcon:n.jsx(ae,{}),onClick:()=>U(!1),children:o.I18n.t("Close")})})]}),n.jsx(te,{children:o.I18n.t("AI code generator")}),n.jsxs(se,{style:{display:"flex",flexDirection:"column",gap:8,height:"100%"},children:[n.jsx("div",{children:n.jsx(me,{variant:"standard",multiline:!0,autoFocus:!0,disabled:!!S,fullWidth:!0,onKeyUp:i=>{i.key==="Enter"&&i.ctrlKey&&B()},label:o.I18n.t("Enter your question"),helperText:o.I18n.t("Press Ctrl+Enter to get the answer"),value:h,onChange:i=>{window.localStorage.setItem("openai-question",i.target.value),a(i.target.value)}})}),n.jsxs("div",{style:{display:"flex",alignItems:"baseline"},children:[n.jsx(K,{variant:"contained",disabled:!!S||!h||!C,startIcon:n.jsx(Se,{}),onClick:async()=>B(),children:S?n.jsxs(n.Fragment,{children:[n.jsx(ue,{size:18,style:{marginRight:8}}),S]}):o.I18n.t("Ask")}),n.jsxs(he,{style:{width:300,marginLeft:20},disabled:!!S,variant:"standard",error:!!c,children:[n.jsx(ge,{children:o.I18n.t("Model")}),n.jsxs(fe,{variant:"standard",value:C,disabled:l||!!c,renderValue:i=>n.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:8},children:[n.jsx(oe,{provider:b.current[i]}),i]}),onChange:i=>{window.localStorage.setItem("openai-model",i.target.value),D&&R(!1),P(i.target.value)},children:[l&&n.jsx(ie,{value:"",disabled:!0,children:o.I18n.t("Loading models...")}),z.map(i=>n.jsx(ie,{value:i,children:n.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:8},children:[n.jsx(oe,{provider:b.current[i]}),i]})},i))]})]}),c&&n.jsx(K,{style:{marginLeft:10},variant:"outlined",color:"error",startIcon:n.jsx(be,{}),onClick:()=>{V()},children:o.I18n.t("Retry")})]}),c&&n.jsx("div",{style:{color:e.themeType==="dark"?"#984242":"#bb0000"},children:c}),$&&n.jsxs("div",{style:{marginBottom:4},children:[n.jsxs(K,{size:"small",variant:"text",onClick:()=>M(!W),style:{textTransform:"none",padding:"2px 8px"},children:[W?"▼":"►"," ",o.I18n.t("Show plan")]}),W&&n.jsx("pre",{style:{margin:"4px 0",padding:8,backgroundColor:e.themeType==="dark"?"#1e1e1e":"#f5f5f5",borderRadius:4,fontSize:12,maxHeight:200,overflow:"auto",whiteSpace:"pre-wrap",wordBreak:"break-word"},children:$})]}),n.jsx("div",{children:o.I18n.t("Result")}),n.jsx("div",{style:{flex:1,minHeight:100,overflow:"hidden"},children:D?n.jsx("div",{style:{color:e.themeType==="dark"?"#984242":"#bb0000"},children:D}):n.jsx(je,{triggerPrettier:1,adapterName:e.adapterName,runningInstances:e.runningInstances,style:{height:"100%",width:"100%",resize:"none"},name:"ai",socket:e.socket,readOnly:!0,checkJs:!0,code:I,isDark:e.themeType==="dark",language:e.language||"javascript"})})]}),n.jsxs(ne,{children:[n.jsx(K,{color:"grey",variant:"outlined",disabled:!I,startIcon:n.jsx(Ie,{}),onClick:()=>{o.Utils.copyToClipboard(I),window.alert(o.I18n.t("Copied"))},children:o.I18n.t("Copy to clipboard")}),n.jsx(K,{color:"primary",variant:"contained",disabled:!I||!!D,startIcon:n.jsx(xe,{}),onClick:()=>{e.onAddCode(I),e.onClose()},children:o.I18n.t("Use generated code")}),n.jsx(K,{color:"grey",variant:"contained",startIcon:n.jsx(ae,{}),onClick:()=>e.onClose(),children:o.I18n.t("Close")})]})]})};export{Ye as default}; diff --git a/admin/assets/docs-BrInh2Pn.js b/admin/assets/docs-BrInh2Pn.js deleted file mode 100644 index 2fb6d797..00000000 --- a/admin/assets/docs-BrInh2Pn.js +++ /dev/null @@ -1,2036 +0,0 @@ -const e=`### exec - execute some OS command, like \`cp file1 file2\` - -\`\`\`js -exec(cmd, [options], callback); -\`\`\` - -Execute system command and get the outputs. - -\`\`\`js -// reboot linux system :) -exec('reboot'); - -// Get the list of files and directories in /var/log -exec('ls /var/log', function (error, stdout, stderr) { - log(\`stdout: \${stdout}\`); -}); -\`\`\` - -Node.js uses /bin/sh to execute commands. If you want to use another shell, you can use the option object as described in the [Node.js documentation](https://nodejs.org/api/child_process.html#child_processexeccommand-options-callback) for child_process.exec. -It is the best practice to always use fill path names to commands to make sure the right command is executed. - -**Notice:** you must enable _Enable command "exec"_ option to use this feature! - -### on - Subscribe on changes or updates of some state - -\`\`\`js -on(pattern, callbackOrId, value); -\`\`\` - -The callback function will return the object as parameter with the following content: - -\`\`\`json -{ - "id": "javascript.0.myplayer", - "state": { - "val": "new state", - "ts": 1416149118, - "ack": true, - "lc": 1416149118, - "from": "system.adapter.sonos.0" - }, - "oldState": { - "val": "old state", - "ts": 1416148233, - "ack": true, - "lc": 1416145154, - "from": "system.adapter.sonos.0" - } -} -\`\`\` - -**Note:** \`state\` was previously called \`newState\`. That is still working. - -Example: - -\`\`\`js -let timer; - -// Create state "javascript.0.counter" -createState('counter', 0); - -// On change -on('adapter.0.device.channel.sensor', data => { - // But not ofter than 30 seconds - if (!timer) { - timer = setTimeout(() => { - timer = null; - }, 30000); - - // Set acknowledged value - setState('counter', 1 + getState('counter'), true /*ack*/); - - // Or to set unacknowledged command - setState('adapter.0.device.channel.actor', true); - } -}); -\`\`\` - -You can use the following parameters to specify the trigger: - -| parameter | type/value | description | -|-------------|------------|-----------------------------------------------------------------------------------------------------------------------------------------------| -| logic | string | "and" or "or" logic to combine the conditions \\(default: "and"\\) | -| | | | -| id | string | id is equal to given one | -| | RegExp | id matched to regular expression | -| | Array | id matched to a list of allowed IDs | -| | | | -| name | string | name is equal to given one | -| | RegExp | name matched to regular expression | -| | Array | name matched to a list of allowed names | -| | | | -| change | string | "eq", "ne", "gt", "ge", "lt", "le", "any" | -| | "eq" | (equal) New value must be equal to old one (state.val == oldState.val) | -| | "ne" | (not equal) New value must be not equal to the old one (state.val != oldState.val) **If pattern is id-string this value is used by default** | -| | "gt" | (greater) New value must be greater than old value (state.val > oldState.val) | -| | "ge" | (greater or equal) New value must be greater or equal to old one (state.val >= oldState.val) | -| | "lt" | (smaller) New value must be smaller than old one (state.val < oldState.val) | -| | "le" | (smaller or equal) New value must be smaller or equal to old value (state.val <= oldState.val) | -| | "any" | Trigger will be raised if just the new value comes | -| | | | -| val | mixed | New value must be equal to given one | -| valNe | mixed | New value must be not equal to given one | -| valGt | mixed | New value must be greater than given one | -| valGe | mixed | New value must be greater or equal to given one | -| valLt | mixed | New value must be smaller than given one | -| valLe | mixed | New value must be smaller or equal to given one | -| | | | -| ack | boolean | Acknowledged state of new value is equal to given one | -| q | number | Quality code state of new value is equal to given one. You can use '\\*' for matching to any code. **If not provided q = 0 is set as pattern!** | -| | | | -| oldVal | mixed | Previous value must be equal to given one | -| oldValNe | mixed | Previous value must be not equal to given one | -| oldValGt | mixed | Previous value must be greater than given one | -| oldValGe | mixed | Previous value must be greater or equal to given one | -| oldValLt | mixed | Previous value must be smaller than given one | -| oldValLe | mixed | Previous value must be smaller or equal to given one | -| | | | -| oldAck | bool | Acknowledged state of previous value is equal to given one | -| oldQ | number | Quality code state of previous value is equal to given one. You can use '\\*' for matching to any code | -| | | | -| ts | string | New value time stamp must be equal to given one (state.ts == ts) | -| tsGt | string | New value time stamp must be not equal to the given one (state.ts != ts) | -| tsGe | string | New value time stamp must be greater than given value (state.ts > ts) | -| tsLt | string | New value time stamp must be greater or equal to given one (state.ts >= ts) | -| tsLe | string | New value time stamp must be smaller than given one (state.ts < ts) | -| | | | -| oldTs | string | Previous time stamp must be equal to given one (oldState.ts == ts) | -| oldTsGt | string | Previous time stamp must be not equal to the given one (oldState.ts != ts) | -| oldTsGe | string | Previous time stamp must be greater than given value (oldState.ts > ts) | -| oldTsLt | string | Previous time stamp must be greater or equal to given one (oldState.ts >= ts) | -| oldTsLe | string | Previous time stamp must be smaller than given one (oldState.ts < ts) | -| | | | -| lc | string | Last change time stamp must be equal to given one (state.lc == lc) | -| lcGt | string | Last change time stamp must be not equal to the given one (state.lc != lc) | -| lcGe | string | Last change time stamp must be greater than given value (state.lc > lc) | -| lcLt | string | Last change time stamp must be greater or equal to given one (state.lc >= lc) | -| lcLe | string | Last change time stamp must be smaller than given one (state.lc < lc) | -| | | | -| oldLc | string | Previous last change time stamp must be equal to given one (oldState.lc == lc) | -| oldLcGt | string | Previous last change time stamp must be not equal to the given one (oldState.lc != lc) | -| oldLcGe | string | Previous last change time stamp must be greater than given value (oldState.lc > lc) | -| oldLcLt | string | Previous last change time stamp must be greater or equal to given one (oldState.lc >= lc) | -| oldLcLe | string | Previous last change time stamp must be smaller than given one (oldState.lc < lc) | -| | | | -| channelId | string | Channel ID must be equal to given one | -| | RegExp | Channel ID matched to regular expression | -| | Array | Channel ID matched to a list of allowed channel IDs | -| | | | -| channelName | string | Channel name must be equal to given one | -| | RegExp | Channel name matched to regular expression | -| | Array | Channel name matched to a list of allowed channel names | -| | | | -| deviceId | string | Device ID must be equal to given one | -| | RegExp | Device ID matched to regular expression | -| | Array | Device ID matched to a list of allowed device IDs | -| | | | -| deviceName | string | Device name must be equal to given one | -| | RegExp | Device name matched to regular expression | -| | Array | Device name matched to a list of allowed device names | -| | | | -| enumId | string | State belongs to given enum | -| | RegExp | One enum ID of the state satisfies the given regular expression | -| | Array | One enum ID of the state is in the given list of enum IDs | -| | | | -| enumName | string | State belongs to given enum | -| | RegExp | One enum name of the state satisfies the given regular expression | -| | Array | One enum name of the state is in the given list of enum names | -| | | | -| from | string | New value is from defined adapter | -| | RegExp | New value is from an adapter that matches the regular expression | -| | Array | New value is from an adapter that appears in the given list of allowed adapters | -| | | | -| fromNe | string | New value is not from defined adapter | -| | RegExp | New value is not from an adapter that matches the regular expression | -| | Array | New value is not from an adapter that appears in the given list of forbidden adapters | -| | | | -| oldFrom | string | Old value is from defined adapter | -| | RegExp | Old value is from an adapter that matches the regular expression | -| | Array | Old value is from an adapter that appears in the given list of allowed adapters | -| | | | -| oldFromNe | string | Old value is not from defined adapter | -| | RegExp | Old value is not from an adapter that matches the regular expression | -| | Array | Old value is not from an adapter that appears in the given list of forbidden adapters | - -Examples: -Trigger on all states with ID \`'*.STATE'\` if they are acknowledged and have new value \`true\`. - -\`\`\`js -{ - id: /\\.STATE$/, - val: true, - ack: true, - logic: 'and' -} -\`\`\` - -**Note:** you can use RegExp directly: - -\`\`\`js -on(/^system\\.adapter\\..*\\.\\d+\\.memRss$/, function (obj) {}); - -// same as -on({ id: /^system\\.adapter\\..*\\.\\d+\\.memRss$/, change: 'ne' }, function (obj) {}); -\`\`\` - -To simply connect two states with each other, write: - -\`\`\`js -on('stateId1', 'stateId2'); -\`\`\` - -All changes of _stateId1_ will be written to _stateId2_. - -If the \`value\` parameter is set in combination with state id as the second parameter, on any change the state will filled with the \`value\`. - -\`\`\`js -on('stateId1', 'stateId2', 'triggered'); -setState('stateId1', 'new value'); - -// stateId2 will be set to 'triggered'. -\`\`\` - -Function \`on\` returns handler back. This handler can be used by unsubscribing. - -_Notice:_ By default only states with quality 0x00 will be passed to callback function. If you want to get all events, add \`{q: '*'}\` to pattern structure. - -_Notice:_ Please note, that by default \`change\` is equal to \`any\`, except when only id as string is set (like \`on('id', () => {});\`). In last case change will be set to "ne". - -_Notice:_ If you want to also get state deletions/expires as trigger, you need to use change with \`ne\` or \`any\` AND q with \`*\` as filter! - -_Notice:_ from 4.3.2 it is possible to write a type of trigger as second parameter: \`on('my.id.0', 'any', obj => log(obj.state.val));\` - -### once - -Registers a one-time subscription which automatically unsubscribes after the first invocation. Same as [on](#on---subscribe-on-changes-or-updates-of-some-state), but just executed once. - -\`\`\`js -once(pattern, callback); -\`\`\` - -### subscribe - same as **[on](#on---subscribe-on-changes-or-updates-of-some-state)** - -### unsubscribe - -\`\`\`js -unsubscribe(id); -// or -unsubscribe(handler); -\`\`\` - -Remove all subscriptions for given object ID or for given handler. - -\`\`\`js -// By handler -let mySubscription = on({ id: 'javascript.0.myState', change: 'any' }, data => { - // unsubscribe after first trigger - if (unsubscribe(mySubscription)) { - log('Subscription deleted'); - } -}); - -// by Object ID -on({ id: 'javascript.0.myState1', change: 'ne' }, data => { - log('Some event'); -}); - -on({ id: 'javascript.0.myState1', change: 'any' }, data => { - // unsubscribe - if (unsubscribe('javascript.0.myState1')) { - log('All subscriptions deleted'); - } -}); -\`\`\` - -### getSubscriptions - -Get the list of subscriptions. - -Example of a result: - -\`\`\`json -{ - "megad.0.dataPointName": [ - { - "name" : "script.js.NameOfScript", - "pattern" : { - "id" : "megad.0.dataPointName", - "change" : "ne" - } - } - ] -} -\`\`\` - -### getFileSubscriptions - -Get the list of file subscriptions. - -Example of a result: - -\`\`\`json -{ - "vis.0$%$main/*": [ - { - "name" : "script.js.NameOfScript", - "id" : "vis.0", - "fileNamePattern": "main/*" - } - ] -} -\`\`\` - -### schedule - -\`\`\`js -schedule(pattern, callback); -\`\`\` - -Time scheduler with astro-function. - -#### Time schedule - -Pattern can be a string with [Cron-Syntax](http://en.wikipedia.org/wiki/Cron), which consists of 5 (without seconds) or 6 (with seconds) digits: - -\`\`\` -* * * * * * -│ │ │ │ │ │ -│ │ │ │ │ │ -│ │ │ │ │ └───── day of week (0 - 6) (0 to 6 are Sunday to Saturday, or use names; 7 is Sunday, the same as 0) -│ │ │ │ └────────── month (1 - 12) -│ │ │ └─────────────── day of month (1 - 31) -│ │ └──────────────────── hour (0 - 23) -│ └───────────────────────── min (0 - 59) -└───────────────────────────── [optional] sec (0 - 59) -\`\`\` - -\`\`\`js -// Example with 5 digits: -schedule('*/2 * * * *', () => { - log('Will be triggered every 2 minutes!'); -}); - -// Example with 6 digits: -schedule('*/3 * * * * *', () => { - log('Will be triggered every 3 seconds!'); -}); -\`\`\` - -The pattern can also be an object, it is used especially if seconds are required: - -the object could have the following properties: - -- \`second\` -- \`minute\` -- \`hour\` -- \`date\` -- \`month\` -- \`year\` -- \`dayOfWeek\` - -\`\`\`js -schedule({ second: [20, 25] }, () => { - log('Will be triggered at xx:xx:20 and xx:xx:25 of every minute!'); -}); - -schedule({ hour: 12, minute: 30 }, () => { - log('Will be triggered at 12:30!'); -}); -\`\`\` - -Pattern can be a JavaScript Date object (some specific time point) - in this case only it will be triggered only one time. - -If start or end times for a schedule are needed, this could also be implemented with usage of an object. In this scenario the object has the properties: - -- \`start\` -- \`end\` -- \`rule\` - -start and end defines a Date object a DateString or a number of milliseconds since 01 January 1970 00:00:00 UTC. -Rule is a schedule string with [Cron-Syntax](http://en.wikipedia.org/wiki/Cron) or an object: - -\`\`\`js -let startTime = new Date(Date.now() + 5000); -let endTime = new Date(startTime.getTime() + 5000); -schedule({ start: startTime, end: endTime, rule: '*/1 * * * * *' }, () => { - log('It will run after 5 seconds and stop after 10 seconds'); -}); -\`\`\` - -The rule itself could be also an object: - -\`\`\`js -let today = new Date(); -let startTime = new Date(today.getFullYear(), today.getMonth(), today.getDate() + 1); -let endTime = new Date(today.getFullYear(), today.getMonth(), today.getDate() + 7); -let ruleData = { hour: 12, minute: 30 }; -schedule({ start: startTime, end: endTime, rule: ruleData }, () => { - log('Will be triggered at 12:30, starting tomorow, ending in 7 days'); -}); -\`\`\` - -#### Astro-function - -Astro-function can be used via "astro" attribute: - -\`\`\`js -schedule({ astro: 'sunrise' }, () => { - log('Sunrise!'); -}); - -schedule({ astro: 'sunset', shift: 10 }, () => { - log('10 minutes after sunset!'); -}); -\`\`\` - -The attribute "shift" is the offset in minutes. It can be negative, too, to define time before astro event. - -The following values can be used as attribute in astro-function: - -- \`"sunrise"\`: sunrise (top edge of the sun appears on the horizon) -- \`"sunriseEnd"\`: sunrise ends (bottom edge of the sun touches the horizon) -- \`"goldenHourEnd"\`: morning golden hour (soft light, the best time for photography) ends -- \`"solarNoon"\`: solar noon (sun is in the highest position) -- \`"goldenHour"\`: evening golden hour starts -- \`"sunsetStart"\`: sunset starts (bottom edge of the sun touches the horizon) -- \`"sunset"\`: sunset (sun disappears below the horizon, evening civil twilight starts) -- \`"dusk"\`: dusk (evening nautical twilight starts) -- \`"nauticalDusk"\`: nautical dusk (evening astronomical twilight starts) -- \`"night"\`: night starts (dark enough for astronomical observations) -- \`"nightEnd"\`: night ends (morning astronomical twilight starts) -- \`"nauticalDawn"\`: nautical dawn (morning nautical twilight starts) -- \`"dawn"\`: dawn (morning nautical twilight ends, morning civil twilight starts) -- \`"nadir"\`: nadir (the darkest moment of the night, sun is in the lowest position) - -**Note:** to use "astro"-function the "latitude" and "longitude" must be defined in JavaScript adapter settings. - -**Note:** in some places sometimes it could be so that no night/nightEnd exists. Please read [here](https://github.com/mourner/suncalc/issues/70) about it. - -**Note:** you can use "on" function for schedule with small modification: - -\`\`\`js -on({ time: '*/2 * * * *' }, () => { - log(new Date().toString() + ' - Will be triggered every 2 minutes!'); -}); - -on({ time: { hour: 12, minute: 30 } }, () => { - log(new Date().toString() + ' - Will be triggered at 12:30!'); -}); - -on({ astro: 'sunset', shift: 10 }, () => { - log(new Date().toString() + ' - 10 minutes after sunset!'); -}); -\`\`\` - -## scheduleById - -\`\`\`js -scheduleById(id, callback); -scheduleById(id, ack, callback); -\`\`\` - -Allows to create a schedule based on a state value. If the state value changes, the old schedule will be deleted and a new schedule is created automatically. - -Supported formats: - -- \`[h]h:[m]m:ss\` (e.g. \`12:42:15\`, \`15:3:12\`, \`3:10:25\`) -- \`[h]h:[m]m\` (e.g. \`13:37\`, \`9:40\`) - -\`\`\`js -scheduleById('0_userdata.0.configurableTimeFormat', () => { - log('Executed!'); -}); -\`\`\` - -Example: Create state and register schedule on changes: - -\`\`\`js -createState( - '0_userdata.0.myTime', - '00:00:00', // default value - { - type: 'string', - read: true, - write: true, - }, - () => { - scheduleById('0_userdata.0.myTime', () => { - log('Executed!'); - }); - }, -); -\`\`\` - -### getSchedules - -\`\`\`js -const list = getSchedules(true); -\`\`\` - -Returns the list of all CRON jobs and schedules (except astro). -Argument must be \`true\` if you want to get the list for **every running script**. Otherwise, only schedules in the current script will be returned. - -\`\`\`js -const list = getSchedules(true); -list.forEach(schedule => log(JSON.stringify(schedule))); - -// clear all schedules in all scripts! -list.forEach(schedule => clearSchedule(schedule)); -\`\`\` - -Example output: - -\`\`\` -2020-11-01 20:15:19.929 - {"type":"cron","pattern":"0 * * * *","scriptName":"script.js.Heizung","id":"cron_1604258108384_74924"} -2020-11-01 20:15:19.931 - {"type":"schedule","schedule":"{"period":{}}","scriptName":"script.js.Heizung","id":"schedule_19576"} -\`\`\` - -### clearSchedule - -If **no** "astro" function is used, you can cancel the schedule later. To allow this, the schedule object must be saved: - -\`\`\`js -let sch = schedule('*/2 * * * *', () => { - /* ... */ -}); - -// later: -clearSchedule(sch); -\`\`\` - -### getAttr - -\`\`\`js -getAttr({ attr1: { attr2: 5 } }, 'attr1.attr2'); -\`\`\` - -Returns an attribute of the object. Path to attribute can be nested, like in the example. - -If the first attribute is string, the function will try to parse the string as JSON string. - -### getAstroDate - -\`\`\`js -getAstroDate(pattern, date, offsetMinutes); -\`\`\` - -Returns a javascript Date object for the specified astro-name (e.g. \`"sunrise"\` or \`"sunriseEnd"\`). For valid values, see the list of allowed values in the [Astro](#astro--function) section in the _schedule_ function. - -The returned Date object is calculated for the passed _date_. If no date is provided, the current day is used. - -\`\`\`js -let sunriseEnd = getAstroDate('sunriseEnd'); -log(\`Sunrise ends today at \${sunriseEnd.toLocaleTimeString()}\`); - -let today = new Date(); -let tomorrow = new Date(today.getFullYear(), today.getMonth(), today.getDate() + 1); -let tomorrowNight = getAstroDate('night', tomorrow); -\`\`\` - -**Note: Depending on your geographical location, there can be cases where e.g. 'night'/'nightEnd' do not exist on certain time points (e.g., locations north in May/June each year!** - -You can use webpages like [suncalc.net](http://suncalc.net) to check if the time points are correct. - -### isAstroDay - -\`\`\`js -isAstroDay(); -\`\`\` - -Returns \`true\` if the current time is between the astro sunrise and sunset. - -### compareTime - -\`\`\`js -compareTime(startTime, endTime, operation, timeToCompare); -\`\`\` - -Compare given time with limits. - -If \`timeToCompare\` is not given, so the actual time will be used. - -The following operations are possible: - -- \`">"\` - if given time is greater than \`startTime\` -- \`">="\` - if given time is greater or equal to \`startTime\` -- \`"<"\` - if given time is less than \`startTime\` -- \`"<="\` - if given time is less or equal to \`startTime\` -- \`"=="\` - if given time is equal to \`startTime\` -- \`"<>"\` - if given time is not equal to \`startTime\` -- \`"between"\` - if given time is between \`startTime\` and \`endTime\` -- \`"not between"\` - if given time is not between \`startTime\` and \`endTime\` - -Time can be Date object or Date with time or just time. - -You can use astro-names for the time definition. All 3 parameters can be set as astro time. -Following values are possible: \`sunrise\`, \`sunset\`, \`sunriseEnd\`, \`sunsetStart\`, \`dawn\`, \`dusk\`, \`nauticalDawn\`, \`nauticalDusk\`, \`nightEnd\`, \`night\`, \`goldenHourEnd\`, \`goldenHour\`. -See [Astro](#astro--function) for detail. - -\`\`\`js -log(compareTime('sunsetStart', 'sunsetEnd', 'between') ? 'Now is sunrise' : 'Now is no sunrise'); -\`\`\` - -It is possible to define the time with offset too: - -\`\`\`js -log( - compareTime({ astro: 'sunsetStart', offset: 30 }, { astro: 'sunrise', offset: -30 }, '>') - ? 'Now is at least 30 minutes after sunset' - : 'No idea', -); -\`\`\` - -Structure of an astro object. - -\`\`\`js -{ - astro: 'sunsetStart',// mandatory, can be written as string and not as object if offset and date are default - offset: 30, // optional - date: new Date() // optional -} -\`\`\` - -### setState - -\`\`\`js -setState(id, state, ack, callback); -\`\`\` - -_Note_: The following commands are identical - -\`\`\`js -setState('myState', 1, false); -setState('myState', { val: 1, ack: false }); -setState('myState', 1); -\`\`\` - -Please refer to https://github.com/ioBroker/ioBroker/wiki/Adapter-Development-Documentation#commands-and-statuses for usage of \`ack\`. -Short: - -- \`ack = false\`: Script wants to send a command to be executed by the target device/adapter -- \`ack = true\`: Command was successfully executed, and state is updated as a positive result - -### setStateAsync - -\`\`\`js -await setStateAsync(id, state, ack); -\`\`\` - -Same as setState, but with \`promise\`. - -### setStateDelayed - -\`\`\`js -setStateDelayed(id, state, isAck, delay, clearRunning, callback); -\`\`\` - -Same as setState but with delay in milliseconds. You can clear all running delays for this ID (by default). E.g. - -\`\`\`js -// Switch ON the light in the kitchen in one second -setStateDelayed('Kitchen.Light.Lamp', true, 1000); - -// Switch OFF the light in the kitchen in 5 seconds and let first timeout run. -setStateDelayed('Kitchen.Light.Lamp', false, 5000, false, () => { - log('Lamp is OFF'); -}); -\`\`\` - -This function returns the handler of the timer, and this timer can be individually stopped by clearStateDelayed - -### setStateChanged - -\`\`\`js -await setStateChanged(id, state, ack); -\`\`\` - -Same as setState, but set value only if the value is really changed. - -### setStateChangedAsync - -\`\`\`js -await setStateChangedAsync(id, state, ack); -\`\`\` - -Same as setStateChanged, but with \`promise\`. - -### clearStateDelayed - -\`\`\`js -clearStateDelayed(id); -\`\`\` - -Clears all delayed tasks for specified state ID or some specific delayed task. - -\`\`\`js -setStateDelayed('Kitchen.Light.Lamp', false, 10000); // Switch OFF the light in the kitchen in ten second -let timer = setStateDelayed('Kitchen.Light.Lamp', true, 5000, false); // Switch ON the light in the kitchen in five second -clearStateDelayed('Kitchen.Light.Lamp', timer); // Nothing will be switched on -clearStateDelayed('Kitchen.Light.Lamp'); // Clear all running delayed tasks for this ID -\`\`\` - -### getStateDelayed - -\`\`\`js -getStateDelayed(id); -\`\`\` - -This is a synchronous call, and you will get the list of all running timers (setStateDelayed) for this id. -You can call this function without id and get timers for all IDs. -In case you call this function for some specific object ID, you will get the following answer: - -\`\`\`js -getStateDelayed('hm-rpc.0.LQE91119.1.STATE'); - -// returns an array like -[ - { timerId: 1, left: 1123, delay: 5000, val: true, ack: false }, - { timerId: 2, left: 12555, delay: 15000, val: false, ack: false }, -]; -\`\`\` - -If you ask for all IDs, the answer will look like: - -\`\`\`js -getStateDelayed(); - -// returns an object like -{ - 'hm-rpc.0.LQE91119.1.STATE': [ - { timerId: 1, left: 1123, delay: 5000, val: true, ack: false }, - { timerId: 2, left: 12555, delay: 15000, val: false, ack: false }, - ], - 'hm-rpc.0.LQE91119.2.LEVEL': [ - { timerId: 3, left: 5679, delay: 10000, val: 100, ack: false } - ] -} -\`\`\` - -- \`left\` is the time left in milliseconds -- \`delay\` is the initial delay value in milliseconds - -You can ask by timerId directly. In this case, the answer will be: - -\`\`\`js -getStateDelayed(3); - -// returns an object like -{ id: 'hm-rpc.0.LQE91119.2.LEVEL', left: 5679, delay: 10000, val: 100, ack: false } -\`\`\` - -### getState - -\`\`\`js -getState(id); -\`\`\` - -Returns state with the given id in the following form: - -\`\`\`js -{ - val: value, - ack: true/false, - ts: timestamp, - lc: lastchanged, - from: origin -} -\`\`\` - -If state does not exist, a warning will be printed in the logs and the object \`{ val: null, notExist: true }\` will be returned. -To suppress the warning check if the state exists before calling getState (see [existsState](#existsState)). - -### getStateAsync - -\`\`\`js -const stateObject = await getStateAsync(id); -\`\`\` - -Same as getState, but with \`promise\`. - -### existsState - -\`\`\`js -existsState(id, (err, isExists) => {}); -\`\`\` - -If option "Do not subscribe all states on start" is deactivated, you can use simpler call: - -\`\`\`js -existsState(id); -\`\`\` - -the function returns in this case true or false. - -Check if a state exists. - -### getObject - -\`\`\`js -getObject(id, enumName); -\`\`\` - -Get description of object id as stored in a system. -You can specify the enumeration name. If this is defined, two additional attributes will be added to result: enumIds and enumNames. -These arrays have all enumerations, where ID is a member of. E.g: - -\`\`\`js -getObject('adapter.N.objectName', 'rooms'); -\`\`\` - -gives back in enumIds all rooms, where the requested object is a member. You can define "true" as enumName to get back _all_ enumerations. - -### setObject - -\`\`\`js -setObject(id, obj, callback); -\`\`\` - -Write an object into DB. This command can be disabled in adapter's settings. Use this function carefully, while the global settings can be damaged. - -You should use it to **modify** an existing object you read beforehand, e.g.: - -\`\`\`js -const obj = getObject('adapter.N.objectName'); -obj.native.settings = 1; -setObject('adapter.N.objectName', obj, err => { - if (err) log('Cannot write object: ' + err); -}); -\`\`\` - -### existsObject - -\`\`\`js -existsObject(id, function (err, isExists) {}); -\`\`\` - -If the option "Do not subscribe all states on start" is deactivated, you can use simpler call: - -\`\`\`js -existsObject(id); -\`\`\` - -the function returns in this case true or false. - -Check if an object exists. - -### extendObject - -\`\`\`js -extendObject(id, obj, callback); -\`\`\` - -It is almost the same as \`setObject\`, but first it reads the object and tries to merge all settings together. - -Use it like this: - -\`\`\`js -// Stop instance -extendObject('system.adapter.sayit.0', { common: { enabled: false } }); -\`\`\` - -### deleteObject - -\`\`\`js -deleteObject(id, isRecursive, callback); -\`\`\` - -Delete an object from DB by ID. If the object has type \`state\`, the state value will be deleted too. - -Additional parameter \`isRecursive\` could be provided, so all children of given ID will be deleted. Very dangerous! - -Use it like this: - -\`\`\`js -// Delete state -deleteObject('javascript.0.createdState'); -\`\`\` - -_Notice: \`isRecursive\` option is available only with js-controller >= 2.2.x_ - -### getIdByName - -\`\`\`js -getIdByName(name, alwaysArray); -\`\`\` - -Returns id of the object with given name. -If there is more than one object with this name, the result will be an array. -If \`alwaysArray\` flag is set, the result will always be an array if some ID found. - -### getEnums - -\`\`\`js -getEnums(enumName); -\`\`\` - -Get the list of existing enumerations with members, like: - -\`\`\`js -getEnums('rooms'); - -// returns: -[ - { - id: 'enum.rooms.LivingRoom', - members: ['hm-rpc.0.JEQ0024123.1', 'hm-rpc.0.BidCoS-RF.4'], - name: 'Living room', - }, - { - id: 'enum.rooms.Bath', - members: ['hm-rpc.0.JEQ0024124.1', 'hm-rpc.0.BidCoS-RF.5'], - name: 'Bath', - }, -]; -\`\`\` - -### createState - -\`\`\`js -createState(name, initialValue, forceCreation, common, native, callback); -\`\`\` - -Create state and object in \`javascript.0\` space if it does not exist, e.g. \`javascript.0.mystate\`. - -!! Prefer to create own data points with the full ID \`0_userdata.0.mystate\` !!! - -#### Parameters: - -- \`name\`: name of the state without namespace, e.g. \`mystate\` -- \`initialValue\`: variable can be initialized after created. Value "undefined" means do not initialize value. -- \`forceCreation\`: create/overwrite state independent of if state yet exists or not. -- \`common\`: common description of object see description [here](https://github.com/ioBroker/ioBroker/blob/master/doc/SCHEMA.md#state) -- \`native\`: native description of an object. Any specific information. -- \`callback\`: called after state is created and initialized. - -If you set in \`common\` the flag \`alias\` to \`true\`, then alias will be created with the same name (but in \`alias.0\` namespace) as the state. -Alias is created only if it does not exist yet. - -The following settings for aliases are valid too: - -\`\`\`js -common => { - alias: { - id: 'alias.0.myOtherState', // will be created automatically if not already exists - write: 'val * 1000', // convert function for write to created state - read: 'val / 1000' // convert function to read from created state - } -} -\`\`\` - -or - -\`\`\`js -common => { - alias: { - id: 'alias.0.myOtherState', // will be created automatically if not already exists - } -} -\`\`\` - -It is possible short type of createState: - -- \`createState('myDatapoint')\` - simply create datapoint if it does not exist -- \`createState('myDatapoint', 1)\` - create datapoint if it does not exist and initialize it with value 1 -- \`createState('myDatapoint', { type: 'string', role: 'json', read: true, write: false }, () => { log('created'); });\` - with common definitions like type, read, write and role -- \`createState('myDatapoint', { name: 'My own datapoint', unit: '°C' }, () => { log('created'); });\` -- \`createState('myDatapoint', 1, { name: 'My own datapoint', unit: '°C' })\` - create datapoint if it does not exist with specific name and units - -### createStateAsync - -\`\`\`js -await createStateAsync(name, initialValue, forceCreation, common, native); -\`\`\` - -Same as \`createState\`, but the promise will be returned. - -### deleteState - -\`\`\`js -deleteState(name, callback); -\`\`\` - -Delete state and object in \`javascript.0\` space, e.g. \`javascript.0.mystate\`. States from other adapters cannot be deleted. - -\`\`\`js -deleteState('myDatapoint'); -\`\`\` - -simply delete datapoint if exists. - -### deleteStateAsync - -\`\`\`js -await deleteStateAsync(name); -\`\`\` - -Same as \`deleteState\`, but the promise will be returned. - -### createAlias - -\`\`\`js -createAlias(name, alias, forceCreation, common, native, callback); -\`\`\` - -Create alias in \`alias.0\` space if it does not exist, e.g. \`javascript.0.myalias\` and reference to a state or read/write states. -The common definition is taken from the read alias id object, but a provided common takes precedence. - -#### Parameters: - -- \`name\`: id of the new alias state with (possible without an alias namespace), e.g. \`test.mystate\` (namespace \`alias.0.\` will be added = \`alias.0.test.mystate\`) -- \`alias\`: can be either an existing state id as string or an object with full alias definition including read/write ids and read/write functions. Note: Alias definitions can not be set as part of the common parameter! -- \`forceCreation\`: create/overwrite alias independent of if state yet exists or not. -- \`common\`: common description of alias object see description [here](https://github.com/ioBroker/ioBroker/blob/master/doc/SCHEMA.md#state). Values provided here will take precedence over the common definition of the read alias id object. Not: Alias definitions can not be set as part of this common parameter, see alias parameter! -- \`native\`: native description of an object. Any specific information. -- \`callback\`: called after state is created and initialized. - -It is possible a short type of createAlias: - -- \`createAlias('myAlias', 'myDatapoint')\` - simply create alias.0.myAlias that references to \`javascript.X.myDatapoint\` if it does not exist -- \`createAlias('myAlias', { id: { read: 'myReadDatapoint', write: 'myWriteDatapoint' }})\` - creates alias and reference to different read/write states - -For other details, see createState, it is similar. - -### createAliasAsync - -\`\`\`js -await createAliasAsync(name, alias, forceCreation, common, native); -\`\`\` - -Same as \`createAlias\`, but the promise will be returned. - -### sendTo - -\`\`\`js -sendTo(adapter, command, message, callback); -sendTo(adapter, command, message, options, callback); -\`\`\` - -Send a message to a specific or all adapter instances. When using the adapter name, the message is sent to all instances. - -To get specific information about messages, you must read the documentation for a particular adapter. - -Example (with custom timeout): - -\`\`\`js -sendTo('telegram', { user: 'UserName', text: 'Test message' }, { timeout: 2000 }); -\`\`\` - -Some adapters also support responses to the sent messages. (e.g. history, SQL, telegram) -The response is only returned to the callback if the message is sent to a specific instance! - -Example (with callback): - -\`\`\`js -sendTo('telegram.0', { user: 'UserName', text: 'Test message' }, res => { - log(\`Sent to \${res} users\`); -}); -\`\`\` - -_Default timeout is 20000 milliseconds (if a callback function has been defined)_ - -\`\`\`js -sendTo('telegram.0', { user: 'UserName', text: 'Test message' }, { timeout: 2000 }, res => { - log(\`Sent to \${res} users\`); -}); -\`\`\` - -### sendToAsync - -\`\`\`js -await sendToAsync(adapter, command, message); -await sendToAsync(adapter, command, message, options); -\`\`\` - -Same as sendTo, but with \`promise\`. - -Example: - -\`\`\`js -const res = await sendToAsync('sql.0', 'getEnabledDPs', {}); -log(JSON.stringify(res)); -\`\`\` - -### sendToHost - -\`\`\`js -sendToHost(hostName, command, message, callback); -\`\`\` - -Send a message to controller instance. - -The following commands are supported: - -- \`"cmdExec"\` -- \`"getRepository"\` -- \`"getInstalled"\` -- \`"getVersion"\` -- \`"getDiagData"\` -- \`"getLocationOnDisk"\` -- \`"getDevList"\` -- \`"getLogs"\` -- \`"getHostInfo"\` - -It is rather specific commands and are not required often. - -Example: - -\`\`\`js -sendToHost('myComputer', 'cmdExec', { data: 'ls /' }, res => { - log('List of files: ' + res.data); -}); -\`\`\` - -**Notice:** you must enable _Enable command "setObject"_ option to call it. - -### sendToHostAsync - -\`\`\`js -await sendToHostAsync(hostName, command, message); -\`\`\` - -Same as sendToHost, but with \`promise\`. - -### setInterval - -\`\`\`js -setInterval(callback, ms, arg1, arg2, arg3, arg4); -\`\`\` - -Same as javascript \`setInterval\`. - -### clearInterval - -\`\`\`js -clearInterval(id); -\`\`\` - -Same as javascript \`clearInterval\`. - -### setTimeout - -\`\`\`js -setTimeout(callback, ms, arg1, arg2, arg3, arg4); -\`\`\` - -Same as javascript \`setTimeout\`. - -### clearTimeout - -\`\`\`js -clearTimeout(id); -\`\`\` - -Same as javascript \`clearTimeout\`. - -### setImmediate - -\`\`\`js -setImmediate(callback, arg1, arg2, arg3, arg4); -\`\`\` - -Same as javascript \`setImmediate\` and almost the same as \`setTimeout(callback, 0, arg1, arg2, arg3, arg4)\` but with higher priority. - -### formatDate - -\`\`\`js -formatDate(millisecondsOrDate, format); -\`\`\` - -#### Parameters: - -- \`millisecondsOrDate\`: number of milliseconds from state.ts or state.lc (Number milliseconds from 1970.01.01 00:00:00) or javascript _new Date()_ object or number of milliseconds from _(new Date().getTime())_ -- \`format\`: Can be \`null\`, so the system time format will be used, otherwise - -* YYYY, JJJJ, ГГГГ - full year, e.g 2015 -* YY, JJ, ГГ - short year, e.g 15 -* MM, ММ(cyrillic) - full month, e.g., 01 -* M, М(cyrillic) - short month, e.g., 1 -* DD, TT, ДД - full day, e.g., 02 -* D, T, Д - short day, e.g., 2 -* hh, SS, чч - full hours, e.g., 03 -* h, S, ч - short hours, e.g., 3 -* mm, мм(cyrillic) - full minutes, e.g., 04 -* m, м(cyrillic) - short minutes, e.g., 4 -* ss, сс(cyrillic) - full seconds, e.g., 05 -* s, с(cyrillic) - short seconds, e.g., 5 -* sss, ссс(cyrillic) - milliseconds -* WW, НН(cyrillic) - full week day as text -* W, Н(cyrillic) - short week day as text -* OO, ОО(cyrillic) - full month as text -* OOO, ООО(cyrillic) - full month as text as genitiv -* O, О(cyrillic) - short month as text - -#### Example - -\`\`\`js -formatDate(new Date(), 'YYYY-MM-DD'); // => Date "2015-02-24" -formatDate(new Date(), 'hh:mm'); // => Hours and minutes "17:41" -formatDate(state.ts); // => "24.02.2015" -formatDate(state.ts, 'JJJJ.MM.TT SS:mm:ss.sss'); // => "2015.02.15 17:41:98.123" -formatDate(new Date(), 'WW'); // => Day of week "Tuesday" -formatDate(new Date(), 'W'); // => Day of week "Tu" -\`\`\` - -### formatTimeDiff - -\`\`\`js -formatTimeDiff(milliseconds, format); -\`\`\` - -#### Parameters: - -- \`milliseconds\`: difference in milliseconds\\* -- \`format\`: Can be \`null\`, so the \`hh:mm:ss\` format will be used, otherwise - -* DD, TT, ДД - full day, e.g., 02 -* D, T, Д - short day, e.g., 2 -* hh, SS, чч - full hours, e.g., 03 -* h, S, ч - short hours, e.g., 3 -* mm, мм(cyrillic) - full minutes, e.g., 04 -* m, м(cyrillic) - short minutes, e.g., 4 -* ss, сс(cyrillic) - full seconds, e.g., 05 -* s, с(cyrillic) - short seconds, e.g., 5 - -#### Example - -\`\`\`js -formatTimeDiff(60000, 'mm:ss'); // => "01:00" - -const diff = 172800000 + 10800000 + 540000 + 15000; // 2 days, 3 hours, 9 minutes + 15 secoonds -formatTimeDiff(diff); // "51:09:15" -formatTimeDiff(diff, 'DD hh:mm'); // "02 03:09" -formatTimeDiff(diff, 'D hh:mm'); // "2 03:09" -formatTimeDiff(diff, 'hh:mm:ss'); // "51:09:15" -formatTimeDiff(diff, 'h:m:s'); // "51:9:15" -formatTimeDiff(diff, 'hh:mm'); // "51:09" -formatTimeDiff(diff, 'mm:ss'); // "3069:15" -formatTimeDiff(diff, 'hh'); // "51" -formatTimeDiff(diff, 'mm'); // "3069" -\`\`\` - -### getDateObject - -\`\`\`js -getDateObject(stringOrNumber); -\`\`\` - -Converts string or number to a Date object. -If only hours are given, it will add current date to it and will try to convert. - -\`\`\`js -getDateObject('20:00'); // 2024-05-18T18:00:00.000Z -getDateObject('2024-01-01'); // 2024-01-01T00:00:00.000Z -\`\`\` - -### formatValue - -\`\`\`js -formatValue(value, decimals, format); -\`\`\` - -Formats any value (strings too) to number. Replaces point with comma if configured in system. -Decimals specify digits after comma. The default value is 2. -Format is optional: - -- '.,': 1234.567 => 1.234,56 -- ',.': 1234.567 => 1,234.56 -- ' .': 1234.567 => 1 234.56 - -### adapterSubscribe - -\`\`\`js -adapterSubscribe(id); -\`\`\` - -It sends to an adapter the message "subscribe" to inform adapter. If adapter has the common flag "subscribable" in case of function "subscribe" this function will be called automatically. - -### adapterUnsubscribe - -\`\`\`js -adapterUnsubscribe(id); -\`\`\` - -It sends to an adapter the message \`unsubscribe\` to inform adapter to not poll the values. - -### $ - Selector - -\`\`\`js -$(selector).on(function (obj) {}); -$(selector).toArray(); // Requires version >= 8.2.0 -$(selector).each(function (id, i) {}); -$(selector).setState(value, ack); -$(selector).getState(); -\`\`\` - -Format of selector: - -\`\`\`js -'name[commonAttr=something1](enumName=something2){nativeName=something3}[id=idfilter][state.id=idfilter]'; -\`\`\` - -name can be: state, channel, device or schedule -\`idfilter\` can have wildcards '\\*' - -Prefixes **_(not implemented - should be discussed)_** : - -- \\# - take by name and not by id -- . - filter by role -- § - filter by room - -**_Example_**: - -- \`$('state[id=*.STATE]')\` or \`$('state[state.id=*.STATE]')\` or \`$('*.STATE')\` - select all states where id ends with ".STATE". -- \`$('state[id='hm-rpc.0.*]')\` or \`$('hm-rpc.0.*')\` - returns all states of adapter instance hm-rpc.0 -- \`$('channel(rooms=Living room)')\` - all states in room "Living room" -- \`$('channel{TYPE=BLIND}[state.id=*.LEVEL]')\` - Get all shutters of Homematic -- \`$('channel[role=switch](rooms=Living room)[state.id=*.STATE]').setState(false)\` - Switch all states with .STATE of channels with role "switch" in "Living room" to false -- \`$('channel[state.id=*.STATE](functions=Windows)').each(function (id, i) {log(id);});\` - print all states of enum "windows" in log -- \`$('schedule[id=*65]').each(function (id, i) {log(id);});\` - print all schedules with 65 at the end -- \`$('.switch §"Living room")\` - Take states with all switches in 'Living room' **_(not implemented - should be discussed)_** -- \`$('channel .switch §"Living room")\` - Take states with all switches in 'Living room' **_(not implemented - should be discussed)_** - -**_Explanation_** -Lets take a look at: - -\`\`\`js -$('channel[role=switch][state.id=*.STATE](rooms=Wohnzimmer)').on(obj => { - log('New state ' + obj.id + ' = ' + obj.state.val); -}); -\`\`\` - -This code searches in channels. -Find all channels with \`common.role="switch"\` and belongs to \`enum.rooms.Wohnzimmer\`. -Take all their states, where id ends with \`".STATE"\` and make subscription on all these states. -If some of these states change, the callback will be called like for "on" function. - -Following functions are possible, setState, getState (only from first), on, each, toArray - -\`\`\`js -// Switch on all switches in "Wohnzimmer" -$('channel[role=switch][state.id=*.STATE](rooms=Wohnzimmer)').setState(true); -\`\`\` - -You can interrupt the "each" loop by returning the false value, like: - -\`\`\`js -// print two first IDs of on all switches in "Wohnzimmer" -$('channel[role=switch][state.id=*.STATE](rooms=Wohnzimmer)').each((id, i) => { - log(id); - if (i == 1) { - return false; - } -}); -\`\`\` - -Or you can get a usual array of IDs and process it your own way: - -\`\`\`js -// get some state and filter only which has an \`true\` value -const enabled = $('channel[role=switch][state.id=*.STATE](rooms=Wohnzimmer)') - .toArray() - .filter(id => getState(id)?.val === true); -\`\`\` - -### readFile - -\`\`\`js -readFile(adapter, fileName, (error, bytes) => {}); -\`\`\` - -The result will be given in callback. -Read a file from DB from folder \`javascript.0\`. - -Argument _adapter_ can be omitted. - -\`\`\`js -// read vis views -readFile('vis.0', '/main/vis-views.json', (error, data) => { - log(data.substring(0, 50)); -}); - -// The same as -//readFile('/../vis.0/main/vis-views.json', (error, data) => { -// log(data.substring(0, 50)); -//}); -\`\`\` - -By default, working directory/adapter is \`javascript.0\`. - -### writeFile - -\`\`\`js -writeFile(adapter, fileName, bytes, error => {}); -\`\`\` - -The optional error code will be given in callback. Argument _adapter_ can be omitted. -\`fileName\` is the name of file in DB. If \`adapter\` is not set, all files are stored in the folder \`javascript.0\`. - -The file that looks like \`'/subfolder/file.txt'\` will be stored under \`"/javascript/subfolder/file.txt"\` and can be accessed over web server with \`"http://ip:8082/javascript/subfolder/file.txt"\` - -\`\`\`js -// store screenshot in DB -const fs = require('node:fs'); -let data = fs.readFileSync('/tmp/screenshot.png'); -writeFile(null, '/screenshots/1.png', data, error => { - log('file written'); -}); - -// The same as -//writeFile('/screenshots/1.png', data, function (error) { -// log('file written'); -//}); -\`\`\` - -\`\`\`js -// store file in '/vis.0' in DB -const fs = require('node:fs'); -let data = fs.readFileSync('/tmp/screenshot.png'); -writeFile('vis.0', '/screenshots/1.png', data, error => { - log('file written'); -}); -\`\`\` - -### delFile - -\`\`\`js -delFile(adapter, fileName, error => {}); -\`\`\` - -Delete file or directory. fileName is the name of file or directory in DB. - -The alternative name of this method is \`unlink\`. - -### renameFile - -\`\`\`js -renameFile(adapter, oldName, newName, error => {}); -\`\`\` - -Rename file or directory. oldName is the name of file or directory in DB and is renamed to newName. - -The alternative name of this method is \`rename\`. - -### onFile - -\`\`\`js -onFile(id, fileName, withFile, (id, fileName, size, fileData, mimeType) => {}); -// or -onFile(id, fileName, (id, fileName, size) => {}); -\`\`\` - -Subscribe to file changes: - -- \`id\` is ID of an object of type \`meta\`, like \`vis.0\` -- \`fileName\` is file name or pattern, like \`main/*\` or \`main/vis-view.json\` -- \`withFile\` if the content of file should be delivered in callback or not. the delivery of file content costs memory and time, so if you want to be just informed about changes, set \`withFile\`to false. - -Arguments in callback: - -- \`id\` - ID of \`meta\` object; -- \`fileName\` - file name (not pattern); -- \`size\` - new file size; -- \`fileData\` - file content of type \`Buffer\` if file is binary (detected by extension) or \`string\`. Delivered only if \`withFile\`; -- \`mimeType\` - mime type of file, like \`image/jpeg\`. Delivered only if \`withFile\`; - -**Important**: this functionality is only available with js-controller@4.1.x or newer. - -### offFile - -\`\`\`js -offFile(id, fileName); -// or -onFile(id, fileName); -\`\`\` - -Unsubscribe from file changes: - -- \`id\` is ID of an object of type \`meta\`, like \`vis.0\` -- \`fileName\` is file name or pattern, like \`main/*\` or \`main/vis-view.json\` - -**Important**: this functionality is only available with js-controller@4.1.x or newer. - -### onStop - -\`\`\`js -onStop(() => { - /* do something when script is stopped */ -}, timeout); -\`\`\` - -Install callback, that will be called if a script stopped. Used, e.g., to stop communication or to close connections. - -\`\`\`js -// establish connection -const conn = require('net'); -// ... - -// close connection if script stopped -onStop(callback => { - if (conn) { - // close connection - conn.destroy(); - } - callback(); -}, 2000 /*ms*/); -\`\`\` - -\`timeout\` is 1000ms by default. - -### getHistory - -\`\`\`js -getHistory(instance, options, (error, result, options, instance) => {}); -\`\`\` - -Read history from specified instance. If no instance is specified, the system default history instance will be taken. - -\`\`\`js -// Read history of 'system.adapter.admin.0.memRss' from sql driver -const end = new Date().getTime(); -getHistory( - 'sql.0', - { - id: 'system.adapter.admin.0.memRss', - start: end - 3600000, - end: end, - aggregate: 'm4', - timeout: 2000, - }, - (err, result) => { - if (err) console.error(err); - if (result) { - for (let i = 0; i < result.length; i++) { - log(result[i].id + ' ' + new Date(result[i].ts).toISOString()); - } - } - }, -); -\`\`\` - -Possible options you can find [here](https://github.com/ioBroker/ioBroker.history#access-values-from-javascript-adapter). - -Additionally, to these parameters you must specify "id" and you may specify timeout (default: 20000ms). - -One more example: - -\`\`\`js -// Get last 50 entries from default history instance with no aggregation: -getHistory( - { - id: 'system.adapter.admin.0.alive', - aggregate: 'none', - count: 50, - }, - (err, result) => { - if (err) console.error(err); - if (result) { - for (let i = 0; i < result.length; i++) { - log(result[i].id + ' ' + new Date(result[i].ts).toISOString()); - } - } - }, -); -\`\`\` - -**Note: ** of course, history must be first enabled for selected ID in admin. - -### runScript - -\`\`\`js -runScript('scriptName', () => { - // Callback is optional - log('Srcipt started, but not yet executed'); -}); -\`\`\` - -Starts or restarts other scripts (and itself too) by name. - -\`\`\`js -// restart script -runScript('groupName.scriptName1'); -\`\`\` - -### runScriptAsync - -Same as runScript, but with \`promise\`. - -\`\`\`js -runScriptAsync('scriptName').then(() => log('Script started, but not yet executed')); - -// or - -await runScriptAsync('scriptName'); -log(\`Script was restarted\`); -\`\`\` - -### startScript - -\`\`\`js -startScript('scriptName', ignoreIfStarted, callback); -\`\`\` - -It starts the script. If \`ignoreIfStarted\` set to true, nothing will be done if a script yet running, otherwise the script will be restarted. - -\`\`\`js -startScript('scriptName', true); // start script if not started -\`\`\` - -### startScriptAsync - -Same as runScript, but with \`promise\`. - -\`\`\`js -startScriptAsync('scriptName', ignoreIfStarted).then(started => - log(\`Script was \${started ? 'started' : 'already started'}\`), -); - -// or - -const started = await startScriptAsync('scriptName', ignoreIfStarted); -log(\`Script was \${started ? 'started' : 'already started'}\`); -\`\`\` - -It starts the script. If \`ignoreIfStarted\` set to true, nothing will be done if a script yet running, otherwise the script will be restarted. - -\`\`\`js -startScript('scriptName', true); // start script if not started -\`\`\` - -### stopScript - -\`\`\`js -stopScript('scriptName', callback); -\`\`\` - -If stopScript is called without arguments, it will stop itself: - -\`\`\`js -stopScript(); -\`\`\` - -### stopScriptAsync - -Same as stopScript, but with \`promise\`: - -\`\`\`js -stopScriptAsync('scriptName').then(stopped => log(\`Script was \${stopped ? 'stopped' : 'already stopped'}\`)); - -//or -const stopped = await stopScriptAsync('scriptName'); -log(\`Script was \${stopped ? 'stopped' : 'already stopped'}\`); -\`\`\` - -If stopScript is called without arguments, it will stop itself: - -\`\`\`js -stopScript(); -\`\`\` - -### isScriptActive - -\`\`\`js -isScriptActive('scriptName'); -\`\`\` - -Returns if a script enabled or disabled. Please note that that does not give back if the script is now running or not. -The script can be finished, but still activated. - -It is not a function. It is a variable with \`javascript\` instance, that is visible in script's scope. - -### toInt - -### toFloat - -### toBoolean - -### jsonataExpression - -### wait - -Just pause the execution of the script. -Warning this function is \`promise\` and must be called as follows: - -\`\`\`js -await wait(1000); -\`\`\` - -### sleep - -Same as [wait](#wait) - -### messageTo - -\`\`\`js -messageTo( - { instance: 'instance', script: 'script.js.common.scriptName', message: 'messageName' }, - data, - { timeout: 1000 }, - result => log(JSON.stringify(result)), -); -\`\`\` - -It sends via the "message bus" the message to some other script. Or even to some handler in the same script. - -Timeout for callback is 5 seconds by default. - -The target could be shorted to: - -\`\`\`js -messageTo('messageName', data, result => { - log(JSON.stringify(result)); -}); -\`\`\` - -Callback and options are optional and timeout is by default 5000 milliseconds (if callback provided). - -\`\`\`js -messageTo('messageName', dataWithNoResponse); -\`\`\` - -### messageToAsync - -\`\`\`js -onMessage('myTopic', async (data, callback) => { - log(data); - - if (!data.myPayload) { - // return error (promise reject) - callback({ error: 'something went wrong!!' }); - } else { - // return result (promise resolve) - callback({ result: 'ok' }); - } -}); - -(async () => { - try { - const msg = await messageToAsync( - { instance: 0, script: 'script.js.test2', message: 'myTopic' }, - { myPayload: true }, - { timeout: 1000 }, - ); - log(\`Done with: \${JSON.stringify(msg)}\`); - } catch (error) { - // contents of result.error - console.error(error); - } -})(); -\`\`\` - -### onMessage - -\`\`\`js -onMessage('messageName', (data, callback) => { - log(\`Received data: \${data}\`); - callback({ result: Date.now() }); -}); -\`\`\` - -Subscribes on JavaScript adapter message bus and delivers response via callback. -The response from script which sends response as first will be accepted as answer, all other answers will be ignored. - -To send a message to a JavaScript script which is then received by this handler, use [messageTo](#messageTo). - -To send a message from any other adapter use - -\`\`\`js -adapter.sendTo('javascript.0', 'toScript', { - script: 'script.js.messagetest', - message: 'messageName', - data: { - flag: true, - }, -}); -\`\`\` - -to send a message from CLI use - -\`\`\`bash -iob message javascript.0 toScript '{"script": "script.js.messagetest", "message": "messageName", "data": { "flag": true }}' -\`\`\` - -### onMessageUnregister - -\`\`\`js -const id = onMessage('messageName', (data, callback) => { - log(data); - callback(Date.now()); -}); - -// unsubscribe specific handler -onMessageUnregister(id); -// or unsubscribe by name -onMessageUnregister('messageName'); -\`\`\` - -Unsubscribes from this message. - -### onLog - -\`\`\`js -onLog('error', data => { - sendTo('telegram.0', { user: 'UserName', text: data.message }); - log('Following was sent to telegram: ' + data.message); -}); -\`\`\` - -Subscribe on logs with specified severity. - -_Important:_ you cannot output logs in handler with the same severity to avoid infinite loops. - -E.g., this will produce no logs: - -\`\`\`js -onLog('error', data => { - console.error('Error: ' + data.message); -}); -\`\`\` - -To receive all logs the \`*\` could be used. In this case, the log output in handler will be disabled completely. - -\`\`\`js -onLog('*', data => { - console.error('Error: ' + data.message); // will produce no logs -}); -\`\`\` - -### onLogUnregister - -\`\`\`js -function logHandler(data) { - console.error('Error: ' + data.message); -} -const id = onLog('warn', logHandler); - -// unsubscribe by ID -onLogUnregister(id); -// or unsubscribe by function handler -onLogUnregister(logHandler); -// or unsubscribe all handlers with specific severity -onLogUnregister('warn'); -\`\`\` - -Unsubscribes from these logs. - -### httpGet - -_Requires version >= 7.9.0_ - -\`\`\`js -httpGet('http://jsonplaceholder.typicode.com/posts', { timeout: 1000 }, (err, response) => { - if (!err) { - console.log(response.statusCode); - console.log(response.data); - } else { - console.error(err); - } -}); -\`\`\` - -Download file to ioBroker file system: - -\`\`\`js -httpGet('http://1.2.3.4/image.jpg', { responseType: 'arraybuffer' }, async (err, response) => { - if (!err) { - writeFile('0_userdata.0', 'test.jpg', response.data, err => { - if (err) { - console.error(err); - } - }); - } else { - console.error(err); - } -}); -\`\`\` - -Disable certificate validation - _Requires version >= 8.4.0_ - -\`\`\`js -httpGet('http://jsonplaceholder.typicode.com/posts', { validateCertificate: false }, (err, response) => { - if (!err) { - console.log(response.statusCode); - console.log(response.data); - } else { - console.error(err); - } -}); -\`\`\` - -### httpPost - -_Requires version >= 7.9.0_ - -\`\`\`js -httpPost( - 'http://jsonplaceholder.typicode.com/posts', - { title: 'foo', body: 'bar', userId: 1 }, - { timeout: 1000 }, - (error, response) => { - if (!error) { - console.log(response.statusCode); - console.log(response.data); - console.log(response.headers); - } else { - console.error(error); - } - }, -); -\`\`\` - -With custom headers and authentication - -\`\`\`js -httpPost( - 'http://jsonplaceholder.typicode.com/posts', - { - title: 'foo', - body: 'bar', - userId: 1, - }, - { - timeout: 2000, - basicAuth: { - user: 'admin', - password: 'dg2LdALNznHFNo', - }, - headers: { - Cookie: 'PHPSESSID=298zf09hf012fh2; csrftoken=u32t4o3tb3gg43; _gat=1', - }, - }, - (error, response) => { - if (!error) { - console.log(response.statusCode); - console.log(response.data); - console.log(response.headers); - } else { - console.error(error); - } - }, -); -\`\`\` - -### createTempFile - -_Requires version >= 8.3.0_ - -\`\`\`js -httpGet( - 'https://raw.githubusercontent.com/ioBroker/ioBroker.javascript/master/admin/javascript.svg', - { responseType: 'arraybuffer' }, - async (err, response) => { - if (err) { - console.error(err); - } else { - const tempFilePath = createTempFile('javascript.svg', response.data); - console.log(\`Saved to \${tempFilePath}\`); - - // Use the new path in other scripts (e.g. sendTo) - } - }, -); -\`\`\` - -\`\`\`js -onFile('0_userdata.0', 'test.jpg', true, async (id, fileName, size, data, mimeType) => { - const tempFilePath = createTempFile(fileName, response.data); - - // Use the new path in other scripts (e.g. sendTo) -}); -\`\`\` - -## Global script variables - -### scriptName - -\`scriptName\` - The name of the script. - -\`\`\`js -log(\`Script \${scriptName} started!\`); -\`\`\` - -### instance - -\`instance\` - The JavaScript instance where thia script is executed (e.g. \`0\`). - -\`\`\`js -log(\`Script \${scriptName} started started by \${instance}\`); -\`\`\` - -### defaultDataDir - -\`defaultDataDir\` - Absolute path to iobroker-data. - -\`\`\`js -log(\`Data dir: \${defaultDataDir}\`); -\`\`\` - -### verbose - -\`verbose\` - Verbose mode enabled? - -\`\`\`js -log(\`Verbose mode: \${verbose ? 'enabled' : 'disabled'}\`); - -// Example -if (verbose) { - log('...'); -} -\`\`\` - -## Option - "Do not subscribe all states on start" - -There are two modes of subscribing to states: - -- Adapter subscribes to all changes at start and receives all changes of all states (it is easy to use getStates(id), but requires more CPU and RAM): - -\`\`\`js -log(getState('someID').val); -\`\`\` - -- Adapter subscribes every time on specified ID if "on/subscribe" called. In this mode, the adapter receives only updates for desired states. - It is very performed and RAM efficiency, but you cannot access states directly in getState. You must use callback to get the result of state: - -\`\`\`js -getState('someID', (error, state) => { - log(state.val); -}); -\`\`\` - -It is because the adapter does not have the value of state in RAM and must ask central DB for the value. - -## Scripts activity - -There is a possibility to enable and disable scripts via states. For every script, the state will be created with the name \`javascript.INSTANCE.scriptEnabled.SCRIPT_NAME\`. -Scripts can be activated and deactivated by controlling this state with \`ack=false\`. -`;export{e as default}; diff --git a/admin/assets/docs-compact-CKNGiYh2.js b/admin/assets/docs-compact-CKNGiYh2.js new file mode 100644 index 00000000..0bd35092 --- /dev/null +++ b/admin/assets/docs-compact-CKNGiYh2.js @@ -0,0 +1,336 @@ +const e=`# ioBroker JavaScript Adapter - API Reference + +IMPORTANT RULES: +- ONLY use functions listed in this document. NEVER define your own helper functions. +- Use on() to react to state changes. NEVER use setTimeout/setInterval for polling states. +- Use setState(id, value) to control devices. Use getState(id).val to read values. +- All functions are pre-imported. NEVER use require() or import. +- Code runs inside an async context. You can use await directly. + +## Quick Reference - Most Used Functions + +\`\`\`js +// React to state changes: +on('adapter.0.device.state', (obj) => { + const val = obj.state.val; +}); + +// Read a state value: +const val = getState('adapter.0.device.state').val; + +// Set a state (control a device): +setState('adapter.0.device.state', true); + +// Time-based schedule (cron): +schedule('0 7 * * *', () => { /* runs daily at 07:00 */ }); + +// Selector - find states by room/function: +$('state[state.id=*.state](rooms=Living room)').each((id) => { + setState(id, false); +}); + +// Log output: +log('message'); +\`\`\` + +--- + +## exec(cmd, [options], callback) +Execute OS command. \`callback(error, stdout, stderr)\`. Requires "Enable command exec" option. + +## on(pattern, callbackOrId, value) +Subscribe to state changes. Alias: \`subscribe\`. Returns handler for \`unsubscribe\`. +Callback receives \`{id, state: {val, ts, ack, lc, from}, oldState: {val, ts, ack, lc, from}}\`. +\`on('stateId1', 'stateId2')\` connects two states. \`on('stateId1', 'stateId2', 'triggered')\` sets fixed value. +Pattern can be: string ID, RegExp, or object with these properties: +- \`logic\` (string): "and"|"or" (default "and") +- \`id\` (string|RegExp|Array): state ID filter +- \`name\` (string|RegExp|Array): state name filter +- \`change\` (string): "eq","ne","gt","ge","lt","le","any" (default "ne" for string ID, "any" otherwise) +- \`val\`, \`valNe\`, \`valGt\`, \`valGe\`, \`valLt\`, \`valLe\` (mixed): new value conditions +- \`ack\` (boolean): new ack filter; \`q\` (number): quality filter (default 0, use '*' for any) +- \`oldVal\`, \`oldValNe\`, \`oldValGt\`, \`oldValGe\`, \`oldValLt\`, \`oldValLe\` (mixed): previous value conditions +- \`oldAck\` (bool), \`oldQ\` (number): previous ack/quality filters +- \`ts\`, \`tsGt\`, \`tsGe\`, \`tsLt\`, \`tsLe\` (string): new timestamp conditions +- \`oldTs\`, \`oldTsGt\`, \`oldTsGe\`, \`oldTsLt\`, \`oldTsLe\` (string): previous timestamp conditions +- \`lc\`, \`lcGt\`, \`lcGe\`, \`lcLt\`, \`lcLe\` (string): last change timestamp conditions +- \`oldLc\`, \`oldLcGt\`, \`oldLcGe\`, \`oldLcLt\`, \`oldLcLe\` (string): previous last change conditions +- \`channelId\`, \`channelName\`, \`deviceId\`, \`deviceName\` (string|RegExp|Array): channel/device filters +- \`enumId\`, \`enumName\` (string|RegExp|Array): enum filters +- \`from\`, \`fromNe\`, \`oldFrom\`, \`oldFromNe\` (string|RegExp|Array): adapter source filters +To get state deletions/expires, use \`change: 'ne'\` or \`'any'\` AND \`q: '*'\`. + +## once(pattern, callback) +Like \`on()\`, but triggers only once then auto-unsubscribes. + +## unsubscribe(idOrHandler) +Remove subscriptions by object ID (removes all) or by handler (removes specific). + +## getSubscriptions() +Returns object \`{stateId: [{name, pattern}]}\` listing all state subscriptions. + +## getFileSubscriptions() +Returns object listing all file subscriptions. + +## schedule(pattern, callback) +Time scheduler with cron and astro support. Returns schedule object for \`clearSchedule\`. +Cron string: \`"sec min hour dayOfMonth month dayOfWeek"\` (sec optional, 5 or 6 fields). +Object pattern: \`{second, minute, hour, date, month, year, dayOfWeek}\`. +Date object: triggers once at that time. +With time range: \`{start, end, rule}\` where start/end are Date/string/ms, rule is cron string or object. +Astro: \`{astro: 'sunrise', shift: 10}\` (shift in minutes, can be negative). +Astro values: sunrise, sunriseEnd, goldenHourEnd, solarNoon, goldenHour, sunsetStart, sunset, dusk, nauticalDusk, night, nightEnd, nauticalDawn, dawn, nadir. +Requires latitude/longitude in adapter settings for astro. +Also works via \`on()\`: \`on({time: '*/2 * * * *'}, cb)\` or \`on({astro: 'sunset', shift: 10}, cb)\`. + +## scheduleById(id, [ack], callback) +Schedule based on state value (format \`[h]h:[m]m[:ss]\`). Auto-updates when state changes. + +## getSchedules(allScripts) +Returns list of all CRON/schedule jobs. Pass \`true\` for all scripts, otherwise current script only. + +## clearSchedule(scheduleObject) +Cancel a schedule created by \`schedule()\`. + +## getAttr(obj, path) +Get nested attribute: \`getAttr({a: {b: 5}}, 'a.b')\` returns 5. Parses JSON strings automatically. + +## getAstroDate(pattern, date, offsetMinutes) +Returns Date object for astro event. Uses current day if no date given. + +## isAstroDay() +Returns \`true\` if current time is between astro sunrise and sunset. + +## compareTime(startTime, endTime, operation, timeToCompare) +Compare time with limits. Operations: ">", ">=", "<", "<=", "==", "<>", "between", "not between". +Times can be Date objects, date strings, time strings, or astro names. +Astro with offset: \`{astro: 'sunsetStart', offset: 30, date: new Date()}\`. + +## setState(id, state, ack, callback) +Set state value. \`setState('id', 1)\` = \`setState('id', {val: 1, ack: false})\`. +\`ack=false\`: command to device; \`ack=true\`: confirmed state update. + +## setStateAsync(id, state, ack) +Promise version of setState. + +## setStateDelayed(id, state, isAck, delay, clearRunning, callback) +setState with delay in ms. Returns timer handler. \`clearRunning\` (default true) cancels previous delays. + +## setStateChanged(id, state, ack) +Like setState, but only sets if value actually changed. + +## setStateChangedAsync(id, state, ack) +Promise version of setStateChanged. + +## clearStateDelayed(id, [timerId]) +Clear delayed tasks for state ID, or specific timer. + +## getStateDelayed(id) +Get list of running timers. Returns \`[{timerId, left, delay, val, ack}]\` for specific ID, or object keyed by ID for all. + +## getState(id) +Returns \`{val, ack, ts, lc, from}\`. Returns \`{val: null, notExist: true}\` if missing. + +## getStateAsync(id) +Promise version of getState. + +## existsState(id, [callback]) +Check if state exists. Sync (returns bool) if "Do not subscribe all states on start" is off, otherwise async. + +## getObject(id, [enumName]) +Get object description. With enumName (e.g. 'rooms' or true for all), adds enumIds/enumNames arrays. + +## setObject(id, obj, callback) +Write object to DB. Use to modify objects read with getObject. Requires "Enable setObject" option. + +## existsObject(id, [callback]) +Check if object exists. Sync or async like existsState. + +## extendObject(id, obj, callback) +Merge-update object. E.g. \`extendObject('system.adapter.sayit.0', {common: {enabled: false}})\`. + +## deleteObject(id, [isRecursive], callback) +Delete object (and state value if type=state). \`isRecursive\` deletes children too. + +## getIdByName(name, [alwaysArray]) +Returns ID(s) for object with given name. Returns array if multiple or if \`alwaysArray\` is true. + +## getEnums(enumName) +Get enums with members. Returns \`[{id, members, name}]\`. + +## createState(name, [initialValue], [forceCreation], [common], [native], [callback]) +Create state in \`javascript.X\` namespace. Prefer \`0_userdata.0.mystate\` for custom data points. +Common options: \`{type, role, read, write, name, unit, min, max, def, alias}\`. +Alias: set \`alias: true\` or \`alias: {id: 'alias.0.x', read: 'val/1000', write: 'val*1000'}\`. + +## createStateAsync(name, [initialValue], [forceCreation], [common], [native]) +Promise version of createState. + +## deleteState(name, [callback]) +Delete state in \`javascript.X\` namespace. + +## deleteStateAsync(name) +Promise version of deleteState. + +## createAlias(name, alias, [forceCreation], [common], [native], [callback]) +Create alias in \`alias.0\` namespace. \`alias\` can be string ID or \`{id: {read: 'id1', write: 'id2'}}\`. + +## createAliasAsync(name, alias, [forceCreation], [common], [native]) +Promise version of createAlias. + +## sendTo(adapter, command, message, [options], [callback]) +Send message to adapter instance(s). \`options: {timeout}\` (default 20000ms). +E.g. \`sendTo('telegram.0', {user: 'User', text: 'Hi'})\`. + +## sendToAsync(adapter, command, message, [options]) +Promise version of sendTo. + +## sendToHost(hostName, command, message, [callback]) +Send message to host controller. Commands: cmdExec, getRepository, getInstalled, getVersion, getDiagData, getLocationOnDisk, getDevList, getLogs, getHostInfo. + +## sendToHostAsync(hostName, command, message) +Promise version of sendToHost. + +## setInterval(callback, ms, ...args) +Same as JS setInterval. + +## clearInterval(id) +Same as JS clearInterval. + +## setTimeout(callback, ms, ...args) +Same as JS setTimeout. + +## clearTimeout(id) +Same as JS clearTimeout. + +## setImmediate(callback, ...args) +Same as JS setImmediate (higher priority than setTimeout 0). + +## formatDate(millisecondsOrDate, [format]) +Format date. Tokens: YYYY(year), MM(month), DD(day), hh(hours), mm(min), ss(sec), sss(ms), WW/W(weekday), OO/O(month name). + +## formatTimeDiff(milliseconds, [format]) +Format time difference. Default \`hh:mm:ss\`. Tokens: DD/D(days), hh/h, mm/m, ss/s. + +## getDateObject(stringOrNumber) +Convert string/number to Date. \`getDateObject('20:00')\` adds current date. + +## formatValue(value, [decimals], [format]) +Format number with locale. \`decimals\` default 2. Format: '.,', ',.', or ' .'. + +## adapterSubscribe(id) +Send "subscribe" message to adapter. Auto-called for subscribable adapters. + +## adapterUnsubscribe(id) +Send "unsubscribe" message to adapter. + +## $(selector) +jQuery-like selector. Methods: \`.on(cb)\`, \`.each(cb)\`, \`.setState(val, ack)\`, \`.getState()\`, \`.toArray()\`. +Format: \`'name[commonAttr=val](enumName=val){nativeAttr=val}[id=filter][state.id=filter]'\`. +Name: state, channel, device, schedule. Wildcards \`*\` supported. +E.g. \`$('channel[role=switch][state.id=*.STATE](rooms=Living room)').setState(false)\`. + +## readFile(adapter, fileName, callback) +Read file from DB. \`callback(error, bytes)\`. Default adapter: \`javascript.0\`. + +## writeFile(adapter, fileName, bytes, callback) +Write file to DB. Accessible via web: \`http://ip:8082/javascript/path/file.ext\`. + +## delFile(adapter, fileName, callback) +Delete file or directory from DB. Alias: \`unlink\`. + +## renameFile(adapter, oldName, newName, callback) +Rename file or directory in DB. Alias: \`rename\`. + +## onFile(id, fileName, withFile, callback) +Subscribe to file changes. \`id\`: meta object ID (e.g. 'vis.0'). \`fileName\`: name or glob pattern. +Callback: \`(id, fileName, size, fileData, mimeType)\`. \`fileData\`/\`mimeType\` only if \`withFile=true\`. + +## offFile(id, fileName) +Unsubscribe from file changes. + +## onStop(callback, [timeout]) +Register callback for script stop. Default timeout 1000ms. Call \`callback()\` when cleanup done. + +## getHistory(instance, options, callback) +Read history data. Options: \`{id, start, end, aggregate, count, timeout}\`. +\`aggregate\`: 'none', 'minmax', 'max', 'min', 'average', 'total', 'count', 'm4'. +If instance omitted, uses system default. \`callback(err, result, options, instance)\`. + +## runScript(scriptName, [callback]) +Start or restart a script by name. + +## runScriptAsync(scriptName) +Promise version of runScript. + +## startScript(scriptName, [ignoreIfStarted], [callback]) +Start script. If \`ignoreIfStarted=true\`, does nothing if already running. + +## startScriptAsync(scriptName, [ignoreIfStarted]) +Promise version of startScript. + +## stopScript([scriptName], [callback]) +Stop script. No args = stop self. + +## stopScriptAsync([scriptName]) +Promise version of stopScript. + +## isScriptActive(scriptName) +Returns if script is enabled (not necessarily running). + +## toInt(val) +Convert to integer. + +## toFloat(val) +Convert to float. + +## toBoolean(val) +Convert to boolean. + +## jsonataExpression(expr) +Evaluate JSONata expression. + +## wait(ms) / sleep(ms) +Pause execution. Must use \`await wait(1000)\`. + +## messageTo(target, data, [options], [callback]) +Send message via message bus to other scripts. Target: \`{instance, script, message}\` or just \`'messageName'\`. +Default timeout 5000ms. + +## messageToAsync(target, data, [options]) +Promise version of messageTo. + +## onMessage(messageName, callback) +Subscribe to message bus. \`callback(data, callback)\` - call callback with response. + +## onMessageUnregister(idOrName) +Unsubscribe from message by handler ID or message name. + +## onLog(severity, callback) +Subscribe to logs. Severity: 'error', 'warn', 'info', 'debug', or '*' for all. +\`callback({message, severity, ts})\`. Cannot log same severity in handler (infinite loop). + +## onLogUnregister(idOrHandlerOrSeverity) +Unsubscribe from log handler by ID, function, or severity string. + +## httpGet(url, [options], callback) +HTTP GET request. Options: \`{timeout, responseType, headers, basicAuth, validateCertificate}\`. +\`callback(err, response)\` where \`response: {statusCode, data, headers}\`. +Use \`responseType: 'arraybuffer'\` for binary data. + +## httpPost(url, data, [options], callback) +HTTP POST request. Same options as httpGet plus \`basicAuth: {user, password}\`. + +## createTempFile(fileName, data) +Create temporary file. Returns file path string. Useful for sendTo with file attachments. + +# Global Variables +- \`scriptName\` - name of current script +- \`instance\` - JavaScript adapter instance number (e.g. 0) +- \`defaultDataDir\` - absolute path to iobroker-data directory +- \`verbose\` - boolean, verbose mode enabled + +# Notes +- "Do not subscribe all states on start" mode: getState requires async callback \`getState(id, (err, state) => {})\`. +- Scripts can be enabled/disabled via state \`javascript.INSTANCE.scriptEnabled.SCRIPT_NAME\` (set with ack=false). +`;export{e as default}; diff --git a/admin/assets/index-CEbKg781.js b/admin/assets/index-CEbKg781.js new file mode 100644 index 00000000..b3e8b0c3 --- /dev/null +++ b/admin/assets/index-CEbKg781.js @@ -0,0 +1,1230 @@ +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-26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My41IDIwOS41djk0aDY5di0xN2MtMTMuNTEuMzI5LTI2Ljg0NC0uMDA0LTQwLTFoNDF2MTloLTcxYTIyNTYuNDEgMjI1Ni40MSAwIDAgMSAxLTk1eiIvPgogICAgPHBhdGggZmlsbD0iI2E2YWNjMCIKICAgICAgICAgIGQ9Ik0zMTYuNSAyMDkuNWMtLjk5OCAzMS4xNjItMS4zMzIgNjIuNDk2LTEgOTRoNzN2LTE3Yy0xNC44NDMuMzI5LTI5LjUxLS4wMDQtNDQtMWg0NXYxOWgtNzVhMjMwNC45NSAyMzA0Ljk1IDAgMCAxIDEtOTZjLjYwNy4xMjQuOTQuNDU3IDEgMXoiLz4KPC9zdmc+";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,A,J,ie,se,me,z,Oe,Ne,Ze,ae,ce,K,ye,he,je,V,tt,q,ee,B,H,U,re,I,de,W,Ce,be,Se,pe,Ve,Je,_e,ke,$e,Pe,bt,X,ct,ze,kt,ve,st,Zs,St,Et,cu,N,ge,la,ot,Hm,Ke,Uo,ca,Ho,Wo,uu,Nn,ua,da,Ln,Wm,du,Ms,yo,hu,pu,ha,gu,Pn,pa,mu,fu,Gm,Vm,Km,Ii,Ym,ga,Jm,Bn,ma,qm,fa,Xm,$a,$u,bu,ba,va,ya,jn,Zm,xi,Fn,_a,Qm,ef,tf,_o,It,zn,vu,ws,Qs,sf,yu,wa,_u,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of 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-CZzmETwg.js b/admin/assets/index-CZzmETwg.js new file mode 100644 index 00000000..c5044705 --- /dev/null +++ b/admin/assets/index-CZzmETwg.js @@ -0,0 +1,16 @@ +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(` +`))}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/assets/index-Cd8FZ0ou.js b/admin/assets/index-Cd8FZ0ou.js new file mode 100644 index 00000000..2eba5532 --- /dev/null +++ b/admin/assets/index-Cd8FZ0ou.js @@ -0,0 +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-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/i18n/de.json b/admin/i18n/de.json index d9c5bdec..b26e674b 100644 --- a/admin/i18n/de.json +++ b/admin/i18n/de.json @@ -61,6 +61,13 @@ "Custom API Base URL": "Eigene API Base-URL (z.B. für Ollama, LM Studio)", "Custom API Base URL help": "Leer lassen für OpenAI. Für Ollama: http://localhost:11434/v1", "Test API connection": "API-Verbindung testen", + "Test OpenAI": "OpenAI testen", + "Test Anthropic": "Anthropic testen", + "Test Gemini": "Gemini testen", + "Test DeepSeek": "DeepSeek testen", + "Test Custom API": "Eigene API testen", + "Custom API key": "API-Schlüssel (optional)", + "Custom API key help": "Nur nötig wenn der Anbieter Authentifizierung erfordert", "AI settings": "KI-Einstellungen", "AI settings description": "Wenn Sie die KI-Codegenerierung nutzen möchten, können Sie hier die API-Schlüssel für die entsprechenden Anbieter hinterlegen. Es wird nur der Schlüssel für den verwendeten Anbieter benötigt.", "ChatGPT API key": "ChatGPT API-Schlüssel", diff --git a/admin/i18n/en.json b/admin/i18n/en.json index 41bbc4a5..e7774ce2 100644 --- a/admin/i18n/en.json +++ b/admin/i18n/en.json @@ -61,6 +61,13 @@ "Custom API Base URL": "Custom API Base URL (e.g. for Ollama, LM Studio)", "Custom API Base URL help": "Leave empty for OpenAI. For Ollama use http://localhost:11434/v1", "Test API connection": "Test API connection", + "Test OpenAI": "Test OpenAI", + "Test Anthropic": "Test Anthropic", + "Test Gemini": "Test Gemini", + "Test DeepSeek": "Test DeepSeek", + "Test Custom API": "Test Custom API", + "Custom API key": "API key (optional)", + "Custom API key help": "Only needed if your provider requires authentication", "AI settings": "AI settings", "AI settings description": "If you want to use AI code generation, you can define API keys for the corresponding providers here. Only the key for the provider you use is required.", "ChatGPT API key": "ChatGPT API key", diff --git a/admin/i18n/es.json b/admin/i18n/es.json index e2a97f05..98451592 100644 --- a/admin/i18n/es.json +++ b/admin/i18n/es.json @@ -61,6 +61,13 @@ "Custom API Base URL": "URL base de API personalizada (p. ej. para Ollama, LM Studio)", "Custom API Base URL help": "Dejar vacío para OpenAI. Para Ollama usar http://localhost:11434/v1", "Test API connection": "Probar conexión API", + "Test OpenAI": "Test OpenAI", + "Test Anthropic": "Test Anthropic", + "Test Gemini": "Test Gemini", + "Test DeepSeek": "Test DeepSeek", + "Test Custom API": "Test Custom API", + "Custom API key": "API key (optional)", + "Custom API key help": "Only needed if your provider requires authentication", "AI settings": "Configuración de IA", "AI settings description": "Si desea utilizar la generación de código con IA, puede definir aquí las claves API de los proveedores correspondientes. Solo se necesita la clave del proveedor que utilice.", "ChatGPT API key": "Clave API de ChatGPT", diff --git a/admin/i18n/fr.json b/admin/i18n/fr.json index 95c719e6..8394b0bb 100644 --- a/admin/i18n/fr.json +++ b/admin/i18n/fr.json @@ -61,6 +61,13 @@ "Custom API Base URL": "URL de base API personnalisée (ex. pour Ollama, LM Studio)", "Custom API Base URL help": "Laisser vide pour OpenAI. Pour Ollama utiliser http://localhost:11434/v1", "Test API connection": "Tester la connexion API", + "Test OpenAI": "Test OpenAI", + "Test Anthropic": "Test Anthropic", + "Test Gemini": "Test Gemini", + "Test DeepSeek": "Test DeepSeek", + "Test Custom API": "Test Custom API", + "Custom API key": "API key (optional)", + "Custom API key help": "Only needed if your provider requires authentication", "AI settings": "Paramètres IA", "AI settings description": "Si vous souhaitez utiliser la génération de code par IA, vous pouvez définir ici les clés API des fournisseurs correspondants. Seule la clé du fournisseur utilisé est requise.", "ChatGPT API key": "Clé API ChatGPT", diff --git a/admin/i18n/it.json b/admin/i18n/it.json index 1228d924..845dcab4 100644 --- a/admin/i18n/it.json +++ b/admin/i18n/it.json @@ -61,6 +61,13 @@ "Custom API Base URL": "URL base API personalizzata (es. per Ollama, LM Studio)", "Custom API Base URL help": "Lasciare vuoto per OpenAI. Per Ollama usare http://localhost:11434/v1", "Test API connection": "Testa connessione API", + "Test OpenAI": "Test OpenAI", + "Test Anthropic": "Test Anthropic", + "Test Gemini": "Test Gemini", + "Test DeepSeek": "Test DeepSeek", + "Test Custom API": "Test Custom API", + "Custom API key": "API key (optional)", + "Custom API key help": "Only needed if your provider requires authentication", "AI settings": "Impostazioni IA", "AI settings description": "Se si desidera utilizzare la generazione di codice tramite IA, è possibile definire qui le chiavi API per i rispettivi provider. È necessaria solo la chiave del provider utilizzato.", "ChatGPT API key": "Chiave API ChatGPT", diff --git a/admin/i18n/nl.json b/admin/i18n/nl.json index 4b7d71d3..43e6ef02 100644 --- a/admin/i18n/nl.json +++ b/admin/i18n/nl.json @@ -61,6 +61,13 @@ "Custom API Base URL": "Aangepaste API Base URL (bijv. voor Ollama, LM Studio)", "Custom API Base URL help": "Leeg laten voor OpenAI. Voor Ollama gebruik http://localhost:11434/v1", "Test API connection": "API-verbinding testen", + "Test OpenAI": "Test OpenAI", + "Test Anthropic": "Test Anthropic", + "Test Gemini": "Test Gemini", + "Test DeepSeek": "Test DeepSeek", + "Test Custom API": "Test Custom API", + "Custom API key": "API key (optional)", + "Custom API key help": "Only needed if your provider requires authentication", "AI settings": "AI-instellingen", "AI settings description": "Als u AI-codegeneratie wilt gebruiken, kunt u hier de API-sleutels voor de betreffende providers opgeven. Alleen de sleutel voor de gebruikte provider is vereist.", "ChatGPT API key": "ChatGPT API-sleutel", diff --git a/admin/i18n/pl.json b/admin/i18n/pl.json index ddb03e7f..a6230932 100644 --- a/admin/i18n/pl.json +++ b/admin/i18n/pl.json @@ -61,6 +61,13 @@ "Custom API Base URL": "Niestandardowy bazowy URL API (np. dla Ollama, LM Studio)", "Custom API Base URL help": "Pozostaw puste dla OpenAI. Dla Ollama użyj http://localhost:11434/v1", "Test API connection": "Testuj połączenie API", + "Test OpenAI": "Test OpenAI", + "Test Anthropic": "Test Anthropic", + "Test Gemini": "Test Gemini", + "Test DeepSeek": "Test DeepSeek", + "Test Custom API": "Test Custom API", + "Custom API key": "API key (optional)", + "Custom API key help": "Only needed if your provider requires authentication", "AI settings": "Ustawienia AI", "AI settings description": "Jeśli chcesz korzystać z generowania kodu przez AI, możesz tutaj zdefiniować klucze API dla odpowiednich dostawców. Wymagany jest tylko klucz dla używanego dostawcy.", "ChatGPT API key": "Klucz API ChatGPT", diff --git a/admin/i18n/pt.json b/admin/i18n/pt.json index 7fbf5d36..34803bd9 100644 --- a/admin/i18n/pt.json +++ b/admin/i18n/pt.json @@ -61,6 +61,13 @@ "Custom API Base URL": "URL base da API personalizada (ex. para Ollama, LM Studio)", "Custom API Base URL help": "Deixar vazio para OpenAI. Para Ollama usar http://localhost:11434/v1", "Test API connection": "Testar conexão API", + "Test OpenAI": "Test OpenAI", + "Test Anthropic": "Test Anthropic", + "Test Gemini": "Test Gemini", + "Test DeepSeek": "Test DeepSeek", + "Test Custom API": "Test Custom API", + "Custom API key": "API key (optional)", + "Custom API key help": "Only needed if your provider requires authentication", "AI settings": "Configurações de IA", "AI settings description": "Se pretender utilizar a geração de código com IA, pode definir aqui as chaves API dos respetivos fornecedores. Apenas a chave do fornecedor utilizado é necessária.", "ChatGPT API key": "Chave API do ChatGPT", diff --git a/admin/i18n/ru.json b/admin/i18n/ru.json index 1e53128e..e3fe50c9 100644 --- a/admin/i18n/ru.json +++ b/admin/i18n/ru.json @@ -61,6 +61,13 @@ "Custom API Base URL": "Пользовательский базовый URL API (напр. для Ollama, LM Studio)", "Custom API Base URL help": "Оставить пустым для OpenAI. Для Ollama используйте http://localhost:11434/v1", "Test API connection": "Тестировать подключение к API", + "Test OpenAI": "Test OpenAI", + "Test Anthropic": "Test Anthropic", + "Test Gemini": "Test Gemini", + "Test DeepSeek": "Test DeepSeek", + "Test Custom API": "Test Custom API", + "Custom API key": "API key (optional)", + "Custom API key help": "Only needed if your provider requires authentication", "AI settings": "Настройки ИИ", "AI settings description": "Если вы хотите использовать генерацию кода с помощью ИИ, здесь можно указать API-ключи для соответствующих провайдеров. Требуется только ключ для используемого провайдера.", "ChatGPT API key": "API-ключ ChatGPT", diff --git a/admin/i18n/uk.json b/admin/i18n/uk.json index 98582119..9c11dac4 100644 --- a/admin/i18n/uk.json +++ b/admin/i18n/uk.json @@ -61,6 +61,13 @@ "Custom API Base URL": "Власний базовий URL API (напр. для Ollama, LM Studio)", "Custom API Base URL help": "Залишити порожнім для OpenAI. Для Ollama використовуйте http://localhost:11434/v1", "Test API connection": "Тестувати підключення до API", + "Test OpenAI": "Test OpenAI", + "Test Anthropic": "Test Anthropic", + "Test Gemini": "Test Gemini", + "Test DeepSeek": "Test DeepSeek", + "Test Custom API": "Test Custom API", + "Custom API key": "API key (optional)", + "Custom API key help": "Only needed if your provider requires authentication", "AI settings": "Налаштування ШІ", "AI settings description": "Якщо ви хочете використовувати генерацію коду за допомогою ШІ, тут можна вказати API-ключі для відповідних провайдерів. Потрібен лише ключ для використовуваного провайдера.", "ChatGPT API key": "API-ключ ChatGPT", diff --git a/admin/i18n/zh-cn.json b/admin/i18n/zh-cn.json index 46866bc2..1ef472f6 100644 --- a/admin/i18n/zh-cn.json +++ b/admin/i18n/zh-cn.json @@ -61,6 +61,13 @@ "Custom API Base URL": "自定义 API 基础 URL(例如 Ollama、LM Studio)", "Custom API Base URL help": "OpenAI 留空。Ollama 使用 http://localhost:11434/v1", "Test API connection": "测试 API 连接", + "Test OpenAI": "Test OpenAI", + "Test Anthropic": "Test Anthropic", + "Test Gemini": "Test Gemini", + "Test DeepSeek": "Test DeepSeek", + "Test Custom API": "Test Custom API", + "Custom API key": "API key (optional)", + "Custom API key help": "Only needed if your provider requires authentication", "AI settings": "AI 设置", "AI settings description": "如果您想使用 AI 代码生成功能,可以在此处为相应的提供商定义 API 密钥。只需要您所使用的提供商的密钥。", "ChatGPT API key": "ChatGPT API 密钥", diff --git a/admin/img/anthropic.svg b/admin/img/anthropic.svg new file mode 100644 index 00000000..c24f900a --- /dev/null +++ b/admin/img/anthropic.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/admin/img/custom.svg b/admin/img/custom.svg new file mode 100644 index 00000000..dbd16783 --- /dev/null +++ b/admin/img/custom.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/admin/img/deepseek.svg b/admin/img/deepseek.svg new file mode 100644 index 00000000..11be9d55 --- /dev/null +++ b/admin/img/deepseek.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/admin/img/gemini.svg b/admin/img/gemini.svg new file mode 100644 index 00000000..55cccdd4 --- /dev/null +++ b/admin/img/gemini.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/admin/img/openai.svg b/admin/img/openai.svg new file mode 100644 index 00000000..1b493136 --- /dev/null +++ b/admin/img/openai.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/admin/jsonConfig.json b/admin/jsonConfig.json index d65538a1..8e4ea6c5 100644 --- a/admin/jsonConfig.json +++ b/admin/jsonConfig.json @@ -142,56 +142,121 @@ "type": "text", "label": "ChatGPT API key", "xs": 12, - "sm": 12, + "sm": 9, "help": "platform.openai.com", "helpLink": "https://platform.openai.com/api-keys" }, + "_testOpenAi": { + "type": "sendTo", + "label": "Test OpenAI", + "icon": "img/openai.svg", + "command": "testApiConnection", + "jsonData": "{\"apiKey\": \"${data.gptKey}\", \"provider\": \"openai\"}", + "variant": "outlined", + "disabled": "!data.gptKey", + "xs": 12, + "sm": 3, + "alsoDependsOn": ["gptKey"], + "showProcess": true, + "resultStringToError": "error" + }, "claudeKey": { "newLine": true, "type": "text", "label": "Anthropic API key", "xs": 12, - "sm": 12, + "sm": 9, "help": "console.anthropic.com", "helpLink": "https://console.anthropic.com/settings/keys" }, + "_testClaude": { + "type": "sendTo", + "label": "Test Anthropic", + "icon": "img/anthropic.svg", + "command": "testApiConnection", + "jsonData": "{\"apiKey\": \"${data.claudeKey}\", \"provider\": \"anthropic\"}", + "variant": "outlined", + "disabled": "!data.claudeKey", + "xs": 12, + "sm": 3, + "alsoDependsOn": ["claudeKey"], + "showProcess": true, + "resultStringToError": "error" + }, "geminiKey": { "newLine": true, "type": "text", "label": "Gemini API key", "xs": 12, - "sm": 12, + "sm": 9, "help": "aistudio.google.com", "helpLink": "https://aistudio.google.com/apikey" }, + "_testGemini": { + "type": "sendTo", + "label": "Test Gemini", + "icon": "img/gemini.svg", + "command": "testApiConnection", + "jsonData": "{\"apiKey\": \"${data.geminiKey}\", \"provider\": \"gemini\"}", + "variant": "outlined", + "disabled": "!data.geminiKey", + "xs": 12, + "sm": 3, + "alsoDependsOn": ["geminiKey"], + "showProcess": true, + "resultStringToError": "error" + }, "deepseekKey": { "newLine": true, "type": "text", "label": "DeepSeek API key", "xs": 12, - "sm": 12, + "sm": 9, "help": "platform.deepseek.com", "helpLink": "https://platform.deepseek.com/api_keys" }, + "_testDeepseek": { + "type": "sendTo", + "label": "Test DeepSeek", + "icon": "img/deepseek.svg", + "command": "testApiConnection", + "jsonData": "{\"apiKey\": \"${data.deepseekKey}\", \"provider\": \"deepseek\"}", + "variant": "outlined", + "disabled": "!data.deepseekKey", + "xs": 12, + "sm": 3, + "alsoDependsOn": ["deepseekKey"], + "showProcess": true, + "resultStringToError": "error" + }, "gptBaseUrl": { "newLine": true, "type": "text", "label": "Custom API Base URL", "xs": 12, - "sm": 12, + "sm": 5, "help": "Custom API Base URL help", "placeholder": "https://api.openai.com/v1" }, - "_testApiConnection": { - "newLine": true, + "gptBaseUrlKey": { + "type": "text", + "label": "Custom API key", + "xs": 12, + "sm": 4, + "help": "Custom API key help", + "placeholder": "optional" + }, + "_testCustom": { "type": "sendTo", - "label": "Test API connection", + "label": "Test Custom API", + "icon": "img/custom.svg", "command": "testApiConnection", - "jsonData": "{\"apiKey\": \"${data.gptKey}\", \"baseUrl\": \"${data.gptBaseUrl}\"}", + "jsonData": "{\"apiKey\": \"${data.gptBaseUrlKey}\", \"baseUrl\": \"${data.gptBaseUrl}\", \"provider\": \"openai\"}", "variant": "outlined", + "disabled": "!data.gptBaseUrl", "xs": 12, - "sm": 6, - "alsoDependsOn": ["gptKey", "gptBaseUrl"], + "sm": 3, + "alsoDependsOn": ["gptBaseUrl", "gptBaseUrlKey"], "showProcess": true, "resultStringToError": "error" } diff --git a/admin/tab.html b/admin/tab.html index 40e6d386..7da25698 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/protectFs.js.map b/build/lib/protectFs.js.map index e46dcbcf..a6a74d92 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;QAEl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AuzBC","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.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 +{"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,IA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AAE,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;;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"]} diff --git a/build/main.js b/build/main.js index 533d7c51..3c30c376 100644 --- a/build/main.js +++ b/build/main.js @@ -225,6 +225,19 @@ const jsDeclarationServer = new virtual_tsc_1.Server(typescriptSettings_1.jsDecl * Stores the IDs of script objects whose change should be ignored because * the compiled source was just updated */ +function httpStatusText(code) { + const texts = { + 400: 'Bad Request', + 401: 'Unauthorized', + 403: 'Forbidden', + 404: 'Not Found', + 429: 'Too Many Requests / Rate Limit', + 500: 'Internal Server Error', + 502: 'Bad Gateway', + 503: 'Service Unavailable', + }; + return texts[code] || `Error ${code}`; +} class JavaScript extends adapter_core_1.Adapter { context; errorLogFunction = { @@ -959,7 +972,13 @@ class JavaScript extends adapter_core_1.Adapter { if (apiKey) { chatHeaders.Authorization = `Bearer ${apiKey}`; } - bodyObj = { model: chatModel, messages, stream: false }; + bodyObj = { + model: chatModel, + messages, + stream: false, + // Disable thinking/reasoning for local models to save context and speed + ...(baseUrl ? { reasoning_effort: 'none' } : {}), + }; } const body = JSON.stringify(bodyObj); const bodyBuffer = Buffer.from(body, 'utf8'); @@ -1003,17 +1022,17 @@ class JavaScript extends adapter_core_1.Adapter { } } else { - let errorMsg = `API returned status ${res.statusCode}`; + let detail = ''; try { - const parsed = JSON.parse(data); - if (parsed.error?.message) { - errorMsg = parsed.error.message; - } + const errParsed = JSON.parse(data); + detail = errParsed.error?.message || data.substring(0, 200); } catch { - // ignore parse error + detail = data.substring(0, 200); } - this.sendTo(obj.from, obj.command, { error: errorMsg }, obj.callback); + this.sendTo(obj.from, obj.command, { + error: `${detail || httpStatusText(res.statusCode || 0)} (${res.statusCode})`, + }, obj.callback); } }); }); @@ -1106,7 +1125,18 @@ class JavaScript extends adapter_core_1.Adapter { this.sendTo(obj.from, obj.command, { error: 'Access denied (403)' }, obj.callback); } else { - this.sendTo(obj.from, obj.command, { error: `API returned status ${res.statusCode}` }, obj.callback); + // Include response body for debugging + let detail = ''; + try { + const errParsed = JSON.parse(data); + detail = errParsed.error?.message || data.substring(0, 200); + } + catch { + detail = data.substring(0, 200); + } + this.sendTo(obj.from, obj.command, { + error: `${detail || httpStatusText(res.statusCode || 0)} (${res.statusCode})`, + }, obj.callback); } }); }); diff --git a/build/main.js.map b/build/main.js.map index 4f07f887..f171402c 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;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C,KAAK,GAAG,IAAI,CAAC;oBAC7B,OAAO,CAAC,IAAI,CAAC,CAAC;gBAClB,CAAC,CAAC,CAAC;YACP,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;IACX,CAAC;CACJ;AAED,SAAS,eAAe,CACpB,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\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 = { model: chatModel, messages, stream: false };\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 errorMsg = `API returned status ${res.statusCode}`;\n try {\n const parsed = JSON.parse(data);\n if (parsed.error?.message) {\n errorMsg = parsed.error.message;\n }\n } catch {\n // ignore parse error\n }\n this.sendTo(obj.from, obj.command, { error: errorMsg }, obj.callback);\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 this.sendTo(\n obj.from,\n obj.command,\n { error: `API returned status ${res.statusCode}` },\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 +{"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;AAC7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ACnB,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 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"]} diff --git a/docs/de/README.md b/docs/de/README.md index 9223b8a7..6193d42b 100644 --- a/docs/de/README.md +++ b/docs/de/README.md @@ -45,26 +45,39 @@ DeepSeek bietet hervorragende Code-Generierung zu sehr niedrigen Kosten (~0,001 #### Lokale Modelle (Ollama / LM Studio) -Lokale Modelle laufen auf eigener Hardware ohne Internet. Für gute ioBroker-Code-Generierung werden jedoch Modelle mit mindestens 14B+ Parametern empfohlen. Kleine Modelle (7B) erzeugen häufig falsche API-Aufrufe. +Lokale Modelle laufen auf eigener Hardware ohne Internet. -- **Ollama**: **Base-URL** auf `http://localhost:11434/v1` setzen, beliebigen Text als API-Key verwenden -- **LM Studio**: **Base-URL** auf `http://localhost:1234/v1` setzen +**Mindestanforderung: 14B-Parameter-Modelle** (z.B. `qwen2.5-coder:14b`). Kleinere Modelle (7B/9B) erzeugen unzuverlässigen Code mit falschen API-Aufrufen. Eine GPU mit mindestens 12GB VRAM (z.B. RTX 3060) wird für 14B-Modelle empfohlen. + +Getestete und empfohlene Modelle: +- `qwen2.5-coder:14b` - Gute Codequalität, läuft auf 12GB VRAM +- `qwen2.5-coder:32b` - Bessere Qualität, erfordert 24GB+ VRAM + +Einrichtung: +- **Ollama**: **Base-URL** auf `http://localhost:11434/v1` setzen, API-Key leer lassen +- **LM Studio**: **Base-URL** auf `http://localhost:1234/v1` setzen, API-Key leer lassen **Hinweis:** Die kostenlose Version der OpenAI-API (ChatGPT) bietet keinen API-Zugang mehr für Code-Generierung. Google Gemini (kostenlos) oder DeepSeek (sehr günstig) sind empfohlene Alternativen. ### Konfiguration -In den Adapter-Einstellungen unter "Haupteinstellungen" befinden sich folgende Felder für die KI-Konfiguration: +In den Adapter-Einstellungen unter "KI-Einstellungen" befinden sich API-Key-Felder für jeden Anbieter: | Einstellung | Beschreibung | |-------------|-------------| -| **ChatGPT API-Schlüssel** | Der API-Schlüssel. Erforderlich für alle Anbieter. Für Ollama kann ein beliebiger nicht-leerer Wert verwendet werden (z.B. `ollama`). | -| **Eigene API Base-URL** | Die Base-URL des API-Anbieters. Leer lassen für OpenAI. Beispiele: `https://generativelanguage.googleapis.com/v1beta/openai` (Google Gemini), `http://localhost:11434/v1` (Ollama). | +| **ChatGPT API-Schlüssel** | API-Key für OpenAI (platform.openai.com) | +| **Anthropic API-Schlüssel** | API-Key für Claude (console.anthropic.com) | +| **Gemini API-Schlüssel** | API-Key für Google Gemini (aistudio.google.com) | +| **DeepSeek API-Schlüssel** | API-Key für DeepSeek (platform.deepseek.com) | +| **Eigene API Base-URL** | Base-URL für eigene Anbieter (z.B. `http://localhost:11434/v1` für Ollama) | +| **Eigener API-Schlüssel** | Optionaler API-Key für eigene Anbieter (Ollama benötigt keinen) | + +Es müssen nur die Keys der gewünschten Anbieter eingetragen werden. Jeder Anbieter hat einen eigenen **Test**-Button. ### API-Verbindung testen -Mit dem Button **"API-Verbindung testen"** in den Adapter-Einstellungen kann die Konfiguration überprüft werden. Der Test: -- Verbindet sich mit dem konfigurierten API-Endpunkt +Jeder Anbieter hat einen eigenen **Test**-Button neben seinem API-Key-Feld. Der Test: +- Verbindet sich mit dem API-Endpunkt des Anbieters - Validiert den API-Schlüssel - Gibt die Anzahl der verfügbaren Modelle zurück diff --git a/docs/en/README.md b/docs/en/README.md index f4105e62..d4af7178 100644 --- a/docs/en/README.md +++ b/docs/en/README.md @@ -46,26 +46,39 @@ DeepSeek offers excellent code generation at very low cost (~$0.001 per request) #### Local models (Ollama / LM Studio) -Local models run on your own hardware without internet. However, for good ioBroker code generation, models with at least 14B+ parameters are recommended. Small models (7B) often generate incorrect API calls. +Local models run on your own hardware without internet. -- **Ollama**: Set **Base URL** to `http://localhost:11434/v1`, use any string as API key -- **LM Studio**: Set **Base URL** to `http://localhost:1234/v1` +**Minimum requirement: 14B parameter models** (e.g. `qwen2.5-coder:14b`). Smaller models (7B/9B) produce unreliable code with incorrect API calls. A GPU with at least 12GB VRAM (e.g. RTX 3060) is recommended for 14B models. + +Tested and recommended models: +- `qwen2.5-coder:14b` - Good code quality, runs on 12GB VRAM +- `qwen2.5-coder:32b` - Better quality, requires 24GB+ VRAM + +Setup: +- **Ollama**: Set **Base URL** to `http://localhost:11434/v1`, leave API key empty +- **LM Studio**: Set **Base URL** to `http://localhost:1234/v1`, leave API key empty **Note:** The free tier of the OpenAI API (ChatGPT) no longer provides API access for code generation. Consider using Google Gemini (free) or DeepSeek (very affordable) as alternatives. ### Configuration -In the adapter settings under "Main settings", you will find the following fields for AI configuration: +In the adapter settings under "AI settings", you will find API key fields for each provider: | Setting | Description | |---------|-------------| -| **ChatGPT API key** | Your API key. Required for all providers. For Ollama you can use any non-empty string (e.g. `ollama`). | -| **Custom API Base URL** | The base URL of your API provider. Leave empty for OpenAI. Examples: `https://generativelanguage.googleapis.com/v1beta/openai` (Google Gemini), `http://localhost:11434/v1` (Ollama). | +| **ChatGPT API key** | API key for OpenAI (platform.openai.com) | +| **Anthropic API key** | API key for Claude (console.anthropic.com) | +| **Gemini API key** | API key for Google Gemini (aistudio.google.com) | +| **DeepSeek API key** | API key for DeepSeek (platform.deepseek.com) | +| **Custom API Base URL** | Base URL for custom providers (e.g. `http://localhost:11434/v1` for Ollama) | +| **Custom API key** | Optional API key for custom providers (Ollama doesn't need one) | + +Only enter the keys for providers you want to use. Each provider has its own **Test** button. ### Test API Connection -Use the **"Test API connection"** button in the adapter settings to verify your configuration. The test will: -- Connect to the configured API endpoint +Each provider has a dedicated **Test** button next to its API key field. The test will: +- Connect to the provider's API endpoint - Validate the API key - Return the number of available models diff --git a/src-editor/package-lock.json b/src-editor/package-lock.json index 91a3bc07..555688ba 100644 --- a/src-editor/package-lock.json +++ b/src-editor/package-lock.json @@ -4116,16 +4116,6 @@ "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", "license": "MIT" }, - "node_modules/data-uri-to-buffer": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-4.0.1.tgz", - "integrity": "sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==", - "license": "MIT", - "optional": true, - "engines": { - "node": ">= 12" - } - }, "node_modules/data-urls": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-5.0.0.tgz", @@ -4594,30 +4584,6 @@ "integrity": "sha512-OP2IUU6HeYKJi3i0z4A19kHMQoLVs4Hc+DPqqxI2h/DPZHTm/vjsfC6P0b4jCMy14XizLBqvndQ+UilD7707Jw==", "license": "MIT" }, - "node_modules/fetch-blob": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/fetch-blob/-/fetch-blob-3.2.0.tgz", - "integrity": "sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/jimmywarting" - }, - { - "type": "paypal", - "url": "https://paypal.me/jimmywarting" - } - ], - "license": "MIT", - "optional": true, - "dependencies": { - "node-domexception": "^1.0.0", - "web-streams-polyfill": "^3.0.3" - }, - "engines": { - "node": "^12.20 || >= 14.13" - } - }, "node_modules/file-selector": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/file-selector/-/file-selector-2.1.2.tgz", @@ -4754,19 +4720,6 @@ "node": ">= 6" } }, - "node_modules/formdata-polyfill": { - "version": "4.0.10", - "resolved": "https://registry.npmjs.org/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz", - "integrity": "sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==", - "license": "MIT", - "optional": true, - "dependencies": { - "fetch-blob": "^3.1.2" - }, - "engines": { - "node": ">=12.20.0" - } - }, "node_modules/from": { "version": "0.1.7", "resolved": "https://registry.npmjs.org/from/-/from-0.1.7.tgz", @@ -5840,27 +5793,6 @@ "license": "MIT", "optional": true }, - "node_modules/node-domexception": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz", - "integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==", - "deprecated": "Use your platform's native DOMException instead", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/jimmywarting" - }, - { - "type": "github", - "url": "https://paypal.me/jimmywarting" - } - ], - "license": "MIT", - "optional": true, - "engines": { - "node": ">=10.5.0" - } - }, "node_modules/node-fetch": { "version": "2.7.0", "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", @@ -7768,16 +7700,6 @@ "node": ">=18" } }, - "node_modules/web-streams-polyfill": { - "version": "3.3.3", - "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.3.3.tgz", - "integrity": "sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==", - "license": "MIT", - "optional": true, - "engines": { - "node": ">= 8" - } - }, "node_modules/webidl-conversions": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz", diff --git a/src-editor/src/OpenAi/OpenAiDialog.tsx b/src-editor/src/OpenAi/OpenAiDialog.tsx index 9eeb9e94..593f75eb 100644 --- a/src-editor/src/OpenAi/OpenAiDialog.tsx +++ b/src-editor/src/OpenAi/OpenAiDialog.tsx @@ -18,7 +18,7 @@ import { Check, Close, QuestionMark as Question, FileCopy as Copy, Refresh } fro import { Utils, I18n, type AdminConnection, type ThemeType } from '@iobroker/adapter-react-v5'; -import { detectDevices, type DeviceObject, systemPrompt } from './OpenAiPrompt'; +import { detectDevices, type DeviceObject, systemPromptFull } from './OpenAiPrompt'; import ScriptEditorComponent from '../Components/ScriptEditorVanillaMonaco'; const LANGUAGES: Record = { @@ -35,60 +35,25 @@ const LANGUAGES: Record = { 'zh-cn': 'Chinese', }; -const ICON_STYLE: React.CSSProperties = { flexShrink: 0, opacity: 0.7 }; - -// Provider logos (source: simple-icons, CC0 license) -const PROVIDER_ICONS: Record = { - // OpenAI hexagonal knot - openai: ( - - - - ), - // Anthropic "A" mark - anthropic: ( - - - - ), - // Google Gemini 4-pointed star - gemini: ( - - - - ), - // DeepSeek "D" mark - deepseek: ( - - - - ), +const ICON_STYLE: React.CSSProperties = { width: 16, height: 16, flexShrink: 0, opacity: 0.7 }; + +// Map provider names to icon files downloaded by the adapter at startup +const PROVIDER_ICON_FILES: Record = { + openai: 'img/openai.svg', + anthropic: 'img/anthropic.svg', + gemini: 'img/gemini.svg', + deepseek: 'img/deepseek.svg', + custom: 'img/custom.svg', }; +function ProviderIcon({ provider }: { provider: string }): React.JSX.Element | null { + const file = PROVIDER_ICON_FILES[provider]; + if (!file) { + return null; + } + return {provider} { (e.target as HTMLImageElement).style.display = 'none'; }} />; +} + interface OpenAiDialogProps { adapterName: string; socket: AdminConnection; @@ -105,6 +70,7 @@ interface ApiConfig { geminiKey: string; deepseekKey: string; gptBaseUrl?: string; + gptBaseUrlKey?: string; } async function getApiConfig(socket: AdminConnection, runningInstances: Record): Promise { @@ -116,9 +82,10 @@ async function getApiConfig(socket: AdminConnection, runningInstances: Record { const [question, setQuestion] = useState(window.localStorage.getItem('openai-question') || ''); const [answer, setAnswer] = useState(''); - const [working, setWorking] = useState(false); + const [working, setWorking] = useState(false); + const [plan, setPlan] = useState(''); + const [showPlan, setShowPlan] = useState(false); const [error, setError] = useState(false); const [model, setModel] = useState(window.localStorage.getItem('openai-model') || ''); const [showKeyWarning, setShowKeyWarning] = useState(false); @@ -193,12 +162,11 @@ const OpenAiDialog = (props: OpenAiDialogProps): React.JSX.Element => { } }; - if (config.gptKey || config.gptBaseUrl) { + if (config.gptKey) { queries.push( props.socket .sendTo(instanceId, 'testApiConnection', { apiKey: config.gptKey, - baseUrl: config.gptBaseUrl || '', provider: 'openai', }) .then((result: { models?: string[]; error?: string }) => { @@ -214,6 +182,27 @@ const OpenAiDialog = (props: OpenAiDialogProps): React.JSX.Element => { ); } + if (config.gptBaseUrl) { + queries.push( + props.socket + .sendTo(instanceId, 'testApiConnection', { + apiKey: config.gptBaseUrlKey || '', + baseUrl: config.gptBaseUrl, + provider: 'openai', + }) + .then((result: { models?: string[]; error?: string }) => { + if (result.models) { + addModels(result.models, 'custom'); + } else if (result.error) { + errors.push(`Custom: ${result.error}`); + } + }) + .catch((err: unknown) => { + errors.push(`Custom: ${String(err)}`); + }), + ); + } + if (config.claudeKey) { queries.push( props.socket @@ -338,7 +327,7 @@ const OpenAiDialog = (props: OpenAiDialogProps): React.JSX.Element => { let docs; if (!docsCache.current) { - docs = await systemPrompt(); + docs = await systemPromptFull(); docsCache.current = docs; } else { docs = docsCache.current; @@ -364,9 +353,12 @@ const OpenAiDialog = (props: OpenAiDialogProps): React.JSX.Element => { } else if (provider === 'deepseek') { apiKey = config.deepseekKey; baseUrl = ''; + } else if (provider === 'custom') { + apiKey = config.gptBaseUrlKey || ''; + baseUrl = config.gptBaseUrl || ''; } else { apiKey = config.gptKey; - baseUrl = config.gptBaseUrl || ''; + baseUrl = ''; } const instanceId = Object.keys(props.runningInstances)[0]; @@ -375,34 +367,151 @@ const OpenAiDialog = (props: OpenAiDialogProps): React.JSX.Element => { return; } - setWorking(true); + setWorking(I18n.t('Planning...')); setError(false); + setPlan(''); + setShowPlan(false); + setAnswer(''); try { - const result: { success?: boolean; content?: string; error?: string } = await props.socket.sendTo( + // Step 1: Create an implementation plan with relevant devices + const step1: { success?: boolean; content?: string; error?: string } = await props.socket.sendTo( instanceId, 'chatCompletion', { + timeout: 600000, apiKey, baseUrl, model, provider, messages: [ { - role: 'system', - content: `You are programmer. Here is a documentation:\n\n${docs}`, + role: 'user', + content: `Devices in my smart home: +${JSON.stringify(devices)} + +I need a plan for this task: ${question} + +Answer with max 6 lines. Use FULL device IDs from the list above (e.g. zigbee2mqtt.0.0xa4c1383f5ef5fb07.state). No explanation. No reasoning. +1. IDs: +2. Trigger: +3. Condition: +4. Actions: +5. Else: +6. Extra: +Values are boolean (true/false) or numbers, not strings. Use .state not .state_toggle.`, }, + ], + }, + ); + + if (step1.error) { + setError(step1.error); + setWorking(false); + return; + } + + // Extract plan from step 1 + let planText = (step1.content || '').trim(); + // Strip thinking artifacts + planText = planText.replace(/[\s\S]*?<\/think>/gi, '').trim(); + planText = planText.replace(/<\|endoftext\|>/g, '').trim(); + planText = planText.replace(/<\|im_start\|>[\s\S]*?<\|im_end\|>/g, '').trim(); + setPlan(planText); + + // Step 2: Generate code based on the plan + full API docs + setWorking(I18n.t('Generating code...')); + const result: { success?: boolean; content?: string; error?: string } = await props.socket.sendTo( + instanceId, + 'chatCompletion', + { + timeout: 600000, + apiKey, + baseUrl, + model, + provider, + messages: [ { role: 'system', - content: `Here is list of devices:\n\n${JSON.stringify(devices, null, 2)}`, + content: `You write ioBroker JavaScript adapter scripts. +Copy EXACTLY this syntax. Do NOT change the callback signature. +IMPORTANT: Write all code at top level. NEVER use console.log (use log instead). NEVER define functions with the function keyword. + +// CORRECT: on() always has ONE callback argument called obj +on('zigbee.0.sensor.state', (obj) => { + // obj.state.val = the new value (boolean or number) + // obj.id = the state ID that changed + setState('zigbee.0.lamp.state', obj.state.val); + log('Changed to ' + obj.state.val); +}); + +// CORRECT: on() with filter +on({id: /zigbee\.0\..*\.state$/, change: 'ne'}, (obj) => { + if (obj.state.val === true) { + setState('zigbee.0.other.state', true); + } +}); + +// Other correct examples: +setState('id', true); +setState('id', 50); +const val = getState('id').val; +schedule('0 7 * * *', () => { log('runs daily at 07:00'); }); +schedule('0 22 * * *', () => { setState('id', false); }); + +// CORRECT Telegram: always use sendTo, NEVER setState on telegram +sendTo('telegram.0', 'send', {text: 'Alert: ' + someValue}); + +// CORRECT httpGet: res.data is a STRING, parse JSON with JSON.parse +httpGet('https://api.example.com/data', (err, res) => { + const data = JSON.parse(res.data); + log('Temperature: ' + data.main.temp); +}); + +$('state[state.id=*.state](rooms=Room)').each((id) => { setState(id, false); }); +createState('name', 0, {type: 'number', name: 'Name'}); +setStateDelayed('id', true, false, 5000); +log(formatDate(new Date(), 'DD.MM.YYYY hh:mm')); + +WRONG: on('id', (id, state) => {}) CORRECT: on('id', (obj) => {}) +WRONG: set('id', true) CORRECT: setState('id', true) +WRONG: adapter.setState('id', true) CORRECT: setState('id', true) +WRONG: obj.val or newState.val CORRECT: obj.state.val +WRONG: on('change', {id: 'x'}, cb) CORRECT: on({id: 'x', change: 'ne'}, cb) +WRONG: setState('telegram.0', text) CORRECT: sendTo('telegram.0', 'send', {text: text}) +WRONG: res.body.main.temp CORRECT: JSON.parse(res.data).main.temp +WRONG: function myFunc() {} CORRECT: write code directly, no function definitions +WRONG: setTimeout(fn, ms) CORRECT: schedule('cron', () => {}) or setStateDelayed() +Values are boolean (true/false) or numbers, NEVER strings like 'ON'/'OFF'. +NEVER use: function keyword, require, import, setInterval, setTimeout, console.log, debug(). + +All available functions (use syntax from examples above): +on(pattern, (obj)=>{}) | once(pattern, (obj)=>{}) | unsubscribe(handler) +setState(id, val) | getState(id).val | setStateChanged(id, val) | setStateDelayed(id, val, ack, ms) | clearStateDelayed(id) +existsState(id) | existsObject(id) | getObject(id) | setObject(id, obj) | extendObject(id, obj) | deleteObject(id) +createState(name, initVal, {type,name,role}) | deleteState(name) | createAlias(name, alias) +schedule(cron, ()=>{}) | clearSchedule(obj) | scheduleById(id, (obj)=>{}) | getSchedules() +sendTo(adapter, cmd, msg) | sendToHost(host, cmd, msg) +$('selector').each((id)=>{}) | $('selector').setState(val) | $('selector').getState() +log(text) | formatDate(date, 'DD.MM.YYYY hh:mm') | formatTimeDiff(ms) | formatValue(val, decimals) +getDateObject(str) | getAstroDate(pattern) | isAstroDay() | compareTime(start, end, op) +exec(cmd, (err,stdout,stderr)=>{}) | httpGet(url, (err,res)=>{}) | httpPost(url, data, (err,res)=>{}) +readFile(adapter, name, (err,data)=>{}) | writeFile(adapter, name, data, cb) | delFile(adapter, name, cb) +onFile(id, name, withFile, cb) | offFile(id, name) | onStop(cb, timeout) +getHistory(inst, {id,start,end,aggregate,count}, cb) | getEnums(name) | getIdByName(name) +wait(ms) | toInt(val) | toFloat(val) | toBoolean(val) +messageTo(target, data) | onMessage(name, cb) | onLog(severity, cb) +setInterval(cb, ms) | clearInterval(id) | setTimeout(cb, ms) | clearTimeout(id) +runScript(name) | startScript(name) | stopScript(name) | isScriptActive(name)`, }, { role: 'user', - content: `Write JavaScript code that does:\n\n${question} -Return only code. -Write comments in ${LANGUAGES[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.`, + content: `TASK: ${question} + +PLAN: +${planText} + +Write the ioBroker script. Use the exact state IDs from the plan. If the plan contains TODO_DEVICE_ID, keep it as a placeholder with a comment so the user can fill in the correct ID. Write comments in ${LANGUAGES[I18n.getLanguage()] || 'English'}. Return ONLY code.`, }, ], }, @@ -569,7 +678,7 @@ Do not import any libraries as all functions are already imported.`, variant="standard" multiline autoFocus - disabled={working} + disabled={!!working} fullWidth onKeyUp={e => { if (e.key === 'Enter' && e.ctrlKey) { @@ -588,15 +697,15 @@ Do not import any libraries as all functions are already imported.`,
@@ -607,7 +716,7 @@ Do not import any libraries as all functions are already imported.`, disabled={modelsLoading || !!modelsError} renderValue={value => ( - {PROVIDER_ICONS[modelProviderMap.current[value]]} + {value} )} @@ -631,7 +740,7 @@ Do not import any libraries as all functions are already imported.`, value={m} > - {PROVIDER_ICONS[modelProviderMap.current[m]]} + {m} @@ -653,8 +762,33 @@ Do not import any libraries as all functions are already imported.`, {modelsError && (
{modelsError}
)} + {plan && ( +
+ + {showPlan && ( +
{plan}
+ )} +
+ )}
{I18n.t('Result')}
-
+
{error ? (
{error}
) : ( diff --git a/src-editor/src/OpenAi/OpenAiPrompt.tsx b/src-editor/src/OpenAi/OpenAiPrompt.tsx index 6522fb1e..a76f1c5f 100644 --- a/src-editor/src/OpenAi/OpenAiPrompt.tsx +++ b/src-editor/src/OpenAi/OpenAiPrompt.tsx @@ -1,7 +1,7 @@ import ChannelDetector, { type DetectOptions, Types, type PatternControl } from '@iobroker/type-detector'; import { type AdminConnection, I18n } from '@iobroker/adapter-react-v5'; // @ts-expect-error no types in Markdown -const docs = import(`./docs.md?raw`); +const docsFull = import(`./docs-compact.md?raw`); interface DeviceState { id: string; @@ -270,5 +270,5 @@ async function detectDevices(socket: AdminConnection): Promise { return result; } -const systemPrompt: () => Promise = async (): Promise => (await docs).default; -export { systemPrompt, detectDevices }; +const systemPromptFull: () => Promise = async (): Promise => (await docsFull).default; +export { systemPromptFull, detectDevices }; diff --git a/src-editor/src/OpenAi/docs-compact.md b/src-editor/src/OpenAi/docs-compact.md new file mode 100644 index 00000000..1bfbc647 --- /dev/null +++ b/src-editor/src/OpenAi/docs-compact.md @@ -0,0 +1,335 @@ +# ioBroker JavaScript Adapter - API Reference + +IMPORTANT RULES: +- ONLY use functions listed in this document. NEVER define your own helper functions. +- Use on() to react to state changes. NEVER use setTimeout/setInterval for polling states. +- Use setState(id, value) to control devices. Use getState(id).val to read values. +- All functions are pre-imported. NEVER use require() or import. +- Code runs inside an async context. You can use await directly. + +## Quick Reference - Most Used Functions + +```js +// React to state changes: +on('adapter.0.device.state', (obj) => { + const val = obj.state.val; +}); + +// Read a state value: +const val = getState('adapter.0.device.state').val; + +// Set a state (control a device): +setState('adapter.0.device.state', true); + +// Time-based schedule (cron): +schedule('0 7 * * *', () => { /* runs daily at 07:00 */ }); + +// Selector - find states by room/function: +$('state[state.id=*.state](rooms=Living room)').each((id) => { + setState(id, false); +}); + +// Log output: +log('message'); +``` + +--- + +## exec(cmd, [options], callback) +Execute OS command. `callback(error, stdout, stderr)`. Requires "Enable command exec" option. + +## on(pattern, callbackOrId, value) +Subscribe to state changes. Alias: `subscribe`. Returns handler for `unsubscribe`. +Callback receives `{id, state: {val, ts, ack, lc, from}, oldState: {val, ts, ack, lc, from}}`. +`on('stateId1', 'stateId2')` connects two states. `on('stateId1', 'stateId2', 'triggered')` sets fixed value. +Pattern can be: string ID, RegExp, or object with these properties: +- `logic` (string): "and"|"or" (default "and") +- `id` (string|RegExp|Array): state ID filter +- `name` (string|RegExp|Array): state name filter +- `change` (string): "eq","ne","gt","ge","lt","le","any" (default "ne" for string ID, "any" otherwise) +- `val`, `valNe`, `valGt`, `valGe`, `valLt`, `valLe` (mixed): new value conditions +- `ack` (boolean): new ack filter; `q` (number): quality filter (default 0, use '*' for any) +- `oldVal`, `oldValNe`, `oldValGt`, `oldValGe`, `oldValLt`, `oldValLe` (mixed): previous value conditions +- `oldAck` (bool), `oldQ` (number): previous ack/quality filters +- `ts`, `tsGt`, `tsGe`, `tsLt`, `tsLe` (string): new timestamp conditions +- `oldTs`, `oldTsGt`, `oldTsGe`, `oldTsLt`, `oldTsLe` (string): previous timestamp conditions +- `lc`, `lcGt`, `lcGe`, `lcLt`, `lcLe` (string): last change timestamp conditions +- `oldLc`, `oldLcGt`, `oldLcGe`, `oldLcLt`, `oldLcLe` (string): previous last change conditions +- `channelId`, `channelName`, `deviceId`, `deviceName` (string|RegExp|Array): channel/device filters +- `enumId`, `enumName` (string|RegExp|Array): enum filters +- `from`, `fromNe`, `oldFrom`, `oldFromNe` (string|RegExp|Array): adapter source filters +To get state deletions/expires, use `change: 'ne'` or `'any'` AND `q: '*'`. + +## once(pattern, callback) +Like `on()`, but triggers only once then auto-unsubscribes. + +## unsubscribe(idOrHandler) +Remove subscriptions by object ID (removes all) or by handler (removes specific). + +## getSubscriptions() +Returns object `{stateId: [{name, pattern}]}` listing all state subscriptions. + +## getFileSubscriptions() +Returns object listing all file subscriptions. + +## schedule(pattern, callback) +Time scheduler with cron and astro support. Returns schedule object for `clearSchedule`. +Cron string: `"sec min hour dayOfMonth month dayOfWeek"` (sec optional, 5 or 6 fields). +Object pattern: `{second, minute, hour, date, month, year, dayOfWeek}`. +Date object: triggers once at that time. +With time range: `{start, end, rule}` where start/end are Date/string/ms, rule is cron string or object. +Astro: `{astro: 'sunrise', shift: 10}` (shift in minutes, can be negative). +Astro values: sunrise, sunriseEnd, goldenHourEnd, solarNoon, goldenHour, sunsetStart, sunset, dusk, nauticalDusk, night, nightEnd, nauticalDawn, dawn, nadir. +Requires latitude/longitude in adapter settings for astro. +Also works via `on()`: `on({time: '*/2 * * * *'}, cb)` or `on({astro: 'sunset', shift: 10}, cb)`. + +## scheduleById(id, [ack], callback) +Schedule based on state value (format `[h]h:[m]m[:ss]`). Auto-updates when state changes. + +## getSchedules(allScripts) +Returns list of all CRON/schedule jobs. Pass `true` for all scripts, otherwise current script only. + +## clearSchedule(scheduleObject) +Cancel a schedule created by `schedule()`. + +## getAttr(obj, path) +Get nested attribute: `getAttr({a: {b: 5}}, 'a.b')` returns 5. Parses JSON strings automatically. + +## getAstroDate(pattern, date, offsetMinutes) +Returns Date object for astro event. Uses current day if no date given. + +## isAstroDay() +Returns `true` if current time is between astro sunrise and sunset. + +## compareTime(startTime, endTime, operation, timeToCompare) +Compare time with limits. Operations: ">", ">=", "<", "<=", "==", "<>", "between", "not between". +Times can be Date objects, date strings, time strings, or astro names. +Astro with offset: `{astro: 'sunsetStart', offset: 30, date: new Date()}`. + +## setState(id, state, ack, callback) +Set state value. `setState('id', 1)` = `setState('id', {val: 1, ack: false})`. +`ack=false`: command to device; `ack=true`: confirmed state update. + +## setStateAsync(id, state, ack) +Promise version of setState. + +## setStateDelayed(id, state, isAck, delay, clearRunning, callback) +setState with delay in ms. Returns timer handler. `clearRunning` (default true) cancels previous delays. + +## setStateChanged(id, state, ack) +Like setState, but only sets if value actually changed. + +## setStateChangedAsync(id, state, ack) +Promise version of setStateChanged. + +## clearStateDelayed(id, [timerId]) +Clear delayed tasks for state ID, or specific timer. + +## getStateDelayed(id) +Get list of running timers. Returns `[{timerId, left, delay, val, ack}]` for specific ID, or object keyed by ID for all. + +## getState(id) +Returns `{val, ack, ts, lc, from}`. Returns `{val: null, notExist: true}` if missing. + +## getStateAsync(id) +Promise version of getState. + +## existsState(id, [callback]) +Check if state exists. Sync (returns bool) if "Do not subscribe all states on start" is off, otherwise async. + +## getObject(id, [enumName]) +Get object description. With enumName (e.g. 'rooms' or true for all), adds enumIds/enumNames arrays. + +## setObject(id, obj, callback) +Write object to DB. Use to modify objects read with getObject. Requires "Enable setObject" option. + +## existsObject(id, [callback]) +Check if object exists. Sync or async like existsState. + +## extendObject(id, obj, callback) +Merge-update object. E.g. `extendObject('system.adapter.sayit.0', {common: {enabled: false}})`. + +## deleteObject(id, [isRecursive], callback) +Delete object (and state value if type=state). `isRecursive` deletes children too. + +## getIdByName(name, [alwaysArray]) +Returns ID(s) for object with given name. Returns array if multiple or if `alwaysArray` is true. + +## getEnums(enumName) +Get enums with members. Returns `[{id, members, name}]`. + +## createState(name, [initialValue], [forceCreation], [common], [native], [callback]) +Create state in `javascript.X` namespace. Prefer `0_userdata.0.mystate` for custom data points. +Common options: `{type, role, read, write, name, unit, min, max, def, alias}`. +Alias: set `alias: true` or `alias: {id: 'alias.0.x', read: 'val/1000', write: 'val*1000'}`. + +## createStateAsync(name, [initialValue], [forceCreation], [common], [native]) +Promise version of createState. + +## deleteState(name, [callback]) +Delete state in `javascript.X` namespace. + +## deleteStateAsync(name) +Promise version of deleteState. + +## createAlias(name, alias, [forceCreation], [common], [native], [callback]) +Create alias in `alias.0` namespace. `alias` can be string ID or `{id: {read: 'id1', write: 'id2'}}`. + +## createAliasAsync(name, alias, [forceCreation], [common], [native]) +Promise version of createAlias. + +## sendTo(adapter, command, message, [options], [callback]) +Send message to adapter instance(s). `options: {timeout}` (default 20000ms). +E.g. `sendTo('telegram.0', {user: 'User', text: 'Hi'})`. + +## sendToAsync(adapter, command, message, [options]) +Promise version of sendTo. + +## sendToHost(hostName, command, message, [callback]) +Send message to host controller. Commands: cmdExec, getRepository, getInstalled, getVersion, getDiagData, getLocationOnDisk, getDevList, getLogs, getHostInfo. + +## sendToHostAsync(hostName, command, message) +Promise version of sendToHost. + +## setInterval(callback, ms, ...args) +Same as JS setInterval. + +## clearInterval(id) +Same as JS clearInterval. + +## setTimeout(callback, ms, ...args) +Same as JS setTimeout. + +## clearTimeout(id) +Same as JS clearTimeout. + +## setImmediate(callback, ...args) +Same as JS setImmediate (higher priority than setTimeout 0). + +## formatDate(millisecondsOrDate, [format]) +Format date. Tokens: YYYY(year), MM(month), DD(day), hh(hours), mm(min), ss(sec), sss(ms), WW/W(weekday), OO/O(month name). + +## formatTimeDiff(milliseconds, [format]) +Format time difference. Default `hh:mm:ss`. Tokens: DD/D(days), hh/h, mm/m, ss/s. + +## getDateObject(stringOrNumber) +Convert string/number to Date. `getDateObject('20:00')` adds current date. + +## formatValue(value, [decimals], [format]) +Format number with locale. `decimals` default 2. Format: '.,', ',.', or ' .'. + +## adapterSubscribe(id) +Send "subscribe" message to adapter. Auto-called for subscribable adapters. + +## adapterUnsubscribe(id) +Send "unsubscribe" message to adapter. + +## $(selector) +jQuery-like selector. Methods: `.on(cb)`, `.each(cb)`, `.setState(val, ack)`, `.getState()`, `.toArray()`. +Format: `'name[commonAttr=val](enumName=val){nativeAttr=val}[id=filter][state.id=filter]'`. +Name: state, channel, device, schedule. Wildcards `*` supported. +E.g. `$('channel[role=switch][state.id=*.STATE](rooms=Living room)').setState(false)`. + +## readFile(adapter, fileName, callback) +Read file from DB. `callback(error, bytes)`. Default adapter: `javascript.0`. + +## writeFile(adapter, fileName, bytes, callback) +Write file to DB. Accessible via web: `http://ip:8082/javascript/path/file.ext`. + +## delFile(adapter, fileName, callback) +Delete file or directory from DB. Alias: `unlink`. + +## renameFile(adapter, oldName, newName, callback) +Rename file or directory in DB. Alias: `rename`. + +## onFile(id, fileName, withFile, callback) +Subscribe to file changes. `id`: meta object ID (e.g. 'vis.0'). `fileName`: name or glob pattern. +Callback: `(id, fileName, size, fileData, mimeType)`. `fileData`/`mimeType` only if `withFile=true`. + +## offFile(id, fileName) +Unsubscribe from file changes. + +## onStop(callback, [timeout]) +Register callback for script stop. Default timeout 1000ms. Call `callback()` when cleanup done. + +## getHistory(instance, options, callback) +Read history data. Options: `{id, start, end, aggregate, count, timeout}`. +`aggregate`: 'none', 'minmax', 'max', 'min', 'average', 'total', 'count', 'm4'. +If instance omitted, uses system default. `callback(err, result, options, instance)`. + +## runScript(scriptName, [callback]) +Start or restart a script by name. + +## runScriptAsync(scriptName) +Promise version of runScript. + +## startScript(scriptName, [ignoreIfStarted], [callback]) +Start script. If `ignoreIfStarted=true`, does nothing if already running. + +## startScriptAsync(scriptName, [ignoreIfStarted]) +Promise version of startScript. + +## stopScript([scriptName], [callback]) +Stop script. No args = stop self. + +## stopScriptAsync([scriptName]) +Promise version of stopScript. + +## isScriptActive(scriptName) +Returns if script is enabled (not necessarily running). + +## toInt(val) +Convert to integer. + +## toFloat(val) +Convert to float. + +## toBoolean(val) +Convert to boolean. + +## jsonataExpression(expr) +Evaluate JSONata expression. + +## wait(ms) / sleep(ms) +Pause execution. Must use `await wait(1000)`. + +## messageTo(target, data, [options], [callback]) +Send message via message bus to other scripts. Target: `{instance, script, message}` or just `'messageName'`. +Default timeout 5000ms. + +## messageToAsync(target, data, [options]) +Promise version of messageTo. + +## onMessage(messageName, callback) +Subscribe to message bus. `callback(data, callback)` - call callback with response. + +## onMessageUnregister(idOrName) +Unsubscribe from message by handler ID or message name. + +## onLog(severity, callback) +Subscribe to logs. Severity: 'error', 'warn', 'info', 'debug', or '*' for all. +`callback({message, severity, ts})`. Cannot log same severity in handler (infinite loop). + +## onLogUnregister(idOrHandlerOrSeverity) +Unsubscribe from log handler by ID, function, or severity string. + +## httpGet(url, [options], callback) +HTTP GET request. Options: `{timeout, responseType, headers, basicAuth, validateCertificate}`. +`callback(err, response)` where `response: {statusCode, data, headers}`. +Use `responseType: 'arraybuffer'` for binary data. + +## httpPost(url, data, [options], callback) +HTTP POST request. Same options as httpGet plus `basicAuth: {user, password}`. + +## createTempFile(fileName, data) +Create temporary file. Returns file path string. Useful for sendTo with file attachments. + +# Global Variables +- `scriptName` - name of current script +- `instance` - JavaScript adapter instance number (e.g. 0) +- `defaultDataDir` - absolute path to iobroker-data directory +- `verbose` - boolean, verbose mode enabled + +# Notes +- "Do not subscribe all states on start" mode: getState requires async callback `getState(id, (err, state) => {})`. +- Scripts can be enabled/disabled via state `javascript.INSTANCE.scriptEnabled.SCRIPT_NAME` (set with ack=false). diff --git a/src-editor/src/OpenAi/docs.md b/src-editor/src/OpenAi/docs.md deleted file mode 100644 index f3258c69..00000000 --- a/src-editor/src/OpenAi/docs.md +++ /dev/null @@ -1,2035 +0,0 @@ -### exec - execute some OS command, like `cp file1 file2` - -```js -exec(cmd, [options], callback); -``` - -Execute system command and get the outputs. - -```js -// reboot linux system :) -exec('reboot'); - -// Get the list of files and directories in /var/log -exec('ls /var/log', function (error, stdout, stderr) { - log(`stdout: ${stdout}`); -}); -``` - -Node.js uses /bin/sh to execute commands. If you want to use another shell, you can use the option object as described in the [Node.js documentation](https://nodejs.org/api/child_process.html#child_processexeccommand-options-callback) for child_process.exec. -It is the best practice to always use fill path names to commands to make sure the right command is executed. - -**Notice:** you must enable _Enable command "exec"_ option to use this feature! - -### on - Subscribe on changes or updates of some state - -```js -on(pattern, callbackOrId, value); -``` - -The callback function will return the object as parameter with the following content: - -```json -{ - "id": "javascript.0.myplayer", - "state": { - "val": "new state", - "ts": 1416149118, - "ack": true, - "lc": 1416149118, - "from": "system.adapter.sonos.0" - }, - "oldState": { - "val": "old state", - "ts": 1416148233, - "ack": true, - "lc": 1416145154, - "from": "system.adapter.sonos.0" - } -} -``` - -**Note:** `state` was previously called `newState`. That is still working. - -Example: - -```js -let timer; - -// Create state "javascript.0.counter" -createState('counter', 0); - -// On change -on('adapter.0.device.channel.sensor', data => { - // But not ofter than 30 seconds - if (!timer) { - timer = setTimeout(() => { - timer = null; - }, 30000); - - // Set acknowledged value - setState('counter', 1 + getState('counter'), true /*ack*/); - - // Or to set unacknowledged command - setState('adapter.0.device.channel.actor', true); - } -}); -``` - -You can use the following parameters to specify the trigger: - -| parameter | type/value | description | -|-------------|------------|-----------------------------------------------------------------------------------------------------------------------------------------------| -| logic | string | "and" or "or" logic to combine the conditions \(default: "and"\) | -| | | | -| id | string | id is equal to given one | -| | RegExp | id matched to regular expression | -| | Array | id matched to a list of allowed IDs | -| | | | -| name | string | name is equal to given one | -| | RegExp | name matched to regular expression | -| | Array | name matched to a list of allowed names | -| | | | -| change | string | "eq", "ne", "gt", "ge", "lt", "le", "any" | -| | "eq" | (equal) New value must be equal to old one (state.val == oldState.val) | -| | "ne" | (not equal) New value must be not equal to the old one (state.val != oldState.val) **If pattern is id-string this value is used by default** | -| | "gt" | (greater) New value must be greater than old value (state.val > oldState.val) | -| | "ge" | (greater or equal) New value must be greater or equal to old one (state.val >= oldState.val) | -| | "lt" | (smaller) New value must be smaller than old one (state.val < oldState.val) | -| | "le" | (smaller or equal) New value must be smaller or equal to old value (state.val <= oldState.val) | -| | "any" | Trigger will be raised if just the new value comes | -| | | | -| val | mixed | New value must be equal to given one | -| valNe | mixed | New value must be not equal to given one | -| valGt | mixed | New value must be greater than given one | -| valGe | mixed | New value must be greater or equal to given one | -| valLt | mixed | New value must be smaller than given one | -| valLe | mixed | New value must be smaller or equal to given one | -| | | | -| ack | boolean | Acknowledged state of new value is equal to given one | -| q | number | Quality code state of new value is equal to given one. You can use '\*' for matching to any code. **If not provided q = 0 is set as pattern!** | -| | | | -| oldVal | mixed | Previous value must be equal to given one | -| oldValNe | mixed | Previous value must be not equal to given one | -| oldValGt | mixed | Previous value must be greater than given one | -| oldValGe | mixed | Previous value must be greater or equal to given one | -| oldValLt | mixed | Previous value must be smaller than given one | -| oldValLe | mixed | Previous value must be smaller or equal to given one | -| | | | -| oldAck | bool | Acknowledged state of previous value is equal to given one | -| oldQ | number | Quality code state of previous value is equal to given one. You can use '\*' for matching to any code | -| | | | -| ts | string | New value time stamp must be equal to given one (state.ts == ts) | -| tsGt | string | New value time stamp must be not equal to the given one (state.ts != ts) | -| tsGe | string | New value time stamp must be greater than given value (state.ts > ts) | -| tsLt | string | New value time stamp must be greater or equal to given one (state.ts >= ts) | -| tsLe | string | New value time stamp must be smaller than given one (state.ts < ts) | -| | | | -| oldTs | string | Previous time stamp must be equal to given one (oldState.ts == ts) | -| oldTsGt | string | Previous time stamp must be not equal to the given one (oldState.ts != ts) | -| oldTsGe | string | Previous time stamp must be greater than given value (oldState.ts > ts) | -| oldTsLt | string | Previous time stamp must be greater or equal to given one (oldState.ts >= ts) | -| oldTsLe | string | Previous time stamp must be smaller than given one (oldState.ts < ts) | -| | | | -| lc | string | Last change time stamp must be equal to given one (state.lc == lc) | -| lcGt | string | Last change time stamp must be not equal to the given one (state.lc != lc) | -| lcGe | string | Last change time stamp must be greater than given value (state.lc > lc) | -| lcLt | string | Last change time stamp must be greater or equal to given one (state.lc >= lc) | -| lcLe | string | Last change time stamp must be smaller than given one (state.lc < lc) | -| | | | -| oldLc | string | Previous last change time stamp must be equal to given one (oldState.lc == lc) | -| oldLcGt | string | Previous last change time stamp must be not equal to the given one (oldState.lc != lc) | -| oldLcGe | string | Previous last change time stamp must be greater than given value (oldState.lc > lc) | -| oldLcLt | string | Previous last change time stamp must be greater or equal to given one (oldState.lc >= lc) | -| oldLcLe | string | Previous last change time stamp must be smaller than given one (oldState.lc < lc) | -| | | | -| channelId | string | Channel ID must be equal to given one | -| | RegExp | Channel ID matched to regular expression | -| | Array | Channel ID matched to a list of allowed channel IDs | -| | | | -| channelName | string | Channel name must be equal to given one | -| | RegExp | Channel name matched to regular expression | -| | Array | Channel name matched to a list of allowed channel names | -| | | | -| deviceId | string | Device ID must be equal to given one | -| | RegExp | Device ID matched to regular expression | -| | Array | Device ID matched to a list of allowed device IDs | -| | | | -| deviceName | string | Device name must be equal to given one | -| | RegExp | Device name matched to regular expression | -| | Array | Device name matched to a list of allowed device names | -| | | | -| enumId | string | State belongs to given enum | -| | RegExp | One enum ID of the state satisfies the given regular expression | -| | Array | One enum ID of the state is in the given list of enum IDs | -| | | | -| enumName | string | State belongs to given enum | -| | RegExp | One enum name of the state satisfies the given regular expression | -| | Array | One enum name of the state is in the given list of enum names | -| | | | -| from | string | New value is from defined adapter | -| | RegExp | New value is from an adapter that matches the regular expression | -| | Array | New value is from an adapter that appears in the given list of allowed adapters | -| | | | -| fromNe | string | New value is not from defined adapter | -| | RegExp | New value is not from an adapter that matches the regular expression | -| | Array | New value is not from an adapter that appears in the given list of forbidden adapters | -| | | | -| oldFrom | string | Old value is from defined adapter | -| | RegExp | Old value is from an adapter that matches the regular expression | -| | Array | Old value is from an adapter that appears in the given list of allowed adapters | -| | | | -| oldFromNe | string | Old value is not from defined adapter | -| | RegExp | Old value is not from an adapter that matches the regular expression | -| | Array | Old value is not from an adapter that appears in the given list of forbidden adapters | - -Examples: -Trigger on all states with ID `'*.STATE'` if they are acknowledged and have new value `true`. - -```js -{ - id: /\.STATE$/, - val: true, - ack: true, - logic: 'and' -} -``` - -**Note:** you can use RegExp directly: - -```js -on(/^system\.adapter\..*\.\d+\.memRss$/, function (obj) {}); - -// same as -on({ id: /^system\.adapter\..*\.\d+\.memRss$/, change: 'ne' }, function (obj) {}); -``` - -To simply connect two states with each other, write: - -```js -on('stateId1', 'stateId2'); -``` - -All changes of _stateId1_ will be written to _stateId2_. - -If the `value` parameter is set in combination with state id as the second parameter, on any change the state will filled with the `value`. - -```js -on('stateId1', 'stateId2', 'triggered'); -setState('stateId1', 'new value'); - -// stateId2 will be set to 'triggered'. -``` - -Function `on` returns handler back. This handler can be used by unsubscribing. - -_Notice:_ By default only states with quality 0x00 will be passed to callback function. If you want to get all events, add `{q: '*'}` to pattern structure. - -_Notice:_ Please note, that by default `change` is equal to `any`, except when only id as string is set (like `on('id', () => {});`). In last case change will be set to "ne". - -_Notice:_ If you want to also get state deletions/expires as trigger, you need to use change with `ne` or `any` AND q with `*` as filter! - -_Notice:_ from 4.3.2 it is possible to write a type of trigger as second parameter: `on('my.id.0', 'any', obj => log(obj.state.val));` - -### once - -Registers a one-time subscription which automatically unsubscribes after the first invocation. Same as [on](#on---subscribe-on-changes-or-updates-of-some-state), but just executed once. - -```js -once(pattern, callback); -``` - -### subscribe - same as **[on](#on---subscribe-on-changes-or-updates-of-some-state)** - -### unsubscribe - -```js -unsubscribe(id); -// or -unsubscribe(handler); -``` - -Remove all subscriptions for given object ID or for given handler. - -```js -// By handler -let mySubscription = on({ id: 'javascript.0.myState', change: 'any' }, data => { - // unsubscribe after first trigger - if (unsubscribe(mySubscription)) { - log('Subscription deleted'); - } -}); - -// by Object ID -on({ id: 'javascript.0.myState1', change: 'ne' }, data => { - log('Some event'); -}); - -on({ id: 'javascript.0.myState1', change: 'any' }, data => { - // unsubscribe - if (unsubscribe('javascript.0.myState1')) { - log('All subscriptions deleted'); - } -}); -``` - -### getSubscriptions - -Get the list of subscriptions. - -Example of a result: - -```json -{ - "megad.0.dataPointName": [ - { - "name" : "script.js.NameOfScript", - "pattern" : { - "id" : "megad.0.dataPointName", - "change" : "ne" - } - } - ] -} -``` - -### getFileSubscriptions - -Get the list of file subscriptions. - -Example of a result: - -```json -{ - "vis.0$%$main/*": [ - { - "name" : "script.js.NameOfScript", - "id" : "vis.0", - "fileNamePattern": "main/*" - } - ] -} -``` - -### schedule - -```js -schedule(pattern, callback); -``` - -Time scheduler with astro-function. - -#### Time schedule - -Pattern can be a string with [Cron-Syntax](http://en.wikipedia.org/wiki/Cron), which consists of 5 (without seconds) or 6 (with seconds) digits: - -``` -* * * * * * -│ │ │ │ │ │ -│ │ │ │ │ │ -│ │ │ │ │ └───── day of week (0 - 6) (0 to 6 are Sunday to Saturday, or use names; 7 is Sunday, the same as 0) -│ │ │ │ └────────── month (1 - 12) -│ │ │ └─────────────── day of month (1 - 31) -│ │ └──────────────────── hour (0 - 23) -│ └───────────────────────── min (0 - 59) -└───────────────────────────── [optional] sec (0 - 59) -``` - -```js -// Example with 5 digits: -schedule('*/2 * * * *', () => { - log('Will be triggered every 2 minutes!'); -}); - -// Example with 6 digits: -schedule('*/3 * * * * *', () => { - log('Will be triggered every 3 seconds!'); -}); -``` - -The pattern can also be an object, it is used especially if seconds are required: - -the object could have the following properties: - -- `second` -- `minute` -- `hour` -- `date` -- `month` -- `year` -- `dayOfWeek` - -```js -schedule({ second: [20, 25] }, () => { - log('Will be triggered at xx:xx:20 and xx:xx:25 of every minute!'); -}); - -schedule({ hour: 12, minute: 30 }, () => { - log('Will be triggered at 12:30!'); -}); -``` - -Pattern can be a JavaScript Date object (some specific time point) - in this case only it will be triggered only one time. - -If start or end times for a schedule are needed, this could also be implemented with usage of an object. In this scenario the object has the properties: - -- `start` -- `end` -- `rule` - -start and end defines a Date object a DateString or a number of milliseconds since 01 January 1970 00:00:00 UTC. -Rule is a schedule string with [Cron-Syntax](http://en.wikipedia.org/wiki/Cron) or an object: - -```js -let startTime = new Date(Date.now() + 5000); -let endTime = new Date(startTime.getTime() + 5000); -schedule({ start: startTime, end: endTime, rule: '*/1 * * * * *' }, () => { - log('It will run after 5 seconds and stop after 10 seconds'); -}); -``` - -The rule itself could be also an object: - -```js -let today = new Date(); -let startTime = new Date(today.getFullYear(), today.getMonth(), today.getDate() + 1); -let endTime = new Date(today.getFullYear(), today.getMonth(), today.getDate() + 7); -let ruleData = { hour: 12, minute: 30 }; -schedule({ start: startTime, end: endTime, rule: ruleData }, () => { - log('Will be triggered at 12:30, starting tomorow, ending in 7 days'); -}); -``` - -#### Astro-function - -Astro-function can be used via "astro" attribute: - -```js -schedule({ astro: 'sunrise' }, () => { - log('Sunrise!'); -}); - -schedule({ astro: 'sunset', shift: 10 }, () => { - log('10 minutes after sunset!'); -}); -``` - -The attribute "shift" is the offset in minutes. It can be negative, too, to define time before astro event. - -The following values can be used as attribute in astro-function: - -- `"sunrise"`: sunrise (top edge of the sun appears on the horizon) -- `"sunriseEnd"`: sunrise ends (bottom edge of the sun touches the horizon) -- `"goldenHourEnd"`: morning golden hour (soft light, the best time for photography) ends -- `"solarNoon"`: solar noon (sun is in the highest position) -- `"goldenHour"`: evening golden hour starts -- `"sunsetStart"`: sunset starts (bottom edge of the sun touches the horizon) -- `"sunset"`: sunset (sun disappears below the horizon, evening civil twilight starts) -- `"dusk"`: dusk (evening nautical twilight starts) -- `"nauticalDusk"`: nautical dusk (evening astronomical twilight starts) -- `"night"`: night starts (dark enough for astronomical observations) -- `"nightEnd"`: night ends (morning astronomical twilight starts) -- `"nauticalDawn"`: nautical dawn (morning nautical twilight starts) -- `"dawn"`: dawn (morning nautical twilight ends, morning civil twilight starts) -- `"nadir"`: nadir (the darkest moment of the night, sun is in the lowest position) - -**Note:** to use "astro"-function the "latitude" and "longitude" must be defined in JavaScript adapter settings. - -**Note:** in some places sometimes it could be so that no night/nightEnd exists. Please read [here](https://github.com/mourner/suncalc/issues/70) about it. - -**Note:** you can use "on" function for schedule with small modification: - -```js -on({ time: '*/2 * * * *' }, () => { - log(new Date().toString() + ' - Will be triggered every 2 minutes!'); -}); - -on({ time: { hour: 12, minute: 30 } }, () => { - log(new Date().toString() + ' - Will be triggered at 12:30!'); -}); - -on({ astro: 'sunset', shift: 10 }, () => { - log(new Date().toString() + ' - 10 minutes after sunset!'); -}); -``` - -## scheduleById - -```js -scheduleById(id, callback); -scheduleById(id, ack, callback); -``` - -Allows to create a schedule based on a state value. If the state value changes, the old schedule will be deleted and a new schedule is created automatically. - -Supported formats: - -- `[h]h:[m]m:ss` (e.g. `12:42:15`, `15:3:12`, `3:10:25`) -- `[h]h:[m]m` (e.g. `13:37`, `9:40`) - -```js -scheduleById('0_userdata.0.configurableTimeFormat', () => { - log('Executed!'); -}); -``` - -Example: Create state and register schedule on changes: - -```js -createState( - '0_userdata.0.myTime', - '00:00:00', // default value - { - type: 'string', - read: true, - write: true, - }, - () => { - scheduleById('0_userdata.0.myTime', () => { - log('Executed!'); - }); - }, -); -``` - -### getSchedules - -```js -const list = getSchedules(true); -``` - -Returns the list of all CRON jobs and schedules (except astro). -Argument must be `true` if you want to get the list for **every running script**. Otherwise, only schedules in the current script will be returned. - -```js -const list = getSchedules(true); -list.forEach(schedule => log(JSON.stringify(schedule))); - -// clear all schedules in all scripts! -list.forEach(schedule => clearSchedule(schedule)); -``` - -Example output: - -``` -2020-11-01 20:15:19.929 - {"type":"cron","pattern":"0 * * * *","scriptName":"script.js.Heizung","id":"cron_1604258108384_74924"} -2020-11-01 20:15:19.931 - {"type":"schedule","schedule":"{"period":{}}","scriptName":"script.js.Heizung","id":"schedule_19576"} -``` - -### clearSchedule - -If **no** "astro" function is used, you can cancel the schedule later. To allow this, the schedule object must be saved: - -```js -let sch = schedule('*/2 * * * *', () => { - /* ... */ -}); - -// later: -clearSchedule(sch); -``` - -### getAttr - -```js -getAttr({ attr1: { attr2: 5 } }, 'attr1.attr2'); -``` - -Returns an attribute of the object. Path to attribute can be nested, like in the example. - -If the first attribute is string, the function will try to parse the string as JSON string. - -### getAstroDate - -```js -getAstroDate(pattern, date, offsetMinutes); -``` - -Returns a javascript Date object for the specified astro-name (e.g. `"sunrise"` or `"sunriseEnd"`). For valid values, see the list of allowed values in the [Astro](#astro--function) section in the _schedule_ function. - -The returned Date object is calculated for the passed _date_. If no date is provided, the current day is used. - -```js -let sunriseEnd = getAstroDate('sunriseEnd'); -log(`Sunrise ends today at ${sunriseEnd.toLocaleTimeString()}`); - -let today = new Date(); -let tomorrow = new Date(today.getFullYear(), today.getMonth(), today.getDate() + 1); -let tomorrowNight = getAstroDate('night', tomorrow); -``` - -**Note: Depending on your geographical location, there can be cases where e.g. 'night'/'nightEnd' do not exist on certain time points (e.g., locations north in May/June each year!** - -You can use webpages like [suncalc.net](http://suncalc.net) to check if the time points are correct. - -### isAstroDay - -```js -isAstroDay(); -``` - -Returns `true` if the current time is between the astro sunrise and sunset. - -### compareTime - -```js -compareTime(startTime, endTime, operation, timeToCompare); -``` - -Compare given time with limits. - -If `timeToCompare` is not given, so the actual time will be used. - -The following operations are possible: - -- `">"` - if given time is greater than `startTime` -- `">="` - if given time is greater or equal to `startTime` -- `"<"` - if given time is less than `startTime` -- `"<="` - if given time is less or equal to `startTime` -- `"=="` - if given time is equal to `startTime` -- `"<>"` - if given time is not equal to `startTime` -- `"between"` - if given time is between `startTime` and `endTime` -- `"not between"` - if given time is not between `startTime` and `endTime` - -Time can be Date object or Date with time or just time. - -You can use astro-names for the time definition. All 3 parameters can be set as astro time. -Following values are possible: `sunrise`, `sunset`, `sunriseEnd`, `sunsetStart`, `dawn`, `dusk`, `nauticalDawn`, `nauticalDusk`, `nightEnd`, `night`, `goldenHourEnd`, `goldenHour`. -See [Astro](#astro--function) for detail. - -```js -log(compareTime('sunsetStart', 'sunsetEnd', 'between') ? 'Now is sunrise' : 'Now is no sunrise'); -``` - -It is possible to define the time with offset too: - -```js -log( - compareTime({ astro: 'sunsetStart', offset: 30 }, { astro: 'sunrise', offset: -30 }, '>') - ? 'Now is at least 30 minutes after sunset' - : 'No idea', -); -``` - -Structure of an astro object. - -```js -{ - astro: 'sunsetStart',// mandatory, can be written as string and not as object if offset and date are default - offset: 30, // optional - date: new Date() // optional -} -``` - -### setState - -```js -setState(id, state, ack, callback); -``` - -_Note_: The following commands are identical - -```js -setState('myState', 1, false); -setState('myState', { val: 1, ack: false }); -setState('myState', 1); -``` - -Please refer to https://github.com/ioBroker/ioBroker/wiki/Adapter-Development-Documentation#commands-and-statuses for usage of `ack`. -Short: - -- `ack = false`: Script wants to send a command to be executed by the target device/adapter -- `ack = true`: Command was successfully executed, and state is updated as a positive result - -### setStateAsync - -```js -await setStateAsync(id, state, ack); -``` - -Same as setState, but with `promise`. - -### setStateDelayed - -```js -setStateDelayed(id, state, isAck, delay, clearRunning, callback); -``` - -Same as setState but with delay in milliseconds. You can clear all running delays for this ID (by default). E.g. - -```js -// Switch ON the light in the kitchen in one second -setStateDelayed('Kitchen.Light.Lamp', true, 1000); - -// Switch OFF the light in the kitchen in 5 seconds and let first timeout run. -setStateDelayed('Kitchen.Light.Lamp', false, 5000, false, () => { - log('Lamp is OFF'); -}); -``` - -This function returns the handler of the timer, and this timer can be individually stopped by clearStateDelayed - -### setStateChanged - -```js -await setStateChanged(id, state, ack); -``` - -Same as setState, but set value only if the value is really changed. - -### setStateChangedAsync - -```js -await setStateChangedAsync(id, state, ack); -``` - -Same as setStateChanged, but with `promise`. - -### clearStateDelayed - -```js -clearStateDelayed(id); -``` - -Clears all delayed tasks for specified state ID or some specific delayed task. - -```js -setStateDelayed('Kitchen.Light.Lamp', false, 10000); // Switch OFF the light in the kitchen in ten second -let timer = setStateDelayed('Kitchen.Light.Lamp', true, 5000, false); // Switch ON the light in the kitchen in five second -clearStateDelayed('Kitchen.Light.Lamp', timer); // Nothing will be switched on -clearStateDelayed('Kitchen.Light.Lamp'); // Clear all running delayed tasks for this ID -``` - -### getStateDelayed - -```js -getStateDelayed(id); -``` - -This is a synchronous call, and you will get the list of all running timers (setStateDelayed) for this id. -You can call this function without id and get timers for all IDs. -In case you call this function for some specific object ID, you will get the following answer: - -```js -getStateDelayed('hm-rpc.0.LQE91119.1.STATE'); - -// returns an array like -[ - { timerId: 1, left: 1123, delay: 5000, val: true, ack: false }, - { timerId: 2, left: 12555, delay: 15000, val: false, ack: false }, -]; -``` - -If you ask for all IDs, the answer will look like: - -```js -getStateDelayed(); - -// returns an object like -{ - 'hm-rpc.0.LQE91119.1.STATE': [ - { timerId: 1, left: 1123, delay: 5000, val: true, ack: false }, - { timerId: 2, left: 12555, delay: 15000, val: false, ack: false }, - ], - 'hm-rpc.0.LQE91119.2.LEVEL': [ - { timerId: 3, left: 5679, delay: 10000, val: 100, ack: false } - ] -} -``` - -- `left` is the time left in milliseconds -- `delay` is the initial delay value in milliseconds - -You can ask by timerId directly. In this case, the answer will be: - -```js -getStateDelayed(3); - -// returns an object like -{ id: 'hm-rpc.0.LQE91119.2.LEVEL', left: 5679, delay: 10000, val: 100, ack: false } -``` - -### getState - -```js -getState(id); -``` - -Returns state with the given id in the following form: - -```js -{ - val: value, - ack: true/false, - ts: timestamp, - lc: lastchanged, - from: origin -} -``` - -If state does not exist, a warning will be printed in the logs and the object `{ val: null, notExist: true }` will be returned. -To suppress the warning check if the state exists before calling getState (see [existsState](#existsState)). - -### getStateAsync - -```js -const stateObject = await getStateAsync(id); -``` - -Same as getState, but with `promise`. - -### existsState - -```js -existsState(id, (err, isExists) => {}); -``` - -If option "Do not subscribe all states on start" is deactivated, you can use simpler call: - -```js -existsState(id); -``` - -the function returns in this case true or false. - -Check if a state exists. - -### getObject - -```js -getObject(id, enumName); -``` - -Get description of object id as stored in a system. -You can specify the enumeration name. If this is defined, two additional attributes will be added to result: enumIds and enumNames. -These arrays have all enumerations, where ID is a member of. E.g: - -```js -getObject('adapter.N.objectName', 'rooms'); -``` - -gives back in enumIds all rooms, where the requested object is a member. You can define "true" as enumName to get back _all_ enumerations. - -### setObject - -```js -setObject(id, obj, callback); -``` - -Write an object into DB. This command can be disabled in adapter's settings. Use this function carefully, while the global settings can be damaged. - -You should use it to **modify** an existing object you read beforehand, e.g.: - -```js -const obj = getObject('adapter.N.objectName'); -obj.native.settings = 1; -setObject('adapter.N.objectName', obj, err => { - if (err) log('Cannot write object: ' + err); -}); -``` - -### existsObject - -```js -existsObject(id, function (err, isExists) {}); -``` - -If the option "Do not subscribe all states on start" is deactivated, you can use simpler call: - -```js -existsObject(id); -``` - -the function returns in this case true or false. - -Check if an object exists. - -### extendObject - -```js -extendObject(id, obj, callback); -``` - -It is almost the same as `setObject`, but first it reads the object and tries to merge all settings together. - -Use it like this: - -```js -// Stop instance -extendObject('system.adapter.sayit.0', { common: { enabled: false } }); -``` - -### deleteObject - -```js -deleteObject(id, isRecursive, callback); -``` - -Delete an object from DB by ID. If the object has type `state`, the state value will be deleted too. - -Additional parameter `isRecursive` could be provided, so all children of given ID will be deleted. Very dangerous! - -Use it like this: - -```js -// Delete state -deleteObject('javascript.0.createdState'); -``` - -_Notice: `isRecursive` option is available only with js-controller >= 2.2.x_ - -### getIdByName - -```js -getIdByName(name, alwaysArray); -``` - -Returns id of the object with given name. -If there is more than one object with this name, the result will be an array. -If `alwaysArray` flag is set, the result will always be an array if some ID found. - -### getEnums - -```js -getEnums(enumName); -``` - -Get the list of existing enumerations with members, like: - -```js -getEnums('rooms'); - -// returns: -[ - { - id: 'enum.rooms.LivingRoom', - members: ['hm-rpc.0.JEQ0024123.1', 'hm-rpc.0.BidCoS-RF.4'], - name: 'Living room', - }, - { - id: 'enum.rooms.Bath', - members: ['hm-rpc.0.JEQ0024124.1', 'hm-rpc.0.BidCoS-RF.5'], - name: 'Bath', - }, -]; -``` - -### createState - -```js -createState(name, initialValue, forceCreation, common, native, callback); -``` - -Create state and object in `javascript.0` space if it does not exist, e.g. `javascript.0.mystate`. - -!! Prefer to create own data points with the full ID `0_userdata.0.mystate` !!! - -#### Parameters: - -- `name`: name of the state without namespace, e.g. `mystate` -- `initialValue`: variable can be initialized after created. Value "undefined" means do not initialize value. -- `forceCreation`: create/overwrite state independent of if state yet exists or not. -- `common`: common description of object see description [here](https://github.com/ioBroker/ioBroker/blob/master/doc/SCHEMA.md#state) -- `native`: native description of an object. Any specific information. -- `callback`: called after state is created and initialized. - -If you set in `common` the flag `alias` to `true`, then alias will be created with the same name (but in `alias.0` namespace) as the state. -Alias is created only if it does not exist yet. - -The following settings for aliases are valid too: - -```js -common => { - alias: { - id: 'alias.0.myOtherState', // will be created automatically if not already exists - write: 'val * 1000', // convert function for write to created state - read: 'val / 1000' // convert function to read from created state - } -} -``` - -or - -```js -common => { - alias: { - id: 'alias.0.myOtherState', // will be created automatically if not already exists - } -} -``` - -It is possible short type of createState: - -- `createState('myDatapoint')` - simply create datapoint if it does not exist -- `createState('myDatapoint', 1)` - create datapoint if it does not exist and initialize it with value 1 -- `createState('myDatapoint', { type: 'string', role: 'json', read: true, write: false }, () => { log('created'); });` - with common definitions like type, read, write and role -- `createState('myDatapoint', { name: 'My own datapoint', unit: '°C' }, () => { log('created'); });` -- `createState('myDatapoint', 1, { name: 'My own datapoint', unit: '°C' })` - create datapoint if it does not exist with specific name and units - -### createStateAsync - -```js -await createStateAsync(name, initialValue, forceCreation, common, native); -``` - -Same as `createState`, but the promise will be returned. - -### deleteState - -```js -deleteState(name, callback); -``` - -Delete state and object in `javascript.0` space, e.g. `javascript.0.mystate`. States from other adapters cannot be deleted. - -```js -deleteState('myDatapoint'); -``` - -simply delete datapoint if exists. - -### deleteStateAsync - -```js -await deleteStateAsync(name); -``` - -Same as `deleteState`, but the promise will be returned. - -### createAlias - -```js -createAlias(name, alias, forceCreation, common, native, callback); -``` - -Create alias in `alias.0` space if it does not exist, e.g. `javascript.0.myalias` and reference to a state or read/write states. -The common definition is taken from the read alias id object, but a provided common takes precedence. - -#### Parameters: - -- `name`: id of the new alias state with (possible without an alias namespace), e.g. `test.mystate` (namespace `alias.0.` will be added = `alias.0.test.mystate`) -- `alias`: can be either an existing state id as string or an object with full alias definition including read/write ids and read/write functions. Note: Alias definitions can not be set as part of the common parameter! -- `forceCreation`: create/overwrite alias independent of if state yet exists or not. -- `common`: common description of alias object see description [here](https://github.com/ioBroker/ioBroker/blob/master/doc/SCHEMA.md#state). Values provided here will take precedence over the common definition of the read alias id object. Not: Alias definitions can not be set as part of this common parameter, see alias parameter! -- `native`: native description of an object. Any specific information. -- `callback`: called after state is created and initialized. - -It is possible a short type of createAlias: - -- `createAlias('myAlias', 'myDatapoint')` - simply create alias.0.myAlias that references to `javascript.X.myDatapoint` if it does not exist -- `createAlias('myAlias', { id: { read: 'myReadDatapoint', write: 'myWriteDatapoint' }})` - creates alias and reference to different read/write states - -For other details, see createState, it is similar. - -### createAliasAsync - -```js -await createAliasAsync(name, alias, forceCreation, common, native); -``` - -Same as `createAlias`, but the promise will be returned. - -### sendTo - -```js -sendTo(adapter, command, message, callback); -sendTo(adapter, command, message, options, callback); -``` - -Send a message to a specific or all adapter instances. When using the adapter name, the message is sent to all instances. - -To get specific information about messages, you must read the documentation for a particular adapter. - -Example (with custom timeout): - -```js -sendTo('telegram', { user: 'UserName', text: 'Test message' }, { timeout: 2000 }); -``` - -Some adapters also support responses to the sent messages. (e.g. history, SQL, telegram) -The response is only returned to the callback if the message is sent to a specific instance! - -Example (with callback): - -```js -sendTo('telegram.0', { user: 'UserName', text: 'Test message' }, res => { - log(`Sent to ${res} users`); -}); -``` - -_Default timeout is 20000 milliseconds (if a callback function has been defined)_ - -```js -sendTo('telegram.0', { user: 'UserName', text: 'Test message' }, { timeout: 2000 }, res => { - log(`Sent to ${res} users`); -}); -``` - -### sendToAsync - -```js -await sendToAsync(adapter, command, message); -await sendToAsync(adapter, command, message, options); -``` - -Same as sendTo, but with `promise`. - -Example: - -```js -const res = await sendToAsync('sql.0', 'getEnabledDPs', {}); -log(JSON.stringify(res)); -``` - -### sendToHost - -```js -sendToHost(hostName, command, message, callback); -``` - -Send a message to controller instance. - -The following commands are supported: - -- `"cmdExec"` -- `"getRepository"` -- `"getInstalled"` -- `"getVersion"` -- `"getDiagData"` -- `"getLocationOnDisk"` -- `"getDevList"` -- `"getLogs"` -- `"getHostInfo"` - -It is rather specific commands and are not required often. - -Example: - -```js -sendToHost('myComputer', 'cmdExec', { data: 'ls /' }, res => { - log('List of files: ' + res.data); -}); -``` - -**Notice:** you must enable _Enable command "setObject"_ option to call it. - -### sendToHostAsync - -```js -await sendToHostAsync(hostName, command, message); -``` - -Same as sendToHost, but with `promise`. - -### setInterval - -```js -setInterval(callback, ms, arg1, arg2, arg3, arg4); -``` - -Same as javascript `setInterval`. - -### clearInterval - -```js -clearInterval(id); -``` - -Same as javascript `clearInterval`. - -### setTimeout - -```js -setTimeout(callback, ms, arg1, arg2, arg3, arg4); -``` - -Same as javascript `setTimeout`. - -### clearTimeout - -```js -clearTimeout(id); -``` - -Same as javascript `clearTimeout`. - -### setImmediate - -```js -setImmediate(callback, arg1, arg2, arg3, arg4); -``` - -Same as javascript `setImmediate` and almost the same as `setTimeout(callback, 0, arg1, arg2, arg3, arg4)` but with higher priority. - -### formatDate - -```js -formatDate(millisecondsOrDate, format); -``` - -#### Parameters: - -- `millisecondsOrDate`: number of milliseconds from state.ts or state.lc (Number milliseconds from 1970.01.01 00:00:00) or javascript _new Date()_ object or number of milliseconds from _(new Date().getTime())_ -- `format`: Can be `null`, so the system time format will be used, otherwise - -* YYYY, JJJJ, ГГГГ - full year, e.g 2015 -* YY, JJ, ГГ - short year, e.g 15 -* MM, ММ(cyrillic) - full month, e.g., 01 -* M, М(cyrillic) - short month, e.g., 1 -* DD, TT, ДД - full day, e.g., 02 -* D, T, Д - short day, e.g., 2 -* hh, SS, чч - full hours, e.g., 03 -* h, S, ч - short hours, e.g., 3 -* mm, мм(cyrillic) - full minutes, e.g., 04 -* m, м(cyrillic) - short minutes, e.g., 4 -* ss, сс(cyrillic) - full seconds, e.g., 05 -* s, с(cyrillic) - short seconds, e.g., 5 -* sss, ссс(cyrillic) - milliseconds -* WW, НН(cyrillic) - full week day as text -* W, Н(cyrillic) - short week day as text -* OO, ОО(cyrillic) - full month as text -* OOO, ООО(cyrillic) - full month as text as genitiv -* O, О(cyrillic) - short month as text - -#### Example - -```js -formatDate(new Date(), 'YYYY-MM-DD'); // => Date "2015-02-24" -formatDate(new Date(), 'hh:mm'); // => Hours and minutes "17:41" -formatDate(state.ts); // => "24.02.2015" -formatDate(state.ts, 'JJJJ.MM.TT SS:mm:ss.sss'); // => "2015.02.15 17:41:98.123" -formatDate(new Date(), 'WW'); // => Day of week "Tuesday" -formatDate(new Date(), 'W'); // => Day of week "Tu" -``` - -### formatTimeDiff - -```js -formatTimeDiff(milliseconds, format); -``` - -#### Parameters: - -- `milliseconds`: difference in milliseconds\* -- `format`: Can be `null`, so the `hh:mm:ss` format will be used, otherwise - -* DD, TT, ДД - full day, e.g., 02 -* D, T, Д - short day, e.g., 2 -* hh, SS, чч - full hours, e.g., 03 -* h, S, ч - short hours, e.g., 3 -* mm, мм(cyrillic) - full minutes, e.g., 04 -* m, м(cyrillic) - short minutes, e.g., 4 -* ss, сс(cyrillic) - full seconds, e.g., 05 -* s, с(cyrillic) - short seconds, e.g., 5 - -#### Example - -```js -formatTimeDiff(60000, 'mm:ss'); // => "01:00" - -const diff = 172800000 + 10800000 + 540000 + 15000; // 2 days, 3 hours, 9 minutes + 15 secoonds -formatTimeDiff(diff); // "51:09:15" -formatTimeDiff(diff, 'DD hh:mm'); // "02 03:09" -formatTimeDiff(diff, 'D hh:mm'); // "2 03:09" -formatTimeDiff(diff, 'hh:mm:ss'); // "51:09:15" -formatTimeDiff(diff, 'h:m:s'); // "51:9:15" -formatTimeDiff(diff, 'hh:mm'); // "51:09" -formatTimeDiff(diff, 'mm:ss'); // "3069:15" -formatTimeDiff(diff, 'hh'); // "51" -formatTimeDiff(diff, 'mm'); // "3069" -``` - -### getDateObject - -```js -getDateObject(stringOrNumber); -``` - -Converts string or number to a Date object. -If only hours are given, it will add current date to it and will try to convert. - -```js -getDateObject('20:00'); // 2024-05-18T18:00:00.000Z -getDateObject('2024-01-01'); // 2024-01-01T00:00:00.000Z -``` - -### formatValue - -```js -formatValue(value, decimals, format); -``` - -Formats any value (strings too) to number. Replaces point with comma if configured in system. -Decimals specify digits after comma. The default value is 2. -Format is optional: - -- '.,': 1234.567 => 1.234,56 -- ',.': 1234.567 => 1,234.56 -- ' .': 1234.567 => 1 234.56 - -### adapterSubscribe - -```js -adapterSubscribe(id); -``` - -It sends to an adapter the message "subscribe" to inform adapter. If adapter has the common flag "subscribable" in case of function "subscribe" this function will be called automatically. - -### adapterUnsubscribe - -```js -adapterUnsubscribe(id); -``` - -It sends to an adapter the message `unsubscribe` to inform adapter to not poll the values. - -### $ - Selector - -```js -$(selector).on(function (obj) {}); -$(selector).toArray(); // Requires version >= 8.2.0 -$(selector).each(function (id, i) {}); -$(selector).setState(value, ack); -$(selector).getState(); -``` - -Format of selector: - -```js -'name[commonAttr=something1](enumName=something2){nativeName=something3}[id=idfilter][state.id=idfilter]'; -``` - -name can be: state, channel, device or schedule -`idfilter` can have wildcards '\*' - -Prefixes **_(not implemented - should be discussed)_** : - -- \# - take by name and not by id -- . - filter by role -- § - filter by room - -**_Example_**: - -- `$('state[id=*.STATE]')` or `$('state[state.id=*.STATE]')` or `$('*.STATE')` - select all states where id ends with ".STATE". -- `$('state[id='hm-rpc.0.*]')` or `$('hm-rpc.0.*')` - returns all states of adapter instance hm-rpc.0 -- `$('channel(rooms=Living room)')` - all states in room "Living room" -- `$('channel{TYPE=BLIND}[state.id=*.LEVEL]')` - Get all shutters of Homematic -- `$('channel[role=switch](rooms=Living room)[state.id=*.STATE]').setState(false)` - Switch all states with .STATE of channels with role "switch" in "Living room" to false -- `$('channel[state.id=*.STATE](functions=Windows)').each(function (id, i) {log(id);});` - print all states of enum "windows" in log -- `$('schedule[id=*65]').each(function (id, i) {log(id);});` - print all schedules with 65 at the end -- `$('.switch §"Living room")` - Take states with all switches in 'Living room' **_(not implemented - should be discussed)_** -- `$('channel .switch §"Living room")` - Take states with all switches in 'Living room' **_(not implemented - should be discussed)_** - -**_Explanation_** -Lets take a look at: - -```js -$('channel[role=switch][state.id=*.STATE](rooms=Wohnzimmer)').on(obj => { - log('New state ' + obj.id + ' = ' + obj.state.val); -}); -``` - -This code searches in channels. -Find all channels with `common.role="switch"` and belongs to `enum.rooms.Wohnzimmer`. -Take all their states, where id ends with `".STATE"` and make subscription on all these states. -If some of these states change, the callback will be called like for "on" function. - -Following functions are possible, setState, getState (only from first), on, each, toArray - -```js -// Switch on all switches in "Wohnzimmer" -$('channel[role=switch][state.id=*.STATE](rooms=Wohnzimmer)').setState(true); -``` - -You can interrupt the "each" loop by returning the false value, like: - -```js -// print two first IDs of on all switches in "Wohnzimmer" -$('channel[role=switch][state.id=*.STATE](rooms=Wohnzimmer)').each((id, i) => { - log(id); - if (i == 1) { - return false; - } -}); -``` - -Or you can get a usual array of IDs and process it your own way: - -```js -// get some state and filter only which has an `true` value -const enabled = $('channel[role=switch][state.id=*.STATE](rooms=Wohnzimmer)') - .toArray() - .filter(id => getState(id)?.val === true); -``` - -### readFile - -```js -readFile(adapter, fileName, (error, bytes) => {}); -``` - -The result will be given in callback. -Read a file from DB from folder `javascript.0`. - -Argument _adapter_ can be omitted. - -```js -// read vis views -readFile('vis.0', '/main/vis-views.json', (error, data) => { - log(data.substring(0, 50)); -}); - -// The same as -//readFile('/../vis.0/main/vis-views.json', (error, data) => { -// log(data.substring(0, 50)); -//}); -``` - -By default, working directory/adapter is `javascript.0`. - -### writeFile - -```js -writeFile(adapter, fileName, bytes, error => {}); -``` - -The optional error code will be given in callback. Argument _adapter_ can be omitted. -`fileName` is the name of file in DB. If `adapter` is not set, all files are stored in the folder `javascript.0`. - -The file that looks like `'/subfolder/file.txt'` will be stored under `"/javascript/subfolder/file.txt"` and can be accessed over web server with `"http://ip:8082/javascript/subfolder/file.txt"` - -```js -// store screenshot in DB -const fs = require('node:fs'); -let data = fs.readFileSync('/tmp/screenshot.png'); -writeFile(null, '/screenshots/1.png', data, error => { - log('file written'); -}); - -// The same as -//writeFile('/screenshots/1.png', data, function (error) { -// log('file written'); -//}); -``` - -```js -// store file in '/vis.0' in DB -const fs = require('node:fs'); -let data = fs.readFileSync('/tmp/screenshot.png'); -writeFile('vis.0', '/screenshots/1.png', data, error => { - log('file written'); -}); -``` - -### delFile - -```js -delFile(adapter, fileName, error => {}); -``` - -Delete file or directory. fileName is the name of file or directory in DB. - -The alternative name of this method is `unlink`. - -### renameFile - -```js -renameFile(adapter, oldName, newName, error => {}); -``` - -Rename file or directory. oldName is the name of file or directory in DB and is renamed to newName. - -The alternative name of this method is `rename`. - -### onFile - -```js -onFile(id, fileName, withFile, (id, fileName, size, fileData, mimeType) => {}); -// or -onFile(id, fileName, (id, fileName, size) => {}); -``` - -Subscribe to file changes: - -- `id` is ID of an object of type `meta`, like `vis.0` -- `fileName` is file name or pattern, like `main/*` or `main/vis-view.json` -- `withFile` if the content of file should be delivered in callback or not. the delivery of file content costs memory and time, so if you want to be just informed about changes, set `withFile`to false. - -Arguments in callback: - -- `id` - ID of `meta` object; -- `fileName` - file name (not pattern); -- `size` - new file size; -- `fileData` - file content of type `Buffer` if file is binary (detected by extension) or `string`. Delivered only if `withFile`; -- `mimeType` - mime type of file, like `image/jpeg`. Delivered only if `withFile`; - -**Important**: this functionality is only available with js-controller@4.1.x or newer. - -### offFile - -```js -offFile(id, fileName); -// or -onFile(id, fileName); -``` - -Unsubscribe from file changes: - -- `id` is ID of an object of type `meta`, like `vis.0` -- `fileName` is file name or pattern, like `main/*` or `main/vis-view.json` - -**Important**: this functionality is only available with js-controller@4.1.x or newer. - -### onStop - -```js -onStop(() => { - /* do something when script is stopped */ -}, timeout); -``` - -Install callback, that will be called if a script stopped. Used, e.g., to stop communication or to close connections. - -```js -// establish connection -const conn = require('net'); -// ... - -// close connection if script stopped -onStop(callback => { - if (conn) { - // close connection - conn.destroy(); - } - callback(); -}, 2000 /*ms*/); -``` - -`timeout` is 1000ms by default. - -### getHistory - -```js -getHistory(instance, options, (error, result, options, instance) => {}); -``` - -Read history from specified instance. If no instance is specified, the system default history instance will be taken. - -```js -// Read history of 'system.adapter.admin.0.memRss' from sql driver -const end = new Date().getTime(); -getHistory( - 'sql.0', - { - id: 'system.adapter.admin.0.memRss', - start: end - 3600000, - end: end, - aggregate: 'm4', - timeout: 2000, - }, - (err, result) => { - if (err) console.error(err); - if (result) { - for (let i = 0; i < result.length; i++) { - log(result[i].id + ' ' + new Date(result[i].ts).toISOString()); - } - } - }, -); -``` - -Possible options you can find [here](https://github.com/ioBroker/ioBroker.history#access-values-from-javascript-adapter). - -Additionally, to these parameters you must specify "id" and you may specify timeout (default: 20000ms). - -One more example: - -```js -// Get last 50 entries from default history instance with no aggregation: -getHistory( - { - id: 'system.adapter.admin.0.alive', - aggregate: 'none', - count: 50, - }, - (err, result) => { - if (err) console.error(err); - if (result) { - for (let i = 0; i < result.length; i++) { - log(result[i].id + ' ' + new Date(result[i].ts).toISOString()); - } - } - }, -); -``` - -**Note: ** of course, history must be first enabled for selected ID in admin. - -### runScript - -```js -runScript('scriptName', () => { - // Callback is optional - log('Srcipt started, but not yet executed'); -}); -``` - -Starts or restarts other scripts (and itself too) by name. - -```js -// restart script -runScript('groupName.scriptName1'); -``` - -### runScriptAsync - -Same as runScript, but with `promise`. - -```js -runScriptAsync('scriptName').then(() => log('Script started, but not yet executed')); - -// or - -await runScriptAsync('scriptName'); -log(`Script was restarted`); -``` - -### startScript - -```js -startScript('scriptName', ignoreIfStarted, callback); -``` - -It starts the script. If `ignoreIfStarted` set to true, nothing will be done if a script yet running, otherwise the script will be restarted. - -```js -startScript('scriptName', true); // start script if not started -``` - -### startScriptAsync - -Same as runScript, but with `promise`. - -```js -startScriptAsync('scriptName', ignoreIfStarted).then(started => - log(`Script was ${started ? 'started' : 'already started'}`), -); - -// or - -const started = await startScriptAsync('scriptName', ignoreIfStarted); -log(`Script was ${started ? 'started' : 'already started'}`); -``` - -It starts the script. If `ignoreIfStarted` set to true, nothing will be done if a script yet running, otherwise the script will be restarted. - -```js -startScript('scriptName', true); // start script if not started -``` - -### stopScript - -```js -stopScript('scriptName', callback); -``` - -If stopScript is called without arguments, it will stop itself: - -```js -stopScript(); -``` - -### stopScriptAsync - -Same as stopScript, but with `promise`: - -```js -stopScriptAsync('scriptName').then(stopped => log(`Script was ${stopped ? 'stopped' : 'already stopped'}`)); - -//or -const stopped = await stopScriptAsync('scriptName'); -log(`Script was ${stopped ? 'stopped' : 'already stopped'}`); -``` - -If stopScript is called without arguments, it will stop itself: - -```js -stopScript(); -``` - -### isScriptActive - -```js -isScriptActive('scriptName'); -``` - -Returns if a script enabled or disabled. Please note that that does not give back if the script is now running or not. -The script can be finished, but still activated. - -It is not a function. It is a variable with `javascript` instance, that is visible in script's scope. - -### toInt - -### toFloat - -### toBoolean - -### jsonataExpression - -### wait - -Just pause the execution of the script. -Warning this function is `promise` and must be called as follows: - -```js -await wait(1000); -``` - -### sleep - -Same as [wait](#wait) - -### messageTo - -```js -messageTo( - { instance: 'instance', script: 'script.js.common.scriptName', message: 'messageName' }, - data, - { timeout: 1000 }, - result => log(JSON.stringify(result)), -); -``` - -It sends via the "message bus" the message to some other script. Or even to some handler in the same script. - -Timeout for callback is 5 seconds by default. - -The target could be shorted to: - -```js -messageTo('messageName', data, result => { - log(JSON.stringify(result)); -}); -``` - -Callback and options are optional and timeout is by default 5000 milliseconds (if callback provided). - -```js -messageTo('messageName', dataWithNoResponse); -``` - -### messageToAsync - -```js -onMessage('myTopic', async (data, callback) => { - log(data); - - if (!data.myPayload) { - // return error (promise reject) - callback({ error: 'something went wrong!!' }); - } else { - // return result (promise resolve) - callback({ result: 'ok' }); - } -}); - -(async () => { - try { - const msg = await messageToAsync( - { instance: 0, script: 'script.js.test2', message: 'myTopic' }, - { myPayload: true }, - { timeout: 1000 }, - ); - log(`Done with: ${JSON.stringify(msg)}`); - } catch (error) { - // contents of result.error - console.error(error); - } -})(); -``` - -### onMessage - -```js -onMessage('messageName', (data, callback) => { - log(`Received data: ${data}`); - callback({ result: Date.now() }); -}); -``` - -Subscribes on JavaScript adapter message bus and delivers response via callback. -The response from script which sends response as first will be accepted as answer, all other answers will be ignored. - -To send a message to a JavaScript script which is then received by this handler, use [messageTo](#messageTo). - -To send a message from any other adapter use - -```js -adapter.sendTo('javascript.0', 'toScript', { - script: 'script.js.messagetest', - message: 'messageName', - data: { - flag: true, - }, -}); -``` - -to send a message from CLI use - -```bash -iob message javascript.0 toScript '{"script": "script.js.messagetest", "message": "messageName", "data": { "flag": true }}' -``` - -### onMessageUnregister - -```js -const id = onMessage('messageName', (data, callback) => { - log(data); - callback(Date.now()); -}); - -// unsubscribe specific handler -onMessageUnregister(id); -// or unsubscribe by name -onMessageUnregister('messageName'); -``` - -Unsubscribes from this message. - -### onLog - -```js -onLog('error', data => { - sendTo('telegram.0', { user: 'UserName', text: data.message }); - log('Following was sent to telegram: ' + data.message); -}); -``` - -Subscribe on logs with specified severity. - -_Important:_ you cannot output logs in handler with the same severity to avoid infinite loops. - -E.g., this will produce no logs: - -```js -onLog('error', data => { - console.error('Error: ' + data.message); -}); -``` - -To receive all logs the `*` could be used. In this case, the log output in handler will be disabled completely. - -```js -onLog('*', data => { - console.error('Error: ' + data.message); // will produce no logs -}); -``` - -### onLogUnregister - -```js -function logHandler(data) { - console.error('Error: ' + data.message); -} -const id = onLog('warn', logHandler); - -// unsubscribe by ID -onLogUnregister(id); -// or unsubscribe by function handler -onLogUnregister(logHandler); -// or unsubscribe all handlers with specific severity -onLogUnregister('warn'); -``` - -Unsubscribes from these logs. - -### httpGet - -_Requires version >= 7.9.0_ - -```js -httpGet('http://jsonplaceholder.typicode.com/posts', { timeout: 1000 }, (err, response) => { - if (!err) { - console.log(response.statusCode); - console.log(response.data); - } else { - console.error(err); - } -}); -``` - -Download file to ioBroker file system: - -```js -httpGet('http://1.2.3.4/image.jpg', { responseType: 'arraybuffer' }, async (err, response) => { - if (!err) { - writeFile('0_userdata.0', 'test.jpg', response.data, err => { - if (err) { - console.error(err); - } - }); - } else { - console.error(err); - } -}); -``` - -Disable certificate validation - _Requires version >= 8.4.0_ - -```js -httpGet('http://jsonplaceholder.typicode.com/posts', { validateCertificate: false }, (err, response) => { - if (!err) { - console.log(response.statusCode); - console.log(response.data); - } else { - console.error(err); - } -}); -``` - -### httpPost - -_Requires version >= 7.9.0_ - -```js -httpPost( - 'http://jsonplaceholder.typicode.com/posts', - { title: 'foo', body: 'bar', userId: 1 }, - { timeout: 1000 }, - (error, response) => { - if (!error) { - console.log(response.statusCode); - console.log(response.data); - console.log(response.headers); - } else { - console.error(error); - } - }, -); -``` - -With custom headers and authentication - -```js -httpPost( - 'http://jsonplaceholder.typicode.com/posts', - { - title: 'foo', - body: 'bar', - userId: 1, - }, - { - timeout: 2000, - basicAuth: { - user: 'admin', - password: 'dg2LdALNznHFNo', - }, - headers: { - Cookie: 'PHPSESSID=298zf09hf012fh2; csrftoken=u32t4o3tb3gg43; _gat=1', - }, - }, - (error, response) => { - if (!error) { - console.log(response.statusCode); - console.log(response.data); - console.log(response.headers); - } else { - console.error(error); - } - }, -); -``` - -### createTempFile - -_Requires version >= 8.3.0_ - -```js -httpGet( - 'https://raw.githubusercontent.com/ioBroker/ioBroker.javascript/master/admin/javascript.svg', - { responseType: 'arraybuffer' }, - async (err, response) => { - if (err) { - console.error(err); - } else { - const tempFilePath = createTempFile('javascript.svg', response.data); - console.log(`Saved to ${tempFilePath}`); - - // Use the new path in other scripts (e.g. sendTo) - } - }, -); -``` - -```js -onFile('0_userdata.0', 'test.jpg', true, async (id, fileName, size, data, mimeType) => { - const tempFilePath = createTempFile(fileName, response.data); - - // Use the new path in other scripts (e.g. sendTo) -}); -``` - -## Global script variables - -### scriptName - -`scriptName` - The name of the script. - -```js -log(`Script ${scriptName} started!`); -``` - -### instance - -`instance` - The JavaScript instance where thia script is executed (e.g. `0`). - -```js -log(`Script ${scriptName} started started by ${instance}`); -``` - -### defaultDataDir - -`defaultDataDir` - Absolute path to iobroker-data. - -```js -log(`Data dir: ${defaultDataDir}`); -``` - -### verbose - -`verbose` - Verbose mode enabled? - -```js -log(`Verbose mode: ${verbose ? 'enabled' : 'disabled'}`); - -// Example -if (verbose) { - log('...'); -} -``` - -## Option - "Do not subscribe all states on start" - -There are two modes of subscribing to states: - -- Adapter subscribes to all changes at start and receives all changes of all states (it is easy to use getStates(id), but requires more CPU and RAM): - -```js -log(getState('someID').val); -``` - -- Adapter subscribes every time on specified ID if "on/subscribe" called. In this mode, the adapter receives only updates for desired states. - It is very performed and RAM efficiency, but you cannot access states directly in getState. You must use callback to get the result of state: - -```js -getState('someID', (error, state) => { - log(state.val); -}); -``` - -It is because the adapter does not have the value of state in RAM and must ask central DB for the value. - -## Scripts activity - -There is a possibility to enable and disable scripts via states. For every script, the state will be created with the name `javascript.INSTANCE.scriptEnabled.SCRIPT_NAME`. -Scripts can be activated and deactivated by controlling this state with `ack=false`. diff --git a/src-editor/src/i18n/de.json b/src-editor/src/i18n/de.json index ec5d78ab..9fcebcc1 100644 --- a/src-editor/src/i18n/de.json +++ b/src-editor/src/i18n/de.json @@ -6,6 +6,9 @@ "-": "-", ".": ".", "AI code generator": "KI-Codegenerator", + "Planning...": "Plane...", + "Generating code...": "Generiere Code...", + "Show plan": "Plan anzeigen", "Ack": "Bestätigt", "Actions": "Aktionen", "Actual time of day": "Tatsächliche Tageszeit", diff --git a/src-editor/src/i18n/en.json b/src-editor/src/i18n/en.json index 45c9e7c0..57027793 100644 --- a/src-editor/src/i18n/en.json +++ b/src-editor/src/i18n/en.json @@ -6,6 +6,9 @@ "-": "-", ".": ".", "AI code generator": "AI code generator", + "Planning...": "Planning...", + "Generating code...": "Generating code...", + "Show plan": "Show plan", "Ack": "Acknowledged", "Actions": "Actions", "Actual time of day": "Actual time of day", diff --git a/src-editor/src/i18n/es.json b/src-editor/src/i18n/es.json index 743f402e..7afdbfa4 100644 --- a/src-editor/src/i18n/es.json +++ b/src-editor/src/i18n/es.json @@ -6,6 +6,9 @@ "-": "-", ".": ".", "AI code generator": "Generador de código de IA", + "Planning...": "Planificando...", + "Generating code...": "Generando código...", + "Show plan": "Mostrar plan", "Ack": "Admitido", "Actions": "Comportamiento", "Actual time of day": "Hora real del día", diff --git a/src-editor/src/i18n/fr.json b/src-editor/src/i18n/fr.json index fe65ce1c..7c396723 100644 --- a/src-editor/src/i18n/fr.json +++ b/src-editor/src/i18n/fr.json @@ -6,6 +6,9 @@ "-": "-", ".": ".", "AI code generator": "Générateur de code IA", + "Planning...": "Planification...", + "Generating code...": "Génération du code...", + "Show plan": "Afficher le plan", "Ack": "Reconnu", "Actions": "Actions", "Actual time of day": "Heure réelle de la journée", diff --git a/src-editor/src/i18n/it.json b/src-editor/src/i18n/it.json index ef09021f..705bd125 100644 --- a/src-editor/src/i18n/it.json +++ b/src-editor/src/i18n/it.json @@ -6,6 +6,9 @@ "-": "-", ".": ".", "AI code generator": "Generatore di codice AI", + "Planning...": "Pianificazione...", + "Generating code...": "Generazione codice...", + "Show plan": "Mostra piano", "Ack": "Riconosciuto", "Actions": "Azioni", "Actual time of day": "Ora effettiva della giornata", diff --git a/src-editor/src/i18n/nl.json b/src-editor/src/i18n/nl.json index 24a0d3d3..1b193bfd 100644 --- a/src-editor/src/i18n/nl.json +++ b/src-editor/src/i18n/nl.json @@ -6,6 +6,9 @@ "-": "-", ".": ".", "AI code generator": "AI-codegenerator", + "Planning...": "Planning...", + "Generating code...": "Code genereren...", + "Show plan": "Plan weergeven", "Ack": "Erkend", "Actions": "Acties", "Actual time of day": "Werkelijke tijd van de dag", diff --git a/src-editor/src/i18n/pl.json b/src-editor/src/i18n/pl.json index 6dc081bd..001b6e9a 100644 --- a/src-editor/src/i18n/pl.json +++ b/src-editor/src/i18n/pl.json @@ -6,6 +6,9 @@ "-": "-", ".": ".", "AI code generator": "Generator kodu AI", + "Planning...": "Planowanie...", + "Generating code...": "Generowanie kodu...", + "Show plan": "Pokaż plan", "Ack": "Potwierdzony", "Actions": "Działania", "Actual time of day": "Aktualna pora dnia", diff --git a/src-editor/src/i18n/pt.json b/src-editor/src/i18n/pt.json index c0ca375e..9b177ca2 100644 --- a/src-editor/src/i18n/pt.json +++ b/src-editor/src/i18n/pt.json @@ -6,6 +6,9 @@ "-": "-", ".": ".", "AI code generator": "Gerador de código de IA", + "Planning...": "Planejando...", + "Generating code...": "Gerando código...", + "Show plan": "Mostrar plano", "Ack": "Reconhecido", "Actions": "Ações", "Actual time of day": "Hora real do dia", diff --git a/src-editor/src/i18n/ru.json b/src-editor/src/i18n/ru.json index f407457d..e7b405a3 100644 --- a/src-editor/src/i18n/ru.json +++ b/src-editor/src/i18n/ru.json @@ -6,6 +6,9 @@ "-": "-", ".": ".", "AI code generator": "ИИ Генератор кода", + "Planning...": "Планирование...", + "Generating code...": "Генерация кода...", + "Show plan": "Показать план", "Ack": "Подтверждение", "Actions": "Действия", "Actual time of day": "Фактическое время суток", diff --git a/src-editor/src/i18n/uk.json b/src-editor/src/i18n/uk.json index ce1b97e9..a4f9e658 100644 --- a/src-editor/src/i18n/uk.json +++ b/src-editor/src/i18n/uk.json @@ -6,6 +6,9 @@ "-": "-", ".": ".", "AI code generator": "Генератор коду ШІ", + "Planning...": "Планування...", + "Generating code...": "Генерування коду...", + "Show plan": "Показати план", "Ack": "Визнано", "Actions": "Дії", "Actual time of day": "Фактичний час доби", diff --git a/src-editor/src/i18n/zh-cn.json b/src-editor/src/i18n/zh-cn.json index 7b3d067b..0c2fc0d7 100644 --- a/src-editor/src/i18n/zh-cn.json +++ b/src-editor/src/i18n/zh-cn.json @@ -6,6 +6,9 @@ "-": "-", ".": ".", "AI code generator": "AI代码生成器", + "Planning...": "规划中...", + "Generating code...": "生成代码中...", + "Show plan": "显示计划", "Ack": "确认", "Actions": "动作", "Actual time of day": "一天中的实际时间", diff --git a/src/lib/protectFs.ts b/src/lib/protectFs.ts index 01b09947..52f31b67 100644 --- a/src/lib/protectFs.ts +++ b/src/lib/protectFs.ts @@ -819,7 +819,7 @@ export default class ProtectFs { rmdir(path: PathLike, callback?: NoParamCallback): void { ProtectFs.checkProtected(path, false); if (typeof callback === 'function') { - return nodeFS.rmdir.call(this, path, callback); + return (nodeFS.rmdir as (...args: unknown[]) => void).call(this, path, callback); } return nodeFS.rmdirSync.call(this, path); } diff --git a/src/main.ts b/src/main.ts index 534cf2e8..ebc82e8f 100644 --- a/src/main.ts +++ b/src/main.ts @@ -261,6 +261,20 @@ const jsDeclarationServer: Server = new Server(jsDeclarationCompilerOptions, isC * the compiled source was just updated */ +function httpStatusText(code: number): string { + const texts: Record = { + 400: 'Bad Request', + 401: 'Unauthorized', + 403: 'Forbidden', + 404: 'Not Found', + 429: 'Too Many Requests / Rate Limit', + 500: 'Internal Server Error', + 502: 'Bad Gateway', + 503: 'Service Unavailable', + }; + return texts[code] || `Error ${code}`; +} + class JavaScript extends Adapter { declare public config: JavaScriptAdapterConfig; @@ -1196,7 +1210,13 @@ class JavaScript extends Adapter { if (apiKey) { chatHeaders.Authorization = `Bearer ${apiKey}`; } - bodyObj = { model: chatModel, messages, stream: false }; + bodyObj = { + model: chatModel, + messages, + stream: false, + // Disable thinking/reasoning for local models to save context and speed + ...(baseUrl ? { reasoning_effort: 'none' } : {}), + }; } const body = JSON.stringify(bodyObj); @@ -1258,16 +1278,21 @@ class JavaScript extends Adapter { ); } } else { - let errorMsg = `API returned status ${res.statusCode}`; + let detail = ''; try { - const parsed = JSON.parse(data); - if (parsed.error?.message) { - errorMsg = parsed.error.message; - } + const errParsed = JSON.parse(data); + detail = errParsed.error?.message || data.substring(0, 200); } catch { - // ignore parse error + detail = data.substring(0, 200); } - this.sendTo(obj.from, obj.command, { error: errorMsg }, obj.callback); + this.sendTo( + obj.from, + obj.command, + { + error: `${detail || httpStatusText(res.statusCode || 0)} (${res.statusCode})`, + }, + obj.callback, + ); } }); }, @@ -1388,10 +1413,20 @@ class JavaScript extends Adapter { } else if (res.statusCode === 403) { this.sendTo(obj.from, obj.command, { error: 'Access denied (403)' }, obj.callback); } else { + // Include response body for debugging + let detail = ''; + try { + const errParsed = JSON.parse(data); + detail = errParsed.error?.message || data.substring(0, 200); + } catch { + detail = data.substring(0, 200); + } this.sendTo( obj.from, obj.command, - { error: `API returned status ${res.statusCode}` }, + { + error: `${detail || httpStatusText(res.statusCode || 0)} (${res.statusCode})`, + }, obj.callback, ); } diff --git a/tasks.js b/tasks.js index ba98c468..6a53a287 100644 --- a/tasks.js +++ b/tasks.js @@ -6,7 +6,7 @@ */ const { - rmdirSync, + rmSync, readFileSync, writeFileSync, existsSync, @@ -43,6 +43,7 @@ function clean() { 'javascript.svg', 'vsFont', 'i18n', + 'img', ]); deleteFoldersRecursive(`${__dirname}/src-editor/build`); } @@ -79,7 +80,7 @@ function copyAllFiles() { const dirs = readdirSync(i18nDir); for (const dir of dirs) { if (statSync(`${i18nDir}/${dir}`).isDirectory()) { - rmdirSync(`${i18nDir}/${dir}`, { recursive: true }); + rmSync(`${i18nDir}/${dir}`, { recursive: true }); } } } @@ -278,7 +279,7 @@ function monacoTypescript() { // save the old configure.js renameSync(join(vsDir, 'configure.js'), join(__dirname, 'monaco.configure.js')); // delete everything else - rmdirSync(vsDir, { recursive: true }); + rmSync(vsDir, { recursive: true }); mkdirSync(vsDir, { recursive: true }); console.log('installing new version'); @@ -319,7 +320,7 @@ function monacoUpdate() { // save the old configure.js renameSync(join(vsDir, 'configure.js'), join(__dirname, 'monaco.configure.js')); // delete everything else - rmdirSync(vsDir, { recursive: true }); + rmSync(vsDir, { recursive: true }); mkdirSync(vsDir, { recursive: true }); console.log('installing new version');