iobroker.javascript 10.2.5 → 10.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/README.md +6 -14
  2. package/admin/assets/AiChatPanel-CpY4Bun-.js +27 -0
  3. package/admin/assets/{AiChatService-BOL3J2Jd.js → AiChatService-QKcpW4jQ.js} +1 -1
  4. package/admin/assets/AiDiffView-DscPfZ38.js +1 -0
  5. package/admin/assets/{AiInlineProvider-BIlcrTkS.js → AiInlineProvider-DTSPKoXG.js} +1 -1
  6. package/admin/assets/BlocklyEditor-BZyoN1JE.js +301 -0
  7. package/admin/assets/Compile-B0uHjrBE.css +1 -0
  8. package/admin/assets/Compile-Oss28m_f.js +165 -0
  9. package/admin/assets/{Debugger-DwHHsh9O.js → Debugger-teJTIU-2.js} +4 -4
  10. package/admin/assets/{Documentation-Bc0RmoEF.js → Documentation-uz4Ut9pT.js} +4 -4
  11. package/admin/assets/ExpandMore-V5Ix1QB1.js +1 -0
  12. package/admin/assets/FbEditor-B8S-mCvc.css +1 -0
  13. package/admin/assets/FbEditor-aOZ-RpPV.js +15 -0
  14. package/admin/assets/Import-BIC5Ee9z.js +1 -0
  15. package/admin/assets/NotificationsActive-BdzH44gp.js +1 -0
  16. package/admin/assets/RulesEditor-CcDVthPa.js +1 -0
  17. package/admin/assets/{ScriptEditor-CEHpEFp7.js → ScriptEditor-CviB6Hif.js} +2 -2
  18. package/admin/assets/ScriptEditorVanillaMonaco-ByuXwybM.js +3 -0
  19. package/admin/assets/Send-Mdo32jMb.js +1 -0
  20. package/admin/assets/{_virtual_mf-localSharedImportMap___mfe_internal__iobroker_javascript__mf_owner__1-CM95r358.js → _virtual_mf-localSharedImportMap___mfe_internal__iobroker_javascript__mf_owner__1-BnL93BgK.js} +1 -1
  21. package/admin/assets/{_virtual_mf___mfe_internal__iobroker_javascript__mf_owner__180366418666083__loadShare___mf_0_iobroker_mf_1_gui_mf_2_components__loadShare__.js-BEpNZh4U.js → _virtual_mf___mfe_internal__iobroker_javascript__mf_owner__180366418666083__loadShare___mf_0_iobroker_mf_1_gui_mf_2_components__loadShare__.js-NI-3Uv4e.js} +75 -75
  22. package/admin/assets/{_virtual_mf___mfe_internal__iobroker_javascript__mf_owner__180366418666083__loadShare__react_mf_2_dom_mf_1_client__loadShare__.js-FeM77flT.js → _virtual_mf___mfe_internal__iobroker_javascript__mf_owner__180366418666083__loadShare__react_mf_2_dom_mf_1_client__loadShare__.js-DVaMIZyC.js} +1 -1
  23. package/admin/assets/aiPromptBuilder-yTB6N2VT.js +1 -0
  24. package/admin/assets/blocklyTheme-CGhU3cEO.js +1 -0
  25. package/admin/assets/blocks_action-BQ4O7NRE.js +1 -0
  26. package/admin/assets/{blocks_convert-BP2RjhQH.js → blocks_convert-0VBjfhqQ.js} +1 -1
  27. package/admin/assets/blocks_logic-DAo99xDr.js +1 -0
  28. package/admin/assets/blocks_number-C--e19NU.js +1 -0
  29. package/admin/assets/blocks_object-D0TPhdzg.js +1 -0
  30. package/admin/assets/blocks_procedures-DgTxgXdB.js +3 -0
  31. package/admin/assets/{blocks_sendto-qIKzOAcV.js → blocks_sendto-CRIrtOUc.js} +1 -1
  32. package/admin/assets/blocks_switch-b_GYfF0n.js +2 -0
  33. package/admin/assets/blocks_system-BdkUdSsc.js +1 -0
  34. package/admin/assets/blocks_text-DSFhEVOf.js +1 -0
  35. package/admin/assets/blocks_time-CqALAiJp.js +1 -0
  36. package/admin/assets/blocks_timeout-yrOD2pZp.js +1 -0
  37. package/admin/assets/{blocks_trigger-CnmXLCUE.js → blocks_trigger-DeAYXpSS.js} +1 -1
  38. package/admin/assets/{cronHoverProvider-CcIFAhVy.js → cronHoverProvider-DoO2_tpG.js} +1 -1
  39. package/admin/assets/{field_cron-Ba46q8Qc.js → field_cron-D3Ts_s9M.js} +1 -1
  40. package/admin/assets/{field_oid-lWCjOzuq.js → field_oid-BRNXredg.js} +1 -1
  41. package/admin/assets/{field_script-BCWZHhnW.js → field_script-3X6ousg7.js} +1 -1
  42. package/admin/assets/helpers-BTGaTdnT.js +1 -0
  43. package/admin/assets/{hostInit-CVybS7BB.js → hostInit-2h2Cbsaw.js} +1 -1
  44. package/admin/assets/index-BHhhebRG.css +1 -0
  45. package/admin/assets/index-CbQlIKB_.js +156 -0
  46. package/admin/assets/{inlineChatWidget-N8xIkvxX.js → inlineChatWidget-BwQVCPkx.js} +2 -2
  47. package/admin/assets/{inlineDiffController-BuqYsKKq.js → inlineDiffController-BsDDsDHn.js} +2 -2
  48. package/admin/assets/loadBlocks-RpqM7PwO.js +117 -0
  49. package/admin/assets/loadMonaco-BVOEahNw.js +1 -0
  50. package/admin/assets/{mf-entry-bootstrap-0-a5a39621.js → mf-entry-bootstrap-0-0deef484.js} +3 -3
  51. package/admin/assets/{pendingShares-DOAkyFMS.js → pendingShares-BaAadIDv.js} +1 -1
  52. package/admin/assets/reactour.esm-DX9ZgYlx.js +137 -0
  53. package/admin/assets/{stateHoverProvider-BYAbe1Ay.js → stateHoverProvider-BEadnSXp.js} +1 -1
  54. package/admin/assets/tileFbd-CWAy7R7m.svg +85 -0
  55. package/admin/mf-manifest.json +1 -1
  56. package/admin/mf-stats.json +1 -1
  57. package/admin/remoteEntry.js +2 -2
  58. package/admin/tab.html +3 -7
  59. package/build/lib/fb/analyze.js +288 -0
  60. package/build/lib/fb/analyze.js.map +1 -0
  61. package/build/lib/fb/blocks.js +605 -0
  62. package/build/lib/fb/blocks.js.map +1 -0
  63. package/build/lib/fb/generate.js +326 -0
  64. package/build/lib/fb/generate.js.map +1 -0
  65. package/build/lib/fb/graph.js +240 -0
  66. package/build/lib/fb/graph.js.map +1 -0
  67. package/build/lib/fb/index.js +57 -0
  68. package/build/lib/fb/index.js.map +1 -0
  69. package/build/lib/fb/js.js +33 -0
  70. package/build/lib/fb/js.js.map +1 -0
  71. package/build/lib/fb/layout.js +205 -0
  72. package/build/lib/fb/layout.js.map +1 -0
  73. package/build/lib/fb/library.js +657 -0
  74. package/build/lib/fb/library.js.map +1 -0
  75. package/build/lib/fb/runtime.js +793 -0
  76. package/build/lib/fb/runtime.js.map +1 -0
  77. package/build/lib/fb/time.js +76 -0
  78. package/build/lib/fb/time.js.map +1 -0
  79. package/build/lib/fb/types.js +19 -0
  80. package/build/lib/fb/types.js.map +1 -0
  81. package/build/lib/fb/user.js +78 -0
  82. package/build/lib/fb/user.js.map +1 -0
  83. package/build/lib/javascript.d.ts +1 -1
  84. package/build/lib/mirror.js +4 -0
  85. package/build/lib/mirror.js.map +1 -1
  86. package/build/lib/sandbox.js +44 -0
  87. package/build/lib/sandbox.js.map +1 -1
  88. package/build/main.js +66 -1
  89. package/build/main.js.map +1 -1
  90. package/build/types.d.ts +9 -1
  91. package/docs/de/fbd.md +274 -0
  92. package/docs/en/fbd.md +260 -0
  93. package/io-package.json +39 -15
  94. package/package.json +1 -1
  95. package/admin/assets/AiChatPanel-oBeXbUFv.js +0 -27
  96. package/admin/assets/AiDiffView-C-KKjnJD.js +0 -1
  97. package/admin/assets/Error-DZ4vCykD.js +0 -1
  98. package/admin/assets/Import-Cu02ceLW.js +0 -1
  99. package/admin/assets/RulesEditor-QCbi1lV_.js +0 -1
  100. package/admin/assets/ScriptEditorVanillaMonaco-ChQmnk0p.js +0 -3
  101. package/admin/assets/aiPromptBuilder-DKler0UK.js +0 -1
  102. package/admin/assets/blocks_action-DywZVfRY.js +0 -1
  103. package/admin/assets/blocks_logic-CdTl5YZw.js +0 -1
  104. package/admin/assets/blocks_number-DXFd9Rva.js +0 -1
  105. package/admin/assets/blocks_object-by1uBDHi.js +0 -1
  106. package/admin/assets/blocks_procedures-BcJ7N70D.js +0 -3
  107. package/admin/assets/blocks_switch-dLF6hSJl.js +0 -2
  108. package/admin/assets/blocks_system-DmX-SBy8.js +0 -1
  109. package/admin/assets/blocks_text-BI4zNU3o.js +0 -1
  110. package/admin/assets/blocks_time-BgYA4Y_4.js +0 -1
  111. package/admin/assets/blocks_timeout-DUzgMyAu.js +0 -1
  112. package/admin/assets/helpers-CnEjYAup.js +0 -1
  113. package/admin/assets/index-B3s0zmWC.js +0 -871
  114. package/admin/assets/index-CXaeqPRy.css +0 -1
package/io-package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "common": {
3
3
  "name": "javascript",
4
- "version": "10.2.5",
4
+ "version": "10.3.0",
5
5
  "blockedVersions": [
6
6
  "8.0.0",
7
7
  "8.0.1"
@@ -40,6 +40,19 @@
40
40
  "Matthias Kleine <info@haus-automatisierung.com>"
41
41
  ],
42
42
  "news": {
43
+ "10.3.0": {
44
+ "en": "The code editor (Monaco), Blockly and the Rules blocks are loaded only when a script of that kind is opened, so the editor starts faster\nAdded function block diagrams (FBD, in the style of CFC): timers, counters, flip-flops, edges, comparison, arithmetic, conversions, control, calendar (cron, sun events), log and messages, and a block with own JavaScript - wired to ioBroker states. See [the description](docs/en/fbd.md)",
45
+ "de": "Die Blöcke Code-Editor (Monaco), Blockly und Rules werden nur geladen, wenn ein Skript geöffnet wird.\nFunktionsblockdiagramme (FBD, im CFC-Stil) hinzugefügt: Timer, Zähler, Flipflops, Kanten, Vergleich, Arithmetik, Umrechnungen, Kalender (Cron, Sun), Log und Nachrichten und ein Block mit eigenem JavaScript — mit ioBroker-Status. Siehe [Beschreibung] (docs/en/fbd.md)",
46
+ "ru": "Редактор кода (Monaco), блоки Blockly и Rules загружаются только при открытии такого скрипта, поэтому редактор запускается быстрее\nДобавлены функциональные блок-схемы (FBD, в стиле CFC): таймеры, счетчики, триггеры, сравнение, арифметика, конверсии, управление, календарь (cron, sun events), журнал и сообщения, а также блок с собственным JavaScript, привязанный к состояниям IOBroker. См. [описание] (docs/en/fbd.md)",
47
+ "pt": "O editor de código (Monaco), o Blockly e o Rules só são carregados quando um script é aberto, então o editor começa mais rápido\nForam adicionados diagramas de blocos funcionais (FBD, no estilo CFC): temporizadores, contadores, flip-flops, bordas, comparação, aritmética, conversões, controle, calendário, log e mensagens e um bloco com JavaScript próprio, conectado aos estados do IOBroker. Veja a descrição (docs/en/fbd.md)",
48
+ "nl": "De blokken code-editor (Monaco), Blockly en de Rules worden alleen geladen als een dergelijk script wordt geopend, zodat de editor sneller start\nFunctieblokdiagrammen toegevoegd (FBD, in de stijl van CFC): timers, tellers, flip-flops, randen, vergelijking, rekenen, conversies, controle, kalender (cron, zonnegebeurtenissen), logboek en berichten, en een blok met eigen JavaScript - overgezet naar IOBroker-staten. Zie [de beschrijving] (docs/en/fbd.md)",
49
+ "fr": "L'éditeur de code (Monaco), Blockly et les blocs Rules ne sont chargés que lorsqu'un script de ce type est ouvert.\nAjout de diagrammes de blocs fonctionnels (FBD, style CFC) : chronomètres, compteurs, bascules, bords, comparaison, arithmétique, conversions, contrôle, calendrier (cron, sun events), journal et messages, et un bloc avec son propre JavaScript, connecté aux états d'IObroker. Voir [la description] (docs/en/fbd.md)",
50
+ "it": "I blocchi Code Editor (Monaco), Blockly e Rules si caricano solo all'apertura di quel tipo di script\nAggiunti diagrammi a blocchi funzionali (FBD, in stile CFC): timer, contatori, flip-flop, edge, confronto, aritmetica, conversioni, controllo, calendario (cron, sun events), log e messaggi e un blocco con JavaScript proprio, collegato agli stati IOBroker. Vedi [descrizione] (docs/en/fbd.md)",
51
+ "es": "El editor de código (Mónaco), los bloques Blockly y Rules solo se cargan cuando se abre un guion de ese tipo, por lo que el editor se inicia más rápido\nDiagramas de bloques de funciones (FBD, al estilo de CFC): temporizadores, contadores, chanclas, bordes, comparación, aritmética, conversiones, control, calendario (cron, sun events), registro y mensajes, y un bloque con su propio JavaScript, conectado a los estados de IOBroker. Vea [la descripción] (docs/en/fbd.md)",
52
+ "pl": "Edytor kodu (Monaco), Blockly i bloki Reguły są ładowane tylko po otwarciu tego rodzaju skryptu, więc edytor uruchamia się szybciej\nDodano diagramy blokowe funkcji (FBD, w stylu CFC): timery, liczniki, klapki, krawędzie, porównanie, arytmetyka, konwersje, sterowanie, kalendarz (cron, zdarzenia słoneczne), dzienniki i wiadomości oraz blok z własnym JavaScript - podłączony do stanów ioBroker. Patrz [opis] (docs/en/fbd.md)",
53
+ "uk": "Редактор коду (Монако), блоки Blockly та Rules завантажуються лише тоді, коли відкривається такий сценарій, тому редактор запускається швидше\nДодані функціональні блокові діаграми (FBD, в стилі CFC): таймери, лічильники, шльопанці, ребра, порівняння, арифметика, перетворення, управління, календар (cron, sun events), журнал і повідомлення, а також блок з власним JavaScript - підключений до станів IObroker. Див. [опис] (docs/uk/fbd.md)",
54
+ "zh-cn": "代码编辑器(摩纳哥)、Blockly 和 Rules 块仅在打开此类脚本时加载,因此编辑器启动速度更快\n添加了函数方框图(FBD,采用 CFC 风格):计时器、计数器、触发器、边缘、比较、算术、转换、控制、日历(cron、sun 事件)、日志和消息,以及带有自己的 JavaScript 的方块(连接到 IOBroker 状态)。参见 [描述](docs/en/fbd.md)"
55
+ },
43
56
  "10.2.5": {
44
57
  "en": "Added the functions help dialog in editor",
45
58
  "de": "Hilfedialog im Editor hinzugefügt",
@@ -117,19 +130,6 @@
117
130
  "pl": "Zasady: pusty pasek „i” składa się do nagłówka. Reguła bez warunków uruchamia swoje działania na każdym wyzwalaczu, ale to pasmo nadal było najwyższym elementem reguły - obszar upuszczania z podłogą 64px, selektorem „po prostu sprawdź” i wierszem „lub” na grupę, 292 pikseli za darmo. Ma teraz 41 pikseli i mówi „bez warunku”, kliknięcie nagłówka otwiera go ponownie, przeciągnięcie warunku otwiera go samoistnie, a pasmo, które ma w sobie warunki, nigdy się nie składa\nZasady: paleta bloków zajmuje połowę miejsca, które zrobiła. Wpis zawierał 24px wypełnienia wokół ikony 30 pikseli, która pozostawiła 66 pikseli paska bocznego dla jednej linii tekstu - więc cztery bloki wypełniały całą wysokość, a wszystko inne znajdowało się za paskiem przewijania. Wpisy są teraz oddalone od siebie o 31 pikseli, zakładki tylko ikony nad nimi nie zastrzegają już wysokości etykiety, której nie mają, a pasek boczny ma szerokość 168 pikseli zamiast 200 pikseli. Nazwa zbyt długa na to otrzymuje pełny tekst jako podpowiedź. Przycisk, który składa paletę, znajduje się teraz na linii palety zamiast jednego piksela po lewej stronie, gdzie wisiał nad krawędzią okna po złożeniu palety\nReguły: wybranie stanu wyzwalacza spowodowało usunięcie edytora z „n.replace is not a function”, gdy warunek stanu łańcucha nie miał jeszcze wprowadzonej wartości. Wybór stanu ponownie kompiluje całą regułę, a pusta wartość dotarła do porównania jako logiczna „fałsz”. Warunek bez wartości porównuje się teraz z pustym tekstem, a liczba wprowadzona dla stanu będącego ciągiem jest używana jako jego tekst\nEdytor skryptów informuje teraz adapterowi co 10 sekund, że jest otwarty, a adapter zachowuje definicje typów i kompilator na gorąco, podczas gdy tak jest, więc zapisanie skryptu nie czeka na ich ponowne zbudowanie. 30 sekund po ostatnim znaku życia GUI liczy się jako zniknął i wszystko jest oddane - około 100 MB. Karta w tle nie jest liczona jako otwarta, więc zapomniana karta przeglądarki nie może utrzymać pamięci przy życiu przez wiele dni (#2373)\nDefinicje typów Node.js, ioBroker i skonfigurowanych bibliotek były odczytywane na każdym początku, niezależnie od tego, czy cokolwiek ich chciało, czy nie. Robią się tylko dwie rzeczy - skompilowanie skryptu TypeScript i wbudowany edytor - i dodają około 90 MB do kompilatora, więc są teraz odczytywane, gdy jeden z nich faktycznie poprosi. Instancja, która uruchamia zwykły JavaScript i jest edytowana gdzie indziej (katalog lustrzany, edytor zewnętrzny) nigdy ich nie czyta; deklaracje globalnych JavaScript są generowane bez nich i wychodzą tak samo. Można je również wyłączyć na dobre („Definicje typów obciążenia”, karta TypeScript) - edytor traci wtedy automatyczne uzupełnianie i skrypty TypeScript przestają się kompilować, o czym adapter ostrzega w dzienniku (#2373)\nKażda instancja utrzymywała przy życiu dwie usługi językowe TypeScript, niezależnie od tego, czy ich potrzebowała, czy nie, a każda z nich utrzymywała około 95 MB po skompilowaniu czegokolwiek. Są one teraz zbudowane tylko na pierwszej kompilacji, a deklaracje globalnych skryptów JavaScript są przechowywane w obiekcie skryptu w taki sam sposób, w jaki były już skompilowane źródła TypeScript - więc ponowne uruchomienie ich nie regeneruje. To, co tworzy usługa językowa, zostaje ponownie wydana minutę po ostatniej kompilacji i odbudowana na żądanie. W systemie testowym zajęło to instancję od 241 MB do 127 MB sterty (352 MB do 233 MB RSS) (#2373)\nPomocnicy, których edytor skryptów rysuje samodzielnie - wiersz „Wyjaśnij/ Refactor/Test” nad każdą funkcją, podpowiedzi dla identyfikatorów obiektów i wyrażeń CRON oraz sugestie kodu wbudowanego - można wyłączyć. Ustawienie instancji „Pokaż pomocników AI w edytorze skryptów” (ustawienia AI) robi to; jest domyślnie włączone, więc nic się nie zmienia dla każdego, kto jest z nich zadowolony. `Alt+I` nadal pokazuje wartość identyfikatora obiektu pod kursorem, gdy są wyłączone\nRozumowanie punktu końcowego zgodnego z OpenAI zostało wyłączone bezwarunkowo: `rationing_esforç: „none\"` wychodziło z każdym żądaniem, gdy tylko skonfigurowano niestandardowy bazowy adres URL. Jest to właściwe dla małego modelu lokalnego i złe dla wszystkiego innego - za proxy wyłącza rozumowanie samego modelu, za który się płaci lub jest odrzucony. Jest to ustawienie teraz („Wysiłek rozumowania”), a domyślny parametr pozostawia poza nim i pozwala punktowi końcowi decydować\nEdytor AI powiedział adapterowi, jak długo chce czekać, a adapter nigdy go nie odczytał: zablokowane ukończenie w linii utrzymywało jego gniazdo przez pełne dziesięć minut zamiast piętnaście sekund, o które prosił\nUkończenie wbudowane obejmowało model wybrany na czacie AI, ale wybrało samego dostawcę, więc model jednego dostawcy można było zażądać z poświadczeniami i w punkcie końcowym innego. Model i dostawca są teraz zapamiętywane i używane razem\nKiedy dwóch dostawców oferuje model o tej samej nazwie - na przykład proxy i sprzedawca, który za nim stoi - który z nich obsługiwał, decyduje kto z nich odpowiedział jako pierwszy i może zmienić się z jednego przeładowania na następne. Dostawca skonfigurowany jako pierwszy wygrywa teraz, więc bezpośrednia trasa jest preferowana niż proxy",
118
131
  "uk": "Правила: порожня смуга «і» складається до свого заголовка. Правило без умов виконує свої дії на кожному тригері, але ця смуга все ще була найвищою річчю в правилі - область падіння з підлогою 64 пікселів, селектор «просто перевірити» та рядок «або» на групу, 292px даремно. Зараз він 41 піксель і говорить «без умови», натискання заголовка знову відкриває його, перетягування умови відкриває його сама, а смуга, яка має умови, ніколи не згортається\nПравила: блокова палітра займає половину кімнати, яку вона зробила. Запис містив 24 пікселі підкладки навколо піктограми 30 пікселів, яка залишила 66 пікселів бічної панелі для одного рядка тексту - тому чотири блоки заповнювали всю висоту, а все інше було за смугою прокрутки. Тепер записи знаходяться на відстані 31 пікселів один від одного, вкладки, що містять лише піктограми над ними, більше не резервують висоту мітки, яку вони не мають, а бічна панель має ширину 168 пікселів замість 200 пікселів. Назва, занадто довга для цього, отримує повний текст як підказку. Кнопка, яка складається палітру, також знаходиться на лінії палітри тепер замість одного пікселя зліва від неї, де вона висіла над краєм вікна, коли палітра була складена\nПравила: вибір стану тригера знизив редактор з «n.replace не є функцією», коли умова стану рядка ще не ввела значення. Вибір стану повторно компілює все правило, і порожнє значення прийшло до порівняння як булеве `false`. Умова без значення тепер порівнюється з порожнім текстом, а число, введене для стану, який є рядком, використовується як його текст\nТепер редактор сценаріїв повідомляє адаптеру кожні 10 секунд, що він відкритий, а адаптер зберігає визначення типів та компілятор гарячими, поки це так, тому збереження сценарію не чекає їх повторного створення. Через 30 секунд після останньої ознаки життя графічний інтерфейс вважається минулим, і все повертається - близько 100 Мб. Вкладка у фоновому режимі не вважається відкритою, тому забута вкладка браузера не може зберегти пам'ять живою протягом кількох днів (#2373)\nВизначення типів Node.js, IObroker та налаштованих бібліотек читалися при кожному запуску, незалежно від того, хотілося б щось їх чи ні. Виконуються лише дві речі - компіляція сценарію TypeScript та вбудований редактор - і вони додають близько 90 Мб до компілятора, тому тепер вони читаються, коли хтось із них насправді запитає. Екземпляр, який виконує простий JavaScript і редагується в іншому місці (дзеркальний каталог, зовнішній редактор), ніколи не читає їх; оголошення глобальних JavaScript генеруються без них і виходять однаковими. Їх також можна вимкнути назавжди («Визначення типів завантаження», вкладка TypeScript) - редактор потім втрачає автодоповнення, і сценарії TypeScript більше не компілюються, про що адаптер попереджає в журналі (#2373)\nКожен екземпляр підтримував дві мовні служби TypeScript живими незалежно від того, потрібні вони їм чи ні, і кожна з них зберігала близько 95 МБ після того, як вона щось зібрав. Тепер вони побудовані лише на першій компіляції, а оголошення глобальних JavaScripts зберігаються на об'єкті сценарію так само, як вже були скомпільовані джерела TypeScript - тому перезапуск більше не відновлює їх. Те, що в кінцевому підсумку створює мовна служба, знову випускається через хвилину після останньої компіляції та перебудовується на вимогу. У тестовій системі це зайняло екземпляр від 241 МБ до 127 МБ купи (352 МБ до 233 МБ RSS) (#2373)\nДопомічники, які редактор сценаріїв малює самостійно - рядок «Explicate/Refactor/Test» над кожною функцією, підказки для ідентифікаторів об'єктів та виразів CRON та вбудовані пропозиції коду - можна вимкнути. Налаштування екземпляра «Показати помічників AI в редакторі сценаріїв» (налаштування AI) робить це; він увімкнений за замовчуванням, тому нічого не змінюється для тих, хто задоволений ними. `Alt+I` все ще показує значення ідентифікатора об'єкта під курсором, коли вони вимкнені\nМіркування кінцевої точки, сумісної з OpenAI, було вимкнено беззастережно: `ing_efort: «none\"` виходило з кожним запитом, як тільки було налаштовано спеціальну базову URL-адресу. Це правильно для невеликої локальної моделі і неправильно для всього іншого - за проксі він відключає міркування тієї самої моделі, за яку платить, або відхиляється. Зараз це налаштування («Зусилля міркування»), і за замовчуванням залишає параметр поза увагою і дозволяє кінцевій точці вирішити\nРедактор AI розповів адаптеру, як довго він готовий чекати, і адаптер ніколи не читав його: застрягла вбудована комплектація тримала свій слот протягом цілих десяти хвилин замість п'ятнадцяти секунд, які він просив\nВбудоване завершення взяло модель, обрану в чаті AI, але вибрало самого провайдера, тому модель одного постачальника можна було запросити з обліковими даними та в кінцевій точці іншого. Модель та постачальник тепер запам'ятовуються та використовуються разом\nКоли два постачальники пропонують однойменну модель - наприклад, проксі та постачальник, який стоїть за нею, - хто з них обслуговував, це вирішувалось тим, хто відповідав першим, і він може змінюватися від одного перезавантаження до іншого. Постачальник, налаштований першим, виграє зараз, тому прямий маршрут є кращим перед проксі-сервером",
119
132
  "zh-cn": "规则:空的 “和” 波段向下折叠到其标题。没有条件的规则会在每个触发器上运行,但是该波段仍然是规则中最高的东西——下拉区域的下限为 64 像素,“只需勾选” 选择器以及每组一个 “或” 行,292px 一无所获。现在是 41px,上面写着 “无条件”,点击标题再次将其打开,将条件拖到标题上方会自行打开,其中有条件的波段永远不会折叠\n规则:方块调色板占用的空间是其空间的一半。一个条目在 30 像素的图标周围有 24 像素的边距,为一行文本留下 66 像素的侧边栏——因此四个方块占据了整个高度,其他所有内容都在滚动条后面。现在,条目相隔 31 像素,上方的纯图标选项卡不再保留它们没有的标签的高度,侧边栏的宽度是 168 像素,而不是 200 像素。如果名称太长,则以全文作为其工具提示。折叠调色板的按钮现在也位于调色板的线条上,而不是调色板左边的一个像素,调色板折叠后它就会悬挂在窗口边缘\n规则:当字符串状态的条件尚未输入任何值时,选择触发器的状态会使编辑器关闭,并显示 “n.replace 不是函数”。选择状态会再次编译整个规则,空值作为布尔值 “false” 得出。现在,没有值的条件与空文本进行比较,并且将为状态输入的字符串数字用作其文本\n现在,脚本编辑器每 10 秒告诉适配器它已打开,在这种情况下,适配器会保持类型定义和编译器处于高温状态,因此保存脚本不会等待它们再次构建。在最后一个生命迹象 30 秒后,GUI 算作消失,所有内容都返还了——大约 100 MB。后台的选项卡不算作已打开,因此被遗忘的浏览器选项卡无法使内存存活数天 (#2373)\n无论是否需要它们,每次启动时都会读取 Node.js、IOBroker 和配置库的类型定义。只有两件事能做——编译 TypeScript 脚本和内置编辑器——它们会为编译器增加大约 90 MB,所以现在当其中一个实际提出要求时,它们就会被读取。运行纯 JavaScript 并在其他地方(镜像目录、外部编辑器)编辑的实例永远不会读取它们;全局 JavaScript 的声明是在没有它们的情况下生成的,输出结果相同。它们也可以永久关闭(“加载类型定义”,TypeScript 选项卡)-然后编辑器会丢失自动完成功能,TypeScript 脚本将无法编译,适配器会在日志中警告这一点 (#2373)\n无论是否需要,每个实例都使两个 TypeScript 语言服务处于活动状态,并且每个实例在编译完任何内容后都会保持大约 95 MB 的容量。它们现在仅建立在第一次编译的基础上,并且全局 JavaScript 的声明存储在脚本对象上,就像编译的 TypeScript 源代码一样,因此重启不会再重新生成它们。语言服务最终构建的内容会在上次编译一分钟后再次发布,并按需重建。在测试系统上,这需要一个从 241 MB 到 127 MB 堆的实例(352 MB 到 233 MB RSS)(#2373)\n脚本编辑器自行绘制的帮助程序——每个函数上方的 “解释/重构/测试” 行、对象 ID 和 CRON 表达式的工具提示以及行内代码建议——可以关闭。实例设置 “在脚本编辑器中显示 AI 助手”(AI 设置)可以做到这一点;它默认处于启用状态,因此任何对它们感到满意的人都不会发生任何变化。当光标关闭时,`Alt+I`仍然在光标下方显示对象 ID 的值\n与OpenAI兼容的终端节点的理由被无条件地关闭了:配置了自定义基础网址后,`reasoning_effort: “无” `即取消了每个请求。这对于小型本地模型来说是对的,对其他所有模式来说都是错误的——在代理服务器的背后,它会掩盖人们为之付出代价的理由,或者被拒绝。现在它是一个设置(“推理工作”),默认设置将参数排除在外,让端点决定\nAI 编辑告诉适配器愿意等待多长时间,但适配器从未读过它:嵌入式完成卡住了整整十分钟,而不是要求的十五秒\n内联完成采用了在 AI 聊天中选择的模型,但选择了提供商本身,因此可以使用证书在另一个提供商的端点请求一个提供商的模型。模型和提供商现已被记住并一起使用\n当两个提供商提供同名模型时(例如代理及其背后的供应商),则由最先回答的人决定,并且可以从一次重新加载更改为下一次重新加载。首先配置的提供商现在获胜,因此直接路由优先于代理"
120
- },
121
- "10.1.4": {
122
- "en": "Rules: the text of an action can round the trigger value with `%.1s` - any number of digits after the decimal point, also `%.2old` for the old value - formatted with the decimal separator of the system, so `Kühlschrank zu warm (%.1s°C)` gives `29,4°C` where `%s` gave `29.400000000000002°C`\nCorrected the function block in blockly\nA custom OpenAI-compatible AI endpoint answered \"Invalid API key\" in the inline completion and while loading the model list, although the test button in the settings said \"ok\": both asked the adapter for the provider `openai`, and the adapter picks the key by that name, so they used the \"OpenAI API key\" instead of the \"Custom API key\". The custom endpoint is now addressed as what it is, everywhere (#2369)\nA configured \"Custom API Base URL\" also redirected every request meant for OpenAI itself to that address - with the OpenAI key attached and no way to switch it off. The base URL now belongs to the custom endpoint alone, so both can be used side by side. If the key of your custom endpoint is in the \"OpenAI API key\" field, move it to the \"Custom API key\" field; the adapter writes a warning in the log if it finds such a setup (#2369)",
123
- "de": "Regeln: Der Text einer Aktion kann den Triggerwert mit `%.1s` runden — beliebig viele Nachkommastellen, auch `%.2old` für den alten Wert — formatiert mit dem Dezimaltrennzeichen des Systems, also `Kühlschrank zu warm (%.1s°C) `ergibt `29,4°C`, während `%s` `29.400000000000002°C` ergibt\nFunktionsblock in Blockly korrigiert\nEin benutzerdefinierter OpenAI-kompatibler KI-Endpunkt antwortete beim Laden der Modellliste mit „Ungültiger API-Schlüssel“, obwohl der Testbutton in den Einstellungen „ok“ sagte: Beide fragten den Adapter nach dem Anbieter `openai`, und der Adapter wählt den Schlüssel mit diesem Namen aus, also nutzten sie den „OpenAI API Key“ statt des „Custom API Key“. Der benutzerdefinierte Endpunkt wird jetzt überall behandelt (#2369)\nEine konfigurierte „Custom API Base URL“ leitete auch jede Anfrage für OpenAI an diese Adresse um — mit OpenAI-Key und ohne Abschaltmöglichkeit. Die Basis-URL gehört nun nur zum Endpunkt, also beide nebeneinander. Wenn der Schlüssel Ihres Endpunkts im Feld „OpenAI API Key“ steht, schreibt der Adapter eine Warnung in das Log (#2369)",
124
- "ru": "Правила: в тексте действия можно округлить значение триггера до «%.1s» — любое количество цифр после десятичной точки, а также «%.2old» для старого значения — отформатированное с использованием десятичного разделителя системы, поэтому `Kühlschrank zu warm (%.1s°C) `дает значение `29,4°C`, где `%s` даёт `29,400000000000002°C`\nИсправлен функциональный блок в blockly\nСпециальная конечная точка искусственного интеллекта, совместимая с OpenAI, ответила «Неверный ключ API» при встраиваемом заполнении и загрузке списка моделей, хотя на кнопке тестирования в настройках было написано «ОК»: обе команды запросили у адаптера поставщика `openai`, и адаптер выбирает ключ под этим именем, поэтому вместо «Custom API key» они использовали «ключ OpenAI API». Настраиваемая конечная точка теперь везде рассматривается как есть (#2369)\nНастроенный «Custom API Base URL» также перенаправлял каждый запрос, предназначенный для самого OpenAI, на этот адрес — при этом ключ OpenAI был прикреплен, и его нельзя было отключить. Теперь базовый URL-адрес принадлежит только настраиваемой конечной точке, поэтому их можно использовать одновременно. Если ключ вашей пользовательской конечной точки находится в поле «Ключ OpenAI API», переместите его в поле «Custom API key»; если адаптер обнаружит такую настройку, в журнал запишет предупреждение (#2369)",
125
- "pt": "Regras: o texto de uma ação pode arredondar o valor do gatilho com `%.1s` - qualquer número de dígitos após o ponto decimal, também `%.2old` para o valor antigo - formatado com o separador decimal do sistema. 2°C”\nCorrigiu o bloco de função em bloco\nUm endpoint de IA compatível com OpenAI respondeu “chave de API inválida” no preenchimento em linha e ao carregar a lista de modelos, embora o botão de teste nas configurações dissesse “ok”: ambos pediram ao adaptador o provedor `openai` e o adaptador escolheu a chave com esse nome, então eles usaram a “chave de API OpenAI” em vez da “chave de API personalizada”. O endpoint personalizado agora é o que é, em todo lugar (#2369)\nUm “URL base de API personalizado” também redirecionava cada solicitação do OpenAI para esse endereço — com a chave OpenAI anexada e sem como desligá-la. O URL base agora pertence ao endpoint personalizado e pode ser usado lado a lado. Se a chave do seu endpoint estiver no campo “Chave de API OpenAI”, mova-a para “Chave de API personalizada”; o adaptador grava um aviso no log (#2369)",
126
- "nl": "Regels: de tekst van een actie kan de triggerwaarde afronden met `%.1s` - een willekeurig aantal cijfers achter de komma, ook `%.2oud` voor de oude waarde - opgemaakt met het decimale scheidingsteken van het systeem, zodat `Kühlschrank zu warm (%.1s°C) `geeft `29,4°C` waarbij `%s` `29.4000002°C` gaf\nHet functieblok in blockly gecorrigeerd\nEen aangepast AI-eindpunt dat compatibel is met OpenAI antwoordde „Ongeldige API-sleutel” in de inline-aanvulling en tijdens het laden van de modellenlijst, hoewel op de testknop in de instellingen „OK” stond: beiden vroegen de adapter naar de provider `openai`, en de adapter kiest de sleutel met die naam, dus gebruikten ze de „OpenAI API-sleutel” in plaats van de „Aangepaste API-sleutel”. Het aangepaste eindpunt wordt nu overal weergegeven zoals het is (#2369)\nEen geconfigureerde „Custom API Base URL” heeft ook elk verzoek dat voor OpenAI zelf was bedoeld, omgeleid naar dat adres - met de OpenAI-sleutel eraan gekoppeld en zonder mogelijkheid om het uit te schakelen. De basis-URL behoort nu alleen tot het aangepaste eindpunt, dus beide kunnen naast elkaar worden gebruikt. Als de sleutel van uw aangepaste eindpunt zich in het veld „OpenAI API-sleutel” bevindt, verplaats deze dan naar het veld „Aangepaste API-sleutel”; de adapter schrijft een waarschuwing in het logboek als er een dergelijke instelling wordt gevonden (#2369)",
127
- "fr": "Règles : le texte d'une action peut arrondir la valeur de déclenchement par « %.1s », un nombre quelconque de chiffres après la virgule, et « %.2old » pour l'ancienne valeur, formaté avec le séparateur décimal du système, donc « Kühlschrank zu warm (%.1s°C) » donne « 29,4°C » où « %s` a donné 29,400000000000002°C »\nCorrection du bloc de fonctions dans Blockly\nUn terminal IA personnalisé compatible avec OpenAI a répondu « Clé API non valide » en ligne et en chargeant la liste des modèles, mais le bouton de test des paramètres indiquait « OK » : les deux ont demandé à l'adaptateur le fournisseur « openai », et l'adaptateur a choisi la clé portant ce nom. Ils ont donc utilisé la « clé API OpenAI » au lieu de la « clé API personnalisée ». Le point de terminaison personnalisé est désormais traité tel quel, partout (#2369)\nUne « URL de base API personnalisée » configurée redirigeait toutes les requêtes destinées à OpenAI vers cette adresse, avec la clé OpenAI attachée, sans moyen de la désactiver. L'URL de base n'appartient qu'au point de terminaison personnalisé, donc côte à côte. Si la clé de votre terminal personnalisé se trouve dans le champ « Clé API OpenAI », l'adaptateur écrit un avertissement dans le journal s'il détecte une telle configuration (#2369)",
128
- "it": "Regole: il testo di un'azione può arrotondare il valore del trigger con «%.1s» - qualsiasi numero di cifre dopo la virgola, anche «%.2old» per il vecchio valore - con il separatore decimale del sistema, quindi «Kühlschrank zu warm (%.1s°C)» dà «29,4°C» dove «%s» dà «29.40000000000000000\" 02 °C»\nCorretto il blocco funzione in blocco\nUn endpoint AI personalizzato compatibile con OpenAI ha risposto «Chiave API non valida» nel completamento in linea e durante il caricamento dell'elenco dei modelli, anche se il pulsante di test diceva «ok»: entrambi hanno chiesto al provider «openai» e l'adattatore ha scelto la chiave con quel nome. L'endpoint personalizzato ora è così, ovunque (#2369)\nUn «Custom API Base URL» reindirizzava anche tutte le richieste di OpenAI a quell'indirizzo, con la chiave OpenAI allegata e senza modo di spegnerla. L'URL di base ora appartiene solo all'endpoint personalizzato. Se la chiave del suo endpoint è nel campo «OpenAI API key», la sposti nel campo «Custom API key»; l'adattatore scrive un avviso nel log se trova tale setup (#2369)",
129
- "es": "Reglas: el texto de una acción puede redondear el valor de activación con `%.1s` (cualquier número de dígitos después de la coma decimal, también `%.2old» para el valor anterior, formateado con el separador decimal del sistema, por lo que `Kühlschrank zu warm (%.1s°C) `da 29,4°C`, donde `%s` daba 29,40000000002°C\nSe corrigió el bloque de funciones en blockly\nUn punto final de IA personalizado compatible con OpenAI respondió «Clave de API no válida» al terminar en línea y al cargar la lista de modelos, aunque el botón de prueba de la configuración decía «vale»: ambos pidieron al adaptador el proveedor `openai` y el adaptador escogió la clave con ese nombre, por lo que usaron la «clave de API de OpenAI» en lugar de la «clave de API personalizada». El punto final personalizado ahora se dirige como es, en todas partes (#2369)\nUna «URL base de API personalizada» configurada también redirigía todas las solicitudes de OpenAI a esa dirección, con la clave de OpenAI adjunta y sin forma de desactivarla. La URL base ahora pertenece solo al punto final personalizado, por lo que pueden usarse. Si la clave de su punto final personalizado está en el campo «Clave API OpenAI», muévala al campo «Clave API personalizada»; el adaptador escribe un aviso en el registro si encuentra esa configuración (#2369)",
130
- "pl": "Reguły: tekst akcji może zaokrąglić wartość wyzwalającą o `%.1s` - dowolną liczbę cyfr po przecinku, także `%.2old` dla starej wartości - sformatowaną za pomocą separatora dziesiętnego systemu, więc `Kühlschrank zu warm (%.1s°C) `daje `29,4°C` gdzie `%s` dało `29.400000000000002°C`\nPoprawiono blok funkcji w bloku\nNiestandardowy punkt końcowy AI zgodny z OpenAI odpowiedział na „Nieprawidłowy klucz API” podczas uzupełniania linii i podczas ładowania listy modeli, chociaż przycisk testowy w ustawieniach powiedział „ok”: obaj poprosili adapter o dostawcę `openai`, a adapter wybiera klucz pod tą nazwą, więc użyli „klucza API OpenAI” zamiast „Custom API key”. Niestandardowy punkt końcowy jest teraz adresowany tak, jak jest, wszędzie (#2369)\nSkonfigurowany „Custom API Base URL” przekierował również każde żądanie przeznaczone dla samego OpenAI na ten adres - z dołączonym kluczem OpenAI i bez możliwości jego wyłączenia. Podstawowy adres URL należy teraz do samego niestandardowego punktu końcowego, więc oba mogą być używane obok siebie. Jeśli klucz niestandardowego punktu końcowego znajduje się w polu „Klucz API OpenAI”, przenieś go do pola „Custom API key”; adapter zapisuje ostrzeżenie w dzienniku, jeśli znajdzie taką konfigurację (#2369)",
131
- "uk": "Правила: текст дії може округлити значення тригера з `%.1s `- будь-якою кількістю цифр після десяткової коми, також `%.2old` для старого значення - відформатоване десятковим роздільником системи, тому `Kühlschrank zu warm (%.1s°C)` дає `29,4°C`, де `%s` дав `29.400000000000002°C`\nВиправлено функціональний блок в blockly\nСпеціальна кінцева точка AI, сумісна з OpenAI, відповіла «Недійсний ключ API» у вбудованому доповненні та під час завантаження списку моделей, хоча на кнопці тестування в налаштуваннях було написано «ok»: обидва запитали у адаптера постачальника `openai`, а адаптер вибирає ключ під цим ім'ям, тому вони використовували «ключ API OpenAI» замість «Custom API key». Користувацьку кінцеву точку тепер адресовано як те, що вона є, скрізь (#2369)\nНалаштована «Custom API Base URL» також перенаправляла кожен запит, призначений для самої OpenAI, на цю адресу - з прикріпленим ключем OpenAI і без можливості його вимкнути. Базова URL-адреса тепер належить лише користувацькій кінцевій точці, тому обидві можуть бути використані поруч. Якщо ключ вашої користувацької кінцевої точки знаходиться в полі «OpenAI API key», перемістіть його в поле «Custom API key»; адаптер записує попередження в журнал, якщо знайде таку настройку (#2369)",
132
- "zh-cn": "规则:动作文本可以用 `%.1s` 对触发值进行四舍五入——小数点后的任意位数,旧值也是 `%.2old` ——使用系统的十进制分隔符进行格式化,因此 `Kühlschrank zu warm (%.1s°C) `给出 `29,4°C`,其中 `%s` 给出 `29.4000000000002°C`\n方块更正了功能块\n一个兼容 OpenAI 的自定义 AI 端点在行内完成和加载模型列表时回答 “无效 API 密钥”,尽管设置中的测试按钮显示 “确定”:两者都要求适配器提供提供商 “openai”,而适配器按该名称选择密钥,因此他们使用 “OpenAI API 密钥” 而不是 “自定义 API 密钥”。现在,自定义终端节点随处可见 (#2369)\n配置的 “自定义API基础网址” 还将所有发送给OpenAI本身的请求重定向到该地址——附加了OpenAI密钥,无法将其关闭。基本 URL 现在仅属于自定义端点,因此两者可以并排使用。如果您的自定义终端节点的密钥位于 “OpenAI API 密钥” 字段中,请将其移至 “自定义 API 密钥” 字段;如果适配器发现此类设置,则会在日志中写入警告 (#2369)"
133
133
  }
134
134
  },
135
135
  "platform": "Javascript/Node.js",
@@ -611,7 +611,7 @@
611
611
  "language": "javascript",
612
612
  "views": {
613
613
  "javascript": {
614
- "map": "function(doc) { if (doc.type === 'script' && doc.common.engineType.match(/^[jJ]ava[sS]cript|^[cC]offee[sS]cript|^[tT]ype[sS]cript|^Blockly|^Rules/)) emit(doc.common.name, doc); }"
614
+ "map": "function(doc) { if (doc.type === 'script' && doc.common.engineType.match(/^[jJ]ava[sS]cript|^[cC]offee[sS]cript|^[tT]ype[sS]cript|^Blockly|^Rules|^FBD/)) emit(doc.common.name, doc); }"
615
615
  }
616
616
  }
617
617
  },
@@ -907,6 +907,30 @@
907
907
  "write": false
908
908
  },
909
909
  "native": {}
910
+ },
911
+ {
912
+ "_id": "debug.fbd",
913
+ "type": "state",
914
+ "common": {
915
+ "name": {
916
+ "en": "Values of a function block diagram for the online view",
917
+ "de": "Werte eines Funktionsplans für die Onlineansicht",
918
+ "ru": "Значения функциональной блок-схемы для онлайн-просмотра",
919
+ "pt": "Valores de um diagrama de blocos funcionais para a vista online",
920
+ "nl": "Waarden van een functieblokdiagram voor de online weergave",
921
+ "fr": "Valeurs d'un diagramme de blocs fonctionnels pour la vue en ligne",
922
+ "it": "Valori di un diagramma a blocchi funzionali per la vista online",
923
+ "es": "Valores de un diagrama de bloques de funciones para la vista en línea",
924
+ "pl": "Wartości diagramu bloków funkcyjnych dla widoku online",
925
+ "uk": "Значення функціональної блок-схеми для онлайн-перегляду",
926
+ "zh-cn": "功能块图在线视图的数值"
927
+ },
928
+ "type": "string",
929
+ "role": "json",
930
+ "read": true,
931
+ "write": false
932
+ },
933
+ "native": {}
910
934
  }
911
935
  ]
912
936
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "iobroker.javascript",
3
- "version": "10.2.5",
3
+ "version": "10.3.0",
4
4
  "description": "Rules Engine for ioBroker",
5
5
  "author": "bluefox <dogafox@gmail.com>",
6
6
  "contributors": [
@@ -1,27 +0,0 @@
1
- import{Bt as e,Cn as t,Er as n,Gn as r,Hn as i,Ht as a,Mn as o,On as s,Qt as c,Rt as l,Sr as u,Tn as d,Ut as f,Vt as p,Wt as m,Zt as h,_r as g,bt as _,dt as v,er as y,hn as b,jn as x,kn as S,m as C,mn as w,mr as T,tr as E,xn as ee,xr as D,xt as O,yr as k,yt as A}from"./_virtual_mf___mfe_internal__iobroker_javascript__mf_owner__180366418666083__loadShare___mf_0_iobroker_mf_1_gui_mf_2_components__loadShare__.js-BEpNZh4U.js";import{t as j}from"./vite-preload-helper-CaC3yEL3.js";import{S as M,g as te,h as N,m as P,s as F}from"./index-B3s0zmWC.js";import{a as I,c as L,d as R,f as z,h as B,i as V,l as H,m as U,n as W,o as G,p as K,r as ne,s as q,t as J,u as Y}from"./AiChatService-BOL3J2Jd.js";var X=i(y(`path`,{d:`M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2m5 11h-4v4h-2v-4H7v-2h4V7h2v4h4z`}),`AddCircleOutlined`),re=i(y(`path`,{d:`M21.99 4c0-1.1-.89-2-1.99-2H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h14l4 4zM17 11h-4v4h-2v-4H7V9h4V5h2v4h4z`}),`AddComment`),ie=i(y(`path`,{d:`M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10h5v-2h-5c-4.34 0-8-3.66-8-8s3.66-8 8-8 8 3.66 8 8v1.43c0 .79-.71 1.57-1.5 1.57s-1.5-.78-1.5-1.57V12c0-2.76-2.24-5-5-5s-5 2.24-5 5 2.24 5 5 5c1.38 0 2.64-.56 3.54-1.47.65.89 1.77 1.47 2.96 1.47 1.97 0 3.5-1.6 3.5-3.57V12c0-5.52-4.48-10-10-10m0 13c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3`}),`AlternateEmail`),ae=i(y(`path`,{d:`M9.01 14H2v2h7.01v3L13 15l-3.99-4zm5.98-1v-3H22V8h-7.01V5L11 9z`}),`CompareArrows`),oe=i(y(`path`,{d:`M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4m0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4`}),`Person`),se=i(y(`path`,{d:`M3 10h11v2H3zm0-4h11v2H3zm0 8h7v2H3zm17.59-2.07-4.25 4.24-2.12-2.12-1.41 1.41L16.34 19 22 13.34z`}),`PlaylistAddCheck`),ce=i(y(`path`,{d:`M20 9V7c0-1.1-.9-2-2-2h-3c0-1.66-1.34-3-3-3S9 3.34 9 5H6c-1.1 0-2 .9-2 2v2c-1.66 0-3 1.34-3 3s1.34 3 3 3v4c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2v-4c1.66 0 3-1.34 3-3s-1.34-3-3-3M7.5 11.5c0-.83.67-1.5 1.5-1.5s1.5.67 1.5 1.5S9.83 13 9 13s-1.5-.67-1.5-1.5M16 17H8v-2h8zm-1-4c-.83 0-1.5-.67-1.5-1.5S14.17 10 15 10s1.5.67 1.5 1.5S15.83 13 15 13`}),`SmartToy`);n();var le=[{type:`function`,function:{name:`search_datapoints`,description:`Search ALL ioBroker objects by ID, name, or role — includes states, channels, devices, folders, enums (rooms/functions), adapters, instances, scripts, meta, etc. Returns matching IDs with object type, name, role, unit, and a hasChildren hint for containers. IMPORTANT: Aliases and physical device groupings are usually CHANNELS containing multiple state children (e.g. a motion sensor is often a channel alias.0.Floor.Room.MotionSensor with states ACTUAL, BATTERY, STATE under it). If a channel/device/folder matches your query, call get_object_info on its ID to list its state children. Role-based queries work too: "sensor.motion", "switch.light", "value.temperature".`,parameters:{type:`object`,properties:{query:{type:`string`,description:`Search pattern (case-insensitive substring) - matches against object ID, name, and role. Examples: "bewegungsmelder", "temperature", "sensor.motion", "alias.0", "küche", "zigbee2mqtt.0.lamp".`},max_results:{type:`number`,description:`Maximum number of results to return (default: 20).`},object_type:{type:`string`,description:`Optional filter by object type: "state", "channel", "device", "folder", "enum", "adapter", "instance", "script", "meta", etc. Omit to search every type.`}},required:[`query`]}}},{type:`function`,function:{name:`get_state_value`,description:`Get the current value of an ioBroker state/datapoint. Returns value, timestamp, and acknowledgment flag.`,parameters:{type:`object`,properties:{id:{type:`string`,description:`The full state ID, e.g. "zigbee2mqtt.0.sensor.temperature"`}},required:[`id`]}}},{type:`function`,function:{name:`get_object_info`,description:`Get detailed info about ANY ioBroker object + its full parent hierarchy + direct children. Works for every object type: state, channel, device, folder, adapter, instance, enum, meta, script. Returns: the object itself, parent chain (all non-state ancestors up to the adapter), and — if the object is a container (channel/device/folder/enum/instance/adapter/meta) — the list of direct children with their types, names, roles and units. Use this to navigate the object tree: start from a channel found by search_datapoints, read its children to see the actual state IDs underneath.`,parameters:{type:`object`,properties:{id:{type:`string`,description:`The full object ID, e.g. "zigbee2mqtt.0.0x1234.state", "alias.0.Room.MotionSensor", or "enum.rooms.kitchen".`}},required:[`id`]}}},{type:`function`,function:{name:`search_scripts`,description:`Search through all ioBroker JavaScript/Blockly/Rules scripts. Can search by script name/path OR by content (e.g. find all scripts that use a specific datapoint ID). Returns matching script names, paths, and matching lines.`,parameters:{type:`object`,properties:{query:{type:`string`,description:`Search term - matches against script name, path, AND source code content. Examples: "carport", "zigbee2mqtt.0.lamp.state", "telegram"`},max_results:{type:`number`,description:`Maximum number of scripts to return (default: 10)`}},required:[`query`]}}},{type:`function`,function:{name:`read_script`,description:`Read the full source code of a specific ioBroker script by its ID or path. Use search_scripts first to find the script ID, then read_script to see its complete code.`,parameters:{type:`object`,properties:{id:{type:`string`,description:`The script ID (e.g. "script.js.common.Licht.Carport") or path (e.g. "common/Licht/Carport")`}},required:[`id`]}}},{type:`function`,function:{name:`list_scripts`,description:`List ALL available ioBroker scripts with their names, paths, types (JavaScript/Blockly/TypeScript), and enabled status. Use this to get an overview of all scripts before searching or reading specific ones.`,parameters:{type:`object`,properties:{}}}},{type:`function`,function:{name:`run_script`,description:"Execute a JavaScript or TypeScript snippet in the live ioBroker javascript engine and get back everything it logged. The code runs with the full script API (log, console.*, setState, getState, on, schedule, $, exec, httpGet, …) in VERBOSE mode, so internal operations (setState/getState/subscribe/…) are logged too — ideal for diagnosing behaviour or inspecting values. The snippet runs for a short window and is then automatically STOPPED and fully cleaned up (timers, subscriptions, schedules removed); it does NOT create a persistent script. Use `log(...)` or `console.log(...)` in the code to surface the values you want to inspect. WARNING: side effects are real (e.g. setState changes actual devices) — prefer read-only diagnostics unless the user explicitly asked to change something.",parameters:{type:`object`,properties:{source:{type:`string`,description:`The JavaScript (or TypeScript) source to execute. Log the values you want to inspect via log(...) / console.log(...). Top-level await is supported.`},engineType:{type:`string`,description:`Optional. "TypeScript/ts" to run the code as TypeScript. Defaults to JavaScript.`},timeout:{type:`number`,description:`Optional. Milliseconds to keep the script alive to collect asynchronous logs before it is stopped (default 5000, max 60000). Increase when waiting for timers, subscriptions or HTTP responses.`},logLevel:{type:`string`,description:`Optional minimum severity to return: silly, debug, info, warn, error. Default silly (everything).`}},required:[`source`]}}},{type:`function`,function:{name:`get_editor_selection`,description:`Read what the user has currently selected in the script editor. Returns the selected text and its line/column range, or a message if nothing is selected. Use this when the user refers to "this", "das hier", "the selection", or asks about a specific piece of code they highlighted.`,parameters:{type:`object`,properties:{}}}},{type:`function`,function:{name:`get_editor_content`,description:`Read the full current content of the script editor (may differ from the initial script version if the user has made edits). Use this when you need the live editor state rather than the saved script.`,parameters:{type:`object`,properties:{}}}},{type:`function`,function:{name:`get_cursor_position`,description:`Read the current cursor position (line and column, 1-based) in the script editor.`,parameters:{type:`object`,properties:{}}}},{type:`function`,function:{name:`highlight_text_in_editor`,description:`Search for a literal text in the script editor and select + scroll to it. Returns how many occurrences were found. Use this to draw the user's attention to a specific snippet you are discussing.`,parameters:{type:`object`,properties:{text:{type:`string`,description:`Exact substring to search for (case-sensitive).`}},required:[`text`]}}},{type:`function`,function:{name:`highlight_line_range`,description:`Select and scroll to a range of lines in the editor. Both line numbers are 1-based and inclusive. Use this to show the user which block of code you are referring to.`,parameters:{type:`object`,properties:{start_line:{type:`number`,description:`First line (1-based, inclusive).`},end_line:{type:`number`,description:`Last line (1-based, inclusive).`}},required:[`start_line`,`end_line`]}}},{type:`function`,function:{name:`go_to_line`,description:`Move the cursor to a specific line (and optional column) and scroll that line into view. Use this to navigate the user to a relevant spot.`,parameters:{type:`object`,properties:{line:{type:`number`,description:`1-based line number.`},column:{type:`number`,description:`1-based column (optional, default 1).`}},required:[`line`]}}},{type:`function`,function:{name:`insert_text_at_cursor`,description:`Insert text at the current cursor position in the editor (or replace the current selection if one exists). Use sparingly — prefer returning code in a fenced markdown block so the user can review and smart-apply it. Only use direct insertion when the user explicitly asked you to write something into the editor.`,parameters:{type:`object`,properties:{text:{type:`string`,description:`Text to insert.`}},required:[`text`]}}},{type:`function`,function:{name:`replace_selection`,description:`Replace the currently selected text in the editor with new text. Fails if nothing is selected. Use this to refactor or rewrite a specific highlighted snippet.`,parameters:{type:`object`,properties:{text:{type:`string`,description:`Replacement text.`}},required:[`text`]}}},{type:`function`,function:{name:`get_diagnostics`,description:`Read all active Monaco diagnostics (errors, warnings, info, hints) from the current editor model — this is what shows up as red/yellow squiggles. Use this to find syntax errors, unused variables, missing types, or other editor-reported issues the user might be asking about.`,parameters:{type:`object`,properties:{}}}},{type:`function`,function:{name:`get_document_symbols`,description:`Get the document outline of the current script: all top-level functions, classes, constants, and variables with their line numbers. Use this to understand the structure of a long script or to find where a specific function is defined.`,parameters:{type:`object`,properties:{}}}}];function Z(e){return e&&typeof e==`object`?e.en||e.de||``:e||``}function ue(e,t,n){let r=(n||``).toLowerCase();if(!r)return!1;if(e.toLowerCase().includes(r))return!0;let i=t==null?void 0:t.common;if(!i)return!1;let a=Z(i.name).toLowerCase();if(a&&a.includes(r))return!0;let o=(i.role||``).toLowerCase();return!!(o&&o.includes(r))}async function de(e,t,n=20,r){let i=await I(e),a=r==null?void 0:r.toLowerCase(),o=[],s=Object.keys(i),c=new Set;for(let e of s){let t=e.lastIndexOf(`.`);t>0&&c.add(e.substring(0,t))}for(let e of s){let r=i[e],s=r==null?void 0:r.type;if(!s||a&&s!==a||!ue(e,r,t))continue;let l=r.common,u={id:e,type:s,name:Z(l==null?void 0:l.name)};if(l!=null&&l.role&&(u.role=l.role),s===`state`?(u.stateType=(l==null?void 0:l.type)||``,l!=null&&l.unit&&(u.unit=l.unit)):c.has(e)&&(u.hasChildren=!0),o.push(u),o.length>=n)break}return o.length===0?JSON.stringify({message:`No objects found matching "${t}". Hint: try a role like "sensor.motion" or a partial path.`}):JSON.stringify(o)}async function fe(e,t){try{let n=await e.getState(t);return JSON.stringify(n?{val:n.val,ts:n.ts?new Date(n.ts).toISOString():null,ack:n.ack,from:n.from}:{error:`State '${t}' not found`})}catch{return JSON.stringify({error:`Failed to read state '${t}'`})}}var pe=new Set([`channel`,`device`,`folder`,`adapter`,`instance`,`enum`,`meta`]),me=50;async function he(e,t){try{let r=await e.getObject(t);if(!r)return JSON.stringify({error:`Object '${t}' not found`});let i={id:r._id,type:r.type,common:r.common},a=t.split(`.`),o=[];for(let t=a.length-1;t>=2;t--){let r=a.slice(0,t).join(`.`);try{let t=await e.getObject(r);if(t&&t.type!==`state`){var n;o.push({id:t._id,type:t.type,name:Z((n=t.common)==null?void 0:n.name),common:t.common})}}catch{}}if(o.length>0&&(i.parents=o),pe.has(r.type)){let n=await I(e),r=[],a=`${t}.`,o=!1;for(let e of Object.keys(n))if(e.startsWith(a)&&!e.substring(a.length).includes(`.`)){let t=n[e],i=t==null?void 0:t.common,a={id:e,name:Z(i==null?void 0:i.name),type:(t==null?void 0:t.type)||``};if(i!=null&&i.role&&(a.role=i.role),(t==null?void 0:t.type)===`state`&&i!=null&&i.unit&&(a.unit=i.unit),r.push(a),r.length>=me){o=!0;break}}r.length>0&&(i.children=r,o&&(i.childrenTruncated=!0,i.childrenHint=`Only the first ${me} children are shown. Use search_datapoints with a more specific query or the object_type filter to narrow down.`))}return JSON.stringify(i)}catch{return JSON.stringify({error:`Failed to read object '${t}'`})}}function ge(e){return N(e)||e}function _e(e,t,n=10){let r=t.toLowerCase(),i=[];for(let t of e){let e=t.id.toLowerCase(),a=t.name.toLowerCase(),o=t.id.replace(/^script\.js\./,``).replace(/\./g,`/`),s=t.engineType===`Blockly`||t.engineType===`Rules`,c=e.includes(r)||a.includes(r),l=s?ge(t.source):t.source,u=l.toLowerCase().includes(r);if(c||u){let e={id:t.id,path:o,name:t.name,type:s?`Blockly`:t.engineType.includes(`TypeScript`)?`TypeScript`:`JavaScript`,enabled:t.enabled};if(u){let t=l.split(`
2
- `),n=[];for(let e=0;e<t.length&&!(t[e].toLowerCase().includes(r)&&(n.push({line:e+1,text:t[e].trim()}),n.length>=5));e++);n.length>0&&(e.matchingLines=n)}if(i.push(e),i.length>=n)break}}return i.length===0?JSON.stringify({message:`No scripts found matching "${t}"`}):JSON.stringify(i)}function ve(e,t){let n=t.replace(/\//g,`.`).toLowerCase(),r=e.find(e=>{let t=e.id.toLowerCase();return t===n||t===`script.js.${n}`||t.endsWith(`.${n}`)});if(!r)return JSON.stringify({error:`Script '${t}' not found. Use search_scripts to find available scripts.`});let i=r.engineType===`Blockly`||r.engineType===`Rules`,a=i?ge(r.source):r.source,o=r.id.replace(/^script\.js\./,``).replace(/\./g,`/`);return JSON.stringify({id:r.id,path:o,name:r.name,type:i?`Blockly`:r.engineType.includes(`TypeScript`)?`TypeScript`:`JavaScript`,enabled:r.enabled,source:a})}function ye(e){let t=e.map(e=>({id:e.id,path:e.id.replace(/^script\.js\./,``).replace(/\./g,`/`),name:e.name,type:e.engineType===`Blockly`||e.engineType===`Rules`?`Blockly`:e.engineType.includes(`TypeScript`)?`TypeScript`:`JavaScript`,enabled:e.enabled}));return JSON.stringify(t)}function Q(){return JSON.stringify({error:`Editor is not available. This tool requires the script editor to be open.`})}async function be(e,t,n){if(!t)return JSON.stringify({error:`No running javascript instance found to execute the script.`});let r=n.source;if(!r||typeof r!=`string`)return JSON.stringify({error:`No source code provided.`});try{var i;let a=await e.sendTo(t,`execute`,{source:r,engineType:n.engineType,timeout:n.timeout,logLevel:n.logLevel});return!a||a.ok===!1?JSON.stringify({error:(a==null?void 0:a.error)||`Execution failed`,logs:(a==null?void 0:a.logs)||[]}):JSON.stringify({engineType:a.engineType,runtime:a.runtime,truncated:a.truncated||!1,logCount:((i=a.logs)==null?void 0:i.length)||0,logs:a.logs||[],output:a.output||``})}catch(e){return JSON.stringify({error:`Failed to execute script: ${e instanceof Error?e.message:String(e)}`})}}async function xe(e,t,n,r,i){let a;try{a=JSON.parse(t.function.arguments)}catch{return JSON.stringify({error:`Invalid arguments: ${t.function.arguments}`})}switch(t.function.name){case`search_datapoints`:return de(e,a.query,a.max_results||20,a.object_type);case`get_state_value`:return fe(e,a.id);case`get_object_info`:return he(e,a.id);case`search_scripts`:return _e(n||[],a.query,a.max_results||10);case`read_script`:return ve(n||[],a.id);case`list_scripts`:return ye(n||[]);case`run_script`:return be(e,i,a);case`get_editor_selection`:{if(!(r!=null&&r.getSelection))return Q();let e=r.getSelection();return JSON.stringify(e||{message:`No text is currently selected in the editor.`})}case`get_editor_content`:return r!=null&&r.getContent?JSON.stringify({content:r.getContent()}):Q();case`get_cursor_position`:{if(!(r!=null&&r.getCursorPosition))return Q();let e=r.getCursorPosition();return JSON.stringify(e||{message:`Editor has no cursor position (not focused).`})}case`highlight_text_in_editor`:{if(!(r!=null&&r.highlightText))return Q();let e=r.highlightText(a.text);return JSON.stringify({matches:e,message:e===0?`Text "${a.text}" was not found in the editor.`:`Highlighted ${e} occurrence(s) of "${a.text}".`})}case`highlight_line_range`:{if(!(r!=null&&r.highlightLineRange))return Q();let e=r.highlightLineRange(a.start_line,a.end_line);return JSON.stringify({success:e,message:e?`Selected lines ${a.start_line}-${a.end_line}.`:`Could not select the requested line range.`})}case`go_to_line`:{if(!(r!=null&&r.goToLine))return Q();let e=r.goToLine(a.line,a.column);return JSON.stringify({success:e,message:e?`Cursor moved to line ${a.line}.`:`Could not move the cursor.`})}case`insert_text_at_cursor`:{if(!(r!=null&&r.insertTextAtCursor))return Q();let e=r.insertTextAtCursor(a.text);return JSON.stringify({success:e,message:e?`Text inserted at cursor.`:`Editor rejected the insertion.`})}case`replace_selection`:{if(!(r!=null&&r.replaceSelection))return Q();let e=r.replaceSelection(a.text);return JSON.stringify({success:e,message:e?`Selection replaced.`:`No text was selected to replace.`})}case`get_diagnostics`:{if(!(r!=null&&r.getDiagnostics))return Q();let e=r.getDiagnostics();return JSON.stringify({count:e.length,diagnostics:e})}case`get_document_symbols`:{if(!(r!=null&&r.getSymbols))return Q();let e=await r.getSymbols();return JSON.stringify({count:e.length,symbols:e})}default:return JSON.stringify({error:`Unknown tool: ${t.function.name}`})}}var Se=0;function Ce(){return`msg_${Date.now()}_${++Se}`}function we(e){let{socket:t,runningInstances:n,currentCode:r,currentLanguage:i,allScripts:a,editorApi:o,currentScriptId:s}=e,c=T((e,t,n)=>e===`none`||!n?null:{range:t,scriptId:s||``,scriptVersion:(r||``).length,kind:e,originalText:n},[s,r]),[l,d]=u(()=>{try{let e=window.localStorage.getItem(`Editor.aiChatMessages`);return e?JSON.parse(e):[]}catch{return[]}}),f=T(e=>{d(t=>{let n=typeof e==`function`?e(t):e,r=n.length>100?n.slice(-100):n;try{window.localStorage.setItem(`Editor.aiChatMessages`,JSON.stringify(r))}catch{try{let e=r.slice(-20);window.localStorage.setItem(`Editor.aiChatMessages`,JSON.stringify(e))}catch{}}return r})},[]),[p,m]=u(!1),[h,_]=u(null),[v,y]=u(window.localStorage.getItem(`Editor.aiChatMode`)||`agent`),b=T(e=>{y(e),window.localStorage.setItem(`Editor.aiChatMode`,e)},[]),[x,S]=u(null),[w,E]=u(window.localStorage.getItem(`openai-model`)||``),[ee,O]=u([]),[k,A]=u({}),[M,N]=u(!0),[F,I]=u(null),W=D(null),J=D(null),X=D(null),re=D(null),ie=T(e=>{E(e),K(e,k[e])},[k]),ae=T(async()=>{N(!0),I(null);try{let e=await R(t,n);if(O(e.models),A(e.providerMap),e.models.length>0){let t=z().model,n=t&&e.models.includes(t)?t:e.models[0];E(n),K(n,e.providerMap[n])}e.errors.length>0&&I(e.errors.join(`; `))}catch(e){I(String(e))}N(!1)},[t,n]);g(()=>{ae()},[ae]);let oe=T(e=>{let t=!1,n=!1,r=[],i=!1,o=/@([\w/äöüÄÖÜß-]+)/g,s;for(;(s=o.exec(e))!==null;){let e=s[1].toLowerCase();if(e===`alle`||e===`all`)t=!0;else if(e===`geräte`||e===`devices`||e===`geraete`)n=!0;else if(i=!0,a&&a.length>0){let e=s[1].replace(/\//g,`.`).toLowerCase(),t=e.split(`.`),n=a.find(n=>{let r=n.id.toLowerCase(),i=r.replace(/^script\.js\./,``);if(i===e||i.endsWith(`.${e}`)||r===`script.js.${e}`)return!0;let a=0;for(let e of t){let t=i.indexOf(e,a);if(t===-1)return!1;a=t+e.length}return!0});if(n)r.push(n.id);else for(let e of t){if(e.length<3)continue;let t=a.filter(t=>t.id.toLowerCase().includes(`.${e}`)||t.name.toLowerCase().includes(e));for(let e of t)r.includes(e.id)||r.push(e.id)}}}return i&&r.length===0&&(t=!0),{cleanMessage:e.replace(/@[\w/äöüÄÖÜß]+\s*/g,``).trim(),mentionedScriptIds:r,includeAll:t,includeDevices:n}},[a]),se=T(async(e,o,s)=>{re.current||=await H(),W.current||=await G(t,n);let c=Y(),l=i===`blockly`,u=e||s.length>0,d=`You are an AI assistant for ioBroker JavaScript adapter scripting. Help the user write, debug, and understand ioBroker scripts. Write comments in ${c}. Use the ioBroker JavaScript API correctly.
3
-
4
- ioBroker object hierarchy: adapter.instance.device.channel.state
5
- - A "state" is a single datapoint (e.g. zigbee2mqtt.0.0x1234.temperature)
6
- - A "channel" groups related states (e.g. zigbee2mqtt.0.0x1234 contains temperature, humidity, battery)
7
- - A "device" groups channels (e.g. zigbee2mqtt.0.0x1234)
8
- - The channel/device often has the human-readable name (e.g. "Living Room Sensor")
9
- When looking up info about a datapoint, ALWAYS also check its parent channel/device for the device name and context. Use get_object_info which returns the full parent hierarchy automatically.
10
-
11
- To verify code or diagnose runtime behaviour, you can use the run_script tool: it executes a JavaScript/TypeScript snippet in the live engine (verbose mode) and returns everything it logged, then auto-stops it. Log the values you want to inspect via log(...) / console.log(...). It runs against the live system, so prefer read-only diagnostics (getState, $, getObject) and only call setState when the user explicitly asked to change something.
12
-
13
- Available API and syntax rules:
14
- ${re.current}`;if(l&&(d+="\n\nThe user is working in the Blockly visual editor. When asked to create or modify code, respond with Blockly XML in a ```xml code block instead of JavaScript."),(o||e)&&(X.current||=await V(t),d+=`\n\nAvailable smart home devices:\n${JSON.stringify(X.current,null,0)}`),!u&&r){if(l){let e=r.indexOf(`%%BLOCKLY_XML%%`),t=e===-1?r:r.substring(0,e).trim(),n=e===-1?``:r.substring(e+15).trim();d+=`\n\nThe user is working on this Blockly script (currently open in the editor).\n\nGenerated JavaScript (shows the logic):\n\`\`\`javascript\n${t}\n\`\`\``,n&&(d+=`\n\nBlockly XML (use for modifications):\n\`\`\`xml\n${n}\n\`\`\``)}else d+=`\n\nThe user's question is about this script (currently open in the editor, ${i||`javascript`}):\n\`\`\`${i||`javascript`}\n${r}\n\`\`\``}if(e&&a&&a.length>0)d+=`\n\nThe user requested ALL scripts. Search through all of them to answer the question. Always identify WHICH script you describe by its full ID. Scripts may reference datapoint IDs via variables.\n\n${P(a,!0)}`;else if(s.length>0&&a){let e=a.filter(e=>s.includes(e.id));e.length>0&&(d+=`\n\nIMPORTANT: The user is asking about the following script(s). Answer ONLY about these scripts, NOT about the currently open editor tab. Analyze the source code below carefully:\n\n${P(e,!0)}`)}return l&&(d+=`\n\n${q(c)}`),[{role:`system`,content:d}]},[t,n,r,i,a]),ce=T(async e=>{if(!e.trim()||p)return;let r=k[w];if(!r){S(C.t(`Please select a valid model`));return}let a=W.current||await G(t,n);if(W.current=a,!a){S(C.t(`No API keys configured`));return}let o=Object.keys(n)[0];if(!o){S(C.t(`No running javascript instance found`));return}let s=r===`custom`&&a.gptBaseUrl||``,c={id:Ce(),role:`user`,content:e,timestamp:Date.now()},l={id:Ce(),role:`assistant`,content:`⏳ ${C.t(`Generating plan...`)}`,timestamp:Date.now()};f(e=>[...e,c,l]),m(!0),S(null);try{let n=Y();X.current||=await V(t);let a=X.current||[],c=`Devices in my smart home:\n${JSON.stringify(a)}\n\nI need a plan for this task: ${e}\n\nAnswer with max 6 lines. Use FULL device IDs from the list above (e.g. zigbee2mqtt.0.0xa4c1383f5ef5fb07.state). No explanation. No reasoning.\n1. IDs: <full IDs from the device list. If a device is not in the list, use TODO_DEVICE_ID as placeholder>\n2. Trigger: <on(id) for state changes OR schedule('min hour * * *') for time-based tasks>\n3. Condition: <when to act>\n4. Actions: <what to set, with full IDs and values. For Telegram use sendTo('telegram.0', 'send', {text: msg})>\n5. Else: <alternative actions or nothing>\n6. Extra: <logging, formatting, etc.>\nValues are boolean (true/false) or numbers, not strings. Use .state not .state_toggle.`,l=await U(t,o,{messages:[{role:`user`,content:c}],model:w,provider:r,baseUrl:s});if(l.error){S(l.error),f(e=>e.slice(0,-2)),m(!1);return}let u=B(l.content||``);f(e=>{let t=[...e],n=t[t.length-1];return(n==null?void 0:n.role)===`assistant`&&(t[t.length-1]={...n,content:`📋 **${C.t(`Plan`)}:**\n${u}`}),t});let d={id:Ce(),role:`assistant`,content:`⏳ ${C.t(`Generating code...`)}`,timestamp:Date.now()};f(e=>[...e,d]);let p=i===`blockly`,h=p?`TASK: ${e}\n\nPLAN:\n${u}\n\nGenerate Blockly XML blocks for this ioBroker automation. Use the exact state IDs from the plan. If the plan contains TODO_DEVICE_ID, keep it as a placeholder. Write comments in ${n}. Put the blocks in a \`\`\`xml code block. You may add a short explanation before or after the XML.`:`TASK: ${e}\n\nPLAN:\n${u}\n\nWrite 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 ${n}. Put the code in a \`\`\`javascript code block. You may add a short explanation before or after the code.`,g=p?q(n):L(n),v=await U(t,o,{messages:[{role:`system`,content:g},{role:`user`,content:h}],model:w,provider:r,baseUrl:s});if(v.error){S(v.error),f(e=>e.slice(0,-1)),m(!1);return}let y=B(v.content||``);f(e=>{let t=[...e],n=t[t.length-1];return(n==null?void 0:n.role)===`assistant`&&(t[t.length-1]={...n,content:y}),t}),_(`${C.t(`devices`)}: ${a.length}`)}catch(e){S(String(e)),f(e=>e.slice(0,-1))}m(!1)},[w,k,p,t,n,i,f]),Z=T(async e=>{if(v===`code`)return ce(e);if(!e.trim()||p)return;let r=k[w];if(!r){S(C.t(`Please select a valid model`));return}let i=W.current||await G(t,n);if(W.current=i,!i){S(C.t(`No API keys configured`));return}let s=Object.keys(n)[0];if(!s){S(C.t(`No running javascript instance found`));return}let u=J.current;if(J.current=null,!u)try{var d;let e=o==null||(d=o.getSelection)==null?void 0:d.call(o);e&&e.text&&(u=c(`selection`,e.range,e.text))}catch{}let h={id:Ce(),role:`user`,content:e,timestamp:Date.now(),sourceRange:u},g={id:Ce(),role:`assistant`,content:``,timestamp:Date.now(),sourceRange:u};f(e=>[...e,h,g]),m(!0),S(null);let{cleanMessage:y,mentionedScriptIds:b,includeAll:x,includeDevices:T}=oe(e),E=[];if(x)E.push(`${C.t(`all scripts`)} (${(a==null?void 0:a.length)||0})`);else if(b.length>0){let e=b.map(e=>e.replace(/^script\.js\./,``));E.push(e.join(`, `))}else E.push(C.t(`current script`));T&&E.push(C.t(`devices`)),_(`${C.t(`Context`)}: ${E.join(` + `)}`);let ee=await se(x,T,b),D=r===`custom`&&i.gptBaseUrl||``,O=y||e;if(a&&a.length>0){let e=O.match(/\b[\w-]+\.\d+\.[\w.-]+/g);if(e){let t=[];for(let n of new Set(e)){let e=te(a,n);e.length>0&&t.push(`Datapoint "${n}" is used in:\n${e.map(e=>` - ${e.scriptName} (${e.scriptId}) line ${e.lineNumber}: ${e.usageType} → ${e.line}`).join(`
15
- `)}`)}t.length>0&&(O+=`\n\n[Automatic analysis results]\n${t.join(`
16
-
17
- `)}`)}}let A=[...ee,...l.filter(e=>e.role!==`system`).map(e=>({role:e.role,content:e.content})),{role:`user`,content:O}],j=v===`agent`;try{let e=[...A];for(let n=0;n<5;n++){let i=await U(t,s,{messages:e,model:w,provider:r,baseUrl:D,...j?{tools:le}:{}});if(i.error){if(j&&n===0&&i.error.toLowerCase().includes(`tool`)){let n=await U(t,s,{messages:e,model:w,provider:r,baseUrl:D});if(n.error)S(n.error),f(e=>e.slice(0,-1));else{let e=B(n.content||``);f(t=>{let n=[...t],r=n[n.length-1];return(r==null?void 0:r.role)===`assistant`&&(n[n.length-1]={...r,content:e}),n})}break}S(i.error),f(e=>e.slice(0,-1));break}let c=i.tool_calls;if((!c||c.length===0)&&j&&i.content){let e=i.content.trim();try{let t=JSON.parse(e);t.name&&t.arguments&&(c=[{id:`text_tool_${Date.now()}`,type:`function`,function:{name:t.name,arguments:JSON.stringify(t.arguments)}}])}catch{}}if(!c||c.length===0){let e=B(i.content||``);f(t=>{let n=[...t],r=n[n.length-1];return(r==null?void 0:r.role)===`assistant`&&(n[n.length-1]={...r,content:e}),n});break}i.tool_calls=c;let l=i.tool_calls.map(e=>{let t={};try{t=JSON.parse(e.function.arguments)}catch{}switch(e.function.name){case`search_datapoints`:return`🔍 ${C.t(`Searching datapoints`)}: "${String(t.query||``)}"`;case`get_state_value`:return`📊 ${C.t(`Reading value`)}: ${String(t.id||``)}`;case`get_object_info`:return`📋 ${C.t(`Loading object info`)}: ${String(t.id||``)}`;case`search_scripts`:return`🔍 ${C.t(`Searching scripts`)}: "${String(t.query||``)}"`;case`read_script`:return`📖 ${C.t(`Reading script`)}: ${String(t.id||``)}`;case`list_scripts`:return`📂 ${C.t(`Loading script list`)}`;default:return`⚙️ ${e.function.name}`}});f(e=>{let t=[...e],n=t[t.length-1];return(n==null?void 0:n.role)===`assistant`&&(t[t.length-1]={...n,content:l.join(`
18
- `)}),t}),e.push({role:`assistant`,content:i.content||``,tool_calls:i.tool_calls});for(let n of i.tool_calls){let r=await xe(t,n,a,o,s);e.push({role:`tool`,tool_call_id:n.id,content:r})}}}catch(e){S(String(e)),f(e=>e.slice(0,-1))}m(!1)},[w,k,l,p,t,n,se,oe,a,v,ce,f,c,o]),ue=T(()=>{f([]),S(null),m(!1),_(null),ne(),window.localStorage.removeItem(`Editor.aiChatHistory`)},[f]),de=T(async(e,r)=>{let a=k[w];if(!a)return`Error: ${C.t(`Please select a valid model`)}`;let o=W.current||await G(t,n);if(W.current=o,!o)return`Error: ${C.t(`No API keys configured`)}`;let s=Object.keys(n)[0];if(!s)return`Error: ${C.t(`No running javascript instance found`)}`;let c=a===`custom`&&o.gptBaseUrl||``,l=i||`javascript`,u=`You are an assistant for writing ioBroker ${l} scripts. The user will ask a question about a snippet of their code. Match your answer to the question: \n- If they ask for an explanation, description, or "what does this do?", reply with clear prose (a few sentences). Do NOT repeat the code unchanged. \n- If they explicitly ask for a change, refactor, fix, or rewrite, reply with a single fenced \`\`\`${l===`blockly`?`xml`:l}\`\`\` code block containing the full replacement for the selection. You may add one short sentence before or after the block. \n- If they ask something ambiguous or meta (e.g. "is this correct?"), reply in prose first and only include code if proposing a change. \nioBroker globals available in scripts: on, setState, getState, schedule, sendTo, log, createState, setStateDelayed, existsState, httpGet, httpPost.`,d=r?`Code from my editor:\n\n\`\`\`${l===`blockly`?`xml`:l}\n${r}\n\`\`\`\n\n${e}`:e;try{let e=await U(t,s,{messages:[{role:`system`,content:u},{role:`user`,content:d}],model:w,provider:a,baseUrl:c});return e.error?`Error: ${e.error}`:e.content||``}catch(e){return`Error: ${e.message||String(e)}`}},[w,k,n,t,i]);return{messages:l,isLoading:p,error:x,model:w,availableModels:ee,modelProviderMap:k,modelsLoading:M,modelsError:F,lastContextInfo:h,mode:v,setMode:b,setModel:ie,sendMessage:Z,triggerAiAction:T(e=>{e.range&&e.code?J.current=c(e.kind||`codelens`,e.range,e.code):J.current=null,j(async()=>{let{buildActionPrompt:e}=await import(`./aiPromptBuilder-DKler0UK.js`);return{buildActionPrompt:e}},[],import.meta.url).then(({buildActionPrompt:t})=>{let n=t({action:e.action,code:e.code,language:i||`javascript`,diagnostic:e.diagnostic,question:e.question,rangeLabel:e.rangeLabel});n?Z(n):J.current=null}).catch(()=>{J.current=null,S(C.t(`Failed to build AI action prompt`))})},[Z,i,c]),askInline:de,clearChat:ue,retryLoadModels:ae}}n();var Te=({code:t,language:n,themeType:r,onInsertCode:i,onShowDiff:o,sourceRange:s})=>{let c=D(null);g(()=>{var e;let i=window.monaco;if(!c.current||!(i!=null&&(e=i.editor)!=null&&e.colorize))return;let a=n===`ts`||n===`typescript`?`typescript`:n||`javascript`;i.editor.colorize(t,a,{theme:r===`dark`?`vs-dark`:`vs`}).then(e=>{c.current&&(c.current.innerHTML=e)})},[t,n,r]);let l=T(()=>{navigator.clipboard.writeText(t)},[t]);return E(a,{sx:{position:`relative`,my:1,borderRadius:1,overflow:`hidden`,border:`1px solid`,borderColor:`divider`},children:[E(a,{sx:{display:`flex`,justifyContent:`space-between`,alignItems:`center`,px:1,py:.5,bgcolor:`action.hover`,borderBottom:`1px solid`,borderColor:`divider`},children:[y(a,{sx:{fontSize:`0.75rem`,color:`text.secondary`,textTransform:`uppercase`},children:n||`javascript`}),E(a,{children:[y(e,{title:C.t(`Copy`),children:y(b,{size:`small`,onClick:l,children:y(A,{sx:{fontSize:16}})})}),i&&y(e,{title:C.t(`Insert into editor`),children:y(b,{size:`small`,onClick:()=>i(t),children:y(X,{sx:{fontSize:16}})})}),o&&y(e,{title:C.t(`Show as diff`),children:y(b,{size:`small`,onClick:()=>o(t,s),children:y(ae,{sx:{fontSize:16}})})})]})]}),y(`pre`,{ref:c,style:{margin:0,padding:`8px 12px`,overflow:`auto`,maxHeight:400,fontSize:`13px`,fontFamily:`'Cascadia Code', 'Fira Code', 'Consolas', monospace`,backgroundColor:r===`dark`?`#1e1e1e`:`#f8f8f8`,color:r===`dark`?`#d4d4d4`:`#333`},children:t})]})};n();var Ee=({xml:e})=>{let t=r(),n=D(null),i=D(null),[o,s]=u(60),c=D(!1);return g(()=>{c.current&&(c.current=!1,requestAnimationFrame(()=>{let e=window.Blockly,t=i.current;e&&t&&(e.svgResize(t),t.scrollCenter())}))},[o]),g(()=>{let r=window.Blockly;if(r&&n.current){i.current&&=(i.current.dispose(),null);try{let a=r.inject(n.current,{readOnly:!0,toolbox:null,trashcan:!1,zoom:{controls:!1,wheel:!1,startScale:1},move:{scrollbars:!1,drag:!1,wheel:!1},sounds:!1,renderer:`thrasos`,theme:F(t),media:`google-blockly/media/`});i.current=a;let o=e.trim();o.startsWith(`<xml`)||(o=`<xml xmlns="https://developers.google.com/blockly/xml">${o}</xml>`);let l=r.utils.xml.textToDom(o),u=10,d=Array.from(l.querySelectorAll(`:scope > block`));for(let e of d)e.setAttribute(`x`,`10`),e.setAttribute(`y`,String(u)),u+=200;r.Xml.domToWorkspace(l,a);let f=a.getTopBlocks(!1);if(f.length>1){let e=10;for(let t of f){let n=t.getRelativeToSurfaceXY();t.moveBy(10-n.x,e-n.y),e+=t.getHeightWidth().height+20}}let p=a.getBlocksBoundingBox();if(p){let e=p.bottom-p.top+20,t=Math.max(60,Math.ceil(e));c.current=!0,s(t)}}catch{}return()=>{i.current&&=(i.current.dispose(),null)}}},[e,t]),y(a,{ref:n,sx:{width:`100%`,height:o,minHeight:60,borderRadius:1,overflow:`hidden`,border:`1px solid`,borderColor:`divider`}})};n();function De(e){let t=[],n=/```(\w*)\n?([\s\S]*?)```/g,r=0,i;for(;(i=n.exec(e))!==null;){if(i.index>r){let n=e.substring(r,i.index).trim();n&&t.push({type:`text`,content:n})}t.push({type:`code`,content:i[2].trim(),language:i[1]||`javascript`}),r=i.index+i[0].length}if(r<e.length){let n=e.substring(r).trim();n&&t.push({type:`text`,content:n})}return t.length===0&&t.push({type:`text`,content:e}),t}function $(e){let t=[],n=/(\*\*(.+?)\*\*|\*(.+?)\*|`(.+?)`)/g,r=0,i,a=0;for(;(i=n.exec(e))!==null;)i.index>r&&t.push(e.substring(r,i.index)),i[2]?t.push(y(`strong`,{children:i[2]},a++)):i[3]?t.push(y(`em`,{children:i[3]},a++)):i[4]&&t.push(y(`code`,{className:`ai-chat-inline-code`,style:{padding:`2px 6px`,borderRadius:4,fontSize:`0.85em`,fontFamily:`'Cascadia Code', 'Fira Code', 'Consolas', monospace`},children:i[4]},a++)),r=i.index+i[0].length;return r<e.length&&t.push(e.substring(r)),t}function Oe(e){return e.trim().startsWith(`|`)&&e.trim().endsWith(`|`)}function ke(e){return/^\|[\s:]*-+[\s:|-]*\|$/.test(e.trim())}function Ae(e,t,n){let r=t.palette.mode===`dark`,i=e=>e.trim().replace(/^\||\|$/g,``).split(`|`).map(e=>e.trim()),o=i(e[0]),s=e.slice(2).map(i);return y(a,{sx:{overflowX:`auto`,my:1},children:E(`table`,{style:{borderCollapse:`collapse`,width:`100%`,fontSize:`0.8rem`,color:t.palette.text.primary},children:[y(`thead`,{children:y(`tr`,{children:o.map((e,n)=>y(`th`,{style:{border:`1px solid ${t.palette.divider}`,padding:`6px 10px`,backgroundColor:r?t.palette.grey[800]:t.palette.grey[100],color:t.palette.text.primary,fontWeight:600,textAlign:`left`},children:$(e)},n))})}),y(`tbody`,{children:s.map((e,n)=>y(`tr`,{style:{backgroundColor:n%2==1?r?t.palette.grey[900]:t.palette.grey[50]:void 0},children:e.map((e,n)=>y(`td`,{style:{border:`1px solid ${t.palette.divider}`,padding:`6px 10px`,color:t.palette.text.primary},children:$(e)},n))},n))})]})},n)}function je(e,t){let n=e.split(`
19
- `),r=[],i=0,a=0;for(;a<n.length;){let e=n[a].trim();if(e===``){a++;continue}if(/^(-{3,}|\*{3,}|_{3,})$/.test(e)){r.push(y(`hr`,{style:{border:`none`,borderTop:`1px solid ${t.palette.divider}`,margin:`8px 0`}},i++)),a++;continue}let o=e.match(/^(#{1,4})\s+(.+)$/);if(o){let e=o[1].length;r.push(y(`div`,{style:{fontWeight:600,fontSize:[`1.2em`,`1.1em`,`1em`,`0.95em`][e-1],margin:`8px 0 4px`},children:$(o[2])},i++)),a++;continue}if(Oe(e)&&a+1<n.length&&ke(n[a+1].trim())&&a+2<n.length){let e=[n[a],n[a+1]],o=a+2;for(;o<n.length&&Oe(n[o]);)e.push(n[o]),o++;r.push(Ae(e,t,i++)),a=o;continue}if(/^[-*+]\s/.test(e)){let e=[];for(;a<n.length&&/^\s*[-*+]\s/.test(n[a]);)e.push(n[a].replace(/^\s*[-*+]\s/,``).trim()),a++;r.push(y(`ul`,{style:{margin:`4px 0`,paddingLeft:20},children:e.map((e,t)=>y(`li`,{children:$(e)},t))},i++));continue}if(/^\d+[.)]\s/.test(e)){let e=[];for(;a<n.length&&/^\s*\d+[.)]\s/.test(n[a]);)e.push(n[a].replace(/^\s*\d+[.)]\s/,``).trim()),a++;r.push(y(`ol`,{style:{margin:`4px 0`,paddingLeft:20},children:e.map((e,t)=>y(`li`,{children:$(e)},t))},i++));continue}r.push(y(`div`,{children:$(e)},i++)),a++}return r}var Me=({message:e,themeType:t,currentLanguage:n,onInsertCode:r,onShowDiff:i,onApplyCode:s})=>{let c=e.role===`user`,l=f(),u=c?t===`dark`?l.palette.primary.dark:l.palette.primary.main:t===`dark`?l.palette.secondary.dark:l.palette.secondary.main,d=l.palette.getContrastText(u),p=k(()=>De(e.content),[e.content]),h=(e,t)=>!!(e===`xml`||e===`blockly`||n===`blockly`&&t&&/<block\s+type=/.test(t));return E(a,{sx:{display:`flex`,gap:1,px:1.5,py:1,mx:.75,my:.5,bgcolor:c?t===`dark`?`rgba(144, 202, 249, 0.10)`:`rgba(25, 118, 210, 0.07)`:t===`dark`?`rgba(206, 147, 216, 0.10)`:`rgba(156, 39, 176, 0.06)`,borderRadius:1.5,borderLeft:`3px solid`,borderLeftColor:u,transition:`background-color 120ms`,"&:hover":{bgcolor:c?t===`dark`?`rgba(144, 202, 249, 0.16)`:`rgba(25, 118, 210, 0.12)`:t===`dark`?`rgba(206, 147, 216, 0.16)`:`rgba(156, 39, 176, 0.10)`}},children:[y(o,{sx:{width:28,height:28,bgcolor:u,color:d,flexShrink:0,mt:.5},children:y(c?oe:ce,{sx:{fontSize:18}})}),y(a,{sx:{flex:1,minWidth:0,fontSize:`0.875rem`,lineHeight:1.6},children:p.map((n,o)=>n.type===`code`?h(n.language,n.content)?E(a,{sx:{my:1},children:[y(Ee,{xml:n.content}),E(a,{sx:{display:`flex`,gap:.5,mt:.5},children:[s&&y(m,{size:`small`,variant:`contained`,color:`primary`,startIcon:y(se,{sx:{fontSize:14}}),onClick:()=>s(n.content),sx:{textTransform:`none`,fontSize:`0.75rem`},children:C.t(`Apply blocks`)}),r&&y(m,{size:`small`,variant:`outlined`,startIcon:y(X,{sx:{fontSize:14}}),onClick:()=>r(n.content),sx:{textTransform:`none`,fontSize:`0.75rem`},children:C.t(`Insert blocks`)})]})]},o):y(Te,{code:n.content,language:n.language||`javascript`,themeType:t,onInsertCode:r,onShowDiff:i,sourceRange:e.sourceRange||null},o):y(a,{sx:{wordBreak:`break-word`,color:l.palette.text.primary},children:je(n.content,l)},o))})]})};function Ne(e){let t=(e||``).toLowerCase();return t.includes(`blockly`)||t.includes(`rules`)?`blockly`:t.includes(`typescript`)?`typescript`:`javascript`}function Pe(e,t){return`\`\`\`${t===`blockly`?`xml`:t}\n${e}\n\`\`\``}function Fe(e){let t=(e.code||``).trim(),n=Ne(e.language),r=e.rangeLabel?` (${e.rangeLabel})`:``;switch(e.action){case`explain`:return t?[`Please explain what this ioBroker ${n} code does${r}.`,`Focus on: which datapoints it reads/writes, which triggers fire it, and any side-effects.`,``,Pe(t,n)].join(`
20
- `):null;case`refactor`:return t?[`Refactor this ioBroker ${n} code${r} to be cleaner and more idiomatic.`,`Preserve behavior exactly. Keep ioBroker APIs (on, setState, getState, schedule, sendTo, log).`,`Return the full refactored block inside a \`\`\`${n===`blockly`?`xml`:n}\`\`\` code block so it can be smart-applied.`,``,Pe(t,n)].join(`
21
- `):null;case`comment`:return t?[`Add clear, concise inline comments to this ioBroker ${n} code${r}.`,`Only add comments where they add real value (non-obvious logic, tricky edge cases, business rules).`,`Do not over-comment trivial lines. Return the commented version in a code block.`,``,Pe(t,n)].join(`
22
- `):null;case`fix`:{if(!t)return null;let i=(e.diagnostic||``).trim();return[`This ioBroker ${n} code has an issue${r}. Please fix it and return the corrected code.${i?`\nReported problem: ${i}`:``}`,`Keep the fix minimal — do not rewrite unrelated parts.`,``,Pe(t,n)].join(`
23
- `)}case`tests`:return t?[`Suggest how to test this ioBroker ${n} script manually inside the ioBroker admin UI${r}.`,``,"ioBroker scripts run inside the adapter sandbox and CANNOT be unit-tested with Jest, Mocha, or any external test framework. Do NOT propose Jest/Mocha tests, do NOT propose extracting the code into a separate Node.js project, do NOT write `describe` / `test` blocks.",``,`Instead, propose a short list of manual test cases. For each case describe:`,` • Setup — which ioBroker datapoints to prepare and to which values (via the objects tree "Values" tab)`,` • Action — what to trigger: set a state with setState, wait for a schedule, change a sensor value, etc.`,` • Expected — what should happen afterwards: which states should change, what should appear in the adapter log (javascript.0), which side effects are visible`,``,`Keep it concise: 3-6 cases covering the happy path, typical edge cases, and any guard conditions the script has.`,``,Pe(t,n)].join(`
24
- `):null;case`ask`:{let i=(e.question||``).trim();return i?t?[`Regarding this ioBroker ${n} code${r}:`,``,Pe(t,n),``,i].join(`
25
- `):i:null}default:return null}}function Ie(e){let t=(e||``).trimStart();if(!t.startsWith(`/`))return null;let n=t.match(/^\/(\w+)(?:\s+([\s\S]*))?$/);if(!n)return null;let r=n[1].toLowerCase(),i=(n[2]||``).trim(),a={explain:`explain`,erklaere:`explain`,erklaeren:`explain`,refactor:`refactor`,refaktor:`refactor`,refaktoriere:`refactor`,comment:`comment`,comments:`comment`,kommentar:`comment`,kommentiere:`comment`,fix:`fix`,fixme:`fix`,tests:`tests`,test:`tests`,ask:`ask`,frag:`ask`,frage:`ask`}[r];return a?{action:a,rest:i}:null}n();function Le(){return[{id:`@all`,label:C.t(`mention @all`),descriptionKey:`All scripts`},{id:`@devices`,label:C.t(`mention @devices`),descriptionKey:`Smart home devices`}]}function Re({provider:e,isDark:t}){return W[e]?y(`img`,{src:`./img/${e}.svg`,alt:e,style:{...J,...t?{filter:`invert(0.85)`}:{}},onError:e=>{e.target.style.display=`none`}}):null}function ze(){try{let e=window.localStorage.getItem(`Editor.aiChatHistory`);return e?JSON.parse(e):[]}catch{return[]}}var Be=({onSend:n,disabled:r,themeType:i,hasSelection:o,selectionText:c,allScripts:f,model:m,availableModels:v,modelProviderMap:w,modelsLoading:O,onModelChange:A,mode:j,onModeChange:te,currentLanguage:N})=>{let[P,F]=u(``),[I,L]=u(!1),[R,z]=u(``),[B,V]=u(0),H=D(null),U=D(-1),W=D(ze()),G=D(-1),K=D(``),ne=k(()=>{let e=Le().map(e=>({...e,description:C.t(e.descriptionKey)}));if(f)for(let t of f){let n=t.id.replace(/^script\.js\./,``).replace(/\./g,`/`);e.push({id:`@${n}`,label:`@${n}`,description:`${t.name} [${t.enabled?`active`:`inactive`}]`})}return e},[f]),q=k(()=>{if(!R)return ne;let e=R.toLowerCase();return ne.filter(t=>t.id.toLowerCase().includes(e)||t.description.toLowerCase().includes(e))},[ne,R]);g(()=>{V(0)},[R]);let J=T(()=>{let e=P.trim();if(!e||r)return;let t=e,i=Ie(e);if(i){let e=o&&c?c:``,n=Fe({action:i.action,code:e,language:N||`javascript`,question:i.action===`ask`?i.rest:void 0,diagnostic:i.action===`fix`&&i.rest||void 0});n&&(t=n)}else o&&c&&(t=`[Selected code in editor]\n\`\`\`\n${c}\n\`\`\`\n\n${e}`);W.current.push(e),G.current=-1,K.current=``;try{let e=W.current.slice(-50);window.localStorage.setItem(`Editor.aiChatHistory`,JSON.stringify(e))}catch{}n(t),F(``),L(!1),requestAnimationFrame(()=>{var e;return(e=H.current)==null?void 0:e.focus()})},[P,r,n,o,c,N]),Y=T(e=>{let t=U.current,n=H.current;if(t<0){let t=P?`${P}${e} `:`${e} `;F(t),L(!1),z(``),setTimeout(()=>{n&&(n.focus(),n.setSelectionRange(t.length,t.length))},0);return}let r=P.substring(0,t),i=(n==null?void 0:n.selectionStart)??P.length,a=`${r}${e} ${P.substring(i)}`;F(a),L(!1),z(``),U.current=-1,setTimeout(()=>{if(n){let t=r.length+e.length+1;n.focus(),n.setSelectionRange(t,t)}},0)},[P]),X=T(()=>{U.current=-1,z(``),L(e=>!e)},[]),re=T(e=>{let t=e.target.value;F(t);let n=e.target.selectionStart??t.length,r=t.substring(0,n).match(/@([\w/äöüÄÖÜß]*)$/);r?(U.current=n-r[0].length,z(r[1]),L(!0)):(L(!1),z(``))},[]),ae=T(e=>{if(I&&q.length>0){if(e.key===`ArrowDown`){e.preventDefault(),V(e=>(e+1)%q.length);return}if(e.key===`ArrowUp`){e.preventDefault(),V(e=>(e-1+q.length)%q.length);return}if(e.key===`Enter`||e.key===`Tab`){e.preventDefault(),Y(q[B].id);return}if(e.key===`Escape`){e.preventDefault(),L(!1);return}}if(e.key===`ArrowUp`&&!I&&W.current.length>0){let t=H.current,n=!t||t.selectionStart===0,r=!P.includes(`
26
- `);if(n&&r){e.preventDefault(),G.current===-1?(K.current=P,G.current=W.current.length-1):G.current>0&&G.current--,F(W.current[G.current]);return}}if(e.key===`ArrowDown`&&!I&&G.current>=0){let t=H.current,n=!t||t.selectionStart===P.length,r=!P.includes(`
27
- `);if(n&&r){e.preventDefault(),G.current<W.current.length-1?(G.current++,F(W.current[G.current])):(G.current=-1,F(K.current));return}}e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),J())},[J,I,q,B,Y,P]);return E(a,{sx:{borderTop:`1px solid`,borderColor:`divider`,position:`relative`},children:[I&&q.length>0&&y(S,{elevation:4,sx:{position:`absolute`,bottom:`100%`,left:8,right:8,maxHeight:200,overflow:`auto`,zIndex:10,mb:.5},children:y(ee,{dense:!0,disablePadding:!0,children:q.slice(0,15).map((e,n)=>y(t,{selected:n===B,onClick:()=>Y(e.id),sx:{py:.25,minHeight:32},children:y(d,{primary:e.label,secondary:e.description,slotProps:{primary:{sx:{fontSize:`0.8rem`,fontWeight:500}},secondary:{sx:{fontSize:`0.7rem`}}}})},e.id))})}),j===`code`&&y(h,{label:`${C.t(`mention @devices`)} — ${C.t(`Smart home devices`)}`,size:`small`,variant:`outlined`,sx:{mx:1,mt:.5,maxWidth:`calc(100% - 16px)`}}),o&&c&&y(h,{icon:y(_,{sx:{fontSize:14}}),label:C.t(`Selected code as context`),size:`small`,variant:`outlined`,sx:{mx:1,mt:.5,maxWidth:`calc(100% - 16px)`}}),E(a,{sx:{mx:1,mt:.5,mb:.5,border:`1px solid`,borderColor:`divider`,borderRadius:1.5,overflow:`hidden`,"&:focus-within":{borderColor:`primary.main`}},children:[y(l,{inputRef:H,fullWidth:!0,multiline:!0,maxRows:6,placeholder:C.t(`Ask about your script...`),value:P,onChange:re,onKeyDown:ae,disabled:r,onBlur:()=>{setTimeout(()=>L(!1),200)},variant:`standard`,slotProps:{input:{disableUnderline:!0}},sx:{px:1.5,pt:1,pb:.5,"& .MuiInputBase-root":{fontSize:`0.875rem`}}}),E(a,{sx:{display:`flex`,alignItems:`center`,gap:.75,px:1,pb:.5},children:[y(e,{title:E(a,{sx:{fontSize:`0.8rem`,lineHeight:1.5,maxWidth:360},children:[y(a,{sx:{fontWeight:600,mb:.75},children:C.t(`AI chat mode`)}),E(a,{sx:{mb:.75},children:[E(`strong`,{children:[`💬 `,C.t(`Chat`)]}),` —`,` `,C.t(`Plain conversation. Use for questions, explanations, syntax help. Does not read or modify your scripts.`)]}),E(a,{sx:{mb:.75},children:[E(`strong`,{children:[`🤖 `,C.t(`Agent`)]}),` —`,` `,C.t(`For larger models with tool support. The AI can read, create, and edit scripts, look up datapoints, and browse the object tree — useful for "create a script that...", "which scripts use this state?" or "analyze my light script".`)]}),E(a,{children:[E(`strong`,{children:[`💻 `,C.t(`Code`)]}),` —`,` `,C.t(`For smaller models without tool support. Two-step script generator (plan then code) — useful for "create a script that..." or "write a Blockly rule for...". Output goes into the editor for smart-apply.`)]})]}),enterDelay:400,placement:`left`,children:E(x,{value:j,onChange:e=>te(e.target.value),size:`small`,variant:`standard`,disableUnderline:!0,sx:{fontSize:`0.7rem`,color:`text.secondary`,border:`1px solid`,borderColor:`text.secondary`,borderRadius:3,bgcolor:`action.hover`,px:.75,"&:hover":{borderColor:`text.disabled`,bgcolor:`action.hover`},"& .MuiSelect-select":{py:`2px`,pr:`18px !important`,display:`flex`,alignItems:`center`,gap:.5}},children:[y(s,{value:`chat`,sx:{fontSize:`0.75rem`},title:C.t(`Plain conversation. Best for: general questions, syntax help, concept explanations.`),children:`💬 Chat`}),y(s,{value:`agent`,sx:{fontSize:`0.75rem`},title:C.t(`For larger models with tool support. Best for: creating, editing, or analyzing scripts; finding datapoint usages; inspecting the object tree.`),children:`🤖 Agent`}),y(s,{value:`code`,sx:{fontSize:`0.75rem`},title:C.t(`For smaller models without tool support. Best for: creating new JavaScript/TypeScript or Blockly scripts from a description.`),children:`💻 Code`})]})}),y(x,{value:m,onChange:e=>A(e.target.value),size:`small`,disabled:O||v.length===0,variant:`standard`,disableUnderline:!0,sx:{fontSize:`0.7rem`,color:`text.secondary`,border:`1px solid`,borderColor:`text.secondary`,borderRadius:3,bgcolor:`action.hover`,px:.75,"&:hover":{borderColor:`text.disabled`,bgcolor:`action.hover`},"& .MuiSelect-select":{py:`2px`,pr:`18px !important`,display:`flex`,alignItems:`center`,gap:.5}},children:v.map(e=>E(s,{value:e,sx:{fontSize:`0.75rem`,display:`flex`,gap:.5},children:[y(Re,{provider:w[e],isDark:i===`dark`}),e]},e))}),y(e,{title:C.t(`Mention scripts as context for the AI. Use @all for all scripts or @scriptName for a specific one.`),enterDelay:500,children:y(b,{size:`small`,onClick:X,sx:{p:`3px`,color:I?`primary.main`:`text.secondary`,border:`1px solid`,borderColor:I?`primary.main`:`text.secondary`,bgcolor:I?void 0:`action.hover`,borderRadius:3,"&:hover":{borderColor:`text.disabled`,bgcolor:`action.hover`}},children:y(ie,{sx:{fontSize:16}})})}),y(a,{sx:{flex:1}}),E(p,{variant:`caption`,sx:{color:`text.disabled`,fontSize:`0.65rem`,mr:.5,whiteSpace:`nowrap`},children:[`Enter `,C.t(`to send`)]}),y(e,{title:`${C.t(`Send`)} (Enter)`,children:y(`span`,{children:y(b,{color:`primary`,onClick:J,disabled:r||!P.trim(),size:`small`,sx:{p:.25},children:y(M,{sx:{fontSize:18}})})})})]})]})]})};n();var Ve=({socket:t,runningInstances:n,themeType:r,currentCode:i,currentLanguage:o,selectedCode:s,allScripts:l,editorApi:u,aiActionRequest:d,onAiActionConsumed:f,onRegisterInlineAsk:m,onInsertCode:h,onShowDiff:_,onApplyCode:x,currentScriptId:S,onClose:ee})=>{var A;let j=D(null),{messages:M,isLoading:te,error:N,model:P,availableModels:F,modelProviderMap:I,modelsLoading:L,modelsError:R,lastContextInfo:z,mode:B,setMode:V,setModel:H,sendMessage:U,triggerAiAction:W,askInline:G,clearChat:K,retryLoadModels:ne}=we(k(()=>({socket:t,runningInstances:n,currentCode:i,currentLanguage:o,allScripts:l,editorApi:u,currentScriptId:S}),[t,n,i,o,l,u,S]));g(()=>(m==null||m(G),()=>m==null?void 0:m(null)),[G,m]);let q=D(null);g(()=>{d&&q.current!==d&&(q.current=d,W(d),f==null||f())},[d,W,f]),g(()=>{var e;(e=j.current)==null||e.scrollIntoView({behavior:`smooth`})},[M]);let J=T(e=>{h==null||h(e)},[h]),Y=T((e,t)=>{_==null||_(e,t)},[_]),X=T(e=>{x==null||x(e)},[x]);return E(a,{sx:{display:`flex`,flexDirection:`column`,height:`100%`,bgcolor:`background.default`,"& .ai-chat-inline-code":{backgroundColor:`action.selected`,color:`text.primary`,border:`1px solid`,borderColor:`divider`}},children:[E(a,{sx:{display:`flex`,alignItems:`center`,gap:1,px:1,py:.5,borderBottom:`1px solid`,borderColor:`divider`,bgcolor:r===`dark`?`grey.900`:`grey.100`,flexShrink:0},children:[y(p,{variant:`subtitle2`,sx:{fontWeight:600,flex:1,color:`text.primary`},children:C.t(`AI Chat`)}),L&&y(c,{size:16}),y(e,{title:C.t(`New chat`),children:y(b,{size:`small`,onClick:K,children:y(re,{sx:{fontSize:18}})})}),y(e,{title:C.t(`Close`),children:y(b,{size:`small`,onClick:ee,children:y(O,{sx:{fontSize:18}})})})]}),(N||R)&&y(w,{severity:`error`,sx:{m:1,py:0},action:R?y(b,{size:`small`,onClick:ne,children:y(v,{sx:{fontSize:16}})}):void 0,children:N||R}),z&&y(p,{variant:`caption`,sx:{px:1.5,py:.25,color:`text.secondary`,fontSize:`0.7rem`,bgcolor:`action.hover`,borderBottom:`1px solid`,borderColor:`divider`,flexShrink:0},children:z}),E(a,{sx:{flex:1,overflow:`auto`,py:1},children:[M.length===0&&!te&&E(a,{sx:{display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,height:`100%`,color:`text.secondary`,px:3,textAlign:`center`},children:[y(p,{variant:`body2`,sx:{mb:1},children:C.t(`Ask questions about your script, request changes, or generate new code.`)}),E(p,{variant:`caption`,color:`text.disabled`,children:[`Enter `,C.t(`to send`),`, Shift+Enter `,C.t(`for new line`)]})]}),M.filter(e=>e.role!==`system`).map(e=>y(Me,{message:e,themeType:r,currentLanguage:o,onInsertCode:J,onShowDiff:Y,onApplyCode:X},e.id)),te&&((A=M[M.length-1])==null?void 0:A.content)===``&&E(a,{sx:{display:`flex`,alignItems:`center`,gap:1,px:2,py:1},children:[y(c,{size:16}),y(p,{variant:`caption`,color:`text.secondary`,children:C.t(`Thinking...`)})]}),y(`div`,{ref:j})]}),y(Be,{onSend:U,disabled:te||F.length===0,themeType:r,hasSelection:!!s,selectionText:s,allScripts:l,model:P,availableModels:F,modelProviderMap:I,modelsLoading:L,onModelChange:H,mode:B,onModeChange:V,currentLanguage:o})]})};export{Ve as default,Ie as n,Fe as t};
@@ -1 +0,0 @@
1
- import{Ct as e,Er as t,Ht as n,Vt as r,Wt as i,_r as a,er as o,m as s,mr as c,tr as l,xr as u,xt as d,zt as f}from"./_virtual_mf___mfe_internal__iobroker_javascript__mf_owner__180366418666083__loadShare___mf_0_iobroker_mf_1_gui_mf_2_components__loadShare__.js-BEpNZh4U.js";t();var p=({originalCode:t,modifiedCode:p,language:m,themeType:h,onAccept:g,onReject:_})=>{let v=u(null),y=u(null),b=u(null);a(()=>{let e=window.monaco;if(!e||!v.current)return;let n=e.editor.createDiffEditor(v.current,{readOnly:!1,originalEditable:!1,renderSideBySide:!0,automaticLayout:!0,theme:h===`dark`?`vs-dark`:`vs`,scrollBeyondLastLine:!1,minimap:{enabled:!1}}),r=e.editor.createModel(t,m),i=e.editor.createModel(p,m);return b.current=i,n.setModel({original:r,modified:i}),y.current=n,()=>{n.dispose(),r.dispose(),i.dispose(),y.current=null,b.current=null}},[t,p,m,h]);let x=c(()=>{var e;g(((e=b.current)==null?void 0:e.getValue())||p)},[p,g]);return l(n,{sx:{display:`flex`,flexDirection:`column`,height:`100%`,width:`100%`},children:[l(f,{variant:`dense`,sx:{minHeight:36,bgcolor:`background.paper`,borderBottom:`1px solid`,borderColor:`divider`,gap:1,flexShrink:0},children:[o(r,{variant:`subtitle2`,sx:{flex:1},children:s.t(`AI suggested changes`)}),o(i,{variant:`contained`,color:`success`,size:`small`,startIcon:o(e,{}),onClick:x,children:s.t(`Accept`)}),o(i,{variant:`outlined`,color:`error`,size:`small`,startIcon:o(d,{}),onClick:_,children:s.t(`Reject`)})]}),o(n,{ref:v,sx:{flex:1,overflow:`hidden`}})]})};export{p as default};
@@ -1 +0,0 @@
1
- import{Ct as e,Er as t,Vn as n,Wt as r,an as i,er as a,in as o,ir as s,m as c,nn as l,rn as u,tn as d,tr as f}from"./_virtual_mf___mfe_internal__iobroker_javascript__mf_owner__180366418666083__loadShare___mf_0_iobroker_mf_1_gui_mf_2_components__loadShare__.js-BEpNZh4U.js";t();var p={title:e=>({background:e.palette.error.main,color:e.palette.error.contrastText,"&>h2":{color:e.palette.error.contrastText}})},m=class extends s.Component{constructor(...e){super(...e),n(this,`handleOk`,()=>{this.props.onClose()})}render(){return f(d,{open:!0,maxWidth:`sm`,fullWidth:!0,onClose:()=>this.handleOk(),"aria-labelledby":`alert-dialog-title`,"aria-describedby":`alert-dialog-description`,children:[a(i,{sx:p.title,id:`alert-dialog-title`,children:this.props.title||c.t(`Error`)}),a(u,{children:a(o,{id:`alert-dialog-description`,children:this.props.text||c.t(`Unknown error!`)})}),a(l,{children:a(r,{variant:`contained`,onClick:()=>this.handleOk(),color:`primary`,autoFocus:!0,startIcon:a(e,{}),children:c.t(`Ok`)})})]})}};export{m as t};
@@ -1 +0,0 @@
1
- import{A as e,An as t,Ct as n,Er as r,Hn as i,R as a,Wt as o,an as s,er as c,ir as l,kn as u,ln as d,lt as f,m as p,nn as m,rn as h,rt as g,tn as _,tr as v,v as y,wt as b,x}from"./_virtual_mf___mfe_internal__iobroker_javascript__mf_owner__180366418666083__loadShare___mf_0_iobroker_mf_1_gui_mf_2_components__loadShare__.js-BEpNZh4U.js";var S=i(c(`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`);r();var C={textArea:{width:`100%`,height:`100%`,overflow:`auto`},textAreaLight:{background:`lightgray`},dialog:{height:`95%`},typography:{padding:16},overflowY:{overflowY:`hidden`}},w=class extends l.Component{constructor(e){super(e),this.state={anchorEl:null,popper:``}}handleCancel(){this.props.onClose()}onCopy(e){y.copyToClipboard(this.props.text);let t=e.currentTarget;setTimeout(()=>{this.setState({popper:p.t(`Copied`),anchorEl:t}),setTimeout(()=>this.setState({popper:``,anchorEl:null}),1e3)},50)}render(){let e=new Blob([this.props.text],{type:`application/xml`}),n=`${this.props.scriptId.substring(10)}.xml`;return v(_,{onClose:()=>!1,maxWidth:`lg`,sx:{"& .MuiDialog-paper":C.dialog},fullWidth:!0,open:!0,"aria-labelledby":`export-dialog-title`,children:[c(s,{id:`export-dialog-title`,children:p.t(`Export selected blocks`)}),c(h,{style:C.overflowY,children:c(`pre`,{id:`export-text`,style:{...C.textArea,...this.props.themeType===`dark`?void 0:C.textAreaLight},children:this.props.text})}),v(m,{children:[c(o,{variant:`contained`,color:`secondary`,startIcon:c(g,{}),children:c(`a`,{download:n,target:`_blank`,rel:`noreferrer`,href:URL.createObjectURL(e),style:{textDecoration:`inherit`,color:`inherit`},children:p.t(`Download as file`)})}),c(o,{variant:`contained`,onClick:e=>this.onCopy(e),color:`secondary`,startIcon:c(S,{}),children:p.t(`Copy to clipboard`)}),c(o,{variant:`contained`,onClick:()=>this.handleCancel(),color:`primary`,startIcon:c(b,{}),children:p.t(`Close`)}),c(t,{id:`popper`,style:{zIndex:1e4},open:!!this.state.popper,placement:`top`,anchorEl:this.state.anchorEl,transition:!0,children:({TransitionProps:e})=>c(d,{...e,timeout:350,children:c(u,{children:c(`p`,{style:C.typography,children:this.state.popper})})})}),c(`textarea`,{id:`copy_input`,readOnly:!0,style:{position:`absolute`,left:-9999},tabIndex:-1,"aria-hidden":!0,value:this.props.text})]})]},`export-dialog`)}};r();var T={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`}},E=class t extends l.Component{constructor(e){super(e),this.state={text:``,imageStatus:``,error:``}}componentDidMount(){setTimeout(()=>{try{var e;(e=window.document.getElementById(`import-text-area`))==null||e.focus()}catch{}},100)}static readFileDataUrl(e,t){let n=new FileReader;n.onload=()=>{t(null,{data:n.result,name:e.name})},n.onabort=()=>{console.error(`file reading was aborted`),t(p.t(`file reading was aborted`))},n.onerror=e=>{console.error(`file reading has failed`),t(p.t(`file reading has failed: %s`,e))},n.readAsText(e)}handleDropFile(e){if(!(e!=null&&e.length))return;let n=e[e.length-1];n&&t.readFileDataUrl(n,(e,t)=>{if(e||!t)this.setState({error:e||`No data`});else{var n;this.setState({text:((n=t.data)==null?void 0:n.toString())||``})}})}handleCancel(){this.props.onClose()}handleOk(){this.props.onClose(this.state.text)}onChange(e){this.setState({text:e.target.value})}render(){let t={...T.dropzone,...this.state.imageStatus===`accepted`?T.dropzoneAccepted:this.state.imageStatus===`rejected`?T.dropzoneRejected:void 0};return v(_,{onClose:()=>!1,maxWidth:`lg`,sx:{"& .MuiDialog-paper":T.dialog},fullWidth:!0,open:!0,"aria-labelledby":`import-dialog-title`,children:[c(s,{id:`import-dialog-title`,children:p.t(`Import blocks`)}),v(h,{style:T.fullHeight,children:[c(`textarea`,{autoFocus:!0,id:`import-text-area`,placeholder:p.t(`Paste your blocks here`),style:{...T.textArea,color:this.props.themeType===`dark`?`#ffffff`:`#000000`},onChange:e=>this.onChange(e),value:this.state.text}),c(f,{maxSize:5e7,onDrop:(e,t)=>{if(e.length)this.handleDropFile(e);else{var n;window.alert((t==null||(n=t[0])==null||(n=n.errors)==null||(n=n[0])==null?void 0:n.message)||p.t(`ra_Cannot upload`))}},multiple:!1,accept:{"text/plain":[],"text/xml":[],"application/xml":[]},children:({getRootProps:n,getInputProps:r,isDragActive:i,isDragReject:o})=>o?(this.state.imageStatus!==`rejected`&&this.setState({imageStatus:`rejected`}),v(`div`,{style:{...t,...T.dropzoneDiv},...n(),children:[c(`input`,{...r()}),c(`span`,{style:T.text,children:p.t(`Some files will be rejected`)},`text`),c(e,{style:{...T.icon,...T.iconError}},`icon`)]})):i?(this.state.imageStatus!==`accepted`&&this.setState({imageStatus:`accepted`}),v(`div`,{style:{...t,...T.dropzoneDiv},...n(),children:[c(`input`,{...r()}),c(`span`,{style:T.text,children:p.t(`All files will be accepted`)},`text`),c(x,{style:{...T.icon,...T.iconOk}},`icon`)]})):(this.state.imageStatus!==`wait`&&this.setState({imageStatus:`wait`}),v(`div`,{style:{...t,...T.dropzoneDiv},...n(),children:[c(`input`,{...r()}),c(`span`,{style:T.text,children:p.t(`Drop some files here or click...`)},`text`),c(a,{style:T.icon},`icon`)]}))})]}),v(m,{children:[c(o,{variant:`contained`,disabled:!this.state.text,onClick:()=>this.handleOk(),color:`primary`,startIcon:c(n,{}),children:p.t(`Import`)}),c(o,{color:`grey`,variant:`contained`,onClick:()=>this.handleCancel(),startIcon:c(b,{}),children:p.t(`Close`)})]})]})}};export{w as n,E as t};
@@ -1 +0,0 @@
1
- import{$n as e,$t as t,Ct as n,Dt as r,En as i,Er as a,Et as o,Hn as s,It as c,Ln as l,On as u,Sr as d,Tt as f,Wt as p,_r as m,an as h,er as g,ft as _,gr as v,hn as y,hr as b,in as x,jn as S,kt as C,m as w,mr as T,nn as E,pr as D,rn as O,tn as k,tr as A,v as j,xr as M,xt as N,yr as P}from"./_virtual_mf___mfe_internal__iobroker_javascript__mf_owner__180366418666083__loadShare___mf_0_iobroker_mf_1_gui_mf_2_components__loadShare__.js-BEpNZh4U.js";import{n as F,t as I}from"./Import-Cu02ceLW.js";import{C as L,_ as R,a as z,b as B,i as V,n as ee,o as H,r as te,t as U,v as W,x as G,y as ne}from"./index-B3s0zmWC.js";var re=s(g(`path`,{d:`M7.5 5.6 10 7 8.6 4.5 10 2 7.5 3.4 5 2l1.4 2.5L5 7zm12 9.8L17 14l1.4 2.5L17 19l2.5-1.4L22 19l-1.4-2.5L22 14zM22 2l-2.5 1.4L17 2l1.4 2.5L17 7l2.5-1.4L22 7l-1.4-2.5zm-7.63 5.29a.996.996 0 0 0-1.41 0L1.29 18.96c-.39.39-.39 1.02 0 1.41l2.34 2.34c.39.39 1.02.39 1.41 0L16.7 11.05c.39-.39.39-1.02 0-1.41zm-1.03 5.49-2.12-2.12 2.44-2.44 2.12 2.12z`}),`AutoFixHigh`),ie=s(g(`path`,{d:`M15.41 7.41 14 6l-6 6 6 6 1.41-1.41L10.83 12z`}),`ChevronLeft`),ae=s(g(`path`,{d:`M10 6 8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z`}),`ChevronRight`),oe=s(g(`path`,{d:`M16 9v10H8V9zm-1.5-6h-5l-1 1H5v2h14V4h-3.5zM18 7H6v12c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2z`}),`DeleteOutlined`),se=s(g(`path`,{d:`M16.59 8.59 12 13.17 7.41 8.59 6 10l6 6 6-6z`}),`ExpandMore`),ce=s(g(`path`,{d:`M15.41 7.41 14 6l-6 6 6 6 1.41-1.41L10.83 12z`}),`NavigateBefore`);a();function le(e){let t=B().getMonitor(),[n,r]=G(t,e);return m(()=>t.subscribeToOffsetChange(r)),m(()=>t.subscribeToStateChange(r)),n}var ue;function de(){return ue||(ue=new Image,ue.src=`data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==`),ue}var K={wrapperRules:`_wrapperRules_147jt_8`,rootWrapper:`_rootWrapper_147jt_14`,bands:`_bands_147jt_26`,emptyRule:`_emptyRule_147jt_39`,emptyRuleText:`_emptyRuleText_147jt_51`},fe={switchesItem:`_switchesItem_b8h5i_6`,switchesItemActive:`_switchesItemActive_b8h5i_35`,iconTheme:`_iconTheme_b8h5i_43`};a();var pe=({name:e,id:t,active:n,icon:r,adapter:i,socket:a,onDoubleClick:o,title:s,onTouchMove:c,style:l})=>A(`div`,{onDoubleClick:o,onTouchMove:c,title:w.t(s||e),className:j.clsx(fe.switchesItem,n&&fe.switchesItemActive,`block-${t}`),children:[g(z,{iconName:r,className:fe.iconTheme,adapter:i,socket:a,style:l}),g(`span`,{children:e?w.t(e):``})]},t),q={cardStyle:`_cardStyle_15e7l_1`,railTriggers:`_railTriggers_15e7l_25`,railConditions:`_railConditions_15e7l_29`,railActions:`_railActions_15e7l_33`,cardStyleActive:`_cardStyleActive_15e7l_37`,controlMenu:`_controlMenu_15e7l_46`,closeBtn:`_closeBtn_15e7l_64`,isDelete:`_isDelete_15e7l_106`,drag_mobile:`_drag_mobile_15e7l_125`};function J(e,t,n){let r;switch(e){case`actions`:if(n===`else`)return r={...t,actions:{...t[e],else:[...t[e].else]}},r;if(n===`then`)return r={...t,actions:{...t[e],then:[...t[e].then]}},r;throw console.error(`Unknown additionalParameter: ${n}`),Error(`Unknown additionalParameter: ${n}`);case`triggers`:return r={...t,triggers:[...t.triggers]},r;case`conditions`:return r={...t,conditions:[...t.conditions]},r;default:throw Error(`Unknown name: ${e}`)}}function Y(e,t,n,r){switch(e){case`actions`:return t.actions[n]=t.actions[n].filter(e=>e._id!==r),t;case`conditions`:var i;return t.conditions[n]=(i=t.conditions[n])==null?void 0:i.filter(e=>e._id!==r),t;default:return t.triggers=t.triggers.filter(e=>e._id!==r),t}}function me(e,t,n){let{_id:r,acceptedBy:i}=e,a;if(!i||!t[i])return console.warn(`Cannot find ${i}`),t;switch(i){case`actions`:if(a=t.actions[n].find(e=>e._id===r),!a)console.warn(`Cannot find ${r}`);else{let r=t.actions[n].indexOf(a);t.actions[n][r]=e}return t;case`conditions`:if(a=t.conditions[n].find(e=>e._id===r),!a)console.warn(`Cannot find ${r}`);else{let r=t.conditions[n].indexOf(a);t.conditions[n][r]=e}return t;default:if(a=t.triggers.find(e=>e._id===r),!a)console.warn(`Cannot find ${r}`);else{let n=t.triggers.indexOf(a);t.triggers[n]=e}return t}}a();var he={triggers:q.railTriggers,conditions:q.railConditions,actions:q.railActions},ge=D(e=>{var t;let{setUserRules:n,userRules:r,_id:i,id:a,blockValue:o,active:s,acceptedBy:c,isTourOpen:l,setTourStep:u,tourStep:f}=e,{blocks:p,socket:m,onUpdate:h,setOnUpdate:_,onDebugMessage:v,enableSimulation:y}=b(U),x=T(e=>p==null?void 0:p.find(t=>t.getStaticData().id===e),[p]),S=T(e=>{let t=me(e,r,o);t&&n(t)},[r]),C=P(()=>{let t=x(a)||V;return g(t,{...e,notFound:!x(a),isTourOpen:l,setTourStep:u,tourStep:f,onUpdate:h,setOnUpdate:_,enableSimulation:y,onDebugMessage:v,onChange:S,className:void 0,socket:m})},[r,h,v,y]),[w,E]=d(!1);return A(`div`,{onMouseDown:e=>{if(e.ctrlKey){let e,t=J(c,r,o);c===`conditions`?(e=t.conditions[o].find(e=>e._id===i),e&&t.conditions[o].splice(t.conditions[o].indexOf(e),0,{...e,_id:Date.now()})):c===`actions`?(e=t.actions[o].find(e=>e._id===i),e&&t.actions[o].splice(t.actions[o].indexOf(e),0,{...e,_id:Date.now()})):(e=t.triggers.find(e=>e._id===i),e&&t.triggers.splice(t[c].indexOf(e),0,{...e,_id:Date.now()})),n(t)}},id:`height`,style:s?{width:(((t=document.getElementById(`width`))==null?void 0:t.clientWidth)||0)-70}:void 0,className:[q.cardStyle,he[c],s&&q.cardStyleActive,w&&q.isDelete].filter(Boolean).join(` `),children:[g(`div`,{className:q.drag_mobile}),C,n&&g(`div`,{className:q.controlMenu,children:g(`div`,{onClick:()=>{let e=J(c,r,o);e=Y(c,e,o,i),E(!0),setTimeout(()=>{c===`triggers`&&_(!0),n(e)},300)},className:q.closeBtn})})]})});a();var _e={position:`fixed`,pointerEvents:`none`,zIndex:100,left:0,top:0,width:`100%`,height:`100%`},ve=(e,t)=>[Math.round(e/32)*32,Math.round(t/32)*32],ye=(e,t,n)=>{if(!e||!t)return{display:`none`};let{x:r,y:i}=t;n&&(r-=e.x,i-=e.y,[r,i]=ve(r,i),r+=e.x,i+=e.y);let a=`translate(${r}px, ${i}px)`;return{transform:a,WebkitTransform:a}},be=e=>{let{itemType:t,isDragging:n,item:r,initialOffset:i,currentOffset:a,targetIds:o}=le(e=>({item:e.getItem(),itemType:e.getItemType(),initialOffset:e.getInitialSourceClientOffset(),currentOffset:e.getSourceClientOffset(),isDragging:e.isDragging(),targetIds:e.getTargetIds()}));return n?g(`div`,{style:_e,children:g(`div`,{style:ye(i,a),children:(()=>{switch(t){case`box`:return o.length?g(ge,{active:!0,...r,allBlocks:e.allBlocks}):g(pe,{active:!0,...r,socket:e.socket});default:return null}})()})}):null},X={emptyBlockStyle:`_emptyBlockStyle_1p9c1_1`,emptyBlock:`_emptyBlock_1p9c1_1`,marginTop:`_marginTop_1p9c1_1`,selectOnChange:`_selectOnChange_1p9c1_17`,selectOnChangeHelp:`_selectOnChangeHelp_1p9c1_23`,selectOnChangeHelpIcon:`_selectOnChangeHelpIcon_1p9c1_29`,emptyBlockNone:`_emptyBlockNone_1p9c1_44`,bandTriggers:`_bandTriggers_1p9c1_57`,bandConditions:`_bandConditions_1p9c1_61`,bandActions:`_bandActions_1p9c1_65`,mainBlockItemRules:`_mainBlockItemRules_1p9c1_69`,nameBlockItems:`_nameBlockItems_1p9c1_93`,nameBlockItemsFoldable:`_nameBlockItemsFoldable_1p9c1_120`,foldIcon:`_foldIcon_1p9c1_124`,foldHint:`_foldHint_1p9c1_124`,contentBlockItem:`_contentBlockItem_1p9c1_145`,wrapperMargin:`_wrapperMargin_1p9c1_153`,contentHeightOn:`_contentHeightOn_1p9c1_160`,heightBlock:`_heightBlock_1p9c1_1`,contentHeightOff:`_contentHeightOff_1p9c1_179`,cardAdd:`_cardAdd_1p9c1_186`,blockCardAdd:`_blockCardAdd_1p9c1_206`};a();function xe(e,t){let[n,r]=d(window.localStorage.getItem(t)?JSON.parse(window.localStorage.getItem(t)||``):e);return[n,e=>{window.localStorage.setItem(t,JSON.stringify(e)),r(e)},!!window.localStorage.getItem(t)]}function Se(e,t){let n=0,r=null,i;return function(...a){let o=Date.now();i=a,o-n>=t?(n=o,e.apply(this,a)):r||=setTimeout(()=>{n=Date.now(),r=null,e.apply(this,i)},t-(o-n))}}function Ce(e){if(Array.isArray(e))return e.map(e=>Ce(e));if(typeof e==`function`)return e.bind(null);if(e&&typeof e==`object`){let t={};return Object.keys(e).forEach(n=>{t[n]=Ce(e[n])}),t}return e}var we=Se((e,t)=>e(t),0);function Te(e,t){let n=t.find(t=>t._id===e);return{card:n,index:n?t.indexOf(n):-1}}function Ee(e,t,n,r,i,a,o,s,c){let{card:l,index:u}=Te(e,n);if(!(u<t&&s<c)&&!(u>t&&s>c)&&l&&u!==t){let e=Ce(n);e.splice(u,1),e.splice(t,0,l);let s=Ce(i);switch(a){case`actions`:s.actions[o]=e,we(r,s);return;case`conditions`:s.conditions[o]=e,we(r,s);return;default:s.triggers=e,we(r,s);return}}}var De={drag:`_drag_7xfhc_1`,root:`_root_7xfhc_11`};a();var Oe=({typeBlock:e,allProperties:t,id:n,isActive:r,setUserRules:i,userRules:a,children:o,_id:s,blockValue:c})=>{let{setOnUpdate:l}=b(U),[{opacity:u},d,f]=ne({type:`box`,item:()=>({...t,id:n,isActive:r,_id:s}),end:(e,t)=>{let{acceptedBy:n}=e,r=t.getDropResult(),o;if(!r)return typeof s==`number`&&!t.getTargetIds().length&&(o=J(n,a,c),o=Y(n,o,c,s),i(o)),null;if(r.blockValue!==c){let t=typeof s==`number`?s:Date.now();o=J(n,a,r.blockValue);let u={id:e.id,acceptedBy:e.acceptedBy};switch(n){case`actions`:return c&&(o=Y(`actions`,o,c,t)),o=Y(`actions`,o,r.blockValue,t),o.actions[r.blockValue].push({...u,_id:t}),i(o);case`conditions`:return typeof c==`number`&&(o=Y(`conditions`,o,c,t)),o=Y(`conditions`,o,r.blockValue,t),o.conditions[r.blockValue].push({...u,_id:t}),i(o);default:return l(!0),o=Y(`triggers`,o,r.blockValue,t),o.triggers.push({...u,_id:t}),i(o)}}},collect:e=>({opacity:e.isDragging()?.4:1,isDragging:e.isDragging()})}),p=M(null),[,h]=W({accept:`box`,canDrop:()=>!1,hover({_id:t,acceptedBy:n},r){var o;if(!p.current||e!==n)return;let l=(o=p.current)==null?void 0:o.getBoundingClientRect(),u=(l.bottom-l.top)/2,d=r.getClientOffset(),f=((d==null?void 0:d.y)||0)-l.top;if(s&&t!==s)switch(n){case`actions`:if(c===`then`||c===`else`){let{index:e}=Te(s,a.actions[c]);e!==t&&Ee(t,e,a[n][c],i,a,n,c,f,u)}return;case`conditions`:if(typeof c==`number`){let{index:e}=Te(s,a[n][c]);e!==t&&Ee(t,e,a[n][c],i,a,n,c,f,u)}return;default:{let{index:e}=Te(s,a[n]);e!==t&&Ee(t,e,a[n],i,a,n,void 0,f,u);return}}}});m(()=>{f(de(),{captureDraggingState:!0})},[]),d(h(p));let _=window.innerWidth<600;return A(`div`,{ref:_&&s?null:p,className:De.root,style:{opacity:u},children:[g(`div`,{className:s?De.drag:null,ref:s&&_?p:null}),o]})};a();var ke=({onClose:e,open:t})=>A(k,{open:t,onClose:e,"aria-labelledby":`alert-dialog-title`,"aria-describedby":`alert-dialog-description`,children:[g(O,{children:A(`div`,{style:{fontSize:`1rem`,fontFamily:`"Roboto", "Helvetica", "Arial", sans-serif`,fontWeight:400,lineHeight:1.5,letterSpacing:`0.00938em`},children:[g(`h3`,{children:w.t(`On condition change`)}),g(`div`,{children:w.t(`help_on_change`)}),g(`h3`,{children:w.t(`Just check`)}),g(`div`,{children:w.t(`help_just_check`)})]})}),g(E,{children:g(p,{onClick:e,color:`primary`,autoFocus:!0,startIcon:g(n,{}),children:w.t(`OK`)})})]});a();var Ae=({onClose:e,open:t})=>A(k,{open:t,onClose:e,"aria-labelledby":`alert-dialog-title`,"aria-describedby":`alert-dialog-description`,children:[g(O,{children:A(x,{id:`alert-dialog-description`,children:[g(`h3`,{children:w.t(`On condition change`)}),g(`div`,{children:w.t(`help_on_change`)}),g(`h3`,{children:w.t(`Just check`)}),g(`div`,{children:w.t(`help_just_check`)})]})}),g(E,{children:g(p,{onClick:e,color:`primary`,autoFocus:!0,children:w.t(`OK`)})})]});a();var je={triggers:X.bandTriggers,conditions:X.bandConditions,actions:X.bandActions},Me=({blockValue:e,boolean:t,typeBlock:n,userRules:r,setUserRules:i,animation:a,setTourStep:o,tourStep:s,isTourOpen:c,theme:l,themeType:u,themeName:f})=>{var p;let[h,_]=d(!1),[v,y]=d(!1),[b,x]=d(!1),[S,C]=d(``);t===void 0&&(t=!0);let w=W({accept:`box`,drop:()=>({blockValue:e}),hover:({acceptedBy:e,_id:t},r)=>{_(e===n),x(!!t),C(r.getHandlerId()||``)},canDrop:({acceptedBy:e})=>(y(e===n),e===n),collect:e=>{var t;return{isOver:e.isOver(),canDrop:((t=e.getItem())==null?void 0:t.acceptedBy)===n,offset:e.getClientOffset(),targetId:e.getHandlerId()}}}),{canDrop:T,isOver:E,offset:D,targetId:O}=w[0],k=w[1];m(()=>{C(``)},[D]);let M=T&&E,N=``;M?N=h?`#00fb003d`:`#fb00002e`:T?N=v?`#00fb003d`:`#fb00002e`:D&&(N=O===S?`#fb00002e`:``);let P;return P=n===`actions`?r.actions[e]:n===`conditions`?r.conditions[e]:r.triggers,g(`div`,{ref:e=>{k(e)},style:{backgroundColor:N},className:j.clsx(X.contentBlockItem,t?a&&X.contentHeightOn:X.contentHeightOff),children:A(`div`,{className:X.wrapperMargin,children:[P.map(t=>g(Oe,{typeBlock:n,...t,blockValue:e,allProperties:t,userRules:r,setUserRules:i,children:g(ge,{...t,isTourOpen:c,setTourStep:o,tourStep:s,settings:t,blockValue:e,userRules:r,setUserRules:i,theme:l,themeType:u,themeName:f})},t._id)),g(`div`,{style:M&&h&&!b?{height:((p=document.getElementById(`height`))==null?void 0:p.clientHeight)||200}:void 0,className:`${X.emptyBlockStyle} ${M&&h&&!b?X.emptyBlock:X.emptyBlockNone}`})]})})},Ne=({typeBlock:t,name:n,nameAdditionally:r,additionally:i,userRules:a,setUserRules:o,iconName:s,adapter:c,socket:l,setTourStep:f,tourStep:p,isTourOpen:h,theme:_,themeType:b,themeName:x})=>{let[C,T,E]=xe(t!==`actions`&&[],`additionallyClickItems_${t}`),[D,O]=d(!1),[k,M]=d(!1),N=t===`conditions`&&!a.conditions.some(e=>e.length),[P,F]=xe(!0,`foldEmptyConditions`),I=N&&P,[,R]=W({accept:`box`,hover:({acceptedBy:e})=>{e===`conditions`&&I&&F(!1)}});m(()=>{if(t===`conditions`&&(C==null?void 0:C.length)!==a.conditions.length-1){let e=[];a.conditions.forEach((t,n)=>{n>0&&e.push({_id:Date.now(),open:!0})}),T([...C,...e])}t===`actions`&&!E&&a.actions.else.length&&T(!0)},[]);let[B,V]=d(!1),ee=a.conditions.some(e=>e.length)||!!a.actions.else.length;return A(`div`,{className:`${X.mainBlockItemRules} ${je[t]}`,children:[A(`span`,{id:`width`,ref:e=>{R(N?e:null)},className:j.clsx(X.nameBlockItems,N&&X.nameBlockItemsFoldable),onClick:N?()=>F(!P):void 0,title:N?w.t(I?`Show conditions`:`Hide empty conditions`):void 0,children:[g(z,{iconName:s,className:X.iconThemCard,adapter:c,socket:l}),n,N?A(e,{children:[g(I?ae:se,{className:X.foldIcon}),I?g(`span`,{className:X.foldHint,children:w.t(`without condition`)}):null]}):null]}),t===`conditions`&&!I?A(`div`,{style:{width:`100%`},children:[A(S,{variant:`standard`,className:X.selectOnChange,value:a.justCheck||!1,onChange:e=>{let t=J(`conditions`,a);t.justCheck=e.target.value===`true`,o(t)},children:[g(u,{value:`false`,children:w.t(`on condition change`)}),g(u,{value:`true`,children:w.t(`just check`)})]}),g(y,{size:`small`,title:w.t(`Explanation`),className:X.selectOnChangeHelp,onClick:()=>O(!0),children:g(L,{className:X.selectOnChangeHelpIcon})})]}):null,I?null:g(Me,{setTourStep:f,tourStep:p,isTourOpen:h,blockValue:t===`actions`?`then`:t===`conditions`?0:t,typeBlock:t,setUserRules:o,userRules:a,theme:_,themeName:x,themeType:b}),!I&&i&&[...Array(t===`actions`?+!!ee:a.conditions.length-1)].map((e,n)=>{let i=(e=n)=>t===`actions`?!!C:!!C.find((t,n)=>n===e&&t.open);return A(v,{children:[A(`div`,{onClick:()=>{if(t===`actions`)return T(!C),null;let e=JSON.parse(JSON.stringify(C));if(a.conditions[n+1].length)return e[n].open=!e[n].open,T(e),null;e=e.filter((e,t)=>t!==n),T(e),V(n),setTimeout(()=>{V(!1),o({...a,conditions:[...a.conditions.filter((e,t)=>t!==n+1)]})},250)},className:X.blockCardAdd,children:[i()?`-`:`+`,g(`div`,{className:X.cardAdd,children:r})]},n),g(Me,{blockValue:t===`actions`?`else`:t===`conditions`?n+1:t,typeBlock:t,setUserRules:o,userRules:a,boolean:i(),animation:B===n,theme:_,themeName:x,themeType:b})]},`${n}_block_${t}`)}),!I&&i&&t===`conditions`&&A(`div`,{onClick:()=>{T([...C,{_id:Date.now(),open:!0}]),o({...a,conditions:[...a.conditions,[]]}),V(a.conditions.length-1),setTimeout(()=>V(!1),1e3)},className:X.blockCardAdd,children:[`+`,g(`div`,{className:X.cardAdd,children:r})]}),g(ke,{open:D,onClose:()=>O(!1)}),g(Ae,{open:k,onClose:()=>M(!1)})]})},Z={menuRules:`_menuRules_1ijaq_1`,wizardButton:`_wizardButton_1ijaq_13`,switchesRenderWrapper:`_switchesRenderWrapper_1ijaq_26`,menuOff:`_menuOff_1ijaq_35`,menuTitle:`_menuTitle_1ijaq_41`,marginAuto:`_marginAuto_1ijaq_55`,inputWidth:`_inputWidth_1ijaq_60`,menuWrapper:`_menuWrapper_1ijaq_72`,hamburgerWrapper:`_hamburgerWrapper_1ijaq_80`,hamburgerOff:`_hamburgerOff_1ijaq_113`,nothingFound:`_nothingFound_1ijaq_121`,resetSearch:`_resetSearch_1ijaq_128`,controlPanel:`_controlPanel_1ijaq_140`,controlPanelAppBar:`_controlPanelAppBar_1ijaq_164`,tabTriggers:`_tabTriggers_1ijaq_180`,tabConditions:`_tabConditions_1ijaq_184`,tabActions:`_tabActions_1ijaq_188`,addClassMenu:`_addClassMenu_1ijaq_192`,addClassBackground:`_addClassBackground_1ijaq_198`,addClassPosition:`_addClassPosition_1ijaq_202`};a();var Pe=e=>{let{allProperties:t,allProperties:{acceptedBy:n,id:r},setUserRules:i,userRules:a,setTourStep:o,tourStep:s,isTourOpen:c,onTouchMove:l,isActive:u}=e;return g(Oe,{allProperties:t,id:t.id,isActive:u,setUserRules:i,userRules:a,children:g(pe,{onDoubleClick:()=>{c&&s===R.addScheduleByDoubleClick&&r===`TriggerScheduleBlock`&&o(R.openTagsMenu),c&&s===R.addActionPrintText&&r===`ActionPrintText`&&o(R.showJavascript);let e=Date.now(),t;switch(n){case`actions`:t=`then`;break;case`conditions`:t=a[n].length-1}let l=J(n,a,t),u={id:r,_id:e,acceptedBy:n};t===void 0?l.triggers.push({...u}):n===`actions`?l.actions[t].push({...u}):n===`conditions`&&l.conditions[t].push({...u}),i(l)},...e,...t,onTouchMove:l})})};a();var Fe={triggers:Z.tabTriggers,conditions:Z.tabConditions,actions:Z.tabActions},Ie=({addClass:e,setAllBlocks:n,allBlocks:r,userRules:a,onChangeBlocks:o,setTourStep:s,tourStep:l,isTourOpen:u,onStartWizard:d})=>{let{blocks:f,socket:h}=b(U),[_,y]=xe(!1,`hamburgerOnOff`),[x,S]=xe({text:``,type:`triggers`,index:0},`filterControlPanel`),T=(e=x.text,t=x.type)=>{if(!f)return;let r=[...f];r=r.filter(t=>{if(!e)return!0;let{name:n}=t.getStaticData();return n&&w.t(n).toLowerCase().includes(e.toLowerCase())}),r=r.filter(e=>t===e.getStaticData().acceptedBy),n(r)},E=(e,t)=>{u&&t===0&&l===R.selectTriggers&&s(R.addScheduleByDoubleClick),u&&t===2&&l===R.selectActions&&s(R.addActionPrintText),S({...x,index:t,type:[`triggers`,`conditions`,`actions`][t]}),T(x.text,[`triggers`,`conditions`,`actions`][t])},D=e=>({id:`scrollable-force-tab-${e}`,"aria-controls":`scrollable-force-tabpanel-${e}`});return m(()=>{T()},[f]),g(t,{mouseEvent:!1,touchEvent:`onTouchStart`,onClickAway:()=>y(!0),children:A(`div`,{className:j.clsx(Z.menuWrapper,e[1035]&&Z.addClassMenu),children:[g(`div`,{className:`${Z.hamburgerWrapper} ${_?Z.hamburgerOff:null}`,onClick:()=>y(!_),children:g(_?ae:ie,{})}),A(`div`,{className:`${j.clsx(Z.menuRules,Fe[x.type],e[1035]&&Z.addClassBackground,e[835]&&Z.addClassPosition)} ${_?Z.menuOff:null}`,children:[g(p,{className:Z.wizardButton,fullWidth:!0,size:`small`,variant:`outlined`,startIcon:g(re,{}),onClick:d,children:w.t(`Wizard`)}),g(`div`,{className:Z.controlPanel,children:g(i,{className:Z.controlPanelAppBar,position:`static`,children:A(c,{value:x.index,onChange:E,children:[g(C,{className:j.clsx(`blocks-triggers`,Z.tabTriggers),title:w.t(`Triggers`),icon:g(z,{iconName:`FlashOn`}),...D(0)}),g(C,{title:w.t(`Conditions`),className:j.clsx(`blocks-conditions`,Z.tabConditions),icon:g(z,{iconName:`Help`}),...D(1)}),g(C,{title:w.t(`Actions`),className:j.clsx(`blocks-actions`,Z.tabActions),icon:g(z,{iconName:`PlayForWork`}),...D(2)})]})})}),g(`div`,{className:Z.switchesRenderWrapper,children:A(`span`,{children:[r.map(e=>{let{name:t,id:n,icon:r,adapter:i}=e.getStaticData();return g(v,{children:g(Pe,{adapter:i,allProperties:e.getStaticData(),icon:r,id:n,isActive:!1,isTourOpen:u,name:t,onTouchMove:()=>y(!0),setTourStep:s,setUserRules:o,socket:h,tourStep:l,userRules:a})},n)}),!r.length&&A(`div`,{className:Z.nothingFound,children:[w.t(`Nothing found`),`...`,g(`div`,{className:Z.resetSearch,onClick:()=>{S({...x,text:``}),T(``)},children:w.t(`reset search`)})]})]})}),g(`div`,{className:j.clsx(Z.menuTitle,Z.marginAuto)}),g(H,{className:Z.inputWidth,fullWidth:!0,customValue:!0,value:x.text,size:`small`,autoComplete:`off`,label:w.t(`search`),variant:`outlined`,onChange:e=>{S({...x,text:e}),T(e)}})]})]})})},Q={bandTriggers:`_bandTriggers_91vrz_5`,bandConditions:`_bandConditions_91vrz_9`,bandActions:`_bandActions_91vrz_13`,paper:`_paper_91vrz_17`,title:`_title_91vrz_22`,close:`_close_91vrz_29`,content:`_content_91vrz_35`,stepper:`_stepper_91vrz_40`,step:`_step_91vrz_40`,hint:`_hint_91vrz_56`,warning:`_warning_91vrz_61`,blockCard:`_blockCard_91vrz_68`,blockBody:`_blockBody_91vrz_79`,remove:`_remove_91vrz_86`,notFound:`_notFound_91vrz_93`,chooser:`_chooser_91vrz_99`,choice:`_choice_91vrz_105`,choiceIcon:`_choiceIcon_91vrz_128`,choiceName:`_choiceName_91vrz_136`,addMore:`_addMore_91vrz_144`,summaryBand:`_summaryBand_91vrz_150`,summaryLabel:`_summaryLabel_91vrz_156`,preview:`_preview_91vrz_164`,actions:`_actions_91vrz_169`,spacer:`_spacer_91vrz_173`};a();var $=[`triggers`,`conditions`,`actions`],Le={triggers:`Triggers`,conditions:`Conditions`,actions:`Actions`},Re={triggers:`What should start the rule?`,conditions:`When should the rule run? This step is optional.`,actions:`What should happen?`},ze={triggers:`when`,conditions:`and`,actions:`then`},Be={triggers:Q.bandTriggers,conditions:Q.bandConditions,actions:Q.bandActions},Ve=()=>({triggers:[],conditions:[],actions:[]}),He=({onCreate:e,onClose:t,hasRule:n,socket:i,theme:a,themeType:s,themeName:c})=>{let{blocks:u}=b(U),[m,v]=d(0),[x,S]=d(Ve),[C,T]=d(null),D=M(0),F=P(()=>{let e={triggers:[],conditions:[],actions:[]};return u==null||u.forEach(t=>{var n;let{acceptedBy:r}=t.getStaticData();(n=e[r])==null||n.push(t)}),e},[u]),I=P(()=>({triggers:x.triggers,conditions:x.conditions.length?[x.conditions]:[[]],justCheck:!1,actions:{then:x.actions,else:[]}}),[x]),L=(e,t)=>{D.current+=1,S(n=>({...n,[e]:[...n[e],{id:t,_id:D.current,acceptedBy:e}]})),T(null)},R=(e,t)=>S(n=>({...n,[e]:n[e].filter(e=>e._id!==t)})),B=(e,t,n)=>S(r=>({...r,[e]:r[e].map(r=>r._id===t?{...n,_id:t,id:r.id,acceptedBy:e}:r)})),V=(e,t,n)=>{let r=u==null?void 0:u.find(t=>t.getStaticData().id===e.id);return r?g(r,{_id:e._id,settings:e,acceptedBy:t,onChange:n?()=>{}:n=>B(t,e._id,n),socket:i,theme:a,themeType:s,themeName:c,enableSimulation:!1,userRules:I,onUpdate:!1,setOnUpdate:()=>{}}):g(`div`,{className:Q.notFound,children:w.t(`Block not found`)})},ee=e=>g(`div`,{className:Q.chooser,children:F[e].map(t=>{let{id:n,name:r,icon:a,adapter:o,title:s}=t.getStaticData();return A(`button`,{type:`button`,className:Q.choice,title:s?w.t(s):void 0,onClick:()=>L(e,n),children:[g(z,{iconName:a,adapter:o,socket:i,className:Q.choiceIcon}),g(`span`,{className:Q.choiceName,children:w.t(r)})]},n)})}),H=(e,t)=>A(`div`,{className:Q.step,hidden:m!==t,children:[g(`div`,{className:Q.hint,children:w.t(Re[e])}),x[e].map(t=>A(`div`,{className:j.clsx(Q.blockCard,Be[e]),children:[g(`div`,{className:Q.blockBody,children:V(t,e)}),g(y,{className:Q.remove,size:`small`,title:w.t(`Delete`),onClick:()=>R(e,t._id),children:g(oe,{fontSize:`small`})})]},t._id)),C===e||!x[e].length?ee(e):g(p,{className:Q.addMore,startIcon:g(f,{}),onClick:()=>T(e),children:w.t(`Add another`)})]},e),te=()=>A(`div`,{className:Q.step,children:[$.map(e=>x[e].length?A(`div`,{className:Q.summaryBand,children:[g(`div`,{className:j.clsx(Q.summaryLabel,Be[e]),children:w.t(ze[e])}),x[e].map(t=>g(`div`,{className:j.clsx(Q.blockCard,Q.preview,Be[e]),children:g(`div`,{className:Q.blockBody,children:V(t,e,!0)})},t._id))]},e):null),x.conditions.length?null:g(`div`,{className:Q.hint,children:w.t(`Without a condition the rule always runs`)}),n?g(`div`,{className:Q.warning,children:w.t(`The current rule will be replaced`)}):null]}),W=m===$.length,G=W||m===1||!!x[$[m]].length;return A(k,{open:!0,fullWidth:!0,maxWidth:`md`,onClose:t,classes:{paper:Q.paper},children:[A(h,{className:Q.title,children:[w.t(`Create a rule step by step`),g(y,{className:Q.close,size:`small`,title:w.t(`Close`),onClick:t,children:g(N,{})})]}),A(O,{className:Q.content,children:[A(r,{className:Q.stepper,activeStep:m,children:[$.map(e=>g(l,{children:g(o,{children:w.t(Le[e])})},e)),g(l,{children:g(o,{children:w.t(`Summary`)})})]}),$.map(H),W?te():null]}),A(E,{className:Q.actions,children:[g(p,{disabled:!m,startIcon:g(ce,{}),onClick:()=>v(m-1),children:w.t(`Back`)}),g(`div`,{className:Q.spacer}),g(p,{onClick:t,children:w.t(`Cancel`)}),W?g(p,{variant:`contained`,color:`primary`,onClick:()=>{e(I),t()},children:w.t(n?`Replace rule`:`Create rule`)}):g(p,{variant:`contained`,color:`primary`,disabled:!G,endIcon:g(_,{}),onClick:()=>v(m+1),children:w.t(m===1&&!x.conditions.length?`Skip`:`Next`)})]})]})};a();var Ue=[],We=({code:e,onChange:t,themeName:n,themeType:r,theme:i,setTourStep:a,tourStep:o,isTourOpen:s,command:c,scriptId:l,changed:u,running:f,newRuleId:h,onNewRuleHandled:_})=>{var v;let{blocks:y,socket:x,setOnUpdate:S,setOnDebugMessage:C,setEnableSimulation:E}=b(U),[D,O]=d([]),[k,j]=d(ee(e)),[N,P]=d(``),[L,R]=d(!1),[z,B]=d(!1);m(()=>{let e,t,n=(n,r)=>{n===`${e}.alive`&&t!==(r==null?void 0:r.val)&&(t=!!(r!=null&&r.val),t&&e&&(x==null||x.sendTo(e.replace(/^system\.adapter\./,``),`rulesOn`,l)))},r=(r,i)=>{var a;if(x&&e!==(i==null||(a=i.common)==null?void 0:a.engine)){var o;e&&(x.unsubscribeState(`${e}.alive`,n),t&&x.sendTo(e.replace(/^system\.adapter\./,``),`rulesOn`,l)),e=i==null||(o=i.common)==null?void 0:o.engine,e&&e&&x.subscribeState(`${e}.alive`,n)}},i=(e,t)=>{if(t)try{let e=JSON.parse(t.val),n=Date.now();if(e.ruleId===l&&n-e.ts<1e3){let t=[...Ue,{blockId:e.blockId,data:e.data,ts:e.ts}];t.length>200&&t.splice(0,t.length-200);for(let e=t.length-1;e>=0;e--)if(t[e].ts<n-5e3){t.splice(0,e);break}Ue=t,C(t)}}catch{console.error(`Cannot parse: ${t.val}`)}};return x==null||x.getObject(l).then(t=>{var a;e=t==null||(a=t.common)==null?void 0:a.engine,x.subscribeObject(l,r),e&&(x.subscribeState(`${e}.alive`,n),x.subscribeState(`${e.replace(/^system\.adapter\./,``)}.debug.rules`,i))}),function(){x==null||x.unsubscribeObject(l,r),e&&(x==null||x.unsubscribeState(`${e}.alive`,n),t&&(x==null||x.sendTo(e.replace(/^system\.adapter\./,``),`rulesOff`,l)),x==null||x.unsubscribeState(`${e.replace(/^system\.adapter\./,``)}.debug.rules`,i))}},[]),m(()=>{E(!u&&f)},[u,f,E]),m(()=>{c&&(P(c),L||R(!0))},[c]),m(()=>{let t=ee(e);JSON.stringify(t)!==JSON.stringify(k)&&(j(t),S(!0))},[e]),m(()=>{document.getElementsByTagName(`HTML`)[0].className=n||`blue`},[n]),m(()=>{h&&h===l&&(_(),B(!0))},[h,l,_]);let V=T(e=>{j(e),y&&t(te(e,y))},[y,t]),H=M(null),[W,G]=d({835:!1,1035:!1});if(m(()=>{H.current&&(H.current.clientWidth<=1035&&G({835:!1,1035:!0}),H.current.clientWidth<=835&&G({1035:!0,835:!0}),H.current.clientWidth>1035&&G({835:!1,1035:!1}))},[((v=H.current)==null?void 0:v.clientWidth)||0]),!y||!x)return null;let ne=!k.triggers.length&&!k.actions.then.length&&!k.actions.else.length&&!k.conditions.some(e=>e.length);return A(`div`,{className:K.wrapperRules,ref:H,children:[g(be,{allBlocks:D,socket:x}),L?N===`export`?g(F,{scriptId:l,themeType:r,onClose:()=>R(!1),text:JSON.stringify(k,null,2)}):g(I,{themeType:r,onClose:e=>{R(!1),e&&V(JSON.parse(e))}}):null,z?g(He,{hasRule:!ne,socket:x,theme:i,themeType:r,themeName:n,onCreate:V,onClose:()=>B(!1)}):null,A(`div`,{className:K.rootWrapper,children:[g(Ie,{setAllBlocks:O,allBlocks:D,userRules:k,onChangeBlocks:V,setTourStep:a,tourStep:o,addClass:W,isTourOpen:s,onStartWizard:()=>B(!0)}),A(`div`,{className:K.bands,children:[ne?A(`div`,{className:K.emptyRule,children:[g(`div`,{className:K.emptyRuleText,children:w.t(`Create a rule step by step`)}),g(p,{variant:`contained`,color:`primary`,startIcon:g(re,{}),onClick:()=>B(!0),children:w.t(`Wizard`)})]}):null,g(Ne,{socket:x,setUserRules:V,userRules:k,isTourOpen:s,setTourStep:a,tourStep:o,name:`${w.t(`when`)}...`,typeBlock:`triggers`,iconName:`FlashOn`,themeType:r,themeName:n,theme:i}),g(Ne,{socket:x,setUserRules:V,isTourOpen:s,setTourStep:a,tourStep:o,userRules:k,name:`...${w.t(`and`)}...`,typeBlock:`conditions`,iconName:`Help`,nameAdditionally:w.t(`or`),additionally:!0,themeType:r,themeName:n,theme:i}),g(Ne,{socket:x,setUserRules:V,isTourOpen:s,setTourStep:a,tourStep:o,userRules:k,name:`...${w.t(`then`)}`,typeBlock:`actions`,iconName:`PlayForWork`,nameAdditionally:w.t(`else`),additionally:!0,themeType:r,themeName:n,theme:i})]})]})]},`rulesEditor`)};export{We as default};
@@ -1,3 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./stateHoverProvider-BYAbe1Ay.js","./cronHoverProvider-CcIFAhVy.js","./AiInlineProvider-BIlcrTkS.js","./AiChatService-BOL3J2Jd.js","./index-B3s0zmWC.js","./Import-Cu02ceLW.js","./Error-DZ4vCykD.js","./blockly-fcfyKYzp.js","./index-CXaeqPRy.css","./inlineDiffController-BuqYsKKq.js","./applyCodeEdit-D3nb7erO.js","./inlineChatWidget-N8xIkvxX.js"])))=>i.map(i=>d[i]);
2
- import{r as e}from"./rolldown-runtime-C0FnF6B9.js";import{Er as t,Fn as n,N as r,Vn as i,Wt as a,an as o,cn as s,er as c,hn as l,ir as u,m as d,nn as f,rn as p,tn as m,tr as h,z as g}from"./_virtual_mf___mfe_internal__iobroker_javascript__mf_owner__180366418666083__loadShare___mf_0_iobroker_mf_1_gui_mf_2_components__loadShare__.js-BEpNZh4U.js";import{t as _}from"./vite-preload-helper-CaC3yEL3.js";import{d as v,p as y,u as b}from"./index-B3s0zmWC.js";var x=e({default:()=>T});t();function S(e){return/^script\.js\.global\./.test(e)}var C=0;function w(e){return e.replace(/\x1b\[[0-9;]*m/g,``)}var T=class extends u.Component{get monacoTS(){var e;return(e=this.monaco)==null||(e=e.languages)==null?void 0:e.typescript}constructor(e){super(e),i(this,`monacoDiv`,null),i(this,`editor`,null),i(this,`monaco`,window.monaco),i(this,`insert`,``),i(this,`originalCode`,void 0),i(this,`runningInstancesStr`,void 0),i(this,`monacoCounter`,0),i(this,`location`,void 0),i(this,`breakpoints`,void 0),i(this,`lastSearch`,``),i(this,`typings`,{}),i(this,`decorations`,[]),i(this,`datapointProviderDisposable`,null),i(this,`inlineProviderDisposable`,null),i(this,`stateHoverDisposable`,null),i(this,`showStateValueDisposable`,null),i(this,`cronHoverDisposable`,null),i(this,`codeLensDisposable`,null),i(this,`aiHelpersUnsubscribe`,null),i(this,`inlineChatWidgetInstance`,null),i(this,`inlineDiffInstance`,null),i(this,`inlineDiffCssInjected`,!1),i(this,`triggerPrettier`,void 0),i(this,`contentChangeDisposable`,null),i(this,`mouseDownDisposable`,null),this.state={name:`current`,isDark:e.isDark||!1,language:e.language||`javascript`,readOnly:e.readOnly||!1,alive:!0,check:!1,searchText:this.props.searchText||``,typingsLoaded:!1,showError:null},this.triggerPrettier=e.triggerPrettier,this.runningInstancesStr=JSON.stringify(this.props.runningInstances),this.originalCode=e.code||``,this.monacoDiv=u.createRef()}waitForMonaco(e){var t;let n=!!((t=this.monacoTS)!=null&&(t=t.typescriptDefaults)!=null&&t.getCompilerOptions);if(!n||!this.props.runningInstances){var r;if(this.monaco=window.monaco,n=!!((r=this.monacoTS)!=null&&(r=r.typescriptDefaults)!=null&&r.getCompilerOptions),this.monacoCounter++,!n&&this.monacoCounter<20){console.log(`wait for monaco loaded`),setTimeout(()=>this.waitForMonaco(e),200);return}this.monacoCounter>=20&&console.error(`Cannot load monaco!`)}else e&&e()}loadTypings(e){if(!this.editor)return;e||=this.props.runningInstances;let t=e&&Object.keys(e).find(t=>e==null?void 0:e[t]);t&&this.props.socket.sendTo(t.replace(`system.adapter.`,``),`loadTypings`,null).then(e=>{this.setState({alive:!0,check:!0,typingsLoaded:!0}),this.setTypeCheck(!0),e.typings?(this.typings=e.typings,this.setEditorTypings(this.state.name)):console.error(`failed to load typings: ${e.error}`)})}componentDidMount(){var e;this.undo,this.redo,this.showInlineDiff,this.getEditorSelection,this.getEditorContent,this.getCursorPosition,this.getWordAtCursor,this.highlightLineRange,this.goToLine,this.replaceSelection,this.getDiagnostics,this.getDocumentSymbols;let t=!!((e=this.monacoTS)!=null&&(e=e.typescriptDefaults)!=null&&e.getCompilerOptions);if(!t||!this.props.runningInstances){var n;if(this.monaco=window.monaco,t=!!((n=this.monacoTS)!=null&&(n=n.typescriptDefaults)!=null&&n.getCompilerOptions),!t){console.log(`wait for monaco loaded...`),this.waitForMonaco(()=>this.componentDidMount());return}}if(!this.editor&&t&&this.monaco){var r,i,a;console.log(`Init editor`),(r=(i=this.props).onRegisterSelect)==null||r.call(i,()=>{if(this.editor){let t=this.editor.getSelection();if(t){var e;return(e=this.editor.getModel())==null?void 0:e.getValueInRange(t)}}});let e=this.monacoTS.typescriptDefaults.getCompilerOptions();if(e.allowJs=!0,e.checkJs=this.props.checkJs!==!1,e.noLib=!0,e.lib=[],e.useUnknownInCatchVariables=!1,e.moduleResolution=this.monacoTS.ModuleResolutionKind.NodeJs,e.target=this.monacoTS.ScriptTarget.ESNext,e.module=this.monacoTS.ModuleKind.ESNext,e.allowNonTsExtensions=!0,this.monacoTS.typescriptDefaults.setCompilerOptions(e),this.setTypeCheck(!1),(a=this.monacoDiv)!=null&&a.current){var o;this.editor=this.monaco.editor.create((o=this.monacoDiv)==null?void 0:o.current,{lineNumbers:`on`,scrollBeyondLastLine:!1,automaticLayout:!0,glyphMargin:!!this.props.breakpoints,colorDecorators:!0,hover:{enabled:`on`,delay:200,sticky:!0},fixedOverflowWidgets:!0}),this.contentChangeDisposable=this.editor.onDidChangeModelContent(()=>this.onChange()),this.monaco&&!this.datapointProviderDisposable&&_(async()=>{let{registerDatapointProvider:e}=await import(`./AiDatapointProvider-DzFpUKkT.js`);return{registerDatapointProvider:e}},[],import.meta.url).then(({registerDatapointProvider:e})=>{this.monaco&&(this.datapointProviderDisposable=e(this.monaco,this.props.socket))}).catch(()=>{}),this.monaco&&!this.showStateValueDisposable&&_(async()=>{let{registerShowStateValueAction:e}=await import(`./stateHoverProvider-BYAbe1Ay.js`);return{registerShowStateValueAction:e}},__vite__mapDeps([0]),import.meta.url).then(({registerShowStateValueAction:e})=>{this.monaco&&this.editor&&!this.showStateValueDisposable&&(this.showStateValueDisposable=e(this.editor,this.monaco,d.t(`Show ioBroker state value`)))}).catch(()=>{}),this.registerAiHelpers(),this.aiHelpersUnsubscribe=v(e=>{e?this.registerAiHelpers():this.disposeAiHelpers()}),this.loadTypings(),this.props.onForceSave&&this.editor.addCommand(this.monaco.KeyMod.CtrlCmd|this.monaco.KeyCode.KeyS,()=>this.props.onForceSave&&this.props.onForceSave()),this.registerAiActions(),setTimeout(()=>{this.highlightText(this.state.searchText),this.location=this.props.location||void 0,this.breakpoints=this.props.breakpoints,this.showDecorators()})}}let s={selectOnLineNumbers:!0,scrollBeyondLastLine:!1,automaticLayout:!0,readOnly:this.state.readOnly,language:this.state.language,isDark:this.state.isDark};this.setEditorOptions(s),this.editor&&(this.editor.focus(),this.editor.setValue(this.originalCode),this.props.onToggleBreakpoint&&(this.mouseDownDisposable=this.editor.onMouseDown(e=>{var t;let n=e.target;this.props.onToggleBreakpoint&&((t=n.detail)==null?void 0:t.glyphMarginLeft)!==void 0&&n.position&&this.props.onToggleBreakpoint(n.position.lineNumber-1)})))}setEditorOptions(e){if(e&&(e.language&&this.setEditorLanguage(e.language),this.editor&&(e.readOnly!==void 0&&this.editor.updateOptions({readOnly:e.readOnly}),e.lineWrap!==void 0&&this.editor.updateOptions({wordWrap:e.lineWrap?`on`:`off`})),e.typeCheck!==void 0&&this.setTypeCheck(e.typeCheck),e.isDark!==void 0)){var t;(t=this.monaco)==null||t.editor.setTheme(e.isDark?`vs-dark`:`vs`)}}registerAiHelpers(){b()&&this.monaco&&this.editor&&(this.stateHoverDisposable||_(async()=>{let{registerStateHoverProvider:e}=await import(`./stateHoverProvider-BYAbe1Ay.js`);return{registerStateHoverProvider:e}},__vite__mapDeps([0]),import.meta.url).then(({registerStateHoverProvider:e})=>{this.monaco&&b()&&!this.stateHoverDisposable&&(this.stateHoverDisposable=e(this.monaco,this.props.socket))}).catch(()=>{}),this.cronHoverDisposable||_(async()=>{let{registerCronHoverProvider:e}=await import(`./cronHoverProvider-CcIFAhVy.js`);return{registerCronHoverProvider:e}},__vite__mapDeps([1]),import.meta.url).then(({registerCronHoverProvider:e})=>{this.monaco&&b()&&!this.cronHoverDisposable&&(this.cronHoverDisposable=e(this.monaco))}).catch(()=>{}),this.props.aiCompletionsEnabled&&!this.inlineProviderDisposable&&_(async()=>{let{registerAiInlineProvider:e}=await import(`./AiInlineProvider-BIlcrTkS.js`);return{registerAiInlineProvider:e}},__vite__mapDeps([2,3]),import.meta.url).then(({registerAiInlineProvider:e})=>{this.monaco&&b()&&!this.inlineProviderDisposable&&(this.inlineProviderDisposable=e(this.monaco,this.props.socket,this.props.runningInstances))}).catch(()=>{}),this.props.onAiAction&&!this.codeLensDisposable&&_(async()=>{let{registerAiCodeLensProvider:e}=await import(`./index-B3s0zmWC.js`).then(e=>e.f);return{registerAiCodeLensProvider:e}},__vite__mapDeps([4,5,6,7,8]),import.meta.url).then(({registerAiCodeLensProvider:e})=>{this.monaco&&this.editor&&this.props.onAiAction&&b()&&!this.codeLensDisposable&&(this.codeLensDisposable=e(this.monaco,this.editor,(e,t,n,r,i)=>{var a,o,s;let c=(a=this.editor)==null?void 0:a.getModel(),l=c?c.getLineMaxColumn(Math.min(i,c.getLineCount())):1;(o=(s=this.props).onAiAction)==null||o.call(s,{action:e,code:t,rangeLabel:n,range:{startLine:r,startColumn:1,endLine:i,endColumn:l},kind:`codelens`})}))}).catch(()=>{}))}disposeAiHelpers(){var e,t,n,r;(e=this.stateHoverDisposable)==null||e.dispose(),this.stateHoverDisposable=null,(t=this.cronHoverDisposable)==null||t.dispose(),this.cronHoverDisposable=null,(n=this.inlineProviderDisposable)==null||n.dispose(),this.inlineProviderDisposable=null,(r=this.codeLensDisposable)==null||r.dispose(),this.codeLensDisposable=null}componentWillUnmount(){var e,t,n,r,i,a,o,s,c,l;if((e=this.contentChangeDisposable)==null||e.dispose(),this.contentChangeDisposable=null,(t=this.mouseDownDisposable)==null||t.dispose(),this.mouseDownDisposable=null,(n=this.datapointProviderDisposable)==null||n.dispose(),this.datapointProviderDisposable=null,_(async()=>{let{clearDatapointCache:e}=await import(`./AiDatapointProvider-DzFpUKkT.js`);return{clearDatapointCache:e}},[],import.meta.url).then(({clearDatapointCache:e})=>e()).catch(()=>{}),(r=this.inlineProviderDisposable)==null||r.dispose(),this.inlineProviderDisposable=null,(i=this.stateHoverDisposable)==null||i.dispose(),this.stateHoverDisposable=null,(a=this.showStateValueDisposable)==null||a.dispose(),this.showStateValueDisposable=null,_(async()=>{let{clearStateHoverCache:e}=await import(`./stateHoverProvider-BYAbe1Ay.js`);return{clearStateHoverCache:e}},__vite__mapDeps([0]),import.meta.url).then(({clearStateHoverCache:e})=>e()).catch(()=>{}),(o=this.cronHoverDisposable)==null||o.dispose(),this.cronHoverDisposable=null,(s=this.codeLensDisposable)==null||s.dispose(),this.codeLensDisposable=null,(c=this.aiHelpersUnsubscribe)==null||c.call(this),this.aiHelpersUnsubscribe=null,(l=this.inlineChatWidgetInstance)==null||l.dispose(),this.inlineChatWidgetInstance=null,this.hideInlineDiff(),this.editor){var u,d;(u=(d=this.props).onRegisterSelect)==null||u.call(d,null),this.editor.dispose(),this.editor=null}}async doPrettier(){var e;let t=this.props.runningInstances&&Object.keys(this.props.runningInstances).find(e=>{var t;return(t=this.props.runningInstances)==null?void 0:t[e]});if(!t){window.alert(d.t(`No script adapter instance found to format the code`));return}let n=await this.props.socket.sendTo(t.replace(`system.adapter.`,``),`prettier`,{code:(e=this.editor)==null?void 0:e.getValue(),type:this.state.language});if(n.error)this.setState({showError:{title:d.t(`Error formatting code`),message:w(n.error)}});else if(n.code){var r,i,a;(r=this.editor)==null||r.setValue(n.code),(i=(a=this.props).onChange)==null||i.call(a,n.code),this.showDecorators()}}setEditorLanguage(e){if(!this.editor)return;let t=this.editor.getModel();if(t){var n;let i=t.getValue(),a=t.uri.path,o=typeof a==`string`&&a.includes(`.`)?a.substring(0,a.lastIndexOf(`.`)):`index`,s=e===`javascript`?`js`:e===`typescript`?`ts`:e;t.dispose();let c=e===`javascript`||e===`typescript`?`typescript`:e,l=(n=this.monaco)==null?void 0:n.editor.createModel(i,c,this.monaco.Uri.from({scheme:window.location.protocol.replace(`:`,``),path:`${o}${C++}.${s}`}));if(l){var r;this.editor.setModel(l),(r=this.contentChangeDisposable)==null||r.dispose(),this.contentChangeDisposable=this.editor.onDidChangeModelContent(()=>this.onChange())}}}setTypeCheck(e){var t,n;let r={noSemanticValidation:!this.state.alive||!e,noSyntaxValidation:!this.state.alive};(t=this.monacoTS)==null||t.typescriptDefaults.setDiagnosticsOptions(r),(n=this.monacoTS)==null||n.javascriptDefaults.setDiagnosticsOptions({noSemanticValidation:!this.state.alive||!e,noSyntaxValidation:!this.state.alive})}setEditorTypings(e=``){var t,n;let r=S(e),i=`${e}.d.ts`,a=[];for(let e of Object.keys(this.typings))r&&(e===`global.d.ts`||e.startsWith(`script.js.global`)&&e!==i)||a.push({filePath:e,content:this.typings[e]});if((t=this.monacoTS)!=null&&(t=t.typescriptDefaults)!=null&&t.setExtraLibs)this.monacoTS.typescriptDefaults.setExtraLibs(a);else if((n=this.monacoTS)!=null&&(n=n.typescriptDefaults)!=null&&n.addExtraLib){let e=this.monacoTS.typescriptDefaults.getExtraLibs();a.forEach(t=>{!e[t.filePath]&&this.monaco&&this.monacoTS.typescriptDefaults.addExtraLib(t.content,t.filePath)})}}undo(){var e;(e=this.editor)==null||e.trigger(`toolbar`,`undo`,null)}redo(){var e;(e=this.editor)==null||e.trigger(`toolbar`,`redo`,null)}insertTextIntoEditor(e){if(!this.editor||!this.monaco)return;let t=this.editor.getSelection();if(t){let n=new this.monaco.Range(t.startLineNumber,t.startColumn,t.endLineNumber,t.endColumn);this.editor.executeEdits(``,[{range:n,text:e,forceMoveMarkers:!0}])}this.editor.focus()}highlightText(e){var t;if(!this.editor||!this.monaco)return 0;let n=e?(t=this.editor.getModel())==null?void 0:t.findMatches(e,!0,!1,!1,null,!0):void 0;if(n!=null&&n.length)return n.forEach(e=>{var t;return(t=this.editor)==null?void 0:t.setSelection(e.range)}),this.editor.revealLine(n[0].range.startLineNumber),n.length;let r=this.editor.getPosition();if(r){let e=r.lineNumber,t=r.column;this.editor.setSelection(new this.monaco.Range(e,t,e,t))}return 0}showInlineDiff(e){if(!this.editor||!this.monaco)return;let t=this.editor,n=this.monaco;this.hideInlineDiff(),_(async()=>{let{InlineDiffController:e,INLINE_DIFF_CSS:t}=await import(`./inlineDiffController-BuqYsKKq.js`);return{InlineDiffController:e,INLINE_DIFF_CSS:t}},__vite__mapDeps([9,10]),import.meta.url).then(({InlineDiffController:r,INLINE_DIFF_CSS:i})=>{if(!this.inlineDiffCssInjected){let e=document.createElement(`style`);e.textContent=i,e.setAttribute(`data-iob-aichat`,`inline-diff`),document.head.appendChild(e),this.inlineDiffCssInjected=!0}let a=new r(t,n,{range:e.range,originalText:e.originalText,modifiedText:e.modifiedText,onAccepted:()=>{var t;this.inlineDiffInstance=null,(t=e.onAccepted)==null||t.call(e)},onRejected:()=>{var t;this.inlineDiffInstance=null,(t=e.onRejected)==null||t.call(e)}});this.inlineDiffInstance=a,a.show()}).catch(()=>{})}hideInlineDiff(){if(this.inlineDiffInstance){try{this.inlineDiffInstance.dispose()}catch{}this.inlineDiffInstance=null}}showInlineChatWidget(){if(!this.editor||!this.monaco||!this.props.onInlineAsk)return;if(this.inlineChatWidgetInstance){this.inlineChatWidgetInstance.show();return}let e=this.editor,t=this.monaco,n=this.props.onInlineAsk,r=this.props.onAiAction;_(async()=>{let{InlineChatWidget:e}=await import(`./inlineChatWidget-N8xIkvxX.js`);return{InlineChatWidget:e}},__vite__mapDeps([11,10]),import.meta.url).then(({InlineChatWidget:i})=>{let a=new i(e,t,{onSubmit:async e=>n({question:e.question,selectedCode:e.selectedCode}),onEscalateToChat:e=>{r&&r({action:`ask`,code:e.selectedCode,question:e.question,rangeLabel:e.range?`lines ${e.range.startLineNumber}-${e.range.endLineNumber}`:`whole file`})}});this.inlineChatWidgetInstance=a,a.show()}).catch(()=>{})}registerAiActions(){if(!this.editor||!this.monaco||!this.props.onAiAction)return;let e=this.monaco,t=(t,n={})=>{if(!this.editor||!this.props.onAiAction)return;let r=this.editor.getModel();if(!r)return;let i=this.editor.getSelection(),a=i&&!i.isEmpty(),o,s,c,l=`selection`;if(a)o=r.getValueInRange(i),s=i.startLineNumber===i.endLineNumber?`line ${i.startLineNumber}`:`lines ${i.startLineNumber}-${i.endLineNumber}`,c={startLine:i.startLineNumber,startColumn:i.startColumn,endLine:i.endLineNumber,endColumn:i.endColumn},l=`selection`;else{let t=this.editor.getPosition(),n=null;if(t)try{n=y(r.getValue(),t.lineNumber)}catch{}if(n){let t=n.startLine,i=n.endLine,a=r.getLineMaxColumn(i),u=new e.Range(t,1,i,a);o=r.getValueInRange(u),s=t===i?`line ${t}`:`lines ${t}-${i}`,c={startLine:t,startColumn:1,endLine:i,endColumn:a},l=`codelens`}else o=r.getValue(),s=`whole file`,l=`none`}this.props.onAiAction({action:t,code:o,rangeLabel:s,range:c,kind:l,...n})},n=[{id:`iobroker.ai.inline`,label:`🤖 ${d.t(`AI: Inline chat…`)}`,keybindings:[e.KeyMod.CtrlCmd|e.KeyMod.Alt|e.KeyCode.KeyI],order:1,run:()=>{if(this.props.onInlineAsk)this.showInlineChatWidget();else{let e=window.prompt(d.t(`Ask the AI about the selected code:`));e&&e.trim()&&t(`ask`,{question:e.trim()})}}},{id:`iobroker.ai.explain`,label:`💡 ${d.t(`AI: Explain`)}`,keybindings:[e.KeyMod.CtrlCmd|e.KeyMod.Alt|e.KeyCode.KeyE],order:2,run:()=>t(`explain`)},{id:`iobroker.ai.refactor`,label:`🔧 ${d.t(`AI: Refactor`)}`,keybindings:[e.KeyMod.CtrlCmd|e.KeyMod.Alt|e.KeyCode.KeyR],order:3,run:()=>t(`refactor`)},{id:`iobroker.ai.comment`,label:`💬 ${d.t(`AI: Add comments`)}`,keybindings:[e.KeyMod.CtrlCmd|e.KeyMod.Alt|e.KeyCode.KeyC],order:4,run:()=>t(`comment`)},{id:`iobroker.ai.fix`,label:`🛠️ ${d.t(`AI: Fix problem`)}`,keybindings:[e.KeyMod.CtrlCmd|e.KeyMod.Alt|e.KeyCode.KeyF],order:5,run:()=>{let n;try{var r,i;let t=(r=this.editor)==null?void 0:r.getModel(),a=(i=this.editor)==null?void 0:i.getPosition();if(t&&a){let r=e.editor.getModelMarkers({resource:t.uri}).find(e=>a.lineNumber>=e.startLineNumber&&a.lineNumber<=e.endLineNumber);r&&(n=r.message)}}catch{}t(`fix`,{diagnostic:n})}},{id:`iobroker.ai.tests`,label:`✅ ${d.t(`AI: Suggest tests`)}`,order:6,run:()=>t(`tests`)}];for(let e of n)try{this.editor.addAction({id:e.id,label:e.label,contextMenuGroupId:`aichat`,contextMenuOrder:e.order,keybindings:e.keybindings,run:()=>e.run()})}catch{}}getEditorSelection(){if(!this.editor)return null;let e=this.editor.getSelection();if(!e||e.isEmpty())return null;let t=this.editor.getModel();return t?{text:t.getValueInRange(e),range:{startLine:e.startLineNumber,startColumn:e.startColumn,endLine:e.endLineNumber,endColumn:e.endColumn}}:null}getEditorContent(){var e;return((e=this.editor)==null||(e=e.getModel())==null?void 0:e.getValue())??``}getWordAtCursor(){var e,t,n;let r=(e=this.editor)==null?void 0:e.getModel(),i=(t=this.editor)==null?void 0:t.getSelection();if(!r||!i)return null;if(!i.isEmpty()){let e=r.getValueInRange(i).trim();return/^[A-Za-z_$][\w$]*$/.test(e)?e:null}return((n=r.getWordAtPosition(i.getPosition()))==null?void 0:n.word)??null}getCursorPosition(){var e;let t=(e=this.editor)==null?void 0:e.getPosition();return t?{line:t.lineNumber,column:t.column}:null}highlightLineRange(e,t){if(!this.editor||!this.monaco)return!1;let n=this.editor.getModel();if(!n)return!1;let r=n.getLineCount(),i=Math.max(1,Math.min(e,r)),a=Math.max(i,Math.min(t,r)),o=n.getLineMaxColumn(a);return this.editor.setSelection(new this.monaco.Range(i,1,a,o)),this.editor.revealLineInCenter(i),!0}goToLine(e,t=1){if(!this.editor||!this.monaco)return!1;let n=this.editor.getModel();if(!n)return!1;let r=n.getLineCount(),i=Math.max(1,Math.min(e,r));return this.editor.setPosition({lineNumber:i,column:t}),this.editor.revealLineInCenter(i),this.editor.focus(),!0}replaceSelection(e){if(!this.editor||!this.monaco)return!1;let t=this.editor.getSelection();if(!t)return!1;let n=new this.monaco.Range(t.startLineNumber,t.startColumn,t.endLineNumber,t.endColumn);return this.editor.executeEdits(``,[{range:n,text:e,forceMoveMarkers:!0}]),this.editor.focus(),!0}getDiagnostics(){if(!this.editor||!this.monaco)return[];let e=this.editor.getModel();if(!e)return[];let t=this.monaco.editor.getModelMarkers({resource:e.uri}),n={8:`error`,4:`warning`,2:`info`,1:`hint`};return t.map(e=>({line:e.startLineNumber,column:e.startColumn,endLine:e.endLineNumber,endColumn:e.endColumn,severity:n[e.severity]||`info`,message:e.message,...e.source?{source:e.source}:{}}))}async getDocumentSymbols(){if(!this.editor||!this.monaco)return[];let e=this.editor.getModel();if(!e)return[];let t=[];try{var n;let r=this.monaco.languages,i=(n=r.getDocumentSymbolProviders)==null?void 0:n.call(r,e);if(i!=null&&i.length){let n={0:`file`,1:`module`,2:`namespace`,3:`package`,4:`class`,5:`method`,6:`property`,7:`field`,8:`constructor`,9:`enum`,10:`interface`,11:`function`,12:`variable`,13:`constant`,14:`string`,15:`number`,16:`boolean`,17:`array`,18:`object`,19:`key`,20:`null`,21:`enum-member`,22:`struct`,23:`event`,24:`operator`,25:`type-parameter`};for(let r of i){let i=await r.provideDocumentSymbols(e,{isCancellationRequested:!1});if(!i)continue;let a=e=>{for(let i of e){var r;t.push({name:i.name,kind:n[i.kind]||String(i.kind),line:i.range.startLineNumber,endLine:i.range.endLineNumber,...i.detail?{detail:i.detail}:{}}),(r=i.children)!=null&&r.length&&a(i.children)}};if(a(i),t.length)break}}}catch{}if(t.length===0){let n=e.getValue().split(`
3
- `),r=[{re:/^(?:export\s+)?(?:async\s+)?function\s+(\w+)/,kind:`function`},{re:/^(?:export\s+)?class\s+(\w+)/,kind:`class`},{re:/^(?:export\s+)?(?:const|let|var)\s+(\w+)/,kind:`variable`}];for(let e=0;e<n.length;e++){let i=n[e].trim();for(let{re:n,kind:a}of r){let r=n.exec(i);if(r!=null&&r[1]){t.push({name:r[1],kind:a,line:e+1,endLine:e+1});break}}}}return t}showDecorators(){var e;let t=[];if(this.location&&this.monaco&&(t.push({range:new this.monaco.Range(this.location.lineNumber+1,(this.location.columnNumber||0)+1,this.location.lineNumber+1,1e3),options:{isWholeLine:!1,className:this.props.isDark?`monacoCurrentLineDark`:`monacoCurrentLine`}}),t.push({range:new this.monaco.Range(this.location.lineNumber+1,0,this.location.lineNumber+1,0),options:{isWholeLine:!0,className:this.props.isDark?`monacoCurrentFullLineDark`:`monacoCurrentFullLine`}})),(e=this.breakpoints)==null||e.forEach(e=>{this.monaco&&t.push({range:new this.monaco.Range(e.location.lineNumber+1,0,e.location.lineNumber+1,100),options:{isWholeLine:!0,glyphMarginClassName:this.props.isDark?`monacoBreakPointDark`:`monacoBreakPoint`}})}),this.editor){let e=this.editor.getModel();e&&(this.decorations=e.deltaDecorations(this.decorations,t))}}initNewScript(e,t){var n;this.setState({name:e}),this.originalCode=t||``,(n=this.editor)==null||n.setValue(t||``),this.highlightText(this.lastSearch),this.showDecorators(),this.setEditorTypings(e)}scrollToLineIfNeeded(e){if(this.editor){let t=this.editor.getVisibleRanges();(!t||!t[0]||t[0].startLineNumber>e||e>t[0].endLineNumber)&&this.editor.revealLineInCenter(e)}}UNSAFE_componentWillReceiveProps(e){let t={};this.state.name!==e.name&&this.initNewScript(e.name,e.code),JSON.stringify(e.runningInstances)!==this.runningInstancesStr&&(this.runningInstancesStr=JSON.stringify(e.runningInstances),this.state.typingsLoaded||this.loadTypings(e.runningInstances)),this.editor&&!e.changed&&(e.code!==this.originalCode||e.code!==this.editor.getValue())&&(this.originalCode=e.code||``,this.editor.setValue(this.originalCode),this.showDecorators(),this.location&&this.scrollToLineIfNeeded(this.location.lineNumber+1)),e.searchText!==this.lastSearch&&(this.lastSearch=e.searchText||``,this.highlightText(this.lastSearch)),JSON.stringify(e.location)!==JSON.stringify(this.location)&&JSON.stringify(e.breakpoints)!==JSON.stringify(this.breakpoints)?(this.location=e.location||void 0,this.breakpoints=e.breakpoints,this.showDecorators(),this.editor&&this.location&&this.scrollToLineIfNeeded(this.location.lineNumber+1)):JSON.stringify(e.breakpoints)===JSON.stringify(this.breakpoints)?JSON.stringify(e.location)!==JSON.stringify(this.location)&&(this.location=e.location||void 0,this.showDecorators(),this.editor&&this.location&&this.scrollToLineIfNeeded(this.location.lineNumber+1)):(this.breakpoints=e.breakpoints,this.showDecorators()),this.state.language===(e.language||`javascript`)?this.state.readOnly===(e.readOnly||!1)?this.state.isDark!==(e.isDark||!1)&&(this.setState({isDark:e.isDark||!1}),t.isDark=e.isDark):(this.setState({readOnly:e.readOnly||!1}),t.readOnly=e.readOnly):(this.setState({language:e.language||`javascript`}),t.language=e.language||`javascript`),this.setEditorOptions(t),e.aiCompletionsEnabled!==this.props.aiCompletionsEnabled&&(e.aiCompletionsEnabled&&this.monaco&&b()?this.inlineProviderDisposable||_(async()=>{let{registerAiInlineProvider:e}=await import(`./AiInlineProvider-BIlcrTkS.js`);return{registerAiInlineProvider:e}},__vite__mapDeps([2,3]),import.meta.url).then(({registerAiInlineProvider:e})=>{this.monaco&&b()&&!this.inlineProviderDisposable&&(this.inlineProviderDisposable=e(this.monaco,this.props.socket,this.props.runningInstances))}).catch(()=>{}):!e.aiCompletionsEnabled&&this.inlineProviderDisposable&&(this.inlineProviderDisposable.dispose(),this.inlineProviderDisposable=null)),this.insert!==e.insert&&(this.insert=e.insert||``,this.insert&&(console.log(`Insert text: ${this.insert}`),setTimeout(e=>{this.insertTextIntoEditor(e),setTimeout(()=>this.props.onInserted&&this.props.onInserted(),100)},100,this.insert)))}onChange(){if(!this.props.readOnly&&this.editor){var e,t;(e=(t=this.props).onChange)==null||e.call(t,this.editor.getValue())}}renderErrorDialog(){return this.state.showError?this.state.showError.full?h(m,{open:!0,maxWidth:`md`,onClose:()=>this.setState({showError:null}),children:[c(o,{children:this.state.showError.title||d.t(`Error`)}),c(p,{children:c(`pre`,{children:c(`code`,{children:this.state.showError.message})})}),c(f,{children:h(a,{variant:`contained`,startIcon:c(r,{}),onClick:()=>this.setState({showError:null}),children:[d.t(`Close`),` `]})})]}):c(n,{open:!0,autoHideDuration:5e3,onClose:()=>this.setState({showError:null}),message:this.state.showError.title,action:h(u.Fragment,{children:[c(a,{color:`secondary`,size:`small`,onClick:()=>this.setState({showError:{...this.state.showError,full:!0}}),children:d.t(`More`)}),c(l,{size:`small`,"aria-label":`close`,color:`inherit`,onClick:()=>this.setState({showError:null}),children:c(r,{fontSize:`small`})})]})}):null}render(){var e;return!((e=this.monacoTS)!=null&&e.typescriptDefaults)||!this.props.runningInstances?(setTimeout(()=>{this.monaco=window.monaco,this.forceUpdate()},200),null):(this.props.triggerPrettier!==this.triggerPrettier&&(this.triggerPrettier=this.props.triggerPrettier,setTimeout(()=>this.doPrettier().catch(e=>console.error(`Error formatting code:`,e)),50)),h(`div`,{ref:this.monacoDiv,style:{...this.props.style,width:`100%`,height:`100%`,overflow:`hidden`,position:`relative`},children:[this.renderErrorDialog(),!this.state.check&&c(s,{size:`small`,title:d.t(`Check is not active, because javascript adapter is disabled`),style:{bottom:10,right:10,opacity:.5,position:`absolute`,zIndex:1,background:`red`,color:`white`},color:`secondary`,children:c(g,{})})]}))}};export{x as n,T as t};
@@ -1 +0,0 @@
1
- import{t as e}from"./AiChatPanel-oBeXbUFv.js";export{e as buildActionPrompt};
@@ -1 +0,0 @@
1
- import{i as e,o as t,r as n,t as r}from"./blockly-fcfyKYzp.js";import{c as i,l as a}from"./index-B3s0zmWC.js";import{c as o,d as s,i as c,p as l,r as u,s as d}from"./helpers-CnEjYAup.js";function f(){let f=window.Blockly,p=f.Translate,m=window.getHelp;f.CustomBlocks=f.CustomBlocks||[],f.CustomBlocks.push(`Action`),f.Action={HUE:330,blocks:{}};let h=()=>new n(`FALSE`,function(e){this.getSourceBlock().updateShape_(u(e))}),g=()=>[[p(`http_timeout_ms`),`ms`],[p(`http_timeout_sec`),`sec`]],_=()=>[[p(`http_type_text`),`text`],[p(`http_type_arraybuffer`),`arraybuffer`]],v=()=>[[p(`http_content_type_default`),`default`],[`application/json`,`application/json`],[`application/x-www-form-urlencoded`,`application/x-www-form-urlencoded`],[`text/plain`,`text/plain`],[`text/xml`,`text/xml`],[`application/xml`,`application/xml`],[p(`http_content_type_custom`),`custom`]],y={mutationToDom:function(){let e=document.createElement(`mutation`);return e.setAttribute(`with_statement`,String(u(this.getFieldValue(`WITH_STATEMENT`)))),e},domToMutation:function(e){this.updateShape_(u(e.getAttribute(`with_statement`)))},updateShape_:function(e){s(this,e)}},b=(t,n,o,s,c,u)=>{r[t]={init:function(){this.appendDummyInput().appendField(n),this.appendDummyInput(`ATTR`).appendField(new e(o),`ATTR`),this.setInputsInline(!0),this.setOutput(!0),this.setColour(f.Action.HUE),this.setTooltip(p(`${t}_tooltip`)),u&&this.setHelpUrl(m(u))},onchange:function(){l(this,s,c)},FUNCTION_TYPES:s},a.forBlock[t]=function(e){return[e.getFieldValue(`ATTR`),i.ATOMIC]}};f.Action.blocks.exec=`<block type="exec"> <mutation with_statement="false"></mutation> <field name="WITH_STATEMENT">FALSE</field> <field name="LOG"></field> <value name="COMMAND"> <shadow type="text"> <field name="TEXT">pwd</field> </shadow> </value></block>`,r.exec={init:function(){this.appendDummyInput(`TEXT`).appendField(`» ${p(`exec`)}`),this.appendValueInput(`COMMAND`).appendField(p(`exec_command`)),this.appendDummyInput(`WITH_STATEMENT`).appendField(p(`with_results`)).appendField(h(),`WITH_STATEMENT`),this.appendDummyInput(`LOG`).appendField(p(`loglevel`)).appendField(new e(c()),`LOG`),this.setInputsInline(!1),this.setPreviousStatement(!0,null),this.setNextStatement(!0,null),this.setColour(f.Action.HUE),this.setTooltip(p(`exec_tooltip`)),this.setHelpUrl(m(`exec_help`))},...y},a.forBlock.exec=function(e){let t=a.valueToCode(e,`COMMAND`,i.ATOMIC),n=e.getFieldValue(`LOG`),r=``;if(n&&(r=`console.${n}('exec: ' + ${t});\n`),u(e.getFieldValue(`WITH_STATEMENT`))){let n=a.statementToCode(e,`STATEMENT`);if(n)return`exec(${t}, async (error, result, stderr) => {\n${n}});\n${r}`}return`exec(${t});\n${r}`},f.Action.blocks.exec_result=`<sep gap="5"></sep><block type="exec_result"> <field name="ATTR">result</field></block>`,b(`exec_result`,`»`,[[p(`exec_result_result`),`result`],[p(`exec_result_stderr`),`stderr`],[p(`exec_result_error`),`error`]],[`exec`],`exec_result_warning`,`exec_help`),f.Action.blocks.http_get=`<block type="http_get"> <field name="TIMEOUT">2000</field> <field name="UNIT">ms</field> <field name="TYPE">text</field> <value name="URL"> <shadow type="text"> <field name="TEXT">http://</field> </shadow> </value></block>`,r.http_get={init:function(){this.appendValueInput(`URL`).appendField(`🌐 ${p(`http_get`)}`),this.appendDummyInput().appendField(p(`http_timeout`)).appendField(new t(`2000`),`TIMEOUT`).appendField(new e(g()),`UNIT`),this.appendDummyInput(`TYPE`).appendField(p(`http_type`)).appendField(new e(_()),`TYPE`),this.appendStatementInput(`STATEMENT`).setCheck(null),this.setInputsInline(!1),this.setPreviousStatement(!0,null),this.setNextStatement(!0,null),this.setColour(f.Action.HUE),this.setTooltip(p(`http_get_tooltip`)),this.setHelpUrl(m(`http_get_help`))}},a.forBlock.http_get=function(e){let t=a.valueToCode(e,`URL`,i.ATOMIC),n=e.getFieldValue(`UNIT`),r=e.getFieldValue(`TIMEOUT`);Number.isNaN(r)&&(r=2e3),n===`sec`&&(r*=1e3);let o=e.getFieldValue(`TYPE`)||`text`,s=a.statementToCode(e,`STATEMENT`);return`httpGet(${t}, { timeout: ${r}, responseType: '${o}' }, async (err, response) => {\n${s}});\n`},f.Action.blocks.http_post=`<sep gap="5"></sep><block type="http_post"> <field name="TIMEOUT">2000</field> <field name="UNIT">ms</field> <field name="TYPE">text</field> <field name="CONTENT_TYPE">default</field> <value name="URL"> <shadow type="text"> <field name="TEXT">http://</field> </shadow> </value> <value name="DATA"> <shadow type="logic_null"></shadow> </value></block>`,r.http_post={init:function(){this.appendValueInput(`URL`).appendField(`🌐 ${p(`http_post`)}`),this.appendDummyInput().appendField(p(`http_timeout`)).appendField(new t(`2000`),`TIMEOUT`).appendField(new e(g()),`UNIT`),this.appendDummyInput(`TYPE`).appendField(p(`http_type`)).appendField(new e(_()),`TYPE`),this.appendDummyInput(`CONTENT_TYPE`).appendField(p(`http_content_type`)).appendField(new e(v(),function(e){this.getSourceBlock().updateContentTypeShape_(e===`custom`)}),`CONTENT_TYPE`),this.appendValueInput(`DATA`).appendField(p(`http_post_data`)),this.appendStatementInput(`STATEMENT`).setCheck(null),this.setInputsInline(!1),this.setPreviousStatement(!0,null),this.setNextStatement(!0,null),this.setColour(f.Action.HUE),this.setTooltip(p(`http_post_tooltip`)),this.setHelpUrl(m(`http_post_help`))},mutationToDom:function(){let e=document.createElement(`mutation`);return e.setAttribute(`custom_content_type`,String(this.getFieldValue(`CONTENT_TYPE`)===`custom`)),e},domToMutation:function(e){this.updateContentTypeShape_(u(e.getAttribute(`custom_content_type`)))},updateContentTypeShape_:function(e){e?this.getInput(`CONTENT_TYPE_CUSTOM`)||(this.appendDummyInput(`CONTENT_TYPE_CUSTOM`).appendField(` `).appendField(new t(`application/json`),`CONTENT_TYPE_CUSTOM`),this.moveInputBefore(`CONTENT_TYPE_CUSTOM`,`DATA`)):this.getInput(`CONTENT_TYPE_CUSTOM`)&&this.removeInput(`CONTENT_TYPE_CUSTOM`)}},a.forBlock.http_post=function(e){let t=a.valueToCode(e,`URL`,i.ATOMIC),n=e.getFieldValue(`UNIT`),r=e.getFieldValue(`TIMEOUT`);isNaN(r)&&(r=2e3),n===`sec`&&(r*=1e3);let s=e.getFieldValue(`TYPE`)||`text`,c=a.valueToCode(e,`DATA`,i.ATOMIC)||`null`,l=a.statementToCode(e,`STATEMENT`),u=e.getFieldValue(`CONTENT_TYPE`)||`default`,d=u===`custom`?(e.getFieldValue(`CONTENT_TYPE_CUSTOM`)||``).trim():u,f=d&&d!=="default"?`, headers: { 'Content-Type': ${o(d)} }`:``;return`httpPost(${t}, ${c}, { timeout: ${r}, responseType: '${s}'${f} }, async (err, response) => {\n${l}});\n`},f.Action.blocks.http_response=`<sep gap="5"></sep><block type="http_response"> <field name="ATTR">response.data</field></block>`,b(`http_response`,`🌐`,[[p(`http_response_data`),`response.data`],[p(`http_response_statuscode`),`response.statusCode`],[p(`http_response_responsetime`),`response.responseTime`],[p(`http_response_headers`),`response.headers`],[p(`http_response_error`),`err`]],[`http_get`,`http_post`],`http_response_warning`,`http_response_help`),f.Action.blocks.http_response_tofile=`<sep gap="5"></sep><block type="http_response_tofile"> <value name="FILENAME"> <shadow type="text"> <field name="TEXT">temp.jpg</field> </shadow> </value></block>`,r.http_response_tofile={init:function(){this.appendDummyInput().appendField(`🌐 ${p(`http_response_tofile`)}`),this.appendValueInput(`FILENAME`).appendField(p(`http_response_tofile_filename`)).setCheck(null),this.setInputsInline(!1),this.setOutput(!0,`String`),this.setColour(f.Action.HUE),this.setTooltip(p(`http_response_tofile_tooltip`)),this.setHelpUrl(m(`http_response_tofile_help`))},onchange:function(){l(this,[`http_get`,`http_post`],`http_response_warning`)},FUNCTION_TYPES:[`http_get`,`http_post`]},a.forBlock.http_response_tofile=function(e){return[`createTempFile(${a.valueToCode(e,`FILENAME`,i.ATOMIC)}, response.data)`,i.ATOMIC]};let x=()=>`${a.prefixLines(`if (err) {`,a.INDENT)}\n${a.prefixLines(`console.error(err);`,a.INDENT+a.INDENT)}\n${a.prefixLines(`}`,a.INDENT)}\n`;f.Action.blocks.file_write=`<block type="file_write"> <value name="OID"> <shadow type="field_oid_meta"> <field name="oid">0_userdata.0</field> </shadow> </value> <value name="FILE"> <shadow type="text"> <field name="TEXT">demo.json</field> </shadow> </value></block>`,r.file_write={init:function(){this.appendValueInput(`OID`).appendField(`📁 ${p(`file_write`)}`),this.appendValueInput(`FILE`).appendField(p(`file_write_filename`)).setCheck(null),this.appendValueInput(`DATA`).appendField(p(`file_write_data`)),this.setInputsInline(!1),this.setPreviousStatement(!0,null),this.setNextStatement(!0,null),this.setColour(f.Action.HUE),this.setTooltip(p(`file_write_tooltip`)),this.setHelpUrl(m(`file_write_help`))}},a.forBlock.file_write=function(e){let t=a.valueToCode(e,`OID`,i.ATOMIC),n=a.valueToCode(e,`FILE`,i.ATOMIC),r=a.valueToCode(e,`DATA`,i.ATOMIC),o=d(t);return`writeFile(${t}${o?` /* ${o} */`:``}, String(${n}), ${r||`null`}, (err) => {\n${x()}});\n`},f.Action.blocks.file_read=`<sep gap="5"></sep><block type="file_read"> <value name="OID"> <shadow type="field_oid_meta"> <field name="oid">0_userdata.0</field> </shadow> </value> <value name="FILE"> <shadow type="text"> <field name="TEXT">demo.json</field> </shadow> </value></block>`,r.file_read={init:function(){this.appendValueInput(`OID`).appendField(`📁 ${p(`file_read`)}`),this.appendValueInput(`FILE`).appendField(p(`file_read_filename`)).setCheck(null),this.appendStatementInput(`STATEMENT`).setCheck(null),this.setInputsInline(!1),this.setPreviousStatement(!0,null),this.setNextStatement(!0,null),this.setColour(f.Action.HUE),this.setTooltip(p(`file_read_tooltip`)),this.setHelpUrl(m(`file_read_help`))}},a.forBlock.file_read=function(e){let t=a.valueToCode(e,`OID`,i.ATOMIC),n=a.valueToCode(e,`FILE`,i.ATOMIC),r=a.statementToCode(e,`STATEMENT`),o=d(t);return`readFile(${t}${o?` /* ${o} */`:``}, String(${n}), (err, data, mimeType) => {\n${x()}${r}});\n`},f.Action.blocks.file_data=`<sep gap="5"></sep><block type="file_data"> <field name="ATTR">data</field></block>`,b(`file_data`,`📁`,[[p(`file_data_data`),`data`],[p(`file_data_mimeType`),`mimeType`]],[`file_read`],`file_data_warning`),f.Action.blocks.request=`<block type="request"> <mutation with_statement="false"></mutation> <field name="WITH_STATEMENT">FALSE</field> <field name="LOG"></field> <value name="URL"> <shadow type="text"> <field name="TEXT">http://</field> </shadow> </value></block>`,r.request={init:function(){this.appendDummyInput(`TEXT`).appendField(p(`request`)),this.appendValueInput(`URL`).appendField(p(`request_url`)),this.appendDummyInput(`WITH_STATEMENT`).appendField(p(`with_results`)).appendField(h(),`WITH_STATEMENT`),this.appendDummyInput(`LOG`).appendField(p(`loglevel`)).appendField(new e(c()),`LOG`),this.setInputsInline(!1),this.setPreviousStatement(!0,null),this.setNextStatement(!0,null),this.setColour(f.Action.HUE),this.setTooltip(p(`request_tooltip`)),this.setHelpUrl(p(`request_help`))},...y},a.forBlock.request=function(e){let t=a.valueToCode(e,`URL`,i.ATOMIC),n=e.getFieldValue(`LOG`),r=``;if(n&&(r=`console.${n}('request: ' + ${t});\n`),u(e.getFieldValue(`WITH_STATEMENT`))){let n=a.statementToCode(e,`STATEMENT`);if(n)return`try {\n require("request")(${t}, async (error, response, result) => {\n ${n} }).on("error", (e) => { console.error(e); });\n} catch (e) { console.error(e); }\n${r}`}return`try {\n require("request")(${t}).on("error", (e) => { console.error(e); });\n} catch (e) { console.error(e); }\n${r}`}}export{f as install};
@@ -1 +0,0 @@
1
- import{f as e,i as t,p as n,t as r}from"./blockly-fcfyKYzp.js";import{c as i,l as a}from"./index-B3s0zmWC.js";import{l as o}from"./helpers-CnEjYAup.js";function s(t,s,c,l,u){let d=window.Blockly.Translate,f=`${t}_container`,p=`${t}_mutator`;r[f]={init:function(){this.appendDummyInput().appendField(d(t)),this.appendStatementInput(`STACK`),this.setColour(`%{BKY_LOGIC_HUE}`),this.setTooltip(d(`${t}_tooltip`)),this.contextMenu=!1}},r[p]={init:function(){this.appendDummyInput(s).appendField(d(c)),this.setPreviousStatement(!0),this.setNextStatement(!0),this.setColour(`%{BKY_LOGIC_HUE}`),this.setTooltip(d(`${t}_tooltip`)),this.contextMenu=!1}},r[t]={init:function(){this.itemCount_=2,this.setMutator(new e.MutatorIcon([p],this)),this.setInputsInline(!1),this.setOutput(!0,`Boolean`),this.setColour(`%{BKY_LOGIC_HUE}`),this.setTooltip(d(`${t}_tooltip`))},mutationToDom:function(){let e=document.createElement(`mutation`);return e.setAttribute(`items`,String(this.itemCount_)),e},domToMutation:function(e){this.itemCount_=parseInt(e.getAttribute(`items`),10),this.updateShape_()},decompose:function(e){var t;let n=e.newBlock(f);n.initSvg();let r=(t=n.getInput(`STACK`))==null?void 0:t.connection;for(let t=0;t<this.itemCount_;t++){let t=e.newBlock(p);t.initSvg(),r.connect(t.previousConnection),r=t.nextConnection}return n},compose:function(e){let t=e.getInputTargetBlock(`STACK`),n=[];for(;t;)n.push(t.valueConnection_),t=t.nextConnection&&t.nextConnection.targetBlock();for(let e=0;e<this.itemCount_;e++){var r;let t=(r=this.getInput(`${s}${e}`))==null||(r=r.connection)==null?void 0:r.targetConnection;t&&!n.includes(t)&&t.disconnect()}this.itemCount_=n.length,this.itemCount_<2&&(this.itemCount_=2),this.updateShape_();for(let e=0;e<this.itemCount_;e++)o(n[e],this,`${s}${e}`)},saveConnections:function(e){let t=e.getInputTargetBlock(`STACK`),n=0;for(;t;){var r,i;let e=this.getInput(`${s}${n}`);t.valueConnection_=e==null||(r=e.connection)==null?void 0:r.targetConnection,n++,t=(i=t.nextConnection)==null?void 0:i.targetBlock()}},updateShape_:function(){for(let e=0;e<this.itemCount_;e++)if(!this.getInput(`${s}${e}`)){let t=this.appendValueInput(`${s}${e}`).setAlign(n.Align.RIGHT);e>0&&t.appendField(d(c))}for(let e=this.itemCount_;this.getInput(`${s}${e}`);e++)this.removeInput(`${s}${e}`)}},a.forBlock[t]=function(e){let t=e,n=[];for(let r=0;r<t.itemCount_;r++){let t=a.valueToCode(e,`${s}${r}`,i.ATOMIC);t&&n.push(t)}return[`${n.length>0?n.join(l):`false`}`,u]}}function c(){let e=window.Blockly.Translate;s(`logic_multi_and`,`AND`,`logic_multi_and_and`,` && `,i.LOGICAL_AND),s(`logic_multi_or`,`OR`,`logic_multi_or_or`,` || `,i.LOGICAL_OR),r.logic_between={init:function(){this.appendValueInput(`MIN`).setCheck(`Number`),this.appendValueInput(`VALUE`).setCheck(`Number`).appendField(new t([[`<`,`LT`],[`≤`,`LE`]]),`MIN_OPERATOR`),this.appendValueInput(`MAX`).setCheck(`Number`).appendField(new t([[`<`,`LT`],[`≤`,`LE`]]),`MAX_OPERATOR`),this.setInputsInline(!0),this.setOutput(!0,`Boolean`),this.setColour(`%{BKY_LOGIC_HUE}`),this.setTooltip(e(`logic_between_tooltip`))}},a.forBlock.logic_between=function(e){let t=a.valueToCode(e,`MIN`,i.RELATIONAL)||0,n=a.valueToCode(e,`VALUE`,i.RELATIONAL)||0,r=a.valueToCode(e,`MAX`,i.RELATIONAL)||0;return[`${t} ${e.getFieldValue(`MIN_OPERATOR`)===`LT`?`<`:`<=`} ${n} && ${n} ${e.getFieldValue(`MAX_OPERATOR`)===`LT`?`<`:`<=`} ${r}`,i.LOGICAL_AND]},r.logic_ifempty={init:function(){this.appendValueInput(`VALUE`).setCheck(null).setAlign(n.Align.RIGHT).appendField(e(`logic_ifempty`)),this.appendValueInput(`DEFLT`).setCheck(null).setAlign(n.Align.RIGHT).appendField(e(`logic_ifempty_then`)),this.setInputsInline(!0),this.setOutput(!0,null),this.setColour(`%{BKY_LOGIC_HUE}`),this.setTooltip(e(`logic_ifempty_tooltip`))}},a.forBlock.logic_ifempty=function(e){return[`${a.valueToCode(e,`VALUE`,i.LOGICAL_OR)||null} || ${a.valueToCode(e,`DEFLT`,i.LOGICAL_OR)||null}`,i.LOGICAL_OR]}}export{c as install};
@@ -1 +0,0 @@
1
- import{a as e,s as t,t as n}from"./blockly-fcfyKYzp.js";import{c as r,l as i}from"./index-B3s0zmWC.js";function a(){let a=window.Blockly.Translate;n.math_rndfixed={init:function(){this.appendValueInput(`x`).setCheck(`Number`).appendField(a(`math_rndfixed_round`)),this.appendDummyInput().appendField(a(`math_rndfixed_to`)).appendField(new e(0,1,25),`n`).appendField(a(`math_rndfixed_decplcs`)),this.setInputsInline(!0),this.setOutput(!0,`Number`),this.setColour(t.MATH_HUE),this.setTooltip(a(`math_rndfixed_tooltip`))}},i.forBlock.math_rndfixed=function(e){let t=i.valueToCode(e,`x`,r.ATOMIC),n=10**Number(e.getFieldValue(`n`));return[`Math.round(${t} * ${n}) / ${n}`,r.ATOMIC]}}export{a as install};
@@ -1 +0,0 @@
1
- import{f as e,o as t,p as n,t as r}from"./blockly-fcfyKYzp.js";import{c as i,l as a}from"./index-B3s0zmWC.js";import{c as o,l as s}from"./helpers-CnEjYAup.js";function c(){let c=window.Blockly,l=c.Translate;c.CustomBlocks=c.CustomBlocks||[],c.CustomBlocks.push(`Object`),c.Object={HUE:40,blocks:{}},c.Object.blocks.object_new=`<block type="object_new"></block>`,r.object_new_container={init:function(){this.setColour(c.Object.HUE),this.appendDummyInput().appendField(l(`object_new_attributes`)),this.appendStatementInput(`STACK`),this.setTooltip(l(`object_new_tooltip`)),this.contextMenu=!1}},r.object_new_mutator={init:function(){this.setColour(c.Object.HUE),this.appendDummyInput(`ATTR`).appendField(l(`object_new_attribute`)).appendField(new t(`attribute1`),`ATTR`),this.setPreviousStatement(!0),this.setNextStatement(!0),this.setTooltip(l(`object_new_tooltip`)),this.contextMenu=!1}},r.object_new={init:function(){this.appendDummyInput(`NAME`).appendField(l(`object_new`)),this.attributes_=[],this.itemCount_=0,this.setMutator(new e.MutatorIcon([`object_new_mutator`],this)),this.setInputsInline(!1),this.setOutput(!0),this.setColour(c.Object.HUE),this.setTooltip(l(`object_new_tooltip`))},mutationToDom:function(){let e=document.createElement(`mutation`);for(let t=0;t<this.attributes_.length;t++){let n=document.createElement(`attribute`);n.setAttribute(`id`,`ATTR_${t}`),n.setAttribute(`name`,this.attributes_[t]),e.appendChild(n)}return e},domToMutation:function(e){this.attributes_=[];for(let t=0,n;n=e.childNodes[t];t++)n.nodeName.toLowerCase()===`attribute`&&this.attributes_.push(n.getAttribute(`name`));this.itemCount_=this.attributes_.length,this.updateShape_()},decompose:function(e){var t;let n=e.newBlock(`object_new_container`);n.initSvg();let r=(t=n.getInput(`STACK`))==null?void 0:t.connection;for(let t=0;t<this.itemCount_;t++){let n=e.newBlock(`object_new_mutator`);n.setFieldValue(this.attributes_[t],`ATTR`),n.initSvg(),r.connect(n.previousConnection),r=n.nextConnection}return n},compose:function(e){this.attributes_=[];let t=e.getInputTargetBlock(`STACK`),n=[];for(;t;){let e=t.getFieldValue(`ATTR`);this.attributes_.push(e),n.push(t.valueConnection_),t=t.nextConnection&&t.nextConnection.targetBlock()}for(let e=0;e<this.itemCount_;e++){var r;let t=(r=this.getInput(`ATTR_${e}`))==null||(r=r.connection)==null?void 0:r.targetConnection;t&&!n.includes(t)&&t.disconnect()}this.itemCount_=n.length,this.itemCount_<0&&(this.itemCount_=0),this.updateShape_();for(let e=0;e<this.itemCount_;e++)s(n[e],this,`ATTR_${e}`)},saveConnections:function(e){let t=e.getInputTargetBlock(`STACK`),n=0;for(;t;){var r,i;let e=this.getInput(`ATTR_${n}`);t.valueConnection_=e==null||(r=e.connection)==null?void 0:r.targetConnection,n++,t=(i=t.nextConnection)==null?void 0:i.targetBlock()}},updateShape_:function(){let e=this.workspace;for(let t=0;t<this.itemCount_;t++){let r=this.getInput(`ATTR_${t}`);r?r.fieldRow[0].setValue(this.attributes_[t]):(r=this.appendValueInput(`ATTR_${t}`).setAlign(n.Align.RIGHT),r.appendField(this.attributes_[t])),setTimeout(t=>{var n;if(!((n=t.connection)!=null&&n.isConnected())){let n=e.newBlock(`text`);n.setShadow(!0),n.initSvg(),n.render(),n.outputConnection.connect(t.connection)}},100,r)}for(let e=this.itemCount_;this.getInput(`ATTR_${e}`);e++)this.removeInput(`ATTR_${e}`)}},a.forBlock.object_new=function(e){let t=e,n=[];for(let r=0;r<t.itemCount_;r++){let s=a.valueToCode(e,`ATTR_${r}`,i.COMMA);s&&n.push(`${o(t.attributes_[r])}: ${s}`)}return[`{ ${n.length?n.join(`, `):``} }`,i.ATOMIC]},c.Object.blocks.object_set_attr=`<block type="object_set_attr"> <field name="ATTR">attribute1</field> <value name="VALUE"> <shadow type="text"> <field name="TEXT">value</field> </shadow> </value></block>`,r.object_set_attr={init:function(){this.appendDummyInput(`ATTR`).appendField(l(`object_set_attr`)).appendField(new t(`attribute1`),`ATTR`),this.appendValueInput(`OBJECT`).appendField(l(`object_set_attr_object`)),this.appendValueInput(`VALUE`).setCheck(null).appendField(l(`object_set_attr_value`)),this.setInputsInline(!1),this.setPreviousStatement(!0,null),this.setNextStatement(!0,null),this.setColour(c.Object.HUE),this.setTooltip(l(`object_set_attr_tooltip`))}},a.forBlock.object_set_attr=function(e){let t=e.getFieldValue(`ATTR`),n=a.valueToCode(e,`VALUE`,i.ATOMIC),r=a.valueToCode(e,`OBJECT`,i.ATOMIC);return r||=`{}`,`((obj) => { if (typeof obj === 'object') { obj[${o(t)}] = ${n}; } })(${r});\n`},c.Object.blocks.object_del_attr=`<block type="object_del_attr"> <field name="ATTR">attribute1</field></block>`,r.object_del_attr={init:function(){this.appendDummyInput(`ATTR`).appendField(l(`object_del_attr`)).appendField(new t(`attribute1`),`ATTR`),this.appendValueInput(`OBJECT`).appendField(l(`object_del_attr_object`)),this.setInputsInline(!1),this.setPreviousStatement(!0,null),this.setNextStatement(!0,null),this.setColour(c.Object.HUE),this.setTooltip(l(`object_del_attr_tooltip`))}},a.forBlock.object_del_attr=function(e){let t=e.getFieldValue(`ATTR`),n=a.valueToCode(e,`OBJECT`,i.ATOMIC);return n||=`{}`,`((obj) => { if (typeof obj === 'object') { delete obj[${o(t)}]; } })(${n});\n`},c.Object.blocks.object_has_attr=`<block type="object_has_attr"> <field name="ATTR">attribute1</field> <value name="OBJECT"> <shadow type="get_object"> <field name="OID">Object ID</field> </shadow> </value></block>`,r.object_has_attr={init:function(){this.appendValueInput(`OBJECT`).appendField(l(`object_has_attr`)),this.appendDummyInput(`ATTR`).appendField(l(`object_has_attr_attr`)).appendField(new t(`attribute1`),`ATTR`),this.setInputsInline(!0),this.setOutput(!0,`Boolean`),this.setColour(c.Object.HUE),this.setTooltip(l(`object_has_attr_tooltip`))}},a.forBlock.object_has_attr=function(e){let t=a.valueToCode(e,`OBJECT`,i.ATOMIC),n=e.getFieldValue(`ATTR`);return[`Object.prototype.hasOwnProperty.call(${t}, ${o(n)})`,i.ATOMIC]},c.Object.blocks.object_keys=`<block type="object_keys"> <value name="OBJECT"> <shadow type="get_object"> <field name="OID">Object ID</field> </shadow> </value></block>`,r.object_keys={init:function(){this.appendValueInput(`OBJECT`).appendField(l(`object_keys`)),this.setInputsInline(!0),this.setOutput(!0,`Array`),this.setColour(c.Object.HUE),this.setTooltip(l(`object_keys_tooltip`))}},a.forBlock.object_keys=function(e){let t=a.valueToCode(e,`OBJECT`,i.ATOMIC);return t||=`{}`,[`Object.keys(${t})`,i.ATOMIC]}}export{c as install};